/* Save Our Family Farms — "Call your senator" section.
   Shares the map's `selected` state. Talking points are tailored per state.
   The feedback form composes a mailto: to the campaign (static-site approach). */
const { NAME: CN, TARGETS: CT } = window.SOFF_DATA;

const SWITCHBOARD_DISPLAY = "(202) 224-3121";
const SWITCHBOARD_TEL = "+12022243121";
const CAMPAIGN_EMAIL = "help@saveourfamilyfarms.org";

function senInitialsC(n) { return n.split(" ").map((w) => w[0]).slice(0, 2).join(""); }
function lastNameC(n) { return n.split(" ").slice(-1)[0]; }

function TalkingPoints({ code }) {
  if (!code) {
    return (
      <div className="call-card">
        <div className="roof-top"><Roofline color="#9c3a2a" height={11} stroke={2.4} /></div>
        <div className="cc-body">
          <h3>Your talking points</h3>
          <p className="tp-empty">Choose your state above (or pick one on the map) and we'll give you a short, tailored script — who to ask for and exactly what to say.</p>
        </div>
      </div>
    );
  }
  const d = CT[code];
  return (
    <div className="call-card" key={code}>
      <div className="roof-top"><Roofline color="#9c3a2a" height={11} stroke={2.4} /></div>
      <div className="cc-body">
        <h3>What to say · {CN[code]}</h3>
        <p className="sub">Ask the operator to connect you to your senator's office, then say:</p>
        <div className="sen-chips">
          {d.senators.map((s) => (
            <span className="sen-chip" key={s.name}>
              <span className="av">{senInitialsC(s.name)}</span>
              <span className="nm">Sen. {s.name} ({s.party})</span>
            </span>
          ))}
        </div>
        <ol className="tp-list">
          {d.points.map((p, i) => <li key={i}>{p}</li>)}
        </ol>
        <p className="tp-tip"><b>Keep it short and polite.</b> Staff tally every call by position — even 60 seconds counts. Leave your name and town so it's logged as a constituent.</p>
      </div>
    </div>
  );
}

function FeedbackForm({ selected }) {
  const [name, setName] = React.useState("");
  const [zip, setZip] = React.useState("");
  const [outcome, setOutcome] = React.useState("Spoke with staff");
  const [report, setReport] = React.useState("");
  const [sent, setSent] = React.useState(false);

  const words = report.trim() ? report.trim().split(/\s+/).length : 0;
  const near = words >= 270;

  function onReport(e) {
    const val = e.target.value;
    const w = val.trim() ? val.trim().split(/\s+/) : [];
    if (w.length <= 300) setReport(val);
    else setReport(w.slice(0, 300).join(" "));
  }

  function onSubmit(e) {
    e.preventDefault();
    const st = selected ? CN[selected] : "(state not specified)";
    const subject = `Call report — ${st}`;
    const body =
      `State: ${st}\n` +
      `Outcome: ${outcome}\n` +
      `From: ${name.trim() || "(anonymous)"}\n` +
      `ZIP: ${zip.trim() || "(not given)"}\n\n` +
      `${report.trim()}\n`;
    window.open(
      `mailto:${CAMPAIGN_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`,
      "_blank", "noopener");
    setSent(true);
  }

  return (
    <div className="call-card">
      <div className="roof-top"><Roofline color="#9c3a2a" height={11} stroke={2.4} /></div>
      <div className="cc-body">
        {sent ? (
          <div className="fb-sent">
            <div className="check">
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>
            </div>
            <h4>Thanks for reporting back</h4>
            <p>Your email app should have opened with your report ready to send to our team. If it didn't, email us at {CAMPAIGN_EMAIL}.</p>
            <button className="again" onClick={() => { setSent(false); setReport(""); setName(""); setZip(""); }}>Log another call →</button>
          </div>
        ) : (
          <form onSubmit={onSubmit}>
            <h3>How did your call go?</h3>
            <p className="sub">Tell us what you heard. Reports help us know which offices are moving — and which need more pressure.</p>
            <div className="fb-row">
              <div className="fb-field">
                <label htmlFor="fb-name">Your name <span style={{ fontWeight: 400, textTransform: "none", letterSpacing: 0, color: "var(--color-text-muted)" }}>(optional)</span></label>
                <input id="fb-name" type="text" value={name} placeholder="First & last" onChange={(e) => setName(e.target.value)} />
              </div>
              <div className="fb-field">
                <label htmlFor="fb-zip">ZIP code <span style={{ fontWeight: 400, textTransform: "none", letterSpacing: 0, color: "var(--color-text-muted)" }}>(optional)</span></label>
                <input id="fb-zip" type="text" inputMode="numeric" maxLength={5} value={zip} placeholder="00000" onChange={(e) => setZip(e.target.value.replace(/\D/g, ""))} />
              </div>
            </div>
            <div className="fb-field">
              <label>How far did you get?</label>
              <div className="fb-outcomes">
                {["Spoke with staff", "Left a voicemail", "Couldn't get through"].map((o) => (
                  <label className="fb-opt" key={o}>
                    <input type="radio" name="fb-outcome" value={o} checked={outcome === o} onChange={() => setOutcome(o)} />
                    {o}
                  </label>
                ))}
              </div>
            </div>
            <div className="fb-field">
              <label htmlFor="fb-report">What happened?</label>
              <textarea id="fb-report" value={report} onChange={onReport} placeholder="Did they take your message? Did the staffer share the senator's position? Anything we should know?" required></textarea>
              <div className="fb-count">
                <span className="lbl">Keep it under 300 words.</span>
                <span className={"num" + (near ? " near" : "")}>{words} / 300</span>
              </div>
            </div>
            <button type="submit" className="btn btn-primary fb-submit">Send my report</button>
          </form>
        )}
      </div>
    </div>
  );
}

function CallSection({ selected, onSelect }) {
  const codes = Object.keys(CT).sort((a, b) => CN[a].localeCompare(CN[b]));
  return (
    <section className="call" id="call">
      <div className="wrap">
        <div className="head">
          <p className="eyebrow">Make the call</p>
          <h2 className="h2">Call your senator</h2>
          <p className="lead">A phone call carries more weight than an email — offices tally them by position, and a handful can move a vote. It takes two minutes. Here's the number, who to ask for, and what to say.</p>
        </div>

        <div className="switchboard">
          <div className="sb-ico">
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z" /></svg>
          </div>
          <div className="sb-copy">
            <span className="sb-lbl">U.S. Capitol Switchboard</span>
            <a className="sb-num" href={`tel:${SWITCHBOARD_TEL}`}>{SWITCHBOARD_DISPLAY}</a>
          </div>
          <span className="sb-hint">Ask the operator to connect you to your senator's office. Calling during business hours (ET) reaches a live staffer.</span>
          <span className="sb-call"><a className="btn btn-lg" href={`tel:${SWITCHBOARD_TEL}`}>Call now</a></span>
        </div>

        <div className="call-state">
          <label htmlFor="call-state-sel">Calling from</label>
          <select id="call-state-sel" value={selected || ""} onChange={(e) => onSelect(e.target.value || null)}>
            <option value="" disabled>Select your state…</option>
            {codes.map((c) => <option key={c} value={c}>{CN[c]}</option>)}
          </select>
        </div>

        <div className="call-grid">
          <TalkingPoints code={selected} />
          <FeedbackForm selected={selected} />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CallSection });
