/* Veterans Deserve Better — campaign CTA checklist + congressional letter tool */
const { useState: useS2, useMemo: useM2 } = React;

/* 2020-apportionment House delegation sizes (effective 2023–2033). Senators are always 2. */
const STATES = [
  ["AL", "Alabama", 7], ["AK", "Alaska", 1], ["AZ", "Arizona", 9], ["AR", "Arkansas", 4], ["CA", "California", 52],
  ["CO", "Colorado", 8], ["CT", "Connecticut", 5], ["DE", "Delaware", 1], ["FL", "Florida", 28], ["GA", "Georgia", 14],
  ["HI", "Hawaii", 2], ["ID", "Idaho", 2], ["IL", "Illinois", 17], ["IN", "Indiana", 9], ["IA", "Iowa", 4],
  ["KS", "Kansas", 4], ["KY", "Kentucky", 6], ["LA", "Louisiana", 6], ["ME", "Maine", 2], ["MD", "Maryland", 8],
  ["MA", "Massachusetts", 9], ["MI", "Michigan", 13], ["MN", "Minnesota", 8], ["MS", "Mississippi", 4], ["MO", "Missouri", 8],
  ["MT", "Montana", 2], ["NE", "Nebraska", 3], ["NV", "Nevada", 4], ["NH", "New Hampshire", 2], ["NJ", "New Jersey", 12],
  ["NM", "New Mexico", 3], ["NY", "New York", 26], ["NC", "North Carolina", 14], ["ND", "North Dakota", 1], ["OH", "Ohio", 15],
  ["OK", "Oklahoma", 5], ["OR", "Oregon", 6], ["PA", "Pennsylvania", 17], ["RI", "Rhode Island", 2], ["SC", "South Carolina", 7],
  ["SD", "South Dakota", 1], ["TN", "Tennessee", 9], ["TX", "Texas", 38], ["UT", "Utah", 4], ["VT", "Vermont", 1],
  ["VA", "Virginia", 11], ["WA", "Washington", 10], ["WV", "West Virginia", 2], ["WI", "Wisconsin", 8], ["WY", "Wyoming", 1],
  ["DC", "District of Columbia", 0], ["PR", "Puerto Rico", 0],
];

/* ---------------- CAMPAIGN CALL TO ACTION ---------------- */
function Campaign({ ink, paper, accent }) {
  const tasks = [
    { id: "share", n: "01", t: "Like and share our social media content", d: "Reach does the work of a press budget. One share puts a sourced fact in front of people who have never seen it.", cta: "Go to our channels", href: "#social" },
    { id: "survey", n: "02", t: "Take our veterans' survey", d: "Eight minutes. Your experience with VSOs and the VA claims process becomes part of the record we bring to Congress.", cta: "Start the survey", href: "#survey" },
    { id: "download", n: "03", t: "Download our one-pagers", d: "Print them. Hand them to a battle buddy at the VFW hall, the VA waiting room, or your next unit reunion.", cta: "Open the library", href: "#library", sub: ["The 5-Point Framework", "10 Questions to Ask"] },
    { id: "letter", n: "04", t: "Write to the Veterans' Affairs Committee", d: "Sign your name and we open a sourced oversight request in your own email app, addressed to the House Veterans' Affairs Committee. You press send. Under two minutes.", cta: "Write the letter", href: "#letter", primary: true },
  ];
  const [done, setDone] = useS2({});
  const count = tasks.filter((t) => done[t.id]).length;
  const toggle = (id) => setDone((p) => ({ ...p, [id]: !p[id] }));
  return (
    <section className="vdb-camp" id="campaign" style={{ background: ink, color: paper }}>
      <div className="vdb-container">
        <div className="vdb-camp__head">
          <div>
            <Eyebrow accent={accent}>Call to action — the campaign</Eyebrow>
            <h2 className="vdb-h2 vdb-camp__h2">Four things you can do this week.</h2>
            <p className="vdb-camp__lede">No donation. No membership. Four concrete actions that put documented facts in front of the people who can act on them.</p>
          </div>
          <div className="vdb-camp__meter" style={{ borderColor: paper + "2e" }}>
            <div className="vdb-camp__meter-n" style={{ color: accent }}>{count}<span style={{ color: paper, opacity: 0.35 }}>/4</span></div>
            <div className="vdb-camp__meter-l">complete</div>
            <div className="vdb-camp__track" style={{ background: paper + "1f" }}>
              <div className="vdb-camp__fill" style={{ transform: `scaleX(${count / tasks.length})`, background: accent }} />
            </div>
          </div>
        </div>
        <ol className="vdb-camp__list">
          {tasks.map((t) => (
            <li key={t.id} className={`vdb-task ${done[t.id] ? "is-done" : ""} ${t.primary ? "is-primary" : ""}`} style={{ borderColor: paper + "22" }}>
              <button className="vdb-task__box" onClick={() => toggle(t.id)} aria-pressed={!!done[t.id]} aria-label={`Mark "${t.t}" complete`} style={{ borderColor: done[t.id] ? accent : paper + "44", background: done[t.id] ? accent : "transparent", color: done[t.id] ? ink : paper }}>
                {done[t.id]
                  ? <svg viewBox="0 0 16 16" width="14" height="14"><path d="M3 8.5 L6.5 12 L13 4.5" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="butt" strokeLinejoin="miter" /></svg>
                  : <span className="vdb-task__n">{t.n}</span>}
              </button>
              <div className="vdb-task__body">
                <h3 className="vdb-task__t">{t.t}</h3>
                <p className="vdb-task__d">{t.d}</p>
                {t.sub && (
                  <ul className="vdb-task__sub">
                    {t.sub.map((s) => <li key={s} style={{ borderColor: paper + "26" }}><DownloadIcon s={12} />{s}</li>)}
                  </ul>
                )}
              </div>
              <a href={t.href} className={`vdb-btn ${t.primary ? "vdb-btn--accent" : "vdb-btn--outline"}`} style={t.primary ? { background: accent, color: ink } : { color: paper, borderColor: paper + "3a" }}>
                {t.cta}<Arrow s={12} />
              </a>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* ---------------- CONGRESSIONAL LETTER TOOL ---------------- */
/* House Veterans' Affairs Committee intake addresses.
   These are committee inboxes — NOT individual member offices. A static site cannot
   send mail on someone's behalf, so we build a mailto: and hand off to the signer's own
   email client: it genuinely sends, from their real address, which also makes it count
   as constituent correspondence. Netlify captures a copy for the record. */
const COMMITTEE_TO = "HouseVetAffairs@mail.house.gov";
const COMMITTEE_CC = "HVAC.DemPress@mail.house.gov";

const LETTER_SUBJECT = "Please Support Greater Transparency and Oversight for Veterans Service Organizations";
const LETTER_BODY = [
  "As one of your veteran constituents (or a supporter of America's veterans), I respectfully ask that you review the accountability, transparency, and oversight of organizations that represent and advocate on behalf of our nation's veterans. Veterans deserve confidence that organizations entrusted with serving them are operating with strong governance, responsible stewardship, and a continued commitment to meeting the evolving needs of today's military community.",
  "I encourage your office to specifically examine publicly available information regarding the Veterans of Foreign Wars (VFW), including questions related to governance, financial transparency, organizational modernization, and the experiences of post-9/11 veterans, women veterans, and other historically underrepresented members of the veteran community. I also ask that Congress continue to support oversight efforts that strengthen trust in all Veterans Service Organizations and ensure they remain focused on serving veterans first.",
  "Thank you for your service to your district and for your continued commitment to those who have served our country. I appreciate your attention to this important issue and respectfully request that you consider whether additional congressional oversight or review is warranted to ensure veterans receive the representation and support they have earned.",
];

/* Condensed body for the mailto handoff. The full three-paragraph letter is ~1,500 chars,
   which pushes the mailto URL past the ~2,048-char cap in Outlook and several mobile
   clients — they truncate silently, cutting the signature off the end. So the email
   carries a tight version plus a link to the full text; the on-page preview and the
   printable template keep the complete letter. */
const LETTER_SHORT = [
  "I respectfully ask the Committee to review the accountability, transparency, and oversight of organizations that represent and advocate on behalf of our nation's veterans. Veterans deserve confidence that organizations entrusted with serving them operate with strong governance and responsible stewardship.",
  "I encourage the Committee to examine publicly available information regarding Veterans Service Organizations — including governance, financial transparency, organizational modernization, and the experiences of post-9/11 veterans, women veterans, and other historically underrepresented members of the veteran community.",
  "I respectfully request that you consider whether additional congressional oversight or review is warranted to ensure veterans receive the representation they have earned. Thank you for your attention to this issue.",
];

function buildLetterText(f, st) {
  const signer = { veteran: "a veteran", family: "a veteran family member", supporter: "a supporter of America's veterans" }[f.veteran] || "a veteran";
  const where = [f.city, st ? st[1] : ""].filter(Boolean).join(", ");
  return [
    "Dear Members of the Committee on Veterans' Affairs,",
    "",
    `I am ${signer}${where ? ` from ${where}` : ""}.`,
    "",
    LETTER_SHORT[0],
    "",
    LETTER_SHORT[1],
    "",
    ...(f.personal.trim() ? [f.personal.trim(), ""] : []),
    LETTER_SHORT[2],
    "",
    "Sincerely,",
    f.name || "",
    where,
    f.email || "",
    "",
    "—",
    "Full letter and sources: veteransdeservebetter.info/letter",
  ].join("\n");
}

function buildMailto(f, st) {
  return `mailto:${COMMITTEE_TO}?cc=${encodeURIComponent(COMMITTEE_CC)}&subject=${encodeURIComponent(LETTER_SUBJECT)}&body=${encodeURIComponent(buildLetterText(f, st))}`;
}

function CongressLetter({ ink, paper, accent }) {
  const [f, setF] = useS2({ name: "", city: "", email: "", zip: "", state: "", veteran: "veteran", personal: "" });
  const [sent, setSent] = useS2(false);
  const [copied, setCopied] = useS2(false);
  const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));
  const st = useM2(() => STATES.find((s) => s[0] === f.state), [f.state]);
  const seats = st ? st[2] : null;
  const recipients = st ? (seats === 0 ? "your delegate and territorial delegation" : `both U.S. Senators for ${st[1]} and your U.S. Representative`) : null;
  const ready = f.name.trim() && f.email.trim() && f.state;
  const send = (e) => {
    e.preventDefault();
    submitToNetlify("letter", { name: f.name, email: f.email, city: f.city, state: st ? st[1] : f.state, zip: f.zip, signer: f.veteran, personal: f.personal });
    window.location.href = buildMailto(f, st);
    setSent(true);
  };

  return (
    <section className="vdb-letter" id="letter">
      <div className="vdb-container">
        <div className="vdb-sechead vdb-sechead--row">
          <div>
            <Eyebrow accent={accent}>Take action</Eyebrow>
            <h2 className="vdb-h2">Write to the House Veterans' Affairs Committee.</h2>
          </div>
          <p className="vdb-letter__intro">
            Fill this in and we open it as an email from your own account, addressed to the House Veterans' Affairs Committee — sent from your real address, which is what makes it count. Nonpartisan, no fee, and you keep a copy. Edit any part of it before you send.
          </p>
        </div>

        <div className="vdb-letter__grid">
          {/* --- form column --- */}
          <form className="vdb-form" onSubmit={send} style={{ borderColor: ink + "1f" }}>
            <div className="vdb-form__head" style={{ borderColor: ink + "1f" }}>
              <span className="vdb-form__step" style={{ background: accent, color: paper }}>1</span>
              <h3 className="vdb-form__h">Where do you live?</h3>
            </div>
            <div className="vdb-form__body">
              <label className="vdb-field vdb-field--full">
                <span className="vdb-field__l">State or territory <em>required</em></span>
                <div className="vdb-select" style={{ borderColor: ink + "2e" }}>
                  <select value={f.state} onChange={set("state")} required>
                    <option value="">Select your state…</option>
                    {STATES.map(([ab, name]) => <option key={ab} value={ab}>{name}</option>)}
                  </select>
                  <span className="vdb-select__chev" aria-hidden>▾</span>
                </div>
              </label>
              {st && (
                <div className="vdb-routing" style={{ borderColor: accent, background: accent + "12" }}>
                  <div className="vdb-routing__row">
                    <span className="vdb-routing__k">Also write to</span>
                    <span className="vdb-routing__v">{recipients}</span>
                  </div>
                  <div className="vdb-routing__stats">
                    <span><strong>2</strong> Senators</span>
                    <span className="vdb-routing__sep" style={{ background: ink + "26" }} />
                    <span><strong>{seats === 0 ? "—" : seats}</strong> House {seats === 1 ? "seat" : "seats"} in {st[0]}</span>
                    <span className="vdb-routing__sep" style={{ background: ink + "26" }} />
                    <span>Add a ZIP to pin your exact district</span>
                  </div>
                </div>
              )}
              <label className="vdb-field">
                <span className="vdb-field__l">ZIP code <em>optional — pins your district</em></span>
                <input value={f.zip} onChange={set("zip")} inputMode="numeric" maxLength="5" placeholder="e.g. 74103" style={{ borderColor: ink + "2e" }} />
              </label>
              <label className="vdb-field">
                <span className="vdb-field__l">City <em>optional</em></span>
                <input value={f.city} onChange={set("city")} placeholder="City" style={{ borderColor: ink + "2e" }} />
              </label>
            </div>

            <div className="vdb-form__head" style={{ borderColor: ink + "1f" }}>
              <span className="vdb-form__step" style={{ background: accent, color: paper }}>2</span>
              <h3 className="vdb-form__h">Sign it</h3>
            </div>
            <div className="vdb-form__body">
              <label className="vdb-field vdb-field--full">
                <span className="vdb-field__l">Full name <em>required</em></span>
                <input value={f.name} onChange={set("name")} placeholder="First and last name" required style={{ borderColor: ink + "2e" }} />
              </label>
              <label className="vdb-field vdb-field--full">
                <span className="vdb-field__l">Email <em>required — for your copy</em></span>
                <input type="email" value={f.email} onChange={set("email")} placeholder="you@example.com" required style={{ borderColor: ink + "2e" }} />
              </label>
              <fieldset className="vdb-field vdb-field--full vdb-radios">
                <span className="vdb-field__l">I am signing as</span>
                <div className="vdb-radios__row">
                  {[["veteran", "A veteran"], ["family", "Veteran family member"], ["supporter", "A supporter"]].map(([v, l]) => (
                    <label key={v} className={`vdb-chip ${f.veteran === v ? "is-on" : ""}`} style={{ borderColor: f.veteran === v ? accent : ink + "2e", background: f.veteran === v ? accent + "16" : "transparent" }}>
                      <input type="radio" name="signer" value={v} checked={f.veteran === v} onChange={set("veteran")} />
                      {l}
                    </label>
                  ))}
                </div>
              </fieldset>
              <label className="vdb-field vdb-field--full">
                <span className="vdb-field__l">Add a personal note <em>optional — staffers read these first</em></span>
                <textarea value={f.personal} onChange={set("personal")} rows="3" maxLength="300" placeholder="One or two sentences in your own words about why this matters to you." style={{ borderColor: ink + "2e" }} />
                <span className="vdb-field__count" style={{ color: f.personal.length > 270 ? accent : undefined }}>{f.personal.length} / 300</span>
              </label>
            </div>

            <div className="vdb-form__foot" style={{ borderColor: ink + "1f" }}>
              <div className="vdb-form__actions">
                <button type="submit" className="vdb-btn vdb-btn--solid vdb-btn--lg vdb-form__submit" disabled={!ready} style={{ background: ready ? ink : ink + "40", color: paper }}>
                  {sent ? "Opened in your email app" : "Open this letter in my email app"}<Arrow />
                </button>
                <button type="button" className="vdb-btn vdb-btn--outline vdb-btn--lg" disabled={!ready}
                  style={{ color: ink, borderColor: ink + "33", opacity: ready ? 1 : 0.45 }}
                  onClick={() => { navigator.clipboard?.writeText(buildLetterText(f, st)); setCopied(true); }}>
                  {copied ? "Copied" : "Copy letter text"}
                </button>
              </div>
              {sent && (
                <div className="vdb-form__sent" style={{ borderColor: accent }}>
                  <p>Your email app should now be open with the letter addressed and written. <strong>Press send there to deliver it.</strong> If nothing opened, or the text looks cut off, use <strong>Copy letter text</strong> and paste it into webmail.</p>
                  <span className="vdb-form__addr">To: {COMMITTEE_TO}<br />Cc: {COMMITTEE_CC}</span>
                </div>
              )}
              <p className="vdb-form__fine">
                Sends from your own email account — we never mail on your behalf, and we don't sell or rent your information. We keep a record of the signature so we can report how many veterans have written in.
              </p>
            </div>
          </form>

          {/* --- letter preview column --- */}
          <div className="vdb-preview">
            <div className="vdb-preview__bar" style={{ borderColor: ink + "1f" }}>
              <span className="vdb-preview__label">Live preview</span>
              <a href="congressional-letter.html" target="_blank" rel="noopener" className="vdb-preview__dl"><DownloadIcon s={12} />Printable template</a>
            </div>
            <article className="vdb-doc" style={{ borderColor: ink + "1f" }}>
              <div className="vdb-doc__meta">
                <span>Subject</span>
                <strong>{LETTER_SUBJECT}</strong>
              </div>
              <p className="vdb-doc__sal">
                Dear {st ? <span className="vdb-doc__fill" style={{ background: accent + "20", borderColor: accent }}>Members of the Committee on Veterans' Affairs</span> : <span className="vdb-doc__blank" style={{ borderColor: ink + "40" }}>Members of the Committee</span>},
              </p>
              {LETTER_BODY.map((p, i) => <p key={i} className="vdb-doc__p">{p}</p>)}
              {f.personal.trim() && (
                <p className="vdb-doc__p vdb-doc__p--personal" style={{ borderColor: accent }}>{f.personal}</p>
              )}
              <p className="vdb-doc__p">Sincerely,</p>
              <dl className="vdb-doc__sig">
                <div><dt>Name</dt><dd style={{ borderColor: ink + "33" }}>{f.name || <span className="vdb-doc__ph">—</span>}</dd></div>
                <div><dt>City &amp; State</dt><dd style={{ borderColor: ink + "33" }}>{[f.city, st ? st[0] : ""].filter(Boolean).join(", ") || <span className="vdb-doc__ph">—</span>}</dd></div>
                <div><dt>Email</dt><dd style={{ borderColor: ink + "33" }}>{f.email || <span className="vdb-doc__ph">—</span>}</dd></div>
              </dl>
            </article>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Campaign, CongressLetter, STATES });
