const { useState, useEffect, useRef } = React;

const DELIVERABLES = [
  {
    num: '01',
    short: 'Comp workbook',
    title: 'Excel comparable-properties workbook',
    fmt: '.xlsx · 22 columns · GCTO format',
    blurb: "The actual GCTO 22-column comparable-properties grid that Galveston ARB panels recognize. Pre-populated with your CAD-appraised values, up to 11 same-street comparables pulled live from the county ArcGIS service, and the automatic median computation per §41.43(b)(3).",
    bullets: [
      'Subject property + up to 11 same-street comparable parcels',
      '22-column GCTO format: address, year built, sqft, CAD value, $/sf, exemptions, adjustments',
      '§41.43(b)(3) median computed automatically with show-your-work footnotes',
      'Variance analysis: subject vs. median, color-coded outliers',
      'Case-strength verdict: STRONG / MODERATE / WEAK',
      'Projected annual tax savings calculated at current GCTO mill rate',
    ],
    preview: 'comp',
  },
  {
    num: '02',
    short: 'Case Summary',
    title: 'Case Summary (one-page brief)',
    fmt: '.md / .pdf · ≈800 words',
    blurb: "A one-page brief covering your property, multi-year value history, identified protest grounds (market value vs. unequal appraisal), exemption audit, and a plain-English recommendation on whether to protest and on which ground.",
    bullets: [
      'Property snapshot: legal description, CAD account, owner name, exemptions on file',
      '5-year appraised value history with year-over-year deltas',
      'Identified protest grounds: market value (§41.41(a)(1)) vs. unequal (§41.41(a)(2))',
      'Exemption audit: homestead, over-65, disability, ag, surviving spouse',
      'Plain-English recommendation: file? on what ground? expected outcome?',
      'STRONG / MODERATE / WEAK verdict with reasoning, not a black box',
    ],
    preview: 'case',
  },
  {
    num: '03',
    short: 'Form 50-132 narrative',
    title: 'Form 50-132 statutory narrative',
    fmt: '.docx · paste-ready into Comptroller form',
    blurb: "The statutory protest narrative ready to paste into Texas Comptroller Form 50-132 (Notice of Protest). Proper §41.41 ground citations, case-specific facts, and language the ARB clerk has seen a hundred times.",
    bullets: [
      'Both §41.41(a)(1) market-value AND §41.41(a)(2) unequal-appraisal grounds checked',
      'Statement-of-grounds paragraph with case-specific facts inserted',
      'Reference to attached comparable-properties workbook by exhibit',
      'Request for an electronic copy of the appraisal record (§25.195)',
      'Owner-occupied homestead language if applicable',
      'Signature block + parcel ID + appointment-of-agent §41.41(c) disclaimer',
    ],
    preview: 'form',
  },
  {
    num: '04',
    short: '§41.461 letter',
    title: '§41.461 evidence-request letter',
    fmt: '.pdf · certified-mail ready',
    blurb: "The certified-mail letter to the Galveston County chief appraiser demanding the CAD's evidence packet 14 days before the hearing. This is a right most homeowners don't know they have — and CADs don't volunteer.",
    bullets: [
      'Cites Tex. Tax Code §41.461 demand for evidence ≥14 days before hearing',
      'Requests both the CAD\'s comparable set AND its adjustment methodology',
      'Specifies certified mail / return receipt requested for legal record',
      'Pre-addressed to the GCAD chief appraiser at 9850 Emmett F. Lowry Expy',
      'Includes a §41.45(g) reminder: CAD may not introduce evidence it didn\'t produce',
      'Print, sign, drop at the post office — no further work',
    ],
    preview: 'letter',
  },
  {
    num: '05',
    short: 'Hearing script',
    title: 'ARB hearing script',
    fmt: '.pdf · 4-minute oral, with cross-exam',
    blurb: "A four-minute hearing script you read from at the ARB panel, plus cross-examination questions for the CAD's staff appraiser. Includes builder-pattern legal research where applicable.",
    bullets: [
      'Four-minute oral statement timed to ARB panel norms — opening, evidence, ask',
      'Cross-examination question set for the CAD appraiser (5–8 questions)',
      'Builder-pattern research where applicable (Meritage stucco, KB roofing, etc.)',
      'Bracketed stage cues: [hand panel exhibit A], [pause for objection]',
      'Fallback script if CAD argues different highest-and-best-use',
      'Closing: specific proposed value + statutory authority for the reduction',
    ],
    preview: 'script',
  },
];

function CompPreview() {
  const rows = [
    { addr: '2418 Pelican Lp', yr: 2014, sqft: 2184, val: 326500, psf: 149.50, exempt: 'HS', adj: '—', subject: true },
    { addr: '2410 Pelican Lp', yr: 2014, sqft: 2180, val: 318420, psf: 146.06, exempt: 'HS', adj: '–0.1%' },
    { addr: '2422 Pelican Lp', yr: 2013, sqft: 2201, val: 328900, psf: 149.43, exempt: 'HS', adj: '+2.2%' },
    { addr: '2414 Pelican Lp', yr: 2014, sqft: 2165, val: 315200, psf: 145.59, exempt: 'HS,O65', adj: '–0.5%' },
    { addr: '2430 Pelican Lp', yr: 2014, sqft: 2210, val: 331440, psf: 149.97, exempt: 'HS', adj: '+2.6%' },
    { addr: '2406 Pelican Lp', yr: 2013, sqft: 2150, val: 311800, psf: 145.02, exempt: 'HS', adj: '–0.9%' },
    { addr: '2426 Pelican Lp', yr: 2015, sqft: 2224, val: 339180, psf: 152.51, exempt: 'HS', adj: '+4.3%' },
    { addr: '2402 Pelican Lp', yr: 2014, sqft: 2170, val: 320100, psf: 147.51, exempt: 'HS', adj: '+0.8%' },
    { addr: '2434 Pelican Lp', yr: 2014, sqft: 2200, val: 334032, psf: 151.83, exempt: 'HS', adj: '+3.8%' },
    { addr: '2398 Pelican Lp', yr: 2013, sqft: 2160, val: 313500, psf: 145.14, exempt: 'HS,DV', adj: '–0.8%' },
    { addr: '2438 Pelican Lp', yr: 2015, sqft: 2215, val: 337200, psf: 152.24, exempt: 'HS', adj: '+4.0%' },
  ];
  const fmt = (n) => '$' + n.toLocaleString('en-US');

  const wrapRef = useRef(null);
  const [median, setMedian] = useState({ sqft: '—', val: '—', psf: '—' });

  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) {
      setMedian({ sqft: '2,184', val: '$320,100', psf: '$146.78' });
      if (wrapRef.current) wrapRef.current.classList.add('animate-rows');
      return;
    }
    // Trigger row stagger
    const rafId = requestAnimationFrame(() => {
      if (wrapRef.current) wrapRef.current.classList.add('animate-rows');
    });
    // Count-up median values after stagger finishes
    const computeAt = 950;
    const duration = 800;
    const targets = { sqft: 2184, val: 320100, psf: 146.78 };
    let raf;
    const timeout = setTimeout(() => {
      const start = performance.now();
      function step(now) {
        const t = Math.min(1, (now - start) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        setMedian({
          sqft: Math.round(targets.sqft * eased).toLocaleString(),
          val: '$' + Math.round(targets.val * eased).toLocaleString(),
          psf: '$' + (targets.psf * eased).toFixed(2),
        });
        if (t < 1) raf = requestAnimationFrame(step);
      }
      raf = requestAnimationFrame(step);
    }, computeAt);
    return () => {
      cancelAnimationFrame(rafId);
      clearTimeout(timeout);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div className="comp-wrap dlv-comp" ref={wrapRef}>
      <div className="comp-toolbar">
        <span className="dot r"></span><span className="dot y"></span><span className="dot g"></span>
        <span className="fname">2418_Pelican_protest_2026.xlsx — Galveston CAD</span>
        <span className="saved">Sheet 1 of 3 · Saved</span>
      </div>
      <table className="xl">
        <thead>
          <tr>
            <th>#</th><th>Address</th><th>YrBlt</th><th>SqFt</th><th>CAD Value</th><th>$/SF</th><th>Exempt</th><th>± Median</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} className={r.subject ? 'subject' : ''}>
              <td>{r.subject ? 'SUBJ' : i}</td>
              <td>{r.addr}</td>
              <td>{r.yr}</td>
              <td>{r.sqft.toLocaleString()}</td>
              <td>{fmt(r.val)}</td>
              <td>${r.psf.toFixed(2)}</td>
              <td>{r.exempt}</td>
              <td className={r.adj && r.adj.startsWith('–') ? 'neg' : 'pos'}>{r.adj}</td>
            </tr>
          ))}
          <tr className="median">
            <td>—</td><td>MEDIAN (n=10 comps)</td><td>—</td><td>{median.sqft}</td><td>{median.val}</td><td>{median.psf}</td><td>—</td><td>—</td>
          </tr>
        </tbody>
      </table>
      <div style={{ marginTop: 16, padding: '12px 0', borderTop: '1px solid var(--rule-soft)', display: 'flex', gap: 24, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--slate-2)', flexWrap: 'wrap' }}>
        <span>SUBJECT $/SF: <strong style={{ color: 'var(--navy)' }}>$149.50</strong></span>
        <span>MEDIAN $/SF: <strong style={{ color: 'var(--navy)' }}>$146.78</strong></span>
        <span>VARIANCE: <strong style={{ color: '#B91C1C' }}>+1.85%</strong></span>
        <span>RECOMMENDED VALUE: <strong style={{ color: 'var(--orange-deep)' }}>$315,000</strong></span>
        <span>VERDICT: <strong style={{ color: '#CA8A04' }}>MODERATE</strong></span>
        <span>EST. SAVINGS: <strong style={{ color: '#15803D' }}>$173/yr</strong></span>
      </div>
    </div>
  );
}

function CasePreview() {
  return (
    <div className="casedoc">
      <div className="title">Case Summary — 2418 Pelican Loop, Galveston</div>
      <div className="subtitle">GCAD Account R-145203 · 2026 protest cycle · Prepared {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>

      <div className="verdict">Verdict · MODERATE</div>

      <h4>Property snapshot</h4>
      <div className="kv">
        <span>Owner-occupied homestead</span><span>Yes (since 2019)</span>
        <span>Land area</span><span>0.16 acres</span>
        <span>Living area</span><span>2,184 sqft</span>
        <span>Year built</span><span>2014 (Meritage)</span>
        <span>2025 CAD appraised value</span><span>$318,420</span>
        <span>2026 CAD appraised value</span><span>$326,500 (+2.5%)</span>
      </div>

      <h4>Identified grounds</h4>
      <p>Subject is appraised at <strong>$149.50/sqft</strong> against a same-street median of <strong>$146.78/sqft</strong> across 10 comparable Meritage builds — a +1.85% inequality. This is below the §41.43(b)(3) "substantially unequal" threshold most ARB panels apply (≈5%), but supports a moderate market-value argument under §41.41(a)(1).</p>

      <h4>Recommendation</h4>
      <p>File on <strong>market value</strong> grounds; check the unequal-appraisal box only as a backup. Lead with the median-$/sqft argument, then introduce the Meritage water-intrusion litigation as a depreciation factor not currently reflected in CAD's mass-appraisal model. Propose <strong>$315,000</strong>.</p>
    </div>
  );
}

function FormPreview() {
  return (
    <div className="formdoc">
      <div className="fhdr">
        <span>Texas Comptroller · Form 50-132</span>
        <span>Notice of Protest</span>
      </div>
      <div className="ftitle">Section 3 — Reason for Protest (Statement of Grounds)</div>
      <div className="fbody">
        <p>The owner protests the 2026 appraised value of $326,500 for the property at 2418 Pelican Loop, Galveston, TX 77554 (Account R-145203) under <span className="cite">Tex. Tax Code §41.41(a)(1)</span> excessive market value and <span className="cite">§41.41(a)(2)</span> unequal appraisal.</p>
        <p>Per <span className="cite">§41.43(b)(3)</span>, the median appraised value of a reasonable number of comparable properties — 10 same-street Meritage-built single-family residences platted in the same subdivision — is <strong>$146.78/sqft</strong>, against the subject's <strong>$149.50/sqft</strong>. See Exhibit A (22-column comparable-properties workbook) attached.</p>
        <p>The owner further notes the subject property is part of the Meritage stucco/water-intrusion class certified in the consolidated litigation in the W.D. Tex., a depreciation factor not reflected in CAD's mass-appraisal cost approach.</p>
        <p>Pursuant to <span className="cite">§25.195</span>, the owner requests an electronic copy of the appraisal record for the subject property prior to the hearing.</p>
        <p>Owner proposes a corrected appraised value of <strong>$315,000</strong>.</p>
      </div>
    </div>
  );
}

function LetterPreview() {
  return (
    <div className="letter">
      <div className="ret">From: Jordan A. Reyes · 2418 Pelican Loop · Galveston, TX 77554</div>
      <div className="to">
        Chief Appraiser<br />
        Galveston Central Appraisal District<br />
        9850 Emmett F. Lowry Expy<br />
        Texas City, TX 77591
      </div>
      <div className="ref">RE: Account R-145203 · 2026 protest · Demand under Tex. Tax Code §41.461</div>
      <p>Pursuant to Tex. Tax Code §41.461, the property owner hereby demands, no later than fourteen (14) days before the scheduled ARB hearing, copies of all data, schedules, formulas, and supporting documentation the appraisal district intends to introduce at the hearing of the above-referenced protest.</p>
      <p>This demand specifically includes (1) the CAD's comparable-properties set used to support the 2026 appraised value, (2) the CAD's adjustment methodology and weighting, and (3) any income-, cost-, or sales-approach worksheets relied upon.</p>
      <p>The property owner reserves the right under §41.45(g) to object to the introduction of any evidence not produced in response to this demand.</p>
      <div className="stamp-cert">CERTIFIED MAIL · RETURN RECEIPT</div>
      <p style={{ marginTop: 28 }}>Respectfully,</p>
      <p style={{ marginTop: 4, fontFamily: 'cursive', fontSize: 18, color: 'var(--navy)' }}>Jordan A. Reyes</p>
      <p style={{ marginTop: 4, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--slate-3)' }}>Property owner of record</p>
    </div>
  );
}

function ScriptPreview() {
  return (
    <div className="script">
      <div className="slug">ARB Hearing · Panel 3 · Galveston CAD · Account R-145203</div>
      <div style={{ fontFamily: 'var(--serif)', fontWeight: 700, color: 'var(--navy)', fontSize: 20, marginBottom: 4 }}>Oral Statement — Four Minutes</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--slate-3)', marginBottom: 18, paddingBottom: 12, borderBottom: '1px solid var(--rule-soft)' }}>Read at conversational pace · pause where indicated</div>

      <div className="tcue">[0:00 — opening, 30 sec]</div>
      <p>Members of the Board, good morning. My name is Jordan Reyes. I'm the homestead owner of 2418 Pelican Loop, Account R-145203. I'm here today on §41.41(a)(1) market value and §41.41(a)(2) unequal-appraisal grounds. I have three exhibits the Board has not previously seen.</p>

      <div className="tcue">[0:30 — exhibit A, 90 sec]</div>
      <p>Exhibit A is a 22-column comparable-properties workbook. Ten Meritage builds on Pelican Loop, all platted within the same subdivision, all between 2,150 and 2,224 square feet. <span className="stage">[hand panel Exhibit A]</span> The median appraised value per square foot is $146.78. The subject is appraised at $149.50. That is a positive variance of one-point-eight-five percent — moderate, but consistent.</p>

      <div className="tcue">[2:00 — exhibit B, 60 sec]</div>
      <p>Exhibit B is the §41.461 demand letter I sent the chief appraiser on April 22. The district did not produce comparable-set documentation in response. Under §41.45(g) I would object to any CAD comparable evidence introduced today that wasn't produced in that demand. <span className="stage">[pause for panel acknowledgment]</span></p>

      <div className="tcue">[3:00 — ask, 60 sec]</div>
      <p>Based on the median-per-square-foot analysis and the Meritage stucco depreciation factor — which is the subject of consolidated federal litigation the Board may take notice of — I'm requesting a corrected 2026 appraised value of $315,000. That's a four-point-five percent reduction. Thank you.</p>

      <div className="tcue">[Cross-examination · if invited]</div>
      <p style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--slate-2)' }}>Q1. Did the district apply a depreciation factor for known builder-defect litigation in this subdivision?</p>
      <p style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--slate-2)' }}>Q2. What is the district's weighting between cost approach and sales approach for 2014-built tract homes in this stratum?</p>
    </div>
  );
}

const PREVIEWS = {
  comp: CompPreview,
  case: CasePreview,
  form: FormPreview,
  letter: LetterPreview,
  script: ScriptPreview,
};

function Deliverables() {
  const [active, setActive] = useState(0);
  const d = DELIVERABLES[active];
  const Preview = PREVIEWS[d.preview];
  return (
    <div>
      <div className="tabs" role="tablist">
        {DELIVERABLES.map((x, i) => (
          <button
            key={x.num}
            role="tab"
            aria-selected={i === active}
            className={i === active ? 'on' : ''}
            onClick={() => setActive(i)}
          >
            <span className="num">{x.fmt.split('·')[0].trim()}</span>
            <span className="ttl">{x.short}</span>
          </button>
        ))}
      </div>

      <div className="panel" key={active}>
        <div className="copy">
          <div className="meta-row">{d.num} · {d.fmt}</div>
          <h3>{d.title}</h3>
          <p>{d.blurb}</p>
          <ul>
            {d.bullets.map((b, i) => <li key={i}>{b}</li>)}
          </ul>
        </div>
        <div className="preview">
          <div className="stamp">Example · 2418 Pelican Loop</div>
          <div style={{ marginTop: 28 }}>
            <Preview />
          </div>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('deliverables-app')).render(<Deliverables />);
