// EzClaim — flow screens: Lookup, Results, Choice, Wizard, Review.

const { lookup: ezLookup, fmtUSD, fmtDate, PROPERTIES, homesteadStatus } = window.EZ_MOCK;
const DEFAULT_LOOKUP_ADDRESS = "4305 Wendover Rd, Baltimore, MD 21218";

// ─────────────────────────────────────────────────────────────────────────────
// Lookup
// ─────────────────────────────────────────────────────────────────────────────
function LookupScreen({ nav, setSession }) {
  const [q, setQ] = useState(DEFAULT_LOOKUP_ADDRESS);
  const [loading, setLoading] = useState(false);
  const [suggestions, setSuggestions] = useState([]);
  const [suggestLoading, setSuggestLoading] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(-1);
  const [selectedSuggestion, setSelectedSuggestion] = useState({ site_address: DEFAULT_LOOKUP_ADDRESS });
  const [err, setErr] = useState("");

  useEffect(() => {
    const query = q.trim();
    if (selectedSuggestion?.site_address === query) return;
    if (query.length < 4) {
      setSuggestions([]);
      setActiveSuggestionIndex(-1);
      setSuggestLoading(false);
      return;
    }

    let cancelled = false;
    setSuggestLoading(true);
    const timer = setTimeout(async () => {
      try {
        const resp = await fetch("/api/suggest?query=" + encodeURIComponent(query));
        const data = resp.ok ? await resp.json() : { items: [] };
        if (cancelled) return;
        const items = Array.isArray(data.items) ? data.items : [];
        setSuggestions(items);
        setActiveSuggestionIndex(items.length ? 0 : -1);
        setShowSuggestions(true);
      } catch (e) {
        if (!cancelled) {
          setSuggestions([]);
          setActiveSuggestionIndex(-1);
        }
      } finally {
        if (!cancelled) setSuggestLoading(false);
      }
    }, 220);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [q, selectedSuggestion?.site_address]);

  function selectSuggestion(item) {
    setQ(item.site_address);
    setSelectedSuggestion(item);
    setSuggestions([]);
    setShowSuggestions(false);
    setActiveSuggestionIndex(-1);
    setErr("");
  }

  function onAddressKeyDown(e) {
    if (!showSuggestions || !suggestions.length) return;
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveSuggestionIndex((idx) => Math.min(idx + 1, suggestions.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveSuggestionIndex((idx) => Math.max(idx - 1, 0));
    } else if (e.key === "Enter" && activeSuggestionIndex >= 0) {
      e.preventDefault();
      selectSuggestion(suggestions[activeSuggestionIndex]);
    } else if (e.key === "Escape") {
      setShowSuggestions(false);
      setActiveSuggestionIndex(-1);
    }
  }

  async function runLookup(address, lookupOptions = {}) {
    if (!address.trim()) { setErr("Enter a Maryland street address."); return; }
    setErr(""); setLoading(true);
    const res = await ezLookup(address, lookupOptions);
    setLoading(false);
    setSession({ query: address, lookup: res });
    if (res.state === "ambiguous") nav("/disambiguate");
    else if (res.state === "none") nav("/no-match");
    else nav("/results");
  }

  async function go(e) {
    e?.preventDefault();
    const resolvedAddress = selectedSuggestion?.site_address === q.trim() ? selectedSuggestion.site_address : q;
    await runLookup(resolvedAddress);
  }

  function quick(addr) {
    setQ(addr);
    setSelectedSuggestion(null);
    setSuggestions([]);
    setShowSuggestions(false);
    setActiveSuggestionIndex(-1);
    runLookup(addr, { allowMockFallback: true });
  }

  return (
    <div className="fade-in">
      <div className="hero">
        <div className="eyebrow">
          <span className="pulse-dot" style={{ color: "var(--good-600)" }}/>
          Maryland Homestead Tax Credit · 2026 filing window
        </div>
        <h1 className="h-display">File for the Homestead Credit on your Maryland home.</h1>
        <p className="lead">
          Look up your property to see whether the Homestead Tax Credit is on file. If it isn't, the State Department of Assessments & Taxation (SDAT) is allowed to raise your taxable assessment without a cap — and you'll pay the difference.
        </p>

        <div className="lookup-card">
          <form onSubmit={go} className="lookup-form">
            <div className="lookup-input-wrap">
              <Input
                size="lg"
                leftIcon={<I.Search size={20}/>}
                placeholder="123 Main St, Baltimore, MD 21201"
                value={q}
                onChange={(e) => {
                  setQ(e.target.value);
                  setSelectedSuggestion(null);
                }}
                onFocus={() => setShowSuggestions(true)}
                onBlur={() => setTimeout(() => setShowSuggestions(false), 120)}
                onKeyDown={onAddressKeyDown}
                aria-label="Property address"
                role="combobox"
                aria-expanded={showSuggestions && suggestions.length > 0}
                aria-controls="address-suggestions"
                aria-autocomplete="list"
                autoComplete="off"
                autoFocus
              />
              {showSuggestions && suggestions.length ? (
                <div id="address-suggestions" className="address-suggestions" role="listbox" aria-label="Address suggestions">
                  {suggestions.map((item, index) => (
                    <button
                      key={item.property_id || item.site_address}
                      type="button"
                      role="option"
                      aria-selected={index === activeSuggestionIndex}
                      className={index === activeSuggestionIndex ? "active" : ""}
                      onMouseDown={(e) => e.preventDefault()}
                      onMouseEnter={() => setActiveSuggestionIndex(index)}
                      onClick={() => selectSuggestion(item)}
                    >
                      <span className="suggestion-address">{item.site_address}</span>
                      {item.secondary ? <span className="suggestion-meta">{item.secondary}</span> : null}
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
            <Button kind="primary" size="lg" type="submit" disabled={loading}>
              {loading ? <><span className="spin"/> Looking up…</> : <>Check my property <I.ArrowRight size={16}/></>}
            </Button>
          </form>
          {suggestLoading ? <div className="lookup-hint"><span className="spin"/> Resolving address…</div> : null}
          {err ? <div className="field-err" style={{ marginTop: 10 }}><I.Alert size={14}/> {err}</div> : null}
          <div className="lookup-quick">
            <span>Try:</span>
            <button type="button" onClick={() => quick("4305 Wendover Rd, Baltimore, MD 21218")}>4305 Wendover Rd</button>
            <button type="button" onClick={() => quick("1923 Maryland Ave, Baltimore, MD 21218")}>1923 Maryland Ave</button>
            <button type="button" onClick={() => quick("412 Linden Ln, Bethesda, MD 20814")}>412 Linden Ln (already approved)</button>
            <button type="button" onClick={() => quick("200 Charles St N, Baltimore, MD")}>200 Charles St (multiple)</button>
            <button type="button" onClick={() => quick("nowhere")}>(no match)</button>
          </div>
        </div>

        <div className="trust">
          <div className="trust-item">
            <span className="ti-ico"><I.Shield size={22}/></span>
            <div>
              <div className="ti-t">Not a government agency</div>
              <div className="ti-d">You can also file free directly with SDAT. We'll show you both options.</div>
            </div>
          </div>
          <div className="trust-item">
            <span className="ti-ico"><I.DollarSign size={22}/></span>
            <div>
              <div className="ti-t">Flat $19.99 if you want help</div>
              <div className="ti-d">We prepare, submit, and track your filing through to SDAT confirmation.</div>
            </div>
          </div>
          <div className="trust-item">
            <span className="ti-ico"><I.Lock size={22}/></span>
            <div>
              <div className="ti-t">Sensitive data isn't stored</div>
              <div className="ti-d">SSN and signatures are used to generate the packet, then deleted from our servers.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Disambiguate — multiple matches
// ─────────────────────────────────────────────────────────────────────────────
function DisambiguateScreen({ nav, session, setSession }) {
  const matches = session?.lookup?.matches || [];
  return (
    <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Button kind="ghost" size="sm" icon={<I.ArrowLeft size={14}/>} onClick={() => nav("/")}>Back</Button>
      <div>
        <h2 className="h-page">We found a few matches</h2>
        <p className="subtle" style={{ marginTop: 6 }}>Pick the unit that's yours. We'll only look up that one parcel.</p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {matches.map((m) => (
          <button key={m.parcel_id} className="match" onClick={async () => {
            // simulate selecting a unit -> use mock as full property
            const full = { ...PROPERTIES[0], site_address: m.site_address, county: m.county, parcel_id: m.parcel_id };
            setSession({ ...session, lookup: { matches: [full], state: "ok" } });
            nav("/results");
          }}>
            <span className="dot"/>
            <span>
              <div className="addr">{m.site_address}</div>
              <div className="sub">{m.county} County · Parcel {m.parcel_id}</div>
            </span>
            <span className="arrow"><I.ChevronRight/></span>
          </button>
        ))}
      </div>
      <Callout kind="info" icon={<I.Info size={18}/>}>
        Don't see your unit? Search again with the exact street, unit, and ZIP. Condo/co-op parcels are listed individually with SDAT.
      </Callout>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// No match
// ─────────────────────────────────────────────────────────────────────────────
function NoMatchScreen({ nav, session }) {
  return (
    <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <Button kind="ghost" size="sm" icon={<I.ArrowLeft size={14}/>} onClick={() => nav("/")}>Back to lookup</Button>
      <div className="card lg">
        <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--warn-100)", color: "var(--warn-700)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <I.Search size={22}/>
          </div>
          <div>
            <h2 className="h-page" style={{ fontSize: 22 }}>We couldn't find that address</h2>
            <p className="subtle" style={{ marginTop: 6 }}>
              We searched the SDAT parcel index for <strong style={{ color: "var(--ink-900)" }}>"{session?.query || "—"}"</strong> and didn't find a Maryland residential parcel.
            </p>
          </div>
        </div>
        <div className="card-divider"/>
        <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 14, color: "var(--ink-700)" }}>
          <div>A few things to try:</div>
          <ul style={{ margin: 0, paddingLeft: 18, color: "var(--ink-600)", lineHeight: 1.6 }}>
            <li>Use the full street name (e.g., "Avenue" not "Ave") and include the ZIP.</li>
            <li>For condos and co-ops, search with the unit number — each unit is a separate parcel.</li>
            <li>If you recently moved in, the deed may not be in the public index yet — try again in 4–6 weeks.</li>
          </ul>
        </div>
        <div className="cta-bar">
          <Button kind="primary" onClick={() => nav("/")} block>Try a different address</Button>
        </div>
      </div>
      <Callout kind="info">
        Still stuck? You can file directly with SDAT for free at{" "}
        <a href="https://sdathtc.dat.maryland.gov" target="_blank" rel="noreferrer">sdathtc.dat.maryland.gov</a>.
      </Callout>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Results screen
// ─────────────────────────────────────────────────────────────────────────────
function ResultsScreen({ nav, session, setSession, tweaks }) {
  const p = session?.lookup?.matches?.[0];
  if (!p) {
    return (
      <div className="card">
        <p>No property loaded.</p>
        <Button kind="primary" onClick={() => nav("/")}>Back to lookup</Button>
      </div>
    );
  }
  const lead = p.homestead_lead || {};
  const status = homesteadStatus(p);
  const actionable = lead.call_to_action === "file_free_or_assisted";
  const savings = lead.estimated_annual_savings || p.estimated_tax_savings || 0;

  // Optional headline variant override from tweaks
  const headlineVariants = {
    rising_assessment_warm: lead.landing_page_headline,
    direct_savings: `You may avoid about ${fmtUSD(savings)} in property-tax increases.`,
    new_owner_friendly: "New owner? Lock in the Homestead cap before next year's bill.",
    already_protected: "You're already protected.",
  };
  const headline = headlineVariants[tweaks?.headlineVariant] || lead.landing_page_headline || "Your property is eligible for the Homestead Credit.";

  return (
    <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <Button kind="ghost" size="sm" icon={<I.ArrowLeft size={14}/>} onClick={() => nav("/")}>Search a different address</Button>

      <PropertyCard p={p} right={
        <Tag kind={status.kind}>
          {status.icon === "check" ? <I.Check size={11}/> : <span className="dot"/>}
          {status.label}
        </Tag>
      } />

      {actionable ? <EligibleBlock p={p} headline={headline} savings={savings} nav={nav} setSession={setSession} session={session}/> : <StatusBlock p={p} status={status} nav={nav}/>}
    </div>
  );
}

function EligibleBlock({ p, headline, savings, nav, setSession, session }) {
  const hasAssessmentDelta = Number(p.previous_assessed_value) > 0 && Number(p.current_assessed_value) > 0;
  const reassessmentText = hasAssessmentDelta
    ? `Estimate based on ${p.county} rates and your reassessed value (${fmtUSD(p.previous_assessed_value)} -> ${fmtUSD(p.current_assessed_value)}, +${Math.round(((p.current_assessed_value/p.previous_assessed_value)-1)*1000)/10}%).`
    : `Estimate based on public Homestead status, owner-occupancy indicators, and available local tax-rate data for ${p.county || "this jurisdiction"}.`;
  return (
    <>
      <div className="savings">
        <div className="s-label">Estimated avoidable increase</div>
        <div className="s-amount tabnum">{fmtUSD(savings)}<span className="per">/yr</span></div>
        <div className="s-sub" style={{ maxWidth: "60ch" }}>
          You may avoid about <strong style={{ color: "#fff" }}>{fmtUSD(savings)}/year</strong> in property-tax increases if SDAT approves your Homestead application.
        </div>
        <div className="s-fine">
          {reassessmentText} This is an estimate, <em>not a guarantee</em>. Approval is determined by SDAT.
        </div>
      </div>

      <div>
        <h2 className="h-page" style={{ fontSize: 24, marginBottom: 8 }}>{headline}</h2>
        <p className="subtle" style={{ fontSize: 15 }}>{p.homestead_lead?.landing_page_body}</p>
      </div>

      <div>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Two ways to file</div>
        <div className="choice-grid">
          <div className="choice">
            <div className="row between">
              <div className="choice-title">File free with SDAT</div>
              <Tag>Free</Tag>
            </div>
            <div className="choice-price"><strong>$0</strong> · paper or online</div>
            <ul>
              <li><span className="ck"><I.Check size={14}/></span>Maryland's official online portal</li>
              <li><span className="ck"><I.Check size={14}/></span>You handle the form, ID checks, and tracking</li>
              <li><span className="x"><I.X size={14}/></span>No reminders or status tracking from us</li>
            </ul>
            <Button kind="secondary" iconRight={<I.ExternalLink size={14}/>} onClick={() => nav("/sdat")}>Continue free with SDAT</Button>
          </div>
          <div className="choice recommended">
            <span className="rec-tag">Most homeowners pick this</span>
            <div className="row between">
              <div className="choice-title">EzClaim files it for you</div>
              <Tag kind="info">$19.99 flat</Tag>
            </div>
            <div className="choice-price"><strong>$19.99</strong> · one-time, no subscription</div>
            <ul>
              <li><span className="ck"><I.Check size={14}/></span>~4 minutes of plain-English questions</li>
              <li><span className="ck"><I.Check size={14}/></span>We generate, fax, and confirm delivery to SDAT</li>
              <li><span className="ck"><I.Check size={14}/></span>Magic-link status page — no login required</li>
              <li><span className="ck"><I.Check size={14}/></span>Sensitive data deleted after submission</li>
            </ul>
            <Button kind="primary" iconRight={<I.ArrowRight size={14}/>} onClick={() => nav("/wizard/address")}>Start my filing — $19.99 later</Button>
          </div>
        </div>
      </div>

      <Callout kind="warn">
        <strong>Heads-up:</strong> This is an estimate based on public data. Final savings depend on your county's tax rate, your assessment trajectory, and SDAT's determination of your Homestead eligibility. We can't guarantee approval.
      </Callout>
    </>
  );
}

function StatusBlock({ p, status, nav }) {
  const approved = status.code === "approved";
  const pending = status.code === "pending" || status.code === "application_received";
  const title = approved ? "You're already protected" : pending ? "SDAT already has an application in progress" : "This record needs review";
  const body = approved
    ? `Your Homestead Credit is on file with SDAT${p.homestead_application_status ? ` (${p.homestead_application_status})` : ""}. Maryland caps your taxable assessment increase at 10%/year for as long as this remains your primary residence.`
    : pending
      ? "Public records show SDAT has received or is processing a Homestead application for this property. We would not start a duplicate filing unless SDAT says a corrected refiling is needed."
      : "Public records do not classify this parcel as a clean filing target. Review the SDAT record before deciding whether to file.";

  return (
    <>
      <div className="card lg">
        <div className="row gap-3" style={{ alignItems: "flex-start" }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: approved ? "var(--good-100)" : "var(--brand-50)", color: approved ? "var(--good-700)" : "var(--brand-700)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            {approved ? <I.CheckCircle size={22}/> : <I.Info size={22}/>}
          </div>
          <div style={{ flex: 1 }}>
            <h2 className="h-page" style={{ fontSize: 22 }}>{title}</h2>
            <p className="subtle" style={{ marginTop: 6 }}>
              {body} <strong style={{ color: "var(--ink-900)" }}>{approved || pending ? "No EzClaim filing is needed right now." : "Manual review recommended."}</strong>
            </p>
          </div>
        </div>
        <div className="card-divider"/>
        <div className="rcpt">
          <div className="row"><span className="k">Status</span><span className="v" style={{ marginLeft: "auto" }}><Tag kind={status.kind}>{status.icon === "check" ? <I.Check size={11}/> : <span className="dot"/>} {status.label}</Tag></span></div>
          <div className="row"><span className="k">Public record</span><span className="v" style={{ marginLeft: "auto" }}>{p.homestead_application_status || "Review"}</span></div>
          <div className="row"><span className="k">Parcel</span><span className="v" style={{ marginLeft: "auto" }}>{p.parcel_id}</span></div>
          <div className="row"><span className="k">Cap rate</span><span className="v" style={{ marginLeft: "auto" }}>10% / yr · {p.county}</span></div>
        </div>
      </div>
      <Callout kind="info">
        <strong>If you move,</strong> you'll need to refile for your new primary residence. The credit doesn't transfer between properties.
      </Callout>
      <div className="cta-bar">
        <Button kind="secondary" onClick={() => nav("/")} block>Check another address</Button>
        <Button kind="ghost" onClick={() => window.open("https://sdat.dat.maryland.gov", "_blank")} block iconRight={<I.ExternalLink size={14}/>}>View on SDAT</Button>
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SDAT free-path explainer
// ─────────────────────────────────────────────────────────────────────────────
function SdatScreen({ nav }) {
  return (
    <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <Button kind="ghost" size="sm" icon={<I.ArrowLeft size={14}/>} onClick={() => nav("/results")}>Back</Button>
      <div>
        <h2 className="h-page">Filing free with SDAT</h2>
        <p className="subtle" style={{ marginTop: 6 }}>You'll need a few things on hand. The state's portal handles ID checks via your one-time access number.</p>
      </div>
      <div className="card">
        <h3 className="h-section">What you'll need</h3>
        <ul style={{ margin: "8px 0 0", paddingLeft: 18, color: "var(--ink-700)", lineHeight: 1.7, fontSize: 14.5 }}>
          <li>Your one-time access number from a recent SDAT letter (or apply by paper if you don't have one)</li>
          <li>Social Security Number(s) for all owners on the deed</li>
          <li>The property's parcel ID and address</li>
          <li>About 15–25 minutes</li>
        </ul>
      </div>
      <Callout kind="info">
        The SDAT online portal is the same form we use to prepare your packet — there's nothing we can do that you can't do yourself. The $19.99 buys handling and tracking, not access.
      </Callout>
      <div className="cta-bar">
        <Button kind="primary" iconRight={<I.ExternalLink size={14}/>} block onClick={() => window.open("https://sdathtc.dat.maryland.gov", "_blank")}>Open the SDAT portal</Button>
        <Button kind="secondary" block onClick={() => nav("/results")}>Maybe later</Button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Wizard
// ─────────────────────────────────────────────────────────────────────────────
const WIZARD_STEPS = [
  { key: "address",   label: "Confirm property",   short: "Property" },
  { key: "identity",  label: "Your contact info",  short: "You" },
  { key: "residency", label: "Primary residence",  short: "Residency" },
  { key: "owners",    label: "Other owners",       short: "Co-owners" },
  { key: "eligibility", label: "Eligibility",      short: "Eligibility" },
];

function WizardScreen({ nav, segs, session, setSession }) {
  const stepKey = segs[1] || "address";
  const idx = WIZARD_STEPS.findIndex(s => s.key === stepKey);
  const step = idx >= 0 ? idx : 0;
  const cur = WIZARD_STEPS[step];

  const filing = session.filing || {};
  function updateFiling(patch) {
    const nx = { ...filing, ...patch };
    setSession({ ...session, filing: nx });
  }
  function goNext() {
    if (step < WIZARD_STEPS.length - 1) nav("/wizard/" + WIZARD_STEPS[step + 1].key);
    else nav("/review");
  }
  function goPrev() {
    if (step > 0) nav("/wizard/" + WIZARD_STEPS[step - 1].key);
    else nav("/results");
  }

  return (
    <div className="fade-in">
      <WizardBar step={step + 1} total={WIZARD_STEPS.length} label={cur.label}/>
      <h2 className="h-page" style={{ marginTop: 6, marginBottom: 6 }}>{cur.label}</h2>
      <p className="subtle" style={{ marginBottom: 18 }}>{stepBlurb(stepKey)}</p>

      <div className="card lg">
        {stepKey === "address" && <StepAddress session={session} filing={filing} update={updateFiling}/>}
        {stepKey === "identity" && <StepIdentity filing={filing} update={updateFiling}/>}
        {stepKey === "residency" && <StepResidency filing={filing} update={updateFiling}/>}
        {stepKey === "owners" && <StepOwners filing={filing} update={updateFiling}/>}
        {stepKey === "eligibility" && <StepEligibility filing={filing} update={updateFiling}/>}
      </div>

      <Callout kind="" icon={<I.Lock size={16}/>} >
        We collect non-sensitive info now. <strong style={{ color: "var(--ink-900)" }}>SSN and signatures are collected after payment</strong>, used only to generate the form, and deleted from our servers after fax delivery.
      </Callout>

      <div className="cta-bar sticky">
        <Button kind="secondary" onClick={goPrev} icon={<I.ArrowLeft size={14}/>}>Back</Button>
        <Button kind="primary" onClick={goNext} iconRight={<I.ArrowRight size={14}/>} disabled={!stepValid(stepKey, filing, session)}>
          {step === WIZARD_STEPS.length - 1 ? "Review my filing" : "Continue"}
        </Button>
      </div>
    </div>
  );
}

function stepBlurb(key) {
  switch (key) {
    case "address":   return "Confirm we have the right parcel. We'll prefill from SDAT's public record where we can.";
    case "identity":  return "How should SDAT reach you if there are questions? We'll also email you your status link.";
    case "residency": return "The Homestead Credit only applies to your primary residence. A few quick yes/no questions.";
    case "owners":    return "If anyone else is on the deed, SDAT needs them on the application too.";
    case "eligibility": return "Final eligibility questions required on the SDAT form.";
    default: return "";
  }
}

function stepValid(key, f, session) {
  if (key === "address") return !!f.confirm_address;
  if (key === "identity") return !!(f.full_name && f.email && f.phone);
  if (key === "residency") return !!(f.is_primary && f.move_in_date);
  if (key === "owners") return f.has_coowners !== undefined && (!f.has_coowners || (f.coowner_name));
  if (key === "eligibility") return f.no_rental === true && f.owner_occupant === true && f.tax_credit_acks === true;
  return true;
}

// Step components ────────────────────────────────────────────────
function StepAddress({ session, filing, update }) {
  const p = session?.lookup?.matches?.[0];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <PropertyCard p={p}/>
      <Field label="Is this the property you want to file for?">
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <RadioCard
            selected={filing.confirm_address === "yes"}
            onClick={() => update({ confirm_address: "yes" })}
            title="Yes, this is my home"
            sub="Use this parcel for the filing."
          />
          <RadioCard
            selected={filing.confirm_address === "different_unit"}
            onClick={() => update({ confirm_address: "different_unit" })}
            title="It's the right building, but a different unit"
            sub="We'll let you pick the right parcel."
          />
        </div>
      </Field>
    </div>
  );
}

function StepIdentity({ filing, update }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Field label="Your full legal name" help="Exactly as it appears on the deed.">
        <Input aria-label="Your full legal name" value={filing.full_name || ""} onChange={(e) => update({ full_name: e.target.value })} placeholder="Renee A. Whitlock"/>
      </Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Field label="Email" help="We'll send your status link here.">
          <Input aria-label="Email" type="email" leftIcon={<I.Mail size={16}/>} value={filing.email || ""} onChange={(e) => update({ email: e.target.value })} placeholder="you@example.com"/>
        </Field>
        <Field label="Phone" hint="optional">
          <Input aria-label="Phone" type="tel" leftIcon={<I.Phone size={16}/>} value={filing.phone || ""} onChange={(e) => update({ phone: e.target.value })} placeholder="(410) 555-0142"/>
        </Field>
      </div>
      <Field label="Mailing address" hint="if different from the property">
        <Input aria-label="Mailing address" value={filing.mailing_address || ""} onChange={(e) => update({ mailing_address: e.target.value })} placeholder="Same as property address"/>
      </Field>
    </div>
  );
}

function StepResidency({ filing, update }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Field label="Is this your primary residence?">
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <RadioCard selected={filing.is_primary === "yes"} onClick={() => update({ is_primary: "yes" })}
            title="Yes — I live here as my primary home"
            sub="It's where I sleep, get mail, register to vote, and file state taxes."/>
          <RadioCard selected={filing.is_primary === "no"} onClick={() => update({ is_primary: "no" })}
            title="No — I rent it out or it's a second home"
            sub="The Homestead Credit isn't available for rentals or vacation properties."/>
        </div>
      </Field>

      {filing.is_primary === "no" ? (
        <Callout kind="warn"><strong>You can't file for this property.</strong> The Homestead Credit applies only to your primary residence. If your primary home changes, come back and file for that address.</Callout>
      ) : null}

      <Field label="Move-in date" help="The date this became your primary residence.">
        <Input aria-label="Move-in date" type="date" value={filing.move_in_date || ""} onChange={(e) => update({ move_in_date: e.target.value })}/>
      </Field>

      <Field label="Are you registered to vote at this address?" hint="recommended">
        <div className="chips">
          {["Yes","No","Prefer not to say"].map(o => (
            <button key={o} className="chip" aria-pressed={filing.voter_reg === o} onClick={() => update({ voter_reg: o })}>{o}</button>
          ))}
        </div>
      </Field>
    </div>
  );
}

function StepOwners({ filing, update }) {
  const has = filing.has_coowners;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Field label="Is anyone else on the deed?">
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <RadioCard selected={has === false} onClick={() => update({ has_coowners: false })}
            title="No — I'm the sole owner"
            sub="We'll prepare a single-applicant filing."/>
          <RadioCard selected={has === true} onClick={() => update({ has_coowners: true })}
            title="Yes — spouse, partner, family member, etc."
            sub="SDAT requires all deed-listed owners on the application."/>
        </div>
      </Field>
      {has ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Field label="Co-owner full name">
            <Input aria-label="Co-owner full name" value={filing.coowner_name || ""} onChange={(e) => update({ coowner_name: e.target.value })} placeholder="Jordan M. Whitlock"/>
          </Field>
          <Field label="Relationship">
            <div className="chips">
              {["Spouse","Partner","Family","Co-purchaser","Other"].map(o => (
                <button key={o} className="chip" aria-pressed={filing.coowner_rel === o} onClick={() => update({ coowner_rel: o })}>{o}</button>
              ))}
            </div>
          </Field>
          <Field label="Does the co-owner also live here as their primary residence?">
            <div className="chips">
              {["Yes","No"].map(o => (
                <button key={o} className="chip" aria-pressed={filing.coowner_primary === o} onClick={() => update({ coowner_primary: o })}>{o}</button>
              ))}
            </div>
          </Field>
        </div>
      ) : null}
    </div>
  );
}

function StepEligibility({ filing, update }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <Checkbox
        checked={!!filing.owner_occupant}
        onChange={(v) => update({ owner_occupant: v })}
        label="I occupy this property as my principal residence."
        sub="I live here for more than 6 months of the calendar year."
      />
      <Checkbox
        checked={!!filing.no_rental}
        onChange={(v) => update({ no_rental: v })}
        label="No portion of this property is rented or used for business."
        sub="If a portion is rented, we can still help — but the credit is prorated."
      />
      <Checkbox
        checked={!!filing.no_other_homestead}
        onChange={(v) => update({ no_other_homestead: v })}
        label="I do not have a Homestead Credit on any other property."
        sub="In Maryland or any other state."
      />
      <div className="card-divider"/>
      <Checkbox
        checked={!!filing.tax_credit_acks}
        onChange={(v) => update({ tax_credit_acks: v })}
        label="I understand EzClaim is not a government agency, the $19.99 is a service fee, and approval is determined by SDAT."
        sub="You can also file free directly with SDAT at sdathtc.dat.maryland.gov."
      />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Review
// ─────────────────────────────────────────────────────────────────────────────
function ReviewScreen({ nav, session, setSession }) {
  const p = session?.lookup?.matches?.[0];
  const f = session?.filing || {};
  const [startingCheckout, setStartingCheckout] = useState(false);
  const savings = p?.homestead_lead?.estimated_annual_savings ?? p?.estimated_tax_savings ?? 0;

  async function startCheckout() {
    setStartingCheckout(true);
    try {
      const resp = await fetch("/api/filings", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          property_id: p?.property_id,
          parcel_id: p?.parcel_id,
          filing: f,
        }),
      });
      const draft = resp.ok ? await resp.json() : {};
      setSession({
        ...session,
        payment_status: "pending",
        filing_id: draft.filing_id || session.filing_id,
        draft_filing: draft,
      });
    } catch (e) {
      setSession({ ...session, payment_status: "pending" });
    } finally {
      setStartingCheckout(false);
      nav("/checkout");
    }
  }

  return (
    <div className="fade-in" style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <Button kind="ghost" size="sm" icon={<I.ArrowLeft size={14}/>} onClick={() => nav("/wizard/eligibility")}>Back</Button>
      <div>
        <h2 className="h-page">Review your filing</h2>
        <p className="subtle" style={{ marginTop: 6 }}>Here's what we'll prepare. After payment we'll ask for SSN and signature — used only to generate the packet.</p>
      </div>

      <PropertyCard p={p}/>

      <ReviewBlock title="Your contact info" onEdit={() => nav("/wizard/identity")}>
        <Kv label="Name" v={f.full_name || "—"}/>
        <Kv label="Email" v={f.email || "—"}/>
        <Kv label="Phone" v={f.phone || "—"}/>
        <Kv label="Mailing address" v={f.mailing_address || "Same as property"}/>
      </ReviewBlock>

      <ReviewBlock title="Residency" onEdit={() => nav("/wizard/residency")}>
        <Kv label="Primary residence" v={f.is_primary === "yes" ? "Yes" : "No"}/>
        <Kv label="Move-in date" v={f.move_in_date ? fmtDate(f.move_in_date) : "—"}/>
        <Kv label="Voter registration here" v={f.voter_reg || "—"}/>
      </ReviewBlock>

      <ReviewBlock title="Other owners" onEdit={() => nav("/wizard/owners")}>
        <Kv label="Co-owners" v={f.has_coowners ? "Yes" : "No"}/>
        {f.has_coowners ? <>
          <Kv label="Name" v={f.coowner_name || "—"}/>
          <Kv label="Relationship" v={f.coowner_rel || "—"}/>
          <Kv label="Also primary residence?" v={f.coowner_primary || "—"}/>
        </> : null}
      </ReviewBlock>

      <ReviewBlock title="Eligibility" onEdit={() => nav("/wizard/eligibility")}>
        <Kv label="Owner-occupant" v={f.owner_occupant ? "Yes" : "—"}/>
        <Kv label="No rental / business use" v={f.no_rental ? "Yes" : "—"}/>
        <Kv label="No other Homestead claim" v={f.no_other_homestead ? "Yes" : "—"}/>
      </ReviewBlock>

      <div className="card lg">
        <div className="row between" style={{ alignItems: "flex-start" }}>
          <div>
            <div className="eyebrow">Order summary</div>
            <div className="h-section" style={{ marginTop: 6, marginBottom: 4 }}>EzClaim filing service</div>
            <div className="subtle">Prepare · submit · track via fax to SDAT</div>
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.01em" }}>$19.99</div>
        </div>
        <div className="card-divider"/>
        <Callout kind="" icon={<I.Sparkle size={16}/>} title="What happens after you pay">
          <ol style={{ margin: "6px 0 0 18px", padding: 0, color: "var(--ink-700)", lineHeight: 1.6 }}>
            <li>We collect your SSN and digital signature on a secure page.</li>
            <li>We assemble the SDAT Homestead application, fax it from a HIPAA-grade fax service, and confirm delivery.</li>
            <li>We email you a unique status link — no login required.</li>
            <li>The temporary packet (including your SSN) is deleted from our servers after fax delivery.</li>
          </ol>
        </Callout>
      </div>

      <div className="cta-bar sticky">
        <Button kind="secondary" onClick={() => nav("/wizard/eligibility")} icon={<I.ArrowLeft size={14}/>}>Back</Button>
        <Button kind="primary" onClick={startCheckout} iconRight={<I.Lock size={14}/>} disabled={startingCheckout}>
          {startingCheckout ? "Creating filing..." : "Pay $19.99 and continue"}
        </Button>
      </div>

      <p className="subtle text-center" style={{ fontSize: 12, color: "var(--ink-500)" }}>
        Payments processed securely by Stripe. You may avoid about <strong style={{ color: "var(--ink-700)" }}>{fmtUSD(savings)}/year</strong> in increases — estimate, not a guarantee.
      </p>
    </div>
  );
}

function ReviewBlock({ title, onEdit, children }) {
  return (
    <div className="card">
      <div className="row between" style={{ marginBottom: 10 }}>
        <div className="h-section" style={{ margin: 0 }}>{title}</div>
        <Button kind="link" onClick={onEdit}>Edit</Button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 8, fontSize: 14 }}>
        {children}
      </div>
    </div>
  );
}
function Kv({ label, v }) {
  return <div className="kv"><span className="k">{label}</span><span className="v">{v}</span></div>;
}

Object.assign(window, {
  LookupScreen, DisambiguateScreen, NoMatchScreen,
  ResultsScreen, SdatScreen, WizardScreen, ReviewScreen,
});
