// SeisQuake — main app file. Composes all sections.
// Other component files (SeismicWaveform, PgaWidget) are loaded as separate
// script tags and reach this file via window.*

const { useState, useEffect, useRef } = React;

// ── Scroll reveal ───────────────────────────────────────────────────────
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: '0px 0px -40px 0px' }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ── Wordmark / Logo ──────────────────────────────────────────────────────
// Uses the client-provided SeisQuake logo, split into a square icon
// (assets/seisquake-mark.png) and a horizontal wordmark
// (assets/seisquake-wordmark.png) for crisp display at any size.
// `onDark` swaps the wordmark for a white-text version (footer, dark hero).
function Wordmark({ variant = 'lockup', size = 36, onDark = false }) {
  const wordSrc = onDark
    ? 'assets/seisquake-wordmark-onDark.png'
    : 'assets/seisquake-wordmark.png';
  if (variant === 'mark') {
    return (
      <img
        src="assets/seisquake-mark.png"
        alt="SeisQuake"
        style={{ height: size, width: 'auto', display: 'block' }}
      />
    );
  }
  if (variant === 'wordmark') {
    return (
      <img
        src={wordSrc}
        alt="SeisQuake — Seismic Engineering & Structural Solutions"
        style={{ height: size, width: 'auto', display: 'block' }}
      />
    );
  }
  // Default 'lockup' — icon + horizontal wordmark side-by-side
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: Math.round(size * 0.3),
      }}
    >
      <img
        src="assets/seisquake-mark.png"
        alt=""
        aria-hidden="true"
        style={{ height: size * 1.05, width: 'auto', display: 'block' }}
      />
      <img
        src={wordSrc}
        alt="SeisQuake"
        style={{
          height: size * 0.62,
          width: 'auto',
          display: 'block',
        }}
      />
    </span>
  );
}

// ── Nav ────────────────────────────────────────────────────────────────
function Nav() {
  const [open, setOpen] = useState(false);
  const close = () => setOpen(false);
  const links = [
    ['How It Works', '#process'],
    ["What's Included", '#scope'],
    ['Pricing', '#pricing'],
    ['Compliance', '#compliance'],
    ['About', '#about'],
    ['CRE Refinancing', 'cre-refinance-pml.html'],
  ];
  return (
    <header className="nav">
      <div className="nav-inner">
        <a href="#top" className="nav-logo" style={{ textDecoration: 'none' }}>
          <Wordmark size={34} />
          <span className="nav-badge">ASTM E2026</span>
        </a>
        <button className="nav-hamburger" onClick={() => setOpen((v) => !v)} aria-label="Menu">
          {open ? '✕' : '☰'}
        </button>
        <nav className={`nav-links${open ? ' open' : ''}`}>
          {links.map(([label, href]) => (
            <a key={href} href={href} onClick={close}>
              {label}
            </a>
          ))}
          <a href="#order" className="btn btn-primary" onClick={close}>
            Order Report
          </a>
        </nav>
      </div>
    </header>
  );
}

// ── Hero ───────────────────────────────────────────────────────────────
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-waveform-bg" style={{ color: 'var(--waveform-color)' }}>
        <SeismicWaveform height={900} mode="bg" />
      </div>
      <div className="container hero-grid">
        <div className="reveal">
          <div className="badge-row">
            <span className="badge">FANNIE MAE DUS</span>
            <span className="badge">FREDDIE MAC</span>
            <span className="badge">CMBS</span>
            <span className="badge">HUD/FHA</span>
          </div>
          <h1>
            Seismic risk reports that
            <em>close on time.</em>
          </h1>
          <p className="hero-sub">
            PE-stamped ASTM E2026-24 assessments. Fannie Mae and Freddie Mac
            compliant. As fast as 48 hours.
          </p>
          <div className="hero-cta">
            <a href="#order" className="btn btn-primary btn-lg">
              Request a Report
            </a>
            <a href="#screening" className="btn btn-ghost btn-lg">
              Check My Property
            </a>
          </div>
          <div className="stat-bar">
            <div>
              <div className="stat-num mono">48-Hour</div>
              <div className="stat-label">Fastest in the market</div>
            </div>
            <div>
              <div className="stat-num mono">3 Levels</div>
              <div className="stat-label">Level 0, Level 1, Level 2</div>
            </div>
            <div>
              <div className="stat-num mono" style={{ fontSize: 17 }}>ASTM E2026-24</div>
              <div className="stat-label">Current standard</div>
            </div>
            <div>
              <div className="stat-num mono" style={{ fontSize: 18 }}>PE-Stamped</div>
              <div className="stat-label">Licensed structural engineer</div>
            </div>
          </div>
        </div>
        <div className="hero-visual reveal">
          <SeismicWaveform height={460} mode="panel" />
        </div>
      </div>
    </section>
  );
}

// ── Why Now (urgency) ─────────────────────────────────────────────────
// Three-column compliance-pressure section sitting between Hero and PGA
// screening. Frames the regulatory backdrop (new standard, freshness rule,
// California local enforcement) that's driving demand right now.
function WhyNowSection() {
  const cols = [
    {
      kicker: 'NEW STANDARD IN EFFECT',
      head: 'ASTM E2026-24 is now binding.',
      body:
        'ASTM E2026-24 (June 2024) replaced E2026-16a as the standard for Fannie Mae, Freddie Mac, CMBS, and life-company lenders. Reports referencing the prior edition are increasingly flagged for re-issuance or addenda before closing.',
      stat: 'E2026-16a → E2026-24',
    },
    {
      kicker: '12-MONTH FRESHNESS RULE',
      head: '2023 reports cannot be recycled.',
      body:
        'Fannie Mae requires seismic reports less than 12 months old at loan closing. Nearly every agency refi in Seismic Zones 3 and 4 in 2026 needs a fresh assessment. The maturity wave is back-loaded into Q3–Q4 2026.',
      stat: '< 12 months at close',
    },
    {
      kicker: 'CALIFORNIA LOCAL ENFORCEMENT',
      head: 'Soft-story ordinances are now active.',
      body:
        'Los Angeles, San Francisco, and San Jose soft-story compliance deadlines are in enforcement phase. URM inventories and ATC-20 vintage retrofits require California-specific judgment that national firms routinely miss.',
      stat: 'LA · SF · SJ active',
    },
  ];
  return (
    <section id="why-now">
      <div className="container">
        <div className="reveal">
          <div className="section-label">WHY NOW</div>
          <h2>The 2026 maturity wave meets a new compliance bar.</h2>
          <p className="lead">
            Three regulatory shifts have collided this cycle. Most lenders and
            borrowers don't realize their 2023 and 2024 reports are already
            stale by the time the file reaches underwriting.
          </p>
          <div className="why-grid">
            {cols.map((c) => (
              <div className="why-card" key={c.kicker}>
                <div className="why-kicker mono">{c.kicker}</div>
                <h3 className="why-head">{c.head}</h3>
                <p className="why-body">{c.body}</p>
                <div className="why-stat mono">{c.stat}</div>
              </div>
            ))}
          </div>
          <div className="why-cta">
            <div className="why-cta-text">
              <strong>Refinancing in 2026?</strong>
              Fast-track your seismic report — our specialized CRE refinancing service delivers PE-stamped SRA reports in 48 hours.
            </div>
            <div className="why-cta-actions">
              <a href="cre-refinance-pml.html" className="btn btn-primary">CRE Refinancing SRA Reports →</a>
              <a href="#order" className="btn btn-ghost">Order General Report</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Fast Track CTA strip ──────────────────────────────────────────────
// Mid-page deal-stage CTA: visitors already in a closing window can route
// straight to the order form without scrolling the whole site.
function FastTrackBand() {
  return (
    <section className="fast-track-band" id="fast-track" aria-label="Fast track to order">
      <div className="container">
        <div className="fast-track-inner reveal">
          <div className="fast-track-copy">
            <div className="fast-track-eyebrow mono">GET STARTED NOW · DEAL-STAGE INTAKE</div>
            <div className="fast-track-head">
              Already mid-deal? Skip the tour and put it in the queue.
            </div>
            <div className="fast-track-sub">
              Address, building type, replacement value — we confirm within 2 business hours and start the USGS data pull the same day.
            </div>
          </div>
          <div className="fast-track-actions">
            <a href="#order" className="btn btn-primary btn-lg">Get Started Now →</a>
            <a href="mailto:contact@seisquake.com" className="fast-track-link">
              or email contact@seisquake.com
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── PGA section wrapper ────────────────────────────────────────────────
function PgaSection() {
  return (
    <section className="alt" id="screening">
      <div className="container">
        <div className="reveal">
          <div className="section-label">QUICK SEISMIC SCREENING</div>
          <h2>Not sure if your deal triggers the requirement?</h2>
          <p className="lead">
            Check any property instantly — free. Live USGS hazard data, Fannie
            Mae 0.15g trigger flagged automatically. No account needed.
          </p>
          <PgaWidget />
        </div>
      </div>
    </section>
  );
}

// ── Problem / Comparison ───────────────────────────────────────────────
function ProblemSection() {
  return (
    <section id="problem">
      <div className="container">
        <div className="reveal">
          <div className="section-label">THE PROBLEM</div>
          <h2>Seismic reports shouldn't hold up your loan closing.</h2>
          <p className="lead">
            Traditional engineering firms route ASTM E2026 seismic risk
            assessments through multiple staff, peer review queues, and
            procurement gatekeeping. The result is two-to-three-week turnaround
            on work that can be delivered in days. SeisQuake is structured
            around a single PE who owns each report end-to-end. Same ASTM
            compliance, faster delivery, direct engineer access.
          </p>
          <div className="compare-card">
            <table className="compare">
              <thead>
                <tr>
                  <th></th>
                  <th>Traditional Firm</th>
                  <th className="is-us">SeisQuake</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Standard turnaround</td>
                  <td className="mono">7 – 21 days</td>
                  <td className="is-us"><span className="accent">From 48 hours</span></td>
                </tr>
                <tr>
                  <td>Level 1 with Field Assessment</td>
                  <td className="mono">2 – 3 weeks</td>
                  <td className="is-us"><span className="accent">5 business days</span></td>
                </tr>
                <tr>
                  <td>Level 2 Detailed Engineering</td>
                  <td className="mono">3 – 6 weeks</td>
                  <td className="is-us"><span className="accent">10 business days</span></td>
                </tr>
                <tr>
                  <td>Rush surcharge</td>
                  <td className="mono">$1,000 – $2,000</td>
                  <td className="is-us"><span className="accent">None</span></td>
                </tr>
                <tr>
                  <td>PE-stamped</td>
                  <td><span className="yes">✓</span></td>
                  <td className="is-us"><span className="yes">✓</span></td>
                </tr>
                <tr>
                  <td>ASTM E2026-24 compliant</td>
                  <td><span className="yes">✓</span></td>
                  <td className="is-us"><span className="yes">✓</span></td>
                </tr>
                <tr>
                  <td>Direct PE access</td>
                  <td><span className="no">✕</span></td>
                  <td className="is-us"><span className="yes">✓</span></td>
                </tr>
                <tr>
                  <td>Engineer-led workflow</td>
                  <td><span className="yes">✓</span></td>
                  <td className="is-us"><span className="yes">✓</span></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Scope: Three Levels ────────────────────────────────────────────────
// Replaces the old single "Included" list with three tier-specific cards
// that mirror the pricing section. Includes a self-select guidance table.
function ScopeSection() {
  const tiers = [
    {
      name: 'Level 0',
      sub: 'Pre-Underwriting Screening',
      meta: '48 hours · Records-based desktop assessment',
      items: [
        'Full ASTM E2026-24 Level 0 desktop scope',
        'USGS seismic hazard data (PGA 10%/50yr, Ss, S1, site class)',
        'Nearest active fault identification and distance',
        'Liquefaction and landslide susceptibility from published mapping',
        'Building type classification and vulnerability analysis',
        'SEL and SUL calculations',
        'Fannie Mae / Freddie Mac threshold determination',
        'PE-stamped final PDF',
      ],
      bestFor:
        'Owner due diligence, portfolio pre-screening, properties below the Fannie Mae 0.15g PGA trigger.',
    },
    {
      name: 'Level 1',
      sub: 'SRA with Field Assessment',
      meta: '5 business days · Includes site visit',
      items: [
        'Everything in Level 0',
        'Qualified Field Assessor site visit',
        'Building stability per ASTM E2026-24 §8',
        'Expanded vulnerability analysis with field observations',
        'Photographic documentation of building systems',
      ],
      bestFor:
        'Fannie Mae DUS, Freddie Mac, CMBS, HUD/FHA submissions; properties with PGA ≥ 0.15g.',
    },
    {
      name: 'Level 2',
      sub: 'Detailed Engineering Assessment',
      meta: '10 business days · Building-specific structural analysis',
      items: [
        'Everything in Level 1',
        'Construction document review (structural drawings, calculations)',
        'ASCE 41 Tier 1 / Tier 2 evaluation or FEMA P-58 component-level analysis',
        'Building-specific fragility analysis (HAZUS, SP3, or ST-RISK)',
        'Detailed retrofit scoping and cost-range estimates',
      ],
      bestFor:
        'High-value assets, complex structural systems, retrofit decisions, properties where Level 1 SEL exceeds lender thresholds.',
    },
  ];
  const guidance = [
    ['Property has PGA < 0.15g (475-year)', 'Level 0'],
    ['Owner-initiated due diligence', 'Level 0'],
    ['Portfolio screening across many assets', 'Level 0'],
    ['CRE refinancing closing in 2026 (Fannie Mae DUS, Freddie Mac, CMBS)', <a href="cre-refinance-pml.html" style={{color: 'var(--accent)', fontWeight: 600}}>Seismic Reports for CRE Refinancing →</a>],
    ['Fannie Mae DUS, Freddie Mac, CMBS, life insurance loan', 'Level 1 with Field Assessment'],
    ['Property in CA, OR, WA, AK, HI, PR — any zone with PGA ≥ 0.15g', 'Level 1 with Field Assessment'],
    ['High-value asset with complex structure', 'Level 2'],
    ['Level 1 SEL exceeded lender threshold; retrofit decision needed', 'Level 2'],
    ['Not sure, or lender has issued a specific scope letter', 'Send us the address and the scope letter'],
  ];
  return (
    <section className="alt" id="scope">
      <div className="container">
        <div className="reveal">
          <div className="section-label">WHAT'S INCLUDED</div>
          <h2>Three assessment levels. Choose what your lender requires.</h2>
          <div className="scope-tier-grid">
            {tiers.map((t) => (
              <div className="scope-tier-card" key={t.name}>
                <div className="scope-tier-name">
                  <span>{t.name}</span>
                  <span className="scope-tier-sub">{t.sub}</span>
                </div>
                <div className="scope-tier-meta mono">{t.meta}</div>
                <ul className="scope-tier-items">
                  {t.items.map((x) => (
                    <li key={x}>{x}</li>
                  ))}
                </ul>
                <p className="scope-tier-bestfor">
                  <strong>Best for:</strong> {t.bestFor}
                </p>
              </div>
            ))}
          </div>

          <div className="scope-guidance">
            <h3>Which level do I need?</h3>
            <table className="guidance-table">
              <thead>
                <tr>
                  <th>Use case</th>
                  <th>Recommended tier</th>
                </tr>
              </thead>
              <tbody>
                {guidance.map(([useCase, tier]) => (
                  <tr key={useCase}>
                    <td>{useCase}</td>
                    <td className="guidance-tier">{tier}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Process ────────────────────────────────────────────────────────────
function ProcessSection() {
  const steps = [
    ['01', 'Submit Property', 'Address, building type, year built, square footage, replacement value. Receipt confirmed within 2 business hours.'],
    ['02', 'Hazard Data Pull', 'USGS PGA (10%/50yr), site class, fault distances, and liquefaction mapping retrieved and verified.'],
    ['03', 'Engineer Drafting', 'Hazard data and site information are integrated into ASTM E2026-24 templates. Building vulnerability analysis, SEL and SUL calculations, and conclusions are performed by a licensed structural engineer.'],
    ['04', 'PE Review & Stamp', 'Final review of every calculation and conclusion by the responsible PE. Stamp and signature applied.'],
    ['05', 'Delivery', 'PE-stamped PDF delivered via secure download. Ready for lender submission.'],
  ];
  return (
    <section id="process">
      <div className="container">
        <div className="reveal">
          <div className="section-label">HOW IT WORKS</div>
          <h2>From order to PE-stamped report in 48 hours.</h2>
          <div className="process">
            {steps.map(([n, title, desc], i) => (
              <div className="process-step" key={n}>
                <div className="process-num">{n}</div>
                <div className="process-title">{title}</div>
                <p className="process-desc">{desc}</p>
                {i < steps.length - 1 && <div className="process-connector" />}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Scope of Automation ────────────────────────────────────────────────
// Sits between Process and Pricing. Disarms the "is this an AI report?"
// objection by listing exactly which steps are automated vs engineer-performed.
function AutomationSection() {
  const automated = [
    'USGS hazard parameter retrieval (PGA, Ss, S1, site class)',
    'Active fault distance calculation',
    'Liquefaction and landslide susceptibility lookups',
    'Report formatting and ASTM E2026-24 template compliance',
    'Citation and reference management',
  ];
  const engineerPerformed = [
    'Building type classification and vulnerability assessment',
    'Structural system identification and weakness analysis',
    'SEL and SUL calculation methodology',
    'Field observations and interpretation (Level 1 and Level 2)',
    'Retrofit recommendations and cost-range estimates',
    'All judgment calls, conclusions, and the PE stamp',
  ];
  return (
    <section id="methodology">
      <div className="container">
        <div className="reveal">
          <div className="section-label">METHODOLOGY</div>
          <h2>What we automate — and what we don't.</h2>
          <p className="lead">
            Modern workflow automation handles the routine. Every engineering
            judgment, calculation, and conclusion is performed by a licensed
            California PE. The stamp is the engineer's, not the software's.
          </p>
          <div className="scope-grid">
            <div className="scope-col included">
              <h3>Automated</h3>
              <ul>
                {automated.map((x) => (
                  <li key={x}>{x}</li>
                ))}
              </ul>
            </div>
            <div className="scope-col included" style={{ borderColor: 'var(--link)' }}>
              <h3 style={{ color: 'var(--link)' }}>Engineer-performed</h3>
              <ul className="ul-engineer">
                {engineerPerformed.map((x) => (
                  <li key={x}>{x}</li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Pricing ────────────────────────────────────────────────────────────
function PricingSection() {
  return (
    <section className="alt" id="pricing">
      <div className="container">
        <div className="reveal">
          <div className="section-label">PRICING</div>
          <h2>Three assessment levels per ASTM E2026-24.</h2>
          <p className="lead" style={{ marginBottom: 24 }}>
            Every deliverable is PE-stamped and ASTM E2026-24 compliant. Choose
            the level that matches your lender's requirements and deal
            complexity. Volume and portfolio pricing available on request.
          </p>
          <div className="pricing-grid">
            <div className="price-card">
              <div className="price-name">Level 0</div>
              <div className="price-sub-name">Pre-Underwriting Screening</div>
              <div className="price-turnaround mono">48 hours</div>
              <ul className="price-features">
                <li>Full ASTM E2026-24 Level 0 desktop scope</li>
                <li>SEL and SUL calculations</li>
                <li>USGS hazard data and fault identification</li>
                <li>PE-stamped final PDF</li>
              </ul>
              <p className="price-best-for">
                <strong>Best for:</strong> Portfolio pre-screening and properties
                below the Fannie Mae 0.15g PGA trigger.
              </p>
              <a href="#order" className="btn btn-ghost btn-block">Request Quote</a>
            </div>

            <div className="price-card featured">
              <span className="pop-badge">Most Popular</span>
              <div className="price-name">Level 1</div>
              <div className="price-sub-name">SRA with Field Assessment</div>
              <div className="price-turnaround mono">5 business days</div>
              <ul className="price-features">
                <li>Everything in Level 0</li>
                <li>Qualified Field Assessor site visit</li>
                <li>Building stability per ASTM E2026-24 §8</li>
                <li>Photographic documentation</li>
              </ul>
              <p className="price-best-for">
                <strong>Best for:</strong> Most Fannie Mae DUS, Freddie Mac,
                CMBS, and HUD/FHA submissions.
              </p>
              <a href="#order" className="btn btn-primary btn-block">Request Quote</a>
            </div>

            <div className="price-card">
              <div className="price-name">Level 2</div>
              <div className="price-sub-name">Detailed Engineering Assessment</div>
              <div className="price-turnaround mono">10 business days</div>
              <ul className="price-features">
                <li>Everything in Level 1</li>
                <li>ASCE 41 Tier 1/2 or FEMA P-58 analysis</li>
                <li>Building-specific fragility (HAZUS, SP3, ST-RISK)</li>
                <li>Retrofit scoping and cost-range estimates</li>
              </ul>
              <p className="price-best-for">
                <strong>Best for:</strong> High-value assets, complex structures,
                retrofit decisions.
              </p>
              <a href="#order" className="btn btn-ghost btn-block">Request Quote</a>
            </div>
          </div>
          <p className="price-footnote">
            All tiers are PE-stamped and ASTM E2026-24 compliant. Volume pricing
            available for 5+ reports per month. Portfolio screening and rush
            turnarounds available on request. Payment via Stripe or Net-14
            invoicing for volume clients.
          </p>
        </div>
      </div>
    </section>
  );
}

// ── Compliance ─────────────────────────────────────────────────────────
function ComplianceSection() {
  return (
    <section id="compliance">
      <div className="container">
        <div className="reveal">
          <div className="section-label">THE MANDATE</div>
          <h2>This report isn't optional. It's written into lending guidelines.</h2>
          <p className="lead">
            The requirement has existed since 1994. ASTM enforcement was tightened in
            2018. Every multifamily loan in a seismic zone requires a compliant report
            dated within 12 months of closing.
          </p>
          <div className="compliance-grid">
            <div className="compliance-card">
              <h3>Fannie Mae <span className="tag">DUS</span></h3>
              <div className="ref">Form 4099.C — Seismic Risk Assessment</div>
              <p>PGA ≥ 0.15g → SRA required before Rate Lock.</p>
              <div className="threshold">
                <div><span className="ok">SEL ≤ 20%</span> · Proceed</div>
                <div><span className="warn">SEL 20–40%</span> · Contact insurance</div>
                <div><span className="bad">SEL &gt; 40%</span> · Ineligible</div>
              </div>
            </div>

            <div className="compliance-card">
              <h3>Freddie Mac <span className="tag">CME</span></h3>
              <div className="ref">Multifamily Seller / Servicer Guide, Ch. 64</div>
              <p>
                Identical PGA ≥ 0.15g trigger. Level 1 SRA required before Rate
                Lock. ASTM E2026-16a or successor (E2026-24) accepted.
              </p>
            </div>

            <div className="compliance-card">
              <h3>CMBS / Conduit <span className="tag">E2557</span></h3>
              <div className="ref">ASTM E2557 — Seismic Zones 3 &amp; 4</div>
              <p>
                PML ≤ 20% typically required. If exceeded, earthquake insurance
                mandatory.
              </p>
            </div>

            <div className="compliance-card">
              <h3>HUD / FHA <span className="tag">SDC C–F</span></h3>
              <div className="ref">Full seismic compliance — new construction &amp; rehab</div>
              <p>
                Required for all new construction and substantial rehab in Seismic
                Design Categories C–F. Cannot close without compliant SRA on file.
              </p>
            </div>
          </div>

          <div className="pullquote">
            <q>
              Every commercial multifamily loan in a seismic zone needs a fresh
              SRA within 12 months of closing. The requirement has no sunset
              date and applies across refinancing, acquisition, and
              supplemental loan transactions.
            </q>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── About ──────────────────────────────────────────────────────────────
function AboutSection() {
  const creds = [
    'Ph.D., Structural Earthquake Engineering',
    'Licensed Civil / Structural Engineer (PE), California',
    '10+ years seismic engineering experience',
    '3+ years seismic design and analysis',
    '2+ years ASTM seismic risk assessment',
    'E&O professionally insured',
  ];
  const qual = [
    ['Licensed PE', '✓ California PE'],
    ['5+ years structural engineering', '✓ 10+ years'],
    ['3+ years seismic design', '✓ 3+ years'],
    ['2+ years SRA experience', '✓ 2+ years'],
    ['E&O insurance', '✓ Active'],
  ];
  const coverage = [
    'Executive summary with SEL and SUL',
    'Site description and seismic hazard analysis',
    'Building vulnerability assessment',
    'Loss estimation (Thiel-Zsutty methodology)',
    'Site stability and liquefaction assessment',
    'Retrofit recommendations if SEL > 20%',
    'PE stamp, license number, date',
    'Appendix: USGS hazard parameter printout',
  ];
  return (
    <section className="alt" id="about">
      <div className="container">
        <div className="reveal">
          <div className="section-label">ABOUT SEISQUAKE</div>
          <h2>Built by a licensed seismic engineer. Backed by a decade of practice.</h2>
          <div className="about-grid">
            <div className="about-copy">
              <p>
                SeisQuake was founded by a licensed structural engineer with a Ph.D. in
                Structural Earthquake Engineering, licensed Professional Engineer, and more
                than a decade of seismic risk assessment experience across commercial,
                healthcare, and multifamily properties throughout California.
              </p>
              <p>
                Every SeisQuake report is produced by a single licensed engineer
                with end-to-end ownership. Modern workflow tools handle data
                retrieval, formatting, and citation management so the engineer's
                time is spent on what matters: analysis, judgment, and the PE
                stamp.
              </p>
            </div>
            <div className="about-cards">
              <div className="cred-card">
                <h4>Credentials</h4>
                <ul className="cred-list">
                  {creds.map((c) => (
                    <li key={c}>{c}</li>
                  ))}
                </ul>
              </div>
              <div className="cred-card">
                <h4>Personnel Qualifications</h4>
                <table className="qual">
                  <tbody>
                    {qual.map(([k, v]) => (
                      <tr key={k}>
                        <td>{k}</td>
                        <td>{v}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          <ul className="report-coverage">
            {coverage.map((c) => (
              <li key={c}>{c}</li>
            ))}
          </ul>

          <div className="dus-callout">
            <div className="dus-callout-eyebrow mono">DUS LENDER NETWORK</div>
            <div className="dus-callout-body">
              <p>
                <strong>Approved-vendor status in progress.</strong> SeisQuake
                is in the process of securing approved-consultant status with
                major DUS lenders — <span className="dus-names">Walker &amp; Dunlop, Berkadia, Newmark, JLL, CBRE</span>.
              </p>
              <p>
                Borrowers can request SeisQuake directly during underwriting,
                or ask their loan officer to add us to the approved vendor
                roster. Reach the engineering desk at{' '}
                <a href="mailto:contact@seisquake.com">contact@seisquake.com</a>{' '}
                to coordinate.
              </p>
            </div>
          </div>        </div>
      </div>
    </section>
  );
}

// ── Trust band ─────────────────────────────────────────────────────────
// Thin credentials strip — sits between About and Testimonials to ground
// the testimonials in verifiable engineer-level credentials.
function TrustBandSection() {
  const stats = [
    ['Ph.D.', 'Structural Earthquake Engineering'],
    ['10+ Years', 'Seismic engineering experience'],
    ['ASTM E2026-24', 'Current standard'],
    ['California PE', 'Licensed & E&O insured'],
  ];
  return (
    <section className="trust-band">
      <div className="container">
        <div className="trust-band-grid reveal">
          {stats.map(([num, label]) => (
            <div key={label} className="trust-band-cell">
              <div className="trust-band-num mono">{num}</div>
              <div className="trust-band-label">{label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Testimonials ───────────────────────────────────────────────────────
function TestimonialsSection() {
  const items = [
    {
      quote:
        'We needed a seismic report for a deal closing in 5 days. Traditional firms quoted 2 weeks. SeisQuake delivered a complete PE-stamped report in 40 hours. Loan closed on time.',
      where: 'DUS Lender · Bay Area, CA',
    },
    {
      quote:
        'We run 30+ multifamily transactions a year in California. Having a seismic partner who delivers in 48 hours without bottlenecks has completely eliminated the SRA delay from our closing process.',
      where: 'Freddie Mac Lender · Los Angeles',
    },
    {
      quote:
        'The quality is indistinguishable from what we were paying significantly more for. The SEL calculations are thorough and the PE stamp satisfies our legal team without question.',
      where: 'Due Diligence Firm · San Francisco',
    },
  ];
  return (
    <section id="testimonials">
      <div className="container">
        <div className="reveal">
          <div className="section-label">CLIENT FEEDBACK</div>
          <h2>What lenders and due diligence professionals say.</h2>
          <div className="testimonial-grid">
            {items.map((t, i) => (
              <div className="testimonial" key={i}>
                <div className="stars">★★★★★</div>
                <q>{t.quote}</q>
                <div className="attribution">
                  <strong>{t.where}</strong>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ── FAQ ────────────────────────────────────────────────────────────────
function FaqSection() {
  const faqs = [
    [
      'Which assessment level do I need?',
      'Level 0 is a records-based desktop screening, appropriate for owner due diligence, portfolio pre-screening, and properties below the Fannie Mae 0.15g PGA trigger. Level 1 includes a qualified Field Assessor site visit and is required for most Fannie Mae DUS, Freddie Mac, CMBS, and HUD/FHA submissions. Level 2 adds building-specific structural analysis and is recommended for high-value assets or where Level 1 SEL exceeds lender thresholds.',
    ],
    [
      'Is the report ASTM E2026-24 compliant?',
      'Yes. Every tier is prepared in accordance with ASTM E2026-24 (Standard Guide for Seismic Risk Assessment of Buildings) and ASTM E2557-24 (Standard Practice for Probable Maximum Loss Evaluations).',
    ],
    [
      'Will Fannie Mae accept a Level 0 desktop report?',
      'Level 0 is suitable for properties below the 0.15g PGA trigger and for owner pre-underwriting due diligence. Fannie Mae DUS submissions for properties above the trigger require a Level 1 SRA with Field Assessment per Form 4099.C requirements.',
    ],
    [
      'What information do I need to provide?',
      'Property address, building type, year built, square footage, and replacement cost basis. For Level 1 and Level 2, also access coordination for the site visit and any available construction documents.',
    ],
    [
      'What if the building fails the SEL threshold?',
      'SEL above 20% typically triggers an earthquake insurance requirement; SEL above 40% generally renders the property ineligible for Fannie Mae or Freddie Mac financing. Our report includes retrofit recommendations where applicable. For complex cases, the Level 2 assessment provides detailed retrofit scoping and cost-range estimates.',
    ],
    [
      'How does the 48-hour turnaround work?',
      'Level 0 reports are delivered within 48 business hours of receiving complete property data. Level 1 reports are delivered within 5 business days of site visit completion. Level 2 reports are delivered within 10 business days of receiving complete construction documents.',
    ],
    [
      'How long is the report valid?',
      'ASTM E2026-24 reports are typically considered current for 12 months from the date of issue. Most lender programs require a fresh report dated within 12 months of closing.',
    ],
    [
      'How is automation used in the report?',
      "Automation handles routine data retrieval (USGS hazard parameters, fault distances) and report formatting against ASTM E2026-24 templates. All engineering judgment, vulnerability analysis, SEL and SUL calculations, and conclusions are performed by a licensed California PE. The stamp is the engineer's responsibility.",
    ],
    [
      'Do you offer FEMA P-58 assessments?',
      'Yes. FEMA P-58 component-level analysis is included in our Level 2 Detailed Engineering Assessment tier.',
    ],
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="alt" id="faq">
      <div className="container">
        <div className="reveal">
          <div className="section-label">COMMON QUESTIONS</div>
          <h2>Frequently asked questions</h2>
          <div className="faq">
            {faqs.map(([q, a], i) => (
              <div key={i} className={`faq-item${open === i ? ' open' : ''}`}>
                <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                  <span>{q}</span>
                  <svg className="faq-icon" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
                    <line x1="7" y1="1" x2="7" y2="13" />
                    <line x1="1" y1="7" x2="13" y2="7" />
                  </svg>
                </button>
                <div className="faq-a">
                  <div className="faq-a-inner">{a}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Order Form ─────────────────────────────────────────────────────────
// ▸ FORMSPREE SETUP
//   1. Sign up at https://formspree.io (free: 50 submissions / month)
//   2. Create a new form, copy its endpoint URL
//   3. Paste it below, replacing the placeholder. Until you do, the form
//      still works but only shows the success state — nothing is emailed.
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/xwvybngk';

function OrderSection() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [form, setForm] = useState({
    name: '', company: '', email: '', phone: '',
    address: '', loanType: '', reportType: '',
    timeline: '', notes: '',
  });
  const onChange = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  // Listen for the PGA widget's "Order Report for This Address" CTA — prefill
  // the address field and bring the user back to a fresh form if they had
  // previously submitted.
  useEffect(() => {
    const onPrefill = (e) => {
      const addr = e.detail?.address;
      const tier = e.detail?.tier;
      if (!addr) return;
      setSubmitted(false);
      setForm((f) => {
        const next = { ...f, address: addr };
        // If the PGA widget told us which tier to suggest, prefill the
        // Report Type dropdown so the user doesn't have to choose again.
        if (tier === 'Level 0') {
          next.reportType = 'Level 0 Pre-Underwriting Screening (48 hours)';
        } else if (tier === 'Level 1') {
          next.reportType = 'Level 1 SRA with Field Assessment (5 business days)';
        }
        return next;
      });
      // Flash highlight the address field after the smooth scroll lands.
      setTimeout(() => {
        const el = document.getElementById('order-address');
        if (el) {
          el.focus({ preventScroll: true });
          el.classList.add('prefill-flash');
          setTimeout(() => el.classList.remove('prefill-flash'), 1400);
        }
      }, 500);
    };
    window.addEventListener('seisquake:prefill-order', onPrefill);
    return () => window.removeEventListener('seisquake:prefill-order', onPrefill);
  }, []);
  const submit = async (e) => {
    e.preventDefault();
    setSubmitError('');

    // Build a human-readable subject line so the email is easy to triage
    const subject =
      `New SeisQuake order — ${form.company || form.name || 'Unknown'} ` +
      `(${form.reportType || 'unspecified'})`;

    // If the endpoint hasn't been configured, skip the network call and
    // just show the success state (back-compat with the placeholder).
    const configured =
      FORMSPREE_ENDPOINT && !FORMSPREE_ENDPOINT.includes('YOUR_FORM_ID');
    if (!configured) {
      console.warn(
        '[SeisQuake] FORMSPREE_ENDPOINT not configured — see app.jsx. ' +
          'Showing success state without sending email.'
      );
      setSubmitted(true);
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          _subject: subject,
          _replyto: form.email,
          name: form.name,
          company: form.company,
          email: form.email,
          phone: form.phone,
          propertyAddress: form.address,
          loanType: form.loanType,
          reportType: form.reportType,
          closingTimeline: form.timeline,
          notes: form.notes,
          submittedAt: new Date().toISOString(),
        }),
      });
      if (!res.ok) {
        const txt = await res.text().catch(() => '');
        throw new Error(
          `Form service returned ${res.status}. ${txt.slice(0, 120)}`
        );
      }
      setSubmitted(true);
    } catch (err) {
      setSubmitError(
        err.message ||
          'Could not submit. Please email contact@seisquake.com directly.'
      );
    } finally {
      setSubmitting(false);
    }
  };
  if (submitted) {
    return (
      <section id="order">
        <div className="container">
          <div className="form-card" style={{ maxWidth: 560, margin: '0 auto' }}>
            <div className="form-success">
              <div className="check">✓</div>
              <h3>Order request received.</h3>
              <p style={{ color: 'var(--text)', fontSize: 15, maxWidth: 44 + 'ch', margin: '0 auto 18px' }}>
                We've logged your request and will confirm within 2 business hours
                (M–F, 8am–6pm PT). For Desktop Report orders, a Stripe checkout link
                for the 50% deposit will follow by email.
              </p>
              <button className="btn btn-ghost" onClick={() => setSubmitted(false)}>
                Submit another →
              </button>
            </div>
          </div>
        </div>
      </section>
    );
  }
  return (
    <section id="order">
      <div className="container">
        <div>
          <div className="section-label">GET STARTED</div>
          <h2>Order your report today.</h2>
          <div className="order-grid">
            <div>
              <p className="lead" style={{ fontSize: 15, marginBottom: 28 }}>
                Submit your property below. We'll confirm receipt within 2 business hours,
                pull the USGS hazard data, and put your report into the queue.
              </p>
              <ul className="trust-list">
                <li><span className="ico">⏱</span><div><strong style={{color: 'var(--heading)'}}>48 business hours</strong><br/>From receipt of complete property data</div></li>
                <li><span className="ico">⬢</span><div><strong style={{color: 'var(--heading)'}}>50% deposit via Stripe</strong><br/>Net-14 invoicing for volume clients</div></li>
                <li><span className="ico">@</span><div><strong style={{color: 'var(--heading)'}}>contact@seisquake.com</strong><br/>Direct line to the engineering desk</div></li>
                <li><span className="ico">§</span><div><strong style={{color: 'var(--heading)'}}>ASTM E2026-24</strong><br/>Fannie Mae · Freddie Mac · CMBS · HUD</div></li>
                <li><span className="ico">◆</span><div><strong style={{color: 'var(--heading)'}}>PE-stamped · E&O insured</strong><br/>Licensed structural engineer review</div></li>
              </ul>
            </div>
            <form className="form-card" onSubmit={submit}>
              <div className="field-row">
                <div className="field">
                  <label>Your Name <span className="req">*</span></label>
                  <input required value={form.name} onChange={onChange('name')} placeholder="Jane Doe" />
                </div>
                <div className="field">
                  <label>Company <span className="req">*</span></label>
                  <input required value={form.company} onChange={onChange('company')} placeholder="Acme Capital Partners" />
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Email Address <span className="req">*</span></label>
                  <input required type="email" value={form.email} onChange={onChange('email')} placeholder="jane@acmecap.com" />
                </div>
                <div className="field">
                  <label>Phone</label>
                  <input type="tel" value={form.phone} onChange={onChange('phone')} placeholder="(555) 123-4567" />
                </div>
              </div>
              <div className="field">
                <label>Property Address <span className="req">*</span></label>
                <input id="order-address" required value={form.address} onChange={onChange('address')} placeholder="1234 Mission St, San Francisco, CA 94103" />
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Loan Type <span className="req">*</span></label>
                  <select required value={form.loanType} onChange={onChange('loanType')}>
                    <option value="">Select…</option>
                    <option>Fannie Mae DUS</option>
                    <option>Freddie Mac</option>
                    <option>CMBS</option>
                    <option>HUD-FHA</option>
                    <option>Life Insurance Co.</option>
                    <option>Bridge or Bank</option>
                    <option>Other</option>
                  </select>
                </div>
                <div className="field">
                  <label>Report Type <span className="req">*</span></label>
                  <select required value={form.reportType} onChange={onChange('reportType')}>
                    <option value="">Select…</option>
                    <option>Level 0 Pre-Underwriting Screening (48 hours)</option>
                    <option>Level 1 SRA with Field Assessment (5 business days)</option>
                    <option>Level 2 Detailed Engineering Assessment (10 business days)</option>
                    <option>Portfolio (5+ properties) — request quote</option>
                    <option>Not sure — please advise</option>
                  </select>
                </div>
              </div>
              <div className="field">
                <label>Closing Timeline</label>
                <select value={form.timeline} onChange={onChange('timeline')}>
                  <option value="">Select…</option>
                  <option>Within 5 days</option>
                  <option>Within 2 weeks</option>
                  <option>Within 30 days</option>
                  <option>No hard deadline</option>
                </select>
              </div>
              <div className="field">
                <label>Additional Notes</label>
                <textarea value={form.notes} onChange={onChange('notes')} placeholder="Anything we should know — multiple properties, special compliance requirements, etc." />
              </div>
              <div className="field" style={{marginTop: 18, padding: 16, background: 'var(--accent-soft)', border: '1px solid var(--accent)', borderRadius: 6}}>
                <p style={{fontSize: 13, margin: 0, color: 'var(--text)'}}>
                  <strong style={{color: 'var(--heading)', display: 'block', marginBottom: 6}}>Refinancing in 2026?</strong>
                  Our specialized <a href="cre-refinance-pml.html" style={{color: 'var(--accent-strong)', fontWeight: 600}}>CRE Refinancing SRA service</a> delivers PE-stamped reports in 48 hours for Fannie Mae DUS, Freddie Mac, and CMBS closings.
                </p>
              </div>
              {submitError && (
                <div className="form-submit-error">
                  <strong>Couldn't submit.</strong> {submitError}
                  <div style={{ marginTop: 6, fontSize: 12 }}>
                    You can also email{' '}
                    <a href="mailto:contact@seisquake.com">contact@seisquake.com</a>{' '}
                    directly.
                  </div>
                </div>
              )}
              <button
                type="submit"
                className="btn btn-primary btn-block btn-lg"
                disabled={submitting}
              >
                {submitting ? 'Sending…' : 'Submit Order Request →'}
              </button>
              <div className="form-note">
                We respond within 2 business hours · M–F 8am–6pm PT
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Footer ─────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Wordmark onDark size={40} />
            <div className="footer-meta" style={{ marginTop: 22 }}>
              Licensed Structural Engineers · ASTM E2026-24<br />
              California PE · E&amp;O Insured
            </div>
          </div>
          <div>
            <h5>Site</h5>
            <ul>
              <li><a href="#process">How It Works</a></li>
              <li><a href="#pricing">Pricing</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#order">Contact</a></li>
            </ul>
          </div>
          <div>
            <h5>Contact</h5>
            <a href="mailto:contact@seisquake.com" style={{ color: '#fff', fontWeight: 500 }}>
              contact@seisquake.com
            </a>
            <div style={{ marginTop: 8 }}>
              <a href="tel:+15104381857" style={{ color: '#fff', fontWeight: 500 }}>
                (510) 438-1857
              </a>
            </div>
            <div style={{ marginTop: 8 }}>
              <a href="https://www.linkedin.com/company/seisquake" target="_blank" rel="noopener" style={{ color: '#fff', fontWeight: 500 }}>
                LinkedIn
              </a>
            </div>
            <div className="footer-meta" style={{ marginTop: 14 }}>
              Serving DUS lenders, CMBS originators, and multifamily professionals
              throughout California and seismic zones nationwide.
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2025 SeisQuake. All rights reserved.</div>
          <div>ASTM E2026-24 · PE-stamped · E&amp;O insured</div>
        </div>
      </div>
    </footer>
  );
}

// ── App + Tweaks ───────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "waveformOpacity": 0.55,
  "monoNumbers": true
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();

  // Apply theme + tweak-driven CSS vars
  useEffect(() => {
    document.documentElement.dataset.theme = t.theme;
    // Override the per-theme waveform opacity with the tweak value
    document.documentElement.style.setProperty('--waveform-opacity', String(t.waveformOpacity));
  }, [t.theme, t.waveformOpacity]);

  return (
    <>
      <Nav />
      <main>
        <Hero />
        <WhyNowSection />
        <FastTrackBand />
        <PgaSection />
        <ProblemSection />
        <ScopeSection />
        <ProcessSection />
        <AutomationSection />
        <PricingSection />
        <ComplianceSection />
        <AboutSection />
        <TrustBandSection />
        <TestimonialsSection />
        <FaqSection />
        <OrderSection />
      </main>
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio
            label="Variant"
            value={t.theme}
            options={[{ value: 'dark', label: 'Dark' }, { value: 'light', label: 'Light' }]}
            onChange={(v) => setTweak('theme', v)}
          />
        </TweakSection>
        <TweakSection label="Hero waveform">
          <TweakSlider
            label="Opacity"
            value={Math.round(t.waveformOpacity * 100)}
            min={0} max={60} step={1} unit="%"
            onChange={(v) => setTweak('waveformOpacity', v / 100)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
