// Membership, Donate, Contact pages

const MembershipPage = ({ navigate }) => {
  const categories = [
    { code: "RA", name: "Regular Member Attorney (U.S.)", shortName: "U.S. Attorney", desc: "For U.S.-admitted attorneys applying as regular attorney members." },
    { code: "RFA", name: "Regular Member Foreign-Trained Attorney", shortName: "Foreign-Trained Attorney", desc: "For foreign-trained attorneys and legal professionals." },
    { code: "LS", name: "Law Student Member", shortName: "Law Student", desc: "For law students, LLM students, and eligible early-career candidates." },
    { code: "RAO", name: "Affiliated Organization Member (U.S.)", shortName: "U.S. Organization", desc: "For U.S. organizations applying through an authorized representative." },
    { code: "RFAO", name: "Affiliated Foreign Organization Member", shortName: "Foreign Organization", desc: "For foreign organizations applying through an authorized representative." },
    { code: "D", name: "Distinguished Member", shortName: "Distinguished", desc: "For applicants seeking merit-based recognition based on documented distinguished professional achievement." },
  ];
  const documentRequirements = {
    RA: [
      { id: "bar_admission", label: "Proof of bar admission", required: true },
    ],
    RFA: [
      { id: "foreign_legal_credentials", label: "Legal credentials or professional verification", required: true },
    ],
    LS: [
      { id: "law_school_enrollment", label: "Law school enrollment verification", required: true },
    ],
    RAO: [
      { id: "organization_authorization", label: "Organizational authorization document", required: true },
    ],
    RFAO: [
      { id: "organization_authorization", label: "Organizational authorization document", required: true },
    ],
    D: [
      { id: "cv_bio", label: "Current curriculum vitae or professional biography", required: true },
      { id: "written_statement", label: "Written statement identifying the applicant's law-related field", required: true },
      { id: "achievement_evidence", label: "Evidence of distinguished achievement and peer recognition", required: true, multiple: true },
      { id: "recommendation_letters", label: "At least two nomination, recommendation, or expert letters", required: true, multiple: true },
      { id: "verification_records", label: "Supporting records for verification of claimed achievements", required: true, multiple: true },
      { id: "additional_distinguished_docs", label: "Additional reliable supporting documentation", required: false, multiple: true },
    ],
  };
  const [categoryCode, setCategoryCode] = React.useState("RA");
  const [status, setStatus] = React.useState("idle");
  const [error, setError] = React.useState("");
  const [application, setApplication] = React.useState({
    name: "",
    email: "",
    phone: "",
    streetAddress: "",
    city: "",
    stateProvince: "",
    postalCode: "",
    country: "United States",
    barAdmission: "",
    lawSchool: "",
    organization: "",
    representativeName: "",
    distinguishedField: "",
    statement: "",
    externalDocumentsUrl: "",
    certificationAccepted: false,
    privacyAccepted: false,
    website: "",
  });
  const [files, setFiles] = React.useState({});
  const [uploadProgress, setUploadProgress] = React.useState(null);
  const selectedCategory = categories.find(c => c.code === categoryCode) || categories[0];
  const selectedDocs = documentRequirements[categoryCode] || [];
  const maxUploadBytes = 10 * 1024 * 1024;
  const distinguishedMaxTotalBytes = 100 * 1024 * 1024;
  const isAttorneyCategory = ["RA", "RFA"].includes(categoryCode);
  const isStudentCategory = categoryCode === "LS";
  const isOrganizationCategory = ["RAO", "RFAO"].includes(categoryCode);
  const showOrganizationField = ["RA", "RFA", "RAO", "RFAO", "D"].includes(categoryCode);
  const isUnitedStates = application.country === "United States";

  const scrollToApplication = () => {
    document.getElementById("membership-application")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const updateApplication = (field, value) => {
    setApplication(prev => ({ ...prev, [field]: value }));
  };

  const updateFiles = (docId, fileList) => {
    setFiles(prev => ({ ...prev, [docId]: Array.from(fileList || []) }));
  };

  const changeCategory = (nextCategoryCode) => {
    setCategoryCode(nextCategoryCode);
    setFiles({});
    setApplication(prev => ({
      ...prev,
      barAdmission: "",
      lawSchool: "",
      organization: "",
      representativeName: "",
      distinguishedField: "",
    }));
  };

  const submitApplication = async (e) => {
    e.preventDefault();
    setError("");
    setStatus("submitting");
    setUploadProgress(null);

    try {
      const missingDoc = selectedDocs.find(doc => doc.required && !(files[doc.id] || []).length);
      if (missingDoc) {
        if (!application.externalDocumentsUrl.trim()) {
          throw new Error(`Please upload: ${missingDoc.label}, or provide a secure cloud folder link.`);
        }
      }
      const oversizedFile = Object.values(files)
        .flat()
        .find(file => file.size > maxUploadBytes);
      if (oversizedFile) {
        throw new Error(`Please upload files no larger than 10 MB. ${oversizedFile.name} exceeds the per-file limit.`);
      }

      const selectedFileList = Object.values(files).flat();
      const totalUploadBytes = selectedFileList.reduce((total, file) => total + file.size, 0);
      if (categoryCode === "D" && totalUploadBytes > distinguishedMaxTotalBytes) {
        throw new Error("Distinguished Member portfolio uploads must total 100 MB or less. You may provide a secure cloud folder link instead.");
      }
      if (selectedFileList.length && !window.CAABABlobSDK?.upload) {
        throw new Error("Document upload is unavailable right now. Please refresh the page or provide a secure cloud folder link.");
      }

      const blobUploads = [];
      let uploadedBytes = 0;
      for (const doc of selectedDocs) {
        const fieldName = `doc_${doc.id}`;
        for (const file of (files[doc.id] || [])) {
          const safeFileName = file.name.replace(/[^a-zA-Z0-9._ -]/g, "-");
          const pathname = `membership-applications/${Date.now()}-${Math.random().toString(36).slice(2)}/${fieldName}/${safeFileName}`;
          const blob = await window.CAABABlobSDK.upload(pathname, file, {
            access: "private",
            handleUploadUrl: "/api/membership-upload",
            clientPayload: JSON.stringify({ website: application.website }),
            contentType: file.type || undefined,
            onUploadProgress: progress => {
              const percentage = totalUploadBytes
                ? Math.round(((uploadedBytes + progress.loaded) / totalUploadBytes) * 100)
                : 100;
              setUploadProgress(Math.min(percentage, 100));
            },
          });
          blobUploads.push({
            fieldName,
            pathname: blob.pathname,
            originalName: file.name,
          });
          uploadedBytes += file.size;
        }
      }

      const formData = new FormData();
      Object.entries(application).forEach(([key, value]) => {
        formData.append(key, String(value));
      });
      formData.append("categoryCode", categoryCode);
      formData.append("categoryName", selectedCategory.name);

      const documentLabels = {};
      selectedDocs.forEach(doc => {
        const fieldName = `doc_${doc.id}`;
        documentLabels[fieldName] = doc.label;
      });
      formData.append("documentLabels", JSON.stringify(documentLabels));
      formData.append("blobUploads", JSON.stringify(blobUploads));

      const response = await fetch("/api/membership", {
        method: "POST",
        body: formData,
      });

      const result = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (response.status === 413) {
          throw new Error("Uploaded files could not be processed. Please use files no larger than 10 MB or provide a secure cloud folder link.");
        }
        throw new Error(result.error || "Unable to submit the application right now.");
      }

      setStatus("success");
      setFiles({});
      setUploadProgress(null);
      setApplication({
        name: "",
        email: "",
        phone: "",
        streetAddress: "",
        city: "",
        stateProvince: "",
        postalCode: "",
        country: "United States",
        barAdmission: "",
        lawSchool: "",
        organization: "",
        representativeName: "",
        distinguishedField: "",
        statement: "",
        externalDocumentsUrl: "",
        certificationAccepted: false,
        privacyAccepted: false,
        website: "",
      });
    } catch (err) {
      setStatus("error");
      setUploadProgress(null);
      setError(err.message || "Unable to submit the application right now.");
    }
  };

  return (
    <div className="page">
      <section style={{background: "var(--ink)", color: "var(--paper)", padding: "clamp(64px, 10vw, 112px) 0 clamp(48px, 7vw, 88px)"}}>
        <div className="wrap">
          <span className="eyebrow light">Membership</span>
          <h1 className="display" style={{fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 1.02, maxWidth: "22ch", marginTop: 24, marginBottom: 32}}>
            A community worth <em style={{color: "var(--gold-soft)", fontStyle: "italic"}}>joining</em>, carefully stewarded
          </h1>
          <p style={{fontSize: "clamp(17px, 1.4vw, 20px)", lineHeight: 1.6, color: "#C9D2DC", maxWidth: "62ch"}}>
            CAABA welcomes legal professionals, students, honored contributors, and mission-aligned supporters through membership categories designed to reflect the different ways people participate in and strengthen the Association.
          </p>
        </div>
      </section>

      <section style={{background: "var(--paper)"}}>
        <div className="wrap">
          <div className="section-head">
            <div className="section-head-left">
              <span className="eyebrow">§ 01 — Membership</span>
              <span className="section-num">Who It's For</span>
            </div>
            <div>
              <h2 className="display">Membership is open to a broader professional community.</h2>
              <p className="lead" style={{marginTop: 20}}>
                Our current membership structure includes regular attorneys, foreign-trained attorneys, law students, affiliated organizations, and merit-based Distinguished Members. Honorary Membership is conferred by the Board and is not a self-selected application category.
              </p>
            </div>
          </div>

          <div>
            <div style={{display: "flex", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)", flexWrap: "wrap"}} className="tier-nav">
              {categories.map((category, i) => (
                <button key={category.code} onClick={() => changeCategory(category.code)} style={{
                  flex: "1 1 200px",
                  padding: "24px 20px",
                  background: "transparent",
                  border: 0,
                  borderRight: i < categories.length - 1 ? "1px solid var(--rule)" : 0,
                  cursor: "pointer",
                  textAlign: "left",
                  fontFamily: "var(--sans)",
                  color: categoryCode === category.code ? "var(--ink)" : "var(--muted)",
                  position: "relative",
                  transition: "color .2s",
                }}>
                  <div style={{
                    position: "absolute", top: 0, left: 0, right: 0, height: 2,
                    background: categoryCode === category.code ? "var(--gold)" : "transparent",
                    transition: "background .2s",
                  }}/>
                  <div className="eyebrow" style={{color: categoryCode === category.code ? "var(--gold-2)" : "var(--muted-light)", marginBottom: 8}}>
                    {category.code}
                  </div>
                  <div className="display" style={{fontSize: 22, lineHeight: 1.1}}>{category.name}</div>
                </button>
              ))}
            </div>
            <div style={{padding: "clamp(32px, 5vw, 64px)", background: "var(--paper-3)", border: "1px solid var(--rule)", borderTop: 0, display: "grid", gridTemplateColumns: "2fr 1fr", gap: "clamp(24px, 5vw, 64px)"}} className="tier-detail">
              <div>
                <span className="eyebrow">Currently Viewing</span>
                <h3 className="display" style={{fontSize: "clamp(28px, 3vw, 40px)", lineHeight: 1.1, marginTop: 10, marginBottom: 16}}>
                  {selectedCategory.name}
                </h3>
                <p style={{fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-3)", maxWidth: "52ch"}}>{selectedCategory.desc}</p>
                <p style={{fontSize: 14, color: "var(--muted)", fontStyle: "italic", fontFamily: "var(--serif)", marginTop: 20}}>
                  Uploaded documents will be stored in a CAABA-controlled application folder and linked to the Association's internal membership records.
                </p>
              </div>
              <div style={{borderLeft: "1px solid var(--rule)", paddingLeft: "clamp(24px, 4vw, 48px)"}} className="tier-right">
                <span className="eyebrow">Category Code</span>
                <div className="display" style={{fontSize: 34, marginTop: 10, marginBottom: 20, color: "var(--gold-2)"}}>{categoryCode}</div>
                <button className="btn btn-primary" onClick={scrollToApplication} style={{width: "100%", justifyContent: "center"}}>
                  Start Application <Arrow/>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Why Join */}
      <section style={{background: "var(--paper-2)", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)"}}>
        <div className="wrap">
          <div className="section-head">
            <div className="section-head-left">
              <span className="eyebrow">§ 02 — Benefits</span>
              <span className="section-num">Why Join CAABA</span>
            </div>
            <div>
              <h2 className="display">Eight reasons to become a member</h2>
            </div>
          </div>
          <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 0, border: "1px solid var(--rule)", background: "var(--paper-3)"}} className="benefits-grid">
            {[
              ["Professional Development", "Substantive programming and continuing education built around real practice."],
              ["Mentorship Pairing", "Thoughtful, practice-aware matching with experienced attorneys across practice areas."],
              ["Trusted Referral Network", "Access to a network anchored in professional reputation and ethical rigor."],
              ["International Career Support", "OPT guidance and practical integration support for foreign-trained lawyers."],
              ["Cross-Border Access", "Engagement with cross-border matters and Central Asian legal institutions."],
              ["Member Convenings", "Salons, dinners, and programming that build durable professional ties."],
              ["Visibility & Platforms", "Speaking, writing, and representation opportunities within the broader bar."],
              ["Community Stewardship", "A voice in shaping the next chapter of the Association."],
            ].map(([h, b], i) => (
              <div key={h} style={{
                padding: "clamp(24px, 3vw, 40px)",
                borderRight: i % 2 === 0 ? "1px solid var(--rule)" : 0,
                borderBottom: i < 6 ? "1px solid var(--rule)" : 0,
                display: "flex", gap: 20, alignItems: "flex-start",
                minHeight: 140,
              }}>
                <span className="serif-num" style={{fontSize: 28, color: "var(--gold-2)", lineHeight: 1, minWidth: 32}}>
                  {String(i+1).padStart(2,"0")}
                </span>
                <div>
                  <h3 className="display" style={{fontSize: 22, lineHeight: 1.15, marginBottom: 6}}>{h}</h3>
                  <p style={{fontSize: 14.5, lineHeight: 1.6, color: "var(--muted)"}}>{b}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section style={{background: "var(--ink)", color: "var(--paper)"}}>
        <div className="wrap" style={{textAlign: "center"}}>
          <span className="eyebrow light">Join the Network</span>
          <h2 className="display" style={{fontSize: "clamp(32px, 5vw, 60px)", lineHeight: 1.05, marginTop: 16, marginBottom: 32, maxWidth: "24ch", marginLeft: "auto", marginRight: "auto", color: "var(--paper)"}}>
            Our community grows, carefully, with every complete application.
          </h2>
          <button className="btn btn-primary on-dark" onClick={scrollToApplication}>
            Apply for Membership <Arrow/>
          </button>
        </div>
      </section>

      <section id="membership-application" style={{background: "var(--paper)"}}>
        <div className="wrap">
          <div style={{display: "grid", gridTemplateColumns: "1fr 1.35fr", gap: "clamp(32px, 6vw, 96px)", alignItems: "start"}} className="membership-application-grid">
            <div>
              <span className="eyebrow">§ 03 — Application</span>
              <h2 className="display" style={{fontSize: "clamp(30px, 3.8vw, 50px)", lineHeight: 1.08, marginTop: 16, marginBottom: 24}}>
                Apply to join CAABA.
              </h2>
              <p style={{fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-3)", maxWidth: "48ch"}}>
                Submit your membership interest here. The Membership team will review the request and follow up with next steps.
              </p>
              <div style={{marginTop: 32, paddingTop: 24, borderTop: "1px solid var(--rule)"}}>
                <label>Selected Membership Category</label>
                <div className="display" style={{fontSize: 26, color: "var(--gold-2)", marginTop: 6}}>{selectedCategory.name}</div>
                <p style={{fontSize: 13.5, lineHeight: 1.6, color: "var(--muted)", marginTop: 12}}>
                  Honorary Membership is conferred by the Board and is not available as a self-selected application category.
                </p>
              </div>
            </div>

            <div style={{background: "var(--paper-3)", border: "1px solid var(--rule)", padding: "clamp(24px, 3vw, 48px)"}}>
              {status === "success" ? (
                <div style={{padding: "36px 0", textAlign: "center"}}>
                  <LogoMark size={48}/>
                  <h3 className="display" style={{fontSize: 32, marginTop: 20, marginBottom: 12}}>Application received.</h3>
                  <p style={{fontSize: 15.5, color: "var(--muted)", maxWidth: "38ch", margin: "0 auto 24px"}}>
                    Thank you for submitting your CAABA membership application. A member of the Association will review it before membership is confirmed.
                  </p>
                  <div style={{
                    border: "1px solid var(--rule)",
                    background: "var(--paper)",
                    padding: "20px 22px",
                    maxWidth: 420,
                    margin: "0 auto 24px",
                    textAlign: "left",
                  }}>
                    <div className="eyebrow" style={{marginBottom: 10}}>Membership Dues</div>
                    <p style={{fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-3)", margin: "0 0 12px"}}>
                      Once reviewed, dues may be paid via <strong>Zelle</strong> to:
                    </p>
                    <div style={{
                      fontFamily: "var(--mono)", fontSize: 14, color: "var(--ink)",
                      padding: "10px 12px", border: "1px solid var(--rule)",
                      background: "var(--paper-3)", wordBreak: "break-all",
                    }}>
                      uscaabar@gmail.com
                    </div>
                    <p style={{fontSize: 12.5, lineHeight: 1.55, color: "var(--muted)", margin: "10px 0 0"}}>
                      For ACH or wire transfer, please email the same address to request bank details.
                    </p>
                  </div>
                  <button className="btn btn-link" onClick={() => {setStatus("idle"); setError("");}}>
                    Submit another application <Arrow/>
                  </button>
                </div>
              ) : (
                <form onSubmit={submitApplication} style={{display: "flex", flexDirection: "column", gap: 24}}>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                    <div>
                      <label>Full Name *</label>
                      <input required value={application.name} onChange={e => updateApplication("name", e.target.value)} placeholder="Jane A. Counselor"/>
                    </div>
                    <div>
                      <label>Email *</label>
                      <input required type="email" value={application.email} onChange={e => updateApplication("email", e.target.value)} placeholder="jane@firm.com"/>
                    </div>
                  </div>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                    <div>
                      <label>Phone</label>
                      <input type="tel" value={application.phone} onChange={e => updateApplication("phone", e.target.value)} placeholder="Optional"/>
                    </div>
                    <div>
                      <label>Country *</label>
                      <select required value={application.country} onChange={e => updateApplication("country", e.target.value)}>
                        <option>United States</option>
                        <option>Kazakhstan</option>
                        <option>Kyrgyzstan</option>
                        <option>Tajikistan</option>
                        <option>Turkmenistan</option>
                        <option>Uzbekistan</option>
                        <option>Afghanistan</option>
                        <option>Canada</option>
                        <option>United Kingdom</option>
                        <option>Other</option>
                      </select>
                    </div>
                  </div>
                  {!isUnitedStates && (
                    <p style={{fontSize: 13.5, lineHeight: 1.55, color: "var(--gold-2)", border: "1px solid var(--rule)", background: "var(--paper)", padding: 14, margin: 0}}>
                      Applicants outside the United States may be required to complete payment before membership is activated.
                    </p>
                  )}
                  <div>
                    <label>Street Address *</label>
                    <input required value={application.streetAddress} onChange={e => updateApplication("streetAddress", e.target.value)} placeholder="Street address"/>
                  </div>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                    <div>
                      <label>City *</label>
                      <input required value={application.city} onChange={e => updateApplication("city", e.target.value)} placeholder="City"/>
                    </div>
                    <div>
                      <label>{isUnitedStates ? "State *" : "State / Province"}</label>
                      <input required={isUnitedStates} value={application.stateProvince} onChange={e => updateApplication("stateProvince", e.target.value)} placeholder={isUnitedStates ? "State" : "Optional"}/>
                    </div>
                  </div>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                    <div>
                      <label>ZIP / Postal Code *</label>
                      <input required value={application.postalCode} onChange={e => updateApplication("postalCode", e.target.value)} placeholder={isUnitedStates ? "ZIP code" : "Postal code"}/>
                    </div>
                    <div>
                      <label>Membership Category *</label>
                      <select required value={categoryCode} onChange={e => changeCategory(e.target.value)}>
                        {categories.map(category => (
                          <option key={category.code} value={category.code}>{category.shortName} - {category.code}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                    {isAttorneyCategory && (
                      <div>
                        <label>{categoryCode === "RA" ? "Bar Admission *" : "Legal Credential *"}</label>
                        <input required value={application.barAdmission} onChange={e => updateApplication("barAdmission", e.target.value)} placeholder={categoryCode === "RA" ? "State and admission status" : "Jurisdiction, credential, or professional status"}/>
                      </div>
                    )}
                    {isStudentCategory && (
                      <div>
                        <label>Law School *</label>
                        <input required value={application.lawSchool} onChange={e => updateApplication("lawSchool", e.target.value)} placeholder="School and program"/>
                      </div>
                    )}
                    {categoryCode === "D" && (
                      <div>
                        <label>Current Organization</label>
                        <input value={application.organization} onChange={e => updateApplication("organization", e.target.value)} placeholder="Optional"/>
                      </div>
                    )}
                  </div>
                  {(showOrganizationField && categoryCode !== "D") && (
                    <div style={{display: "grid", gridTemplateColumns: isOrganizationCategory ? "1fr 1fr" : "1fr", gap: 24}} className="form-row">
                      <div>
                        <label>{isOrganizationCategory ? "Organization *" : "Organization / Firm"}</label>
                        <input required={isOrganizationCategory} value={application.organization} onChange={e => updateApplication("organization", e.target.value)} placeholder={isOrganizationCategory ? "Organization legal name" : "Optional"}/>
                      </div>
                      {isOrganizationCategory && (
                        <div>
                          <label>Representative Name *</label>
                          <input required value={application.representativeName} onChange={e => updateApplication("representativeName", e.target.value)} placeholder="Authorized representative"/>
                        </div>
                      )}
                    </div>
                  )}
                  {categoryCode === "D" && (
                    <div style={{border: "1px solid var(--rule)", background: "var(--paper)", padding: 22}}>
                      <span className="eyebrow">Distinguished Member Portfolio</span>
                      <h3 className="display" style={{fontSize: 26, marginTop: 8, marginBottom: 12}}>Supporting documentation required.</h3>
                      <p style={{fontSize: 14.5, lineHeight: 1.65, color: "var(--muted)", marginBottom: 18}}>
                        Distinguished Member applications require a documented professional portfolio demonstrating outstanding achievements and peer recognition in the legal profession or a closely related law-related field.
                      </p>
                      <label>Field of Professional Activity *</label>
                      <input required value={application.distinguishedField} onChange={e => updateApplication("distinguishedField", e.target.value)} placeholder="Legal practice, scholarship, advocacy, legal technology, public service, etc."/>
                    </div>
                  )}
                  <div>
                    <label>Statement of Interest *</label>
                    <textarea required rows={5} value={application.statement} onChange={e => updateApplication("statement", e.target.value)} placeholder="Tell us briefly about your eligibility and interest in CAABA membership..." style={{resize: "vertical", minHeight: 120}}/>
                  </div>
                  <div>
                    <label>Supporting Documents</label>
                    <div style={{display: "flex", flexDirection: "column", gap: 14, marginTop: 10}}>
                      {selectedDocs.map(doc => (
                        <div key={doc.id} style={{border: "1px solid var(--rule)", background: "var(--paper)", padding: 16}}>
                          <div style={{display: "flex", justifyContent: "space-between", gap: 16, alignItems: "baseline", marginBottom: 10}}>
                            <span style={{fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1.2}}>{doc.label}</span>
                            <span className="section-num" style={{color: doc.required ? "var(--gold-2)" : "var(--muted)"}}>{doc.required ? "Required" : "Optional"}</span>
                          </div>
                          <input
                            type="file"
                            required={doc.required && !application.externalDocumentsUrl.trim()}
                            multiple={!!doc.multiple}
                            accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                            onChange={e => updateFiles(doc.id, e.target.files)}
                          />
                        </div>
                      ))}
                    </div>
                    <p style={{fontSize: 12.5, color: "var(--muted)", lineHeight: 1.6, marginTop: 12}}>
                      Accepted file types: PDF, DOC, DOCX, JPG, PNG. Maximum file size is 10 MB. Distinguished Member portfolio uploads may total up to 100 MB. For larger materials, provide a secure cloud folder link below.
                    </p>
                  </div>
                  <div>
                    <label>Secure Cloud Folder Link</label>
                    <input
                      type="url"
                      value={application.externalDocumentsUrl}
                      onChange={e => updateApplication("externalDocumentsUrl", e.target.value)}
                      placeholder="Optional - Google Drive, Dropbox, OneDrive, or Box link"
                    />
                    <p style={{fontSize: 12.5, color: "var(--muted)", lineHeight: 1.6, marginTop: 10}}>
                      Use this option when a required document exceeds the direct upload limit. Confirm that CAABA reviewers can access the folder before submitting.
                    </p>
                  </div>
                  <label style={{display: "flex", gap: 12, alignItems: "flex-start", fontFamily: "var(--sans)", fontSize: 13.5, lineHeight: 1.55, color: "var(--ink-3)"}}>
                    <input type="checkbox" required checked={application.certificationAccepted} onChange={e => updateApplication("certificationAccepted", e.target.checked)} style={{marginTop: 4}}/>
                    <span>I certify that the information provided is accurate and that I agree to comply with the CAABA Bylaws and policies.</span>
                  </label>
                  <label style={{display: "flex", gap: 12, alignItems: "flex-start", fontFamily: "var(--sans)", fontSize: 13.5, lineHeight: 1.55, color: "var(--ink-3)"}}>
                    <input type="checkbox" required checked={application.privacyAccepted} onChange={e => updateApplication("privacyAccepted", e.target.checked)} style={{marginTop: 4}}/>
                    <span>I authorize CAABA to collect, store, review, and process my application materials for membership eligibility, governance, recordkeeping, dues administration, and related Association purposes.</span>
                  </label>
                  <p style={{fontSize: 12.5, lineHeight: 1.6, color: "var(--muted)", borderTop: "1px solid var(--rule)", paddingTop: 18}}>
                    Material misrepresentation or omission may result in denial, revocation, suspension, or other Board action. Application materials may be reviewed by authorized officers, administrators, reviewers, committee members, and Board members with a need to know.
                  </p>
                  <input
                    tabIndex="-1"
                    autoComplete="off"
                    value={application.website}
                    onChange={e => updateApplication("website", e.target.value)}
                    style={{position: "absolute", left: "-10000px", width: 1, height: 1, opacity: 0}}
                    aria-hidden="true"
                  />
                  {status === "error" && (
                    <p style={{fontSize: 13.5, color: "#8A2D2D", lineHeight: 1.5}}>
                      {error}
                    </p>
                  )}
                  {status === "submitting" && uploadProgress !== null && (
                    <p style={{fontSize: 13.5, color: "var(--muted)", lineHeight: 1.5}}>
                      Uploading documents... {uploadProgress}%
                    </p>
                  )}
                  <TaxNotice/>
                  <button type="submit" className="btn btn-primary" disabled={status === "submitting"} style={{justifyContent: "center", opacity: status === "submitting" ? 0.65 : 1}}>
                    {status === "submitting" ? (uploadProgress === null ? "Submitting..." : "Uploading...") : "Submit Application"} <Arrow/>
                  </button>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 820px) {
          .tier-detail { grid-template-columns: 1fr !important; }
          .tier-right { border-left: 0 !important; padding-left: 0 !important; padding-top: 24px; border-top: 1px solid var(--rule); }
          .benefits-grid { grid-template-columns: 1fr !important; }
          .benefits-grid > div { border-right: 0 !important; border-bottom: 1px solid var(--rule) !important; }
          .membership-application-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
};

const MembershipCardPage = ({ navigate }) => {
  const [status, setStatus] = React.useState("loading");
  const [card, setCard] = React.useState(null);
  const [error, setError] = React.useState("");

  const formatCardDate = (value) => {
    if (!value) return "";
    const datePart = String(value).match(/\d{4}-\d{2}-\d{2}/)?.[0];
    if (!datePart) return value;
    const date = new Date(`${datePart}T12:00:00`);
    if (Number.isNaN(date.getTime())) return value;
    return date.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
  };

  React.useEffect(() => {
    const token = new URLSearchParams(window.location.search).get("token") || "";
    if (!token) {
      setStatus("error");
      setError("Membership card link is missing or invalid.");
      return;
    }

    fetch(`/api/member-card?token=${encodeURIComponent(token)}`)
      .then(async response => {
        const result = await response.json().catch(() => ({}));
        if (!response.ok) throw new Error(result.error || "Unable to load membership card.");
        setCard(result);
        setStatus("success");
      })
      .catch(err => {
        setError(err.message || "Unable to load membership card.");
        setStatus("error");
      });
  }, []);

  return (
    <div className="page">
      <section style={{background: "var(--paper)", minHeight: "72vh", padding: "clamp(72px, 12vw, 132px) 0"}}>
        <div className="wrap" style={{maxWidth: 760}}>
          {status === "loading" && (
            <p style={{fontSize: 16, color: "var(--muted)"}}>Loading membership card...</p>
          )}
          {status === "error" && (
            <div>
              <span className="eyebrow">Membership Card</span>
              <h1 className="display" style={{fontSize: "clamp(38px, 6vw, 64px)", marginTop: 18}}>Card unavailable.</h1>
              <p style={{fontSize: 16, lineHeight: 1.7, color: "var(--muted)", maxWidth: "54ch"}}>{error}</p>
              <button className="btn btn-primary" onClick={() => navigate("membership")}>Return to Membership <Arrow/></button>
            </div>
          )}
          {status === "success" && card && (
            <div>
              <div style={{fontFamily: "var(--sans)", fontSize: "clamp(16px, 2vw, 22px)", letterSpacing: 8, color: "var(--gold-2)", textTransform: "uppercase", marginBottom: "clamp(28px, 5vw, 56px)"}}>
                CAABA Membership Card
              </div>
              <div style={{
                border: "1px solid rgba(200,160,74,.55)",
                background: "var(--ink)",
                color: "var(--paper)",
                padding: "clamp(32px, 7vw, 72px)",
                maxWidth: 980,
                minHeight: 480,
                display: "flex",
                flexDirection: "column",
                justifyContent: "space-between",
              }}>
                <div style={{display: "flex", justifyContent: "space-between", gap: 20, alignItems: "flex-start"}}>
                  <img src="/assets/caaba-logo.png" alt="CAABA" style={{width: "clamp(150px, 22vw, 260px)", height: "auto", objectFit: "contain"}}/>
                  <div style={{textAlign: "right", fontFamily: "var(--sans)", fontSize: "clamp(16px, 2vw, 22px)", letterSpacing: 0, textTransform: "uppercase", color: "var(--gold-soft)", whiteSpace: "nowrap"}}>
                    {card.membershipStatus || "Active"}
                  </div>
                </div>
                <div>
                  <h1 className="display" style={{fontSize: "clamp(44px, 7vw, 78px)", lineHeight: 1.02, marginBottom: 28}}>
                    {card.fullName}
                  </h1>
                  <p style={{fontSize: "clamp(18px, 2.2vw, 26px)", lineHeight: 1.65, color: "#C9D2DC", margin: 0}}>
                    Central Asian American Bar Association<br/>
                    Member ID: {card.memberId}<br/>
                    Category: {card.categoryCode || "-"}<br/>
                    {card.renewalDate
                      ? `Valid through: ${formatCardDate(card.renewalDate)}`
                      : `Current term: ${formatCardDate(card.admissionDate) || "Active"}`}
                  </p>
                </div>
                <div style={{fontSize: "clamp(14px, 1.8vw, 20px)", lineHeight: 1.6, color: "#AEB9C5", borderTop: "1px solid rgba(255,255,255,.2)", paddingTop: 28}}>
                  Admission date: {formatCardDate(card.admissionDate) || "-"}
                </div>
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

const DonatePage = ({ navigate }) => {
  const [amount, setAmount] = React.useState(250);
  const [custom, setCustom] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  const presets = [100, 250, 500, 1000, 2500];
  const finalAmount = (custom || amount || 0).toLocaleString();
  const zelleEmail = "uscaabar@gmail.com";

  const copyZelle = async () => {
    try {
      await navigator.clipboard.writeText(zelleEmail);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("copy failed", err);
    }
  };

  return (
    <div className="page">
      <section style={{background: "var(--ink)", color: "var(--paper)", padding: "clamp(64px, 10vw, 112px) 0 clamp(48px, 7vw, 88px)"}}>
        <div className="wrap">
          <span className="eyebrow light">Support CAABA</span>
          <h1 className="display" style={{fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 1.02, maxWidth: "22ch", marginTop: 24, marginBottom: 32}}>
            Your contribution builds the <em style={{color: "var(--gold-soft)", fontStyle: "italic"}}>next chapter</em>.
          </h1>
          <p style={{fontSize: "clamp(17px, 1.4vw, 20px)", lineHeight: 1.6, color: "#C9D2DC", maxWidth: "62ch"}}>
            CAABA is sustained by the generosity of attorneys, firms, institutional partners, and individual supporters who believe in the long-term work of building a durable professional community.
          </p>
        </div>
      </section>

      <section style={{background: "var(--paper)"}}>
        <div className="wrap">
          <div style={{display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: "clamp(32px, 6vw, 96px)", alignItems: "start"}} className="donate-grid">
            <div>
              <span className="eyebrow">§ 01 — Why Support CAABA</span>
              <h2 className="display" style={{fontSize: "clamp(30px, 3.6vw, 48px)", lineHeight: 1.08, maxWidth: "22ch", marginTop: 16, marginBottom: 24}}>
                Contributions make the community possible.
              </h2>
              <p style={{fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-3)", maxWidth: "52ch", marginBottom: 32}}>
                Donations support the programming, infrastructure, and mentorship that define the Association. Every contribution is stewarded with care and accountability.
              </p>
              <ul style={{listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 20, borderTop: "1px solid var(--rule)"}}>
                {[
                  ["Student & Early-Career Support", "Scholarships, event access, and direct support for law students and LLM candidates."],
                  ["Mentorship Programming", "Pairing, training, and infrastructure that sustain intergenerational mentorship."],
                  ["Events & Community-Building", "Convenings, dinners, and salons that strengthen relationships across the bar."],
                  ["Cross-Border Legal Dialogue", "Delegations, roundtables, and publications between the U.S. and Central Asia."],
                  ["Sponsorship Opportunities", "Named programs and institutional partnerships for firms and foundations."],
                ].map(([h, b]) => (
                  <li key={h} style={{display: "grid", gridTemplateColumns: "24px 1fr", gap: 20, paddingTop: 20, borderBottom: "1px solid var(--rule)", paddingBottom: 20}}>
                    <span style={{width: 16, height: 1, background: "var(--gold)", marginTop: 14}}/>
                    <div>
                      <h3 className="display" style={{fontSize: 22, marginBottom: 6}}>{h}</h3>
                      <p style={{fontSize: 14.5, lineHeight: 1.6, color: "var(--muted)"}}>{b}</p>
                    </div>
                  </li>
                ))}
              </ul>
            </div>

            {/* Donation form */}
            <div style={{background: "var(--paper-3)", border: "1px solid var(--rule)", padding: "clamp(24px, 3vw, 40px)", position: "sticky", top: 100}} className="donate-card">
              <span className="eyebrow">Make a Contribution</span>
              <h3 className="display" style={{fontSize: 30, lineHeight: 1.1, marginTop: 12, marginBottom: 24}}>Choose an amount</h3>
              <div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 20}}>
                {presets.map(a => (
                  <button key={a} onClick={() => {setAmount(a); setCustom("");}} style={{
                    padding: "18px 0",
                    border: `1px solid ${amount === a && !custom ? "var(--gold)" : "var(--rule)"}`,
                    background: amount === a && !custom ? "var(--ink)" : "transparent",
                    color: amount === a && !custom ? "var(--paper)" : "var(--ink)",
                    fontFamily: "var(--serif)",
                    fontSize: 20,
                    cursor: "pointer",
                    transition: "all .2s",
                  }}>
                    ${a.toLocaleString()}
                  </button>
                ))}
              </div>
              <div style={{marginBottom: 20}}>
                <label>Custom Amount (USD)</label>
                <input type="number" placeholder="Other amount" value={custom} onChange={e => {setCustom(e.target.value); setAmount(+e.target.value);}}/>
              </div>
              <div style={{marginBottom: 24}}>
                <label>Gift Type</label>
                <select>
                  <option>One-Time Contribution</option>
                  <option>Monthly Recurring</option>
                  <option>Annual Recurring</option>
                </select>
              </div>
              <div style={{marginBottom: 20}}>
                <TaxNotice compact/>
              </div>

              <div style={{borderTop: "1px solid var(--rule)", paddingTop: 20, marginBottom: 20}}>
                <div className="eyebrow" style={{marginBottom: 12}}>How to send ${finalAmount}</div>

                <div style={{
                  border: "1px solid var(--rule)",
                  padding: "16px 18px",
                  background: "var(--paper)",
                  marginBottom: 12,
                }}>
                  <div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8, gap: 12, flexWrap: "wrap"}}>
                    <span style={{
                      fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink)",
                    }}>Zelle</span>
                    <span style={{
                      fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.14em",
                      textTransform: "uppercase", color: "var(--muted)",
                    }}>Instant · No fees</span>
                  </div>
                  <div style={{
                    fontFamily: "var(--mono)", fontSize: 14, color: "var(--ink)",
                    wordBreak: "break-all", marginBottom: 12,
                  }}>{zelleEmail}</div>
                  <button
                    type="button"
                    onClick={copyZelle}
                    className="btn btn-ghost"
                    style={{width: "100%", justifyContent: "center", padding: "12px 16px"}}
                  >
                    {copied ? "Copied ✓" : "Copy Zelle Address"}
                  </button>
                  <p style={{fontSize: 12.5, lineHeight: 1.6, color: "var(--muted)", marginTop: 12, marginBottom: 0}}>
                    Send via your bank's Zelle feature. Include a brief memo (e.g., "Donation" or "Membership dues").
                  </p>
                </div>

                <div style={{
                  border: "1px solid var(--rule)",
                  padding: "16px 18px",
                  background: "var(--paper)",
                }}>
                  <div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8, gap: 12, flexWrap: "wrap"}}>
                    <span style={{
                      fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink)",
                    }}>Bank Transfer (ACH / Wire)</span>
                    <span style={{
                      fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.14em",
                      textTransform: "uppercase", color: "var(--muted)",
                    }}>For larger gifts</span>
                  </div>
                  <p style={{fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-3)", margin: "0 0 12px"}}>
                    Wire and ACH details are available on request to protect the account from unauthorized debits.
                  </p>
                  <a
                    href={`mailto:${zelleEmail}?subject=${encodeURIComponent("Bank transfer details request")}&body=${encodeURIComponent(
`Hello CAABA Treasury Team,

I would like to make a contribution to CAABA via bank transfer (ACH or wire) in the amount of $${finalAmount}.

Please share the following so that I can complete the transfer:
  • Account name (beneficiary)
  • Bank name and address
  • Routing number (ABA) — for domestic ACH/wire
  • Account number
  • SWIFT / BIC code — if applicable for international wire
  • Any reference or memo I should include

A brief note about me:
  • Name:
  • Organization (if any):
  • Email:
  • Phone (optional):
  • Preferred transfer method: ACH / Domestic wire / International wire

Thank you for your work and for confirming the details at your earliest convenience.

Best regards,`
                    )}`}
                    className="btn btn-ghost"
                    style={{width: "100%", justifyContent: "center", padding: "12px 16px"}}
                  >
                    Request Bank Details
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section style={{background: "var(--paper-2)", borderTop: "1px solid var(--rule)"}}>
        <div className="wrap">
          <div className="section-head">
            <div className="section-head-left">
              <span className="eyebrow">§ 02 — Sponsorship</span>
              <span className="section-num">For Firms & Institutions</span>
            </div>
            <div>
              <h2 className="display">Institutional Sponsorship Opportunities</h2>
            </div>
          </div>
          <div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0, border: "1px solid var(--rule)"}} className="sponsor-grid">
            {[
              {tier: "Contributing", amt: "$5,000+", desc: "Event sponsorship and recognition across CAABA communications."},
              {tier: "Sustaining", amt: "$15,000+", desc: "Named programmatic partnership and prominent annual recognition."},
              {tier: "Founding Circle", amt: "$50,000+", desc: "Principal underwriting status and named institutional partnership."},
            ].map((s, i) => (
              <div key={s.tier} style={{
                padding: "clamp(28px, 3.5vw, 48px)",
                background: i === 2 ? "var(--ink)" : "var(--paper-3)",
                color: i === 2 ? "var(--paper)" : "var(--ink)",
                borderRight: i < 2 ? "1px solid var(--rule)" : 0,
                display: "flex", flexDirection: "column", gap: 14, minHeight: 280,
              }}>
                <span className={`eyebrow ${i === 2 ? "light" : ""}`}>Tier {String(i+1).padStart(2,"0")}</span>
                <h3 className="display" style={{fontSize: 32, lineHeight: 1.05}}>{s.tier}</h3>
                <div className="display" style={{fontSize: 22, color: i === 2 ? "var(--gold-soft)" : "var(--gold-2)"}}>{s.amt}</div>
                <hr className="hr gold" style={{width: 40, margin: "4px 0"}}/>
                <p style={{fontSize: 14.5, lineHeight: 1.65, color: i === 2 ? "#C9D2DC" : "var(--muted)"}}>{s.desc}</p>
                <button className={`btn btn-ghost ${i === 2 ? "on-dark" : ""}`} style={{marginTop: "auto", alignSelf: "flex-start"}} onClick={() => navigate("contact")}>
                  Inquire <Arrow/>
                </button>
              </div>
            ))}
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 900px) {
          .donate-grid { grid-template-columns: 1fr !important; }
          .donate-card { position: static !important; top: auto !important; }
          .sponsor-grid { grid-template-columns: 1fr !important; }
          .sponsor-grid > div { border-right: 0 !important; border-bottom: 1px solid var(--rule) !important; }
        }
      `}</style>
    </div>
  );
};

const ContactPage = ({ navigate }) => {
  const [topic, setTopic] = React.useState("General");
  const [submitted, setSubmitted] = React.useState(false);
  const [status, setStatus] = React.useState("idle");
  const [error, setError] = React.useState("");
  const [form, setForm] = React.useState({name:"", email:"", org:"", message:""});
  const topics = [
    "General Inquiry",
    "Membership Interest",
    "Mentorship",
    "Partnership",
    "Sponsorship / Donor",
    "Volunteer Opportunities",
  ];

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.message) return;
    setError("");
    setStatus("submitting");

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({...form, topic}),
      });

      const result = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(result.error || "Unable to submit the inquiry right now.");
      }

      setStatus("success");
      setSubmitted(true);
    } catch (err) {
      setStatus("error");
      setError(err.message || "Unable to submit the inquiry right now.");
    }
  };

  return (
    <div className="page">
      <section style={{background: "var(--ink)", color: "var(--paper)", padding: "clamp(64px, 10vw, 112px) 0 clamp(48px, 7vw, 88px)"}}>
        <div className="wrap">
          <span className="eyebrow light">Contact</span>
          <h1 className="display" style={{fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 1.02, maxWidth: "20ch", marginTop: 24, marginBottom: 32}}>
            We'd be glad to <em style={{color: "var(--gold-soft)", fontStyle: "italic"}}>hear from you</em>.
          </h1>
          <p style={{fontSize: "clamp(17px, 1.4vw, 20px)", lineHeight: 1.6, color: "#C9D2DC", maxWidth: "62ch"}}>
            Whether you're interested in membership, mentorship, partnership, sponsorship, or simply learning more about our work — please reach out. We respond to every inquiry.
          </p>
        </div>
      </section>

      <section style={{background: "var(--paper)"}}>
        <div className="wrap">
          <div style={{display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: "clamp(32px, 6vw, 96px)"}} className="contact-grid">
            {/* Left: inquiry types */}
            <div>
              <span className="eyebrow">§ 01 — Select a Topic</span>
              <h2 className="display" style={{fontSize: "clamp(28px, 3vw, 40px)", lineHeight: 1.1, marginTop: 12, marginBottom: 28, maxWidth: "18ch"}}>
                How can we help?
              </h2>
              <div style={{display: "flex", flexDirection: "column", border: "1px solid var(--rule)"}}>
                {topics.map((t, i) => (
                  <button key={t} onClick={() => setTopic(t)} style={{
                    padding: "20px 24px",
                    textAlign: "left",
                    background: topic === t ? "var(--paper-2)" : "transparent",
                    border: 0,
                    borderBottom: i < topics.length - 1 ? "1px solid var(--rule)" : 0,
                    cursor: "pointer",
                    fontFamily: "var(--sans)",
                    fontSize: 15,
                    color: "var(--ink)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    transition: "background .2s",
                  }}>
                    <span style={{display: "flex", alignItems: "center", gap: 16}}>
                      <span className="section-num" style={{color: topic === t ? "var(--gold-2)" : "var(--muted-light)"}}>
                        {String(i+1).padStart(2,"0")}
                      </span>
                      {t}
                    </span>
                    {topic === t && <Arrow size={14}/>}
                  </button>
                ))}
              </div>

              <div style={{marginTop: 40, paddingTop: 32, borderTop: "1px solid var(--rule)", display: "flex", flexDirection: "column", gap: 16}}>
                <span className="eyebrow">Direct Channels</span>
                <div>
                  <label>Email</label>
                  <a href="mailto:info@caabar.com" className="display" style={{fontSize: 20, color: "inherit", textDecoration: "none"}}>info@caabar.com</a>
                </div>
                <div>
                  <label>LinkedIn</label>
                  <a href="https://www.linkedin.com/company/central-asian-american-bar-association/posts/?feedView=all" target="_blank" rel="noopener noreferrer" className="display" style={{fontSize: 20, color: "inherit", textDecoration: "none"}}>/company/central-asian-american-bar-association</a>
                </div>
                <div>
                  <label>Instagram</label>
                  <a href="https://www.instagram.com/caabar_com" target="_blank" rel="noopener noreferrer" className="display" style={{fontSize: 20, color: "inherit", textDecoration: "none"}}>@caabar_com</a>
                </div>
                <div>
                  <label>Facebook</label>
                  <a href="https://www.facebook.com/caabarassociation" target="_blank" rel="noopener noreferrer" className="display" style={{fontSize: 20, color: "inherit", textDecoration: "none"}}>/caabarassociation</a>
                </div>
                <div>
                  <label>Mailing Address</label>
                  <div style={{fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.5, color: "var(--ink-3)"}}>
                    Central Asian American<br/>
                    Bar Association<br/>
                    26018 Golden Dawn Tri<br/>
                    Richmond, Texas 77406
                  </div>
                </div>
              </div>
            </div>

            {/* Right: form */}
            <div>
              <div style={{background: "var(--paper-3)", border: "1px solid var(--rule)", padding: "clamp(24px, 3vw, 48px)"}}>
                {submitted ? (
                  <div style={{padding: "40px 0", textAlign: "center"}}>
                    <LogoMark size={48}/>
                    <h3 className="display" style={{fontSize: 32, marginTop: 20, marginBottom: 12}}>Thank you.</h3>
                    <p style={{fontSize: 15.5, color: "var(--muted)", maxWidth: "36ch", margin: "0 auto 24px"}}>
                      Your inquiry has been received. A member of the Association will respond shortly.
                    </p>
                    <button className="btn btn-link" onClick={() => {setSubmitted(false); setStatus("idle"); setError(""); setForm({name:"", email:"", org:"", message:""});}}>
                      Submit another inquiry <Arrow/>
                    </button>
                  </div>
                ) : (
                  <form onSubmit={submit} style={{display: "flex", flexDirection: "column", gap: 24}}>
                    <div>
                      <span className="eyebrow">Inquiry Type</span>
                      <div className="display" style={{fontSize: 24, marginTop: 6}}>{topic}</div>
                    </div>
                    <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24}} className="form-row">
                      <div>
                        <label>Full Name *</label>
                        <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Jane A. Counselor"/>
                      </div>
                      <div>
                        <label>Email *</label>
                        <input required type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="jane@firm.com"/>
                      </div>
                    </div>
                    <div>
                      <label>Organization / Firm</label>
                      <input value={form.org} onChange={e => setForm({...form, org: e.target.value})} placeholder="Optional"/>
                    </div>
                    <div>
                      <label>Message *</label>
                      <textarea required rows={5} value={form.message} onChange={e => setForm({...form, message: e.target.value})} placeholder="Tell us a bit about your interest or inquiry..." style={{resize: "vertical", minHeight: 120}}/>
                    </div>
                    {status === "error" && (
                      <p style={{fontSize: 13.5, color: "#8A2D2D", lineHeight: 1.5}}>
                        {error}
                      </p>
                    )}
                    <div style={{display: "flex", gap: 12, alignItems: "center", paddingTop: 8, borderTop: "1px solid var(--rule)"}}>
                      <button type="submit" className="btn btn-primary" disabled={status === "submitting"} style={{flex: 1, justifyContent: "center", opacity: status === "submitting" ? 0.65 : 1}}>
                        {status === "submitting" ? "Sending..." : "Send Inquiry"} <Arrow/>
                      </button>
                    </div>
                    <div style={{fontSize: 12.5, lineHeight: 1.6, color: "var(--muted)", borderTop: "1px solid var(--rule)", paddingTop: 18}}>
                      <p style={{margin: "0 0 10px"}}>
                        Please do not submit confidential or sensitive information. The Association does not provide legal advice or legal services. Messages submitted may be used to help direct you to appropriate resources or licensed attorneys where appropriate.
                      </p>
                      <p style={{margin: 0}}>
                        The Association does not provide legal services but may help connect individuals with appropriate professionals.
                      </p>
                    </div>
                    <p style={{fontSize: 12, fontFamily: "var(--mono)", letterSpacing: "0.06em", color: "var(--muted)", textAlign: "center"}}>
                      We typically respond within two business days.
                    </p>
                  </form>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 900px) {
          .contact-grid { grid-template-columns: 1fr !important; }
          .form-row { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
};

const LegalPage = ({ eyebrow, title, intro, updated, sections }) => (
  <div className="page">
    <section style={{background: "var(--ink)", color: "var(--paper)", padding: "clamp(64px, 10vw, 112px) 0 clamp(48px, 7vw, 88px)"}}>
      <div className="wrap">
        <span className="eyebrow light">{eyebrow}</span>
        <h1 className="display" style={{fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 1.02, maxWidth: "18ch", marginTop: 24, marginBottom: 28}}>
          {title}
        </h1>
        <p style={{fontSize: "clamp(17px, 1.4vw, 20px)", lineHeight: 1.6, color: "#C9D2DC", maxWidth: "64ch"}}>
          {intro}
        </p>
        <p style={{fontSize: 12, fontFamily: "var(--mono)", letterSpacing: "0.08em", color: "var(--gold-soft)", marginTop: 24}}>
          Last updated: {updated}
        </p>
      </div>
    </section>

    <section style={{background: "var(--paper)"}}>
      <div className="wrap" style={{maxWidth: 980}}>
        <div style={{background: "var(--paper-3)", border: "1px solid var(--rule)"}}>
          {sections.map((section, i) => (
            <div key={section.heading} style={{
              padding: "clamp(28px, 4vw, 48px)",
              borderBottom: i < sections.length - 1 ? "1px solid var(--rule)" : 0,
            }}>
              <span className="section-num">{String(i + 1).padStart(2, "0")}</span>
              <h2 className="display" style={{fontSize: "clamp(26px, 3vw, 38px)", lineHeight: 1.12, marginTop: 10, marginBottom: 18}}>
                {section.heading}
              </h2>
              {section.body.map((item, idx) => (
                <p key={idx} style={{fontSize: 16, lineHeight: 1.75, color: "var(--ink-3)", marginTop: idx ? 14 : 0}}>
                  {item}
                </p>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  </div>
);

const PrivacyPage = () => (
  <LegalPage
    eyebrow="Privacy Policy"
    title="Privacy Policy"
    updated="April 26, 2026"
    intro="This Privacy Policy describes how the Central Asian American Bar Association collects, uses, and protects information submitted through this website."
    sections={[
      {
        heading: "Information We Collect",
        body: [
          "We collect information you choose to provide through website forms, including your name, email address, phone number, organization or firm, professional role, membership interest, and message content.",
          "We may also receive basic technical information generated by hosting, security, analytics, or email delivery providers, such as timestamps, browser information, IP address, pages visited, and delivery status for submitted forms.",
        ],
      },
      {
        heading: "How We Use Information",
        body: [
          "We use submitted information to respond to inquiries, review membership interest, coordinate programming, manage association communications, and maintain appropriate records for organizational operations.",
          "We do not sell personal information. We do not use website form submissions to create an attorney-client relationship or to provide legal advice.",
        ],
      },
      {
        heading: "Service Providers",
        body: [
          "We may use service providers to host the website, process form submissions, send email notifications, protect the website, and support association operations. These providers may process information on our behalf only for the services they provide.",
          "Current website operations may involve Vercel for hosting and Resend for email delivery.",
        ],
      },
      {
        heading: "Your Choices",
        body: [
          "You may contact us at info@caabar.com to request access to, correction of, or deletion of information you submitted, subject to reasonable verification and any records we need to retain for legitimate organizational, legal, or security purposes.",
          "Please do not submit confidential, privileged, highly sensitive, or unnecessary personal information through website forms.",
        ],
      },
      {
        heading: "Security and Retention",
        body: [
          "We use reasonable administrative and technical measures to protect information submitted through the website. No website or email transmission can be guaranteed to be completely secure.",
          "We retain submitted information for as long as reasonably necessary to respond to inquiries, administer membership and programming, maintain records, resolve issues, and comply with applicable obligations.",
        ],
      },
      {
        heading: "Contact",
        body: [
          "Questions about this Privacy Policy or personal information submitted through the website may be sent to info@caabar.com.",
        ],
      },
    ]}
  />
);

const TermsPage = () => (
  <LegalPage
    eyebrow="Terms of Use"
    title="Terms of Use"
    updated="April 26, 2026"
    intro="These Terms of Use govern access to and use of the CAABA website and online materials."
    sections={[
      {
        heading: "Informational Purpose",
        body: [
          "This website is provided for informational, professional networking, membership, and association communication purposes only.",
          "CAABA does not provide legal services or legal advice through this website. No attorney-client relationship is formed by using this website, submitting a form, joining the Association, or communicating with CAABA.",
        ],
      },
      {
        heading: "No Professional Advice",
        body: [
          "Website materials may discuss legal, professional, educational, or community topics in general terms. They should not be relied on as legal advice, tax advice, immigration advice, or any other professional advice.",
          "Individuals seeking legal advice should consult a licensed attorney in the appropriate jurisdiction.",
        ],
      },
      {
        heading: "Membership and Communications",
        body: [
          "Submitting a membership inquiry does not guarantee membership, benefits, referrals, event access, or any other association status.",
          "CAABA may review inquiries and respond at its discretion based on organizational priorities, eligibility, capacity, and alignment with its mission.",
        ],
      },
      {
        heading: "Content and Links",
        body: [
          "Website content may be updated, revised, or removed at any time. Third-party links are provided for convenience and do not imply endorsement or control of third-party websites.",
          "CAABA is not responsible for the content, security, policies, or practices of third-party websites.",
        ],
      },
      {
        heading: "Acceptable Use",
        body: [
          "You may not use this website to submit unlawful, harmful, misleading, confidential, privileged, or malicious content, or to interfere with website operations.",
          "CAABA may restrict or block access where necessary to protect the website, users, members, or the Association.",
        ],
      },
      {
        heading: "Contact",
        body: [
          "Questions about these Terms may be sent to info@caabar.com.",
        ],
      },
    ]}
  />
);

const AccessibilityPage = () => (
  <LegalPage
    eyebrow="Accessibility"
    title="Accessibility"
    updated="April 26, 2026"
    intro="CAABA aims to make its website usable and accessible to visitors with diverse needs and technologies."
    sections={[
      {
        heading: "Our Commitment",
        body: [
          "We aim to provide website content that is perceivable, operable, understandable, and robust for a broad range of users, including visitors using assistive technologies.",
          "We use practical accessibility measures such as semantic page structure, descriptive text alternatives where applicable, keyboard-accessible controls, visible labels, and readable contrast.",
        ],
      },
      {
        heading: "Ongoing Improvements",
        body: [
          "Accessibility is an ongoing effort. As the website grows, we will continue reviewing templates, forms, navigation, images, and interactive components for usability and accessibility issues.",
          "Some third-party services or linked websites may be outside our control, but we welcome reports of issues that affect access to CAABA website content.",
        ],
      },
      {
        heading: "Feedback",
        body: [
          "If you experience difficulty accessing any part of this website, please contact us at info@caabar.com and describe the page, feature, or issue.",
          "We will make reasonable efforts to respond and provide the information or service through an accessible alternative where feasible.",
        ],
      },
    ]}
  />
);

Object.assign(window, { MembershipPage, MembershipCardPage, DonatePage, ContactPage, PrivacyPage, TermsPage, AccessibilityPage });
