/* Stratum Leads — Marketing website (public homepage).
   Landing-page redesign: presentational sections use classNames from ./marketing.css
   (ported from the approved design artifact). The sign-up / sign-in flows further
   down are the live Supabase auth path — do not rewire them casually. */
const M = window.StratumLeadsDesignSystem_6367ed;
const { Button, Field, Checkbox } = M;
const I = (n, s) => <i data-lucide={n} style={s}></i>;
const refresh = () => requestAnimationFrame(() => window.lucide && window.lucide.createIcons({ attrs: { "stroke-width": 1.9 } }));

const CONTACT = {
  address1: "1629 K St NW, Suite 300",
  address2: "Washington, DC 20006",
  phone: "(202) 643-6467",
  phoneHref: "tel:+12026436467",
  email: "support@stratumleads.com",
};

/* ====================== Marketing page (design artifact port) ====================== */

/* Inline SVG icon sprite — every marketing icon references these via <use href="#s-..."/>. */
function IconDefs() {
  return (
    <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden="true"><defs>
      <g id="s-check"><path d="M5 12.5 10 17.5 19 6.5" /></g>
      <g id="s-arrow"><path d="M5 12h13M13 6l6 6-6 6" /></g>
      <g id="s-shield"><path d="M12 3 20 6v5c0 5-3.4 8.5-8 10-4.6-1.5-8-5-8-10V6z" /><path d="M9 12l2 2 4-4" /></g>
      <g id="s-spark"><path d="M12 3v6M12 15v6M3 12h6M15 12h6M6 6l3 3M15 15l3 3M18 6l-3 3M9 15l-3 3" /></g>
      <g id="s-gavel"><path d="M14 3.5 20.5 10 18 12.5 11.5 6z" /><path d="M12 7.5 5.5 14l2.5 2.5L14.5 10" /><path d="M4 20.5h8" /></g>
      <g id="s-users"><circle cx="9" cy="8" r="3.1" /><path d="M3.6 19a5.6 5.6 0 0 1 10.8 0" /><path d="M16 5.4a3 3 0 0 1 0 5.9" /><path d="M17.4 19a5.6 5.6 0 0 0-2.2-4.3" /></g>
      <g id="s-msg"><path d="M4 5.5h16a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H9.5L5.5 20v-3.9H4a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1Z" /></g>
      <g id="s-brief"><rect x="3" y="7.5" width="18" height="12.5" rx="2.2" /><path d="M8 7.5V6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1.5" /><path d="M3 12.5h18" /></g>
      <g id="s-pen"><path d="M4 20h16" /><path d="M14.5 4.5 19.5 9.5 9 20 4 20 4 15z" /></g>
      <g id="s-cash"><rect x="2.5" y="6" width="19" height="12" rx="2" /><circle cx="12" cy="12" r="2.6" /><path d="M6 9v6M18 9v6" /></g>
      <g id="s-mega"><path d="M4 10v4a1 1 0 0 0 1 1h2.3L16 19V5L7.3 9H5a1 1 0 0 0-1 1Z" /><path d="M19 9.2a3 3 0 0 1 0 5.6" /></g>
      <g id="s-coins"><circle cx="9.5" cy="9.5" r="5" /><path d="M15 5.2a5 5 0 0 1 0 9.2" /></g>
      <g id="s-route"><circle cx="6" cy="18" r="2.4" /><circle cx="18" cy="6" r="2.4" /><path d="M8.4 18H14a4 4 0 0 0 0-8H8" /></g>
      <g id="s-chart"><path d="M4 20V4" /><path d="M4 20h16" /><rect x="7.5" y="12" width="3" height="5" /><rect x="12.5" y="8" width="3" height="9" /><rect x="17.5" y="5" width="3" height="12" /></g>
      <g id="s-brand"><circle cx="12" cy="12" r="8.5" /><path d="M12 8.5 13.2 11l2.8.2-2.1 1.8.7 2.7-2.6-1.5-2.6 1.5.7-2.7L8.7 11.2 11.5 11z" /></g>
      <g id="s-x"><path d="M6 6l12 12M18 6 6 18" /></g>
      <g id="s-pin"><path d="M12 21s7-5.5 7-11a7 7 0 0 0-14 0c0 5.5 7 11 7 11Z" /><circle cx="12" cy="10" r="2.6" /></g>
      <g id="s-phone"><path d="M6 3.5 9 4l1 4.5-2 1.5a11 11 0 0 0 5 5l1.5-2 4.5 1 .5 3a2 2 0 0 1-2 2A16 16 0 0 1 4 5.5a2 2 0 0 1 2-2Z" /></g>
      <g id="s-mail"><rect x="3" y="5.5" width="18" height="13" rx="2" /><path d="m4 7 8 6 8-6" /></g>
      <g id="s-flag"><path d="M5 21V4M5 4h11l-2 3.5L16 11H5" /></g>
      <g id="s-list"><path d="M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01" /></g>
      <g id="s-layers"><path d="M12 3 21 8l-9 5-9-5 9-5Z" /><path d="m3 13 9 5 9-5" /></g>
    </defs></svg>
  );
}

/* Sprite icon: <S id="check" size={16} sw={2.2} /> → <svg><use href="#s-check"/></svg> */
const S = ({ id, size = 17, sw = 2, className }) => (
  <svg className={className} width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"><use href={"#s-" + id} /></svg>
);

const BrandMark = ({ size = 28 }) => (
  <svg width={size} height={size} viewBox="0 0 100 100" aria-hidden="true"><rect width="100" height="100" rx="24" fill="#4f22f2" /><path d="M50 26 74 70 26 70Z" fill="none" stroke="#fff" strokeWidth="8" strokeLinejoin="round" strokeLinecap="round" /></svg>
);

const FrameTop = ({ url }) => (
  <div className="top">
    <span className="d" style={{ background: "#e4788a" }} />
    <span className="d" style={{ background: "#f2c14e" }} />
    <span className="d" style={{ background: "#57c98a" }} />
    {url && <span className="u">{url}</span>}
  </div>
);

function Nav({ onSignup, onSignin }) {
  return (
    <nav className="bar">
      <div className="wrap">
        <div className="brand">
          <BrandMark />
          <span className="word">STRATUM <b>LEADS</b></span>
        </div>
        <div className="navlinks">
          <a href="#deals">Deals</a>
          <a href="#how">How it works</a>
          <a href="#save">What it replaces</a>
          <a href="#pricing">Pricing</a>
          <a href="#teams">For teams</a>
        </div>
        <div className="navcta">
          <a className="btn btn-s" onClick={() => onSignin()}>Sign in</a>
          <a className="btn btn-p" onClick={() => onSignup("Beta")}>Sign Up</a>
        </div>
      </div>
    </nav>
  );
}

function Hero({ onSignup, onDemo }) {
  return (
    <header className="hero">
      <div className="herobg"><img src="/site/marketing-assets/hero-agent-clients.jpg" alt="A real-estate agent shaking hands with a happy couple after closing" /></div>
      <div className="heroveil" />
      <div className="inner"><div className="col">
        <p className="eyebrow">Exclusive leads · won at auction</p>
        <h1 className="head">You win the lead.<br />You <span className="hl">own</span> it. No one else gets the call.</h1>
        <p className="lede">Win exclusive, enriched property leads at auction — then run every deal to close in one workspace that replaces your CRM, dialer, e-sign, and invoicing.</p>
        <div className="herocta">
          <a className="btn btn-p" onClick={() => onSignup("Beta")}>Sign Up<S id="arrow" size={17} /></a>
          <a className="btn btn-onphoto" onClick={() => onDemo()}>Book a team demo</a>
        </div>
        <div className="truststrip">
          <span><S className="ic" id="check" size={16} sw={2.2} />Exclusive — never resold</span>
          <span><S className="ic" id="check" size={16} sw={2.2} />Enriched before you dial</span>
          <span><S className="ic" id="check" size={16} sw={2.2} />Replaces ~$500/mo of tools</span>
        </div>
      </div></div>
    </header>
  );
}

function PhotoBand() {
  return (
    <section className="photoband">
      <img className="bg" src="/site/marketing-assets/aerial-neighborhood.jpg" alt="Aerial view of a residential neighborhood" />
      <div className="veil" />
      <div className="inner2">
        <p className="eyebrow">Nationwide coverage</p>
        <h2>Exclusive, verified leads in the neighborhoods you work.</h2>
        <p>Every county, every trigger — pre-foreclosure, tax-delinquent, probate, and more. Won at auction, yours alone.</p>
      </div>
    </section>
  );
}

function SaveSection() {
  const stack = [
    ["Real-estate CRM", "$50–115/mo"],
    ["Power dialer + SMS", "$150–350/mo"],
    ["Email marketing", "$30–100/mo"],
    ["E-signature", "$25–45/mo"],
    ["Invoicing + payments", "$30–70/mo"],
    ["Skip-trace + data", "$60–100/mo"],
  ];
  return (
    <section className="band" id="save"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">One workspace, not seven tabs</p>
        <h2>Cancel the stack that never talked to each other.</h2>
        <p className="sub">Your CRM, power dialer, texting, email marketing, e-sign, invoicing, and lead vendor — one login, one bill, and every lead already inside it.</p>
      </div>
      <div className="consol">
        <div className="stacklist">
          {stack.map(([name, cost]) => (
            <div className="stackrow" key={name}><span className="l"><span className="x"><S id="x" size={13} sw={2.2} /></span>{name}</span><span className="cost">{cost}</span></div>
          ))}
        </div>
        <div className="savecard">
          <div className="cap">Tools consolidated</div>
          <div className="big"><em>~$550–750</em></div>
          <div className="u">per month, gone — roughly <b style={{ color: "#fff" }} className="mono">$6,600–9,000</b> a year</div>
          <div className="row"><span>Closer plan</span><b>$149/mo</b></div>
          <div className="row" style={{ border: 0, paddingTop: 8, marginTop: 8 }}><span>You keep</span><b style={{ color: "#4fe0b0" }}>5–8 hrs / week</b></div>
        </div>
      </div>
    </div></section>
  );
}

function WhySection() {
  return (
    <section id="why"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">The part competitors can't copy</p>
        <h2>Exclusive leads, enriched before you dial.</h2>
        <p className="sub">Anyone can sell you a CRM. Only Stratum sources the lead — won at auction, yours alone, and already researched so you call warm and informed.</p>
      </div>
      <div className="whysplit">
        <div className="frame"><img src="/site/marketing-assets/home-exterior.jpg" alt="A sunny suburban home with the owner out front" /></div>
        <div className="diffcol">
          <div className="diffcard">
            <div className="icn"><S id="gavel" size={23} sw={1.8} /></div>
            <h3>Exclusive — you set the pace</h3>
            <p>Win a lead at auction and it's yours alone. No racing five other agents to a seller who's already annoyed. You're the only call.</p>
            <span className="stat"><S id="spark" size={17} />Worth 3–5× a shared lead</span>
          </div>
          <div className="diffcard">
            <div className="icn"><S id="shield" size={23} sw={1.8} /></div>
            <h3>Enriched — skip the skip-trace</h3>
            <p>Every lead lands with owner detail, valuation, equity, and a motivation score — and drops straight into your pipeline as a deal. No CSV imports, no manual research.</p>
            <span className="stat"><S id="spark" size={17} />Saves 2–4 hrs per batch</span>
          </div>
        </div>
      </div>
    </div></section>
  );
}

function DealsSection() {
  const caps = [
    ["layers", "A workflow for every property", "Phased playbooks — Distressed, Probate, Tax-Delinquent, Wholesale — each with % complete and target close."],
    ["users", "Assign the whole team", "Owner, transaction coordinator, title, escrow, dispositions — each with one-tap call and email."],
    ["list", "Tasks, requirements & schedule", "Track what's done and what's next on every deal, with next-best-action guidance."],
    ["flag", "Flag blockers before they kill it", "Surface risks like a redemption deadline the moment they appear — nothing slips."],
    ["pen", "Documents, e-sign & invoices inside the deal", "Upload, send for signature with ordered signers, and invoice — without leaving the property."],
  ];
  return (
    <section className="band" id="deals"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">Deals &amp; Transactions</p>
        <h2>Every deal gets its own command center.</h2>
        <p className="sub">The project manager you'd otherwise cobble together in Asana or Monday — except it's built for property deals and already knows your lead, your contacts, your documents, and your team.</p>
      </div>
      <div className="spotlight">
        <div>
          <div className="caps">
            {caps.map(([ic, t, d]) => (
              <div className="cap-row" key={ic}><span className="ci"><S id={ic} size={18} sw={1.8} /></span><span><b>{t}</b>{d}</span></div>
            ))}
          </div>
        </div>
        <div className="frame">
          <FrameTop url="app.stratumleads.com/deals" />
          <img src="/site/marketing-assets/app-deals.jpg" alt="A property deal with phase stepper, assigned team, blockers, and next-best action" width="1300" height="690" />
        </div>
      </div>
    </div></section>
  );
}

function HowSection() {
  const steps = [
    ["01", "gavel", "Find & win", "Marketplace + live auctions for exclusive, verified leads.", "tc-h", "Hunter"],
    ["02", "users", "Organize", "Leads, contacts, and properties in your Relationships CRM.", "tc-h", "Hunter"],
    ["03", "msg", "Talk to them", "Call, text, and email from the lead — logged automatically.", "tc-c", "Closer"],
    ["04", "brief", "Run the deal", "A project workspace per property — tasks, team, blockers.", "tc-c", "Closer"],
    ["05", "cash", "Close & get paid", "E-sign documents, then invoice — deposited to your bank.", "tc-c", "Closer"],
    ["06", "mega", "Market at scale", "Campaigns, automated workflows, and QR landing pages.", "tc-r", "Rainmaker"],
  ];
  return (
    <section id="how"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">Won lead → signed contract → paid invoice</p>
        <h2>The whole deal, without switching tabs.</h2>
        <p className="sub">Every stage lives in one workspace — and each plan unlocks the next stretch of the journey.</p>
      </div>
      <div className="journey">
        {steps.map(([n, ic, t, d, tc, tier]) => (
          <div className="step" key={n}>
            <div className="n">{n}</div>
            <div className="si"><S id={ic} size={19} sw={1.8} /></div>
            <h4>{t}</h4><p>{d}</p>
            <span className={"tchip " + tc}>{tier}</span>
          </div>
        ))}
      </div>
    </div></section>
  );
}

function TourSection() {
  const shots = [
    ["/site/marketing-assets/app-pipeline.jpg", "Lead pipeline with stages and Stratum Score", "list", "Pipeline — list, cards, or Kanban"],
    ["/site/marketing-assets/app-contact.jpg", "Contact card with call, email, SMS, schedule, and invoice actions", "msg", "Call, text, email, invoice — in one place"],
    ["/site/marketing-assets/app-campaigns.jpg", "Marketing campaigns with a media library", "mega", "Marketing campaigns + workflows"],
  ];
  return (
    <section className="band" id="tour"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">See it in action</p>
        <h2>One clean workspace for the whole business.</h2>
      </div>
      <div className="gallery">
        {shots.map(([src, alt, ic, cap]) => (
          <div className="gcard" key={src}>
            <div className="frame"><FrameTop /><img src={src} alt={alt} width="1000" height="520" /></div>
            <div className="cardcap"><S id={ic} size={16} />{cap}</div>
          </div>
        ))}
      </div>
    </div></section>
  );
}

function CloseSection() {
  return (
    <section id="close"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">The close</p>
        <h2>Sign, fund, and get paid — right where you found the lead.</h2>
      </div>
      <div className="twoup">
        <figure className="pfig"><div className="frame"><img src="/site/marketing-assets/signing-contract.jpg" alt="Client signing a contract" /></div><figcaption>E-sign contracts with ordered signers — no separate DocuSign tab.</figcaption></figure>
        <figure className="pfig"><div className="frame"><img src="/site/marketing-assets/keys-close.jpg" alt="Handing over the keys to a new home" /></div><figcaption>Invoice and collect through Stratum — funds land in your bank.</figcaption></figure>
      </div>
    </div></section>
  );
}

function Pricing({ onSignup }) {
  const betaFeats = ["Marketplace + live auctions", "Enriched leads + Stratum Score", "Daily Free Strata", "New features first", "Founding pricing, locked in"];
  return (
    <section id="pricing"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">Pricing</p>
        <h2>Start free. Upgrade as you close.</h2>
        <p className="sub">Join the beta today at founding-member pricing. The full Hunter, Closer, and Rainmaker plans launch soon — here's what's coming.</p>
      </div>
      <div className="betacard">
        <div>
          <span className="live"><span className="livedot" />Live now · Limited beta</span>
          <h3>Beta Tester</h3>
          <p className="bt">Full early access while we build. Lock in founding-member pricing, get a direct line to our team, and help shape every tier before it launches.</p>
          <div className="betafeats">
            {betaFeats.map((f) => <span key={f}><S id="check" size={16} sw={2.2} />{f}</span>)}
          </div>
        </div>
        <div className="betaright">
          <div className="price"><span className="amt">$19</span><span className="per">/mo</span></div>
          <a className="btn btn-p" onClick={() => onSignup("Beta")}>Become a beta tester<S id="arrow" size={16} /></a>
          <span className="spots">Limited spots · first ~2 months</span>
        </div>
      </div>
      <p className="coming-label">Full plans — launching soon</p>
      <div className="plans">
        <div className="plan">
          <div className="pt"><span className="chip tc-h">Hunter</span></div>
          <div className="price"><span className="amt">$49</span><span className="per">/mo</span></div>
          <p className="tag">Find and win exclusive leads, and organize them in your CRM.</p>
          <ul>
            {["Auction access + Marketplace", "Enriched leads + Stratum Score", "Daily Free Strata", "Relationships CRM"].map((f) => <li key={f}><S id="check" size={17} sw={2.2} />{f}</li>)}
          </ul>
          <div className="addon"><S id="msg" size={16} /><span>Add <b>Communications</b> — $25/mo + usage</span></div>
          <span className="btn btn-soon" style={{ justifyContent: "center" }}>Coming soon</span>
        </div>
        <div className="plan feat">
          <span className="popchip">Most popular</span>
          <div className="pt"><span className="chip tc-c">Closer</span></div>
          <div className="price"><span className="amt">$149</span><span className="per">/mo</span></div>
          <p className="tag">Everything you need to work a deal from first call to paid invoice.</p>
          <ul>
            {["Everything in Hunter", "Communications — calls, SMS, email, calendar", "Deals & Transactions — projects, e-sign, invoices", "Included messaging allowance"].map((f) => <li key={f}><S id="check" size={17} sw={2.2} />{f}</li>)}
          </ul>
          <div className="addon"><S id="mega" size={16} /><span>Add <b>Marketing</b> — $20/mo + usage</span></div>
          <span className="btn btn-soon" style={{ justifyContent: "center" }}>Coming soon</span>
          <p className="strata-note">Messaging beyond your monthly allowance is billed in Strata — no surprise per-seat invoices.</p>
        </div>
        <div className="plan">
          <div className="pt"><span className="chip tc-r">Rainmaker</span></div>
          <div className="price"><span className="amt">$349</span><span className="per">/mo + seats</span></div>
          <p className="tag">Market at scale and run a team on one bill and one brand.</p>
          <ul>
            {["Everything in Closer", "Marketing — campaigns, workflows, QR pages", "Seats & tenant management", "Shared wallet with per-seat budgets"].map((f) => <li key={f}><S id="check" size={17} sw={2.2} />{f}</li>)}
          </ul>
          <span className="btn btn-soon" style={{ justifyContent: "center" }}>Coming soon</span>
          <p className="strata-note">Marketing sends beyond your allowance are billed in Strata.</p>
        </div>
      </div>
    </div></section>
  );
}

function Teams({ onDemo }) {
  const feats = [
    ["route", "Lead routing", "Auction wins flow to the right agent."],
    ["chart", "Team roll-ups", "Every pipeline and metric on one screen."],
    ["brand", "Brand control", "Locked templates and shared assets."],
    ["coins", "Shared wallet", "Per-agent Strata budgets and caps."],
  ];
  return (
    <section className="teams" id="teams"><div className="wrap"><div className="grid">
      <div>
        <p className="eyebrow">For brokers &amp; teams</p>
        <h2>Stop buying leads and a CRM. Get both — for the whole team.</h2>
        <p className="sub">Give every agent exclusive, enriched leads and one workspace to close them — on your brand, your bill. One platform instead of five subscriptions.</p>
        <div className="feats">
          {feats.map(([ic, t, d]) => (
            <div className="f" key={ic}><S id={ic} size={20} sw={1.8} /><span><b>{t}</b><span>{d}</span></span></div>
          ))}
        </div>
      </div>
      <div className="quote">
        <div className="est">Team estimate · 15 agents</div>
        <div className="n">$1,500<small> – $1,900/mo</small></div>
        <div className="u">Base includes 5 seats · ~$89/seat after · annual saves 2 months</div>
        <a className="btn btn-p" onClick={() => onDemo()}>Book a team demo<S id="arrow" size={16} /></a>
        <p className="fine">Replaces ~$1,500–3,000/mo of team tooling — CRM, transaction mgmt, e-sign, dialer, and marketing.</p>
      </div>
    </div></div></section>
  );
}

function Proof() {
  const stats = [
    ["3–5×", "Value of an exclusive lead vs a shared one"],
    ["5–8 hrs", "Saved per week on tools + research"],
    ["7→1", "Subscriptions collapsed into one"],
    ["$0", "To start — free daily Strata included"],
  ];
  return (
    <section id="proof"><div className="wrap">
      <div className="sec-head center">
        <p className="eyebrow">Why agents stay</p>
        <h2>Better leads, less busywork, more closings.</h2>
      </div>
      <div className="proof">
        {stats.map(([n, l]) => <div className="pstat" key={l}><div className="n">{n}</div><div className="l">{l}</div></div>)}
      </div>
    </div></section>
  );
}

function FinalCta({ onSignup, onDemo }) {
  return (
    <section className="final"><div className="wrap">
      <div className="box">
        <h2>Your next exclusive lead is up for auction.</h2>
        <p>Create a free account, claim your Daily Free Strata, and win your first enriched lead today.</p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <a className="btn btn-p" onClick={() => onSignup("Beta")}>Sign Up</a>
          <a className="btn btn-s" onClick={() => onDemo()}>Book a team demo</a>
        </div>
      </div>
    </div></section>
  );
}

function Footer({ onContact }) {
  return (
    <footer><div className="wrap">
      <div className="foot">
        <div className="col">
          <div className="brand"><BrandMark size={26} /><span className="word">STRATUM <b>LEADS</b></span></div>
          <p>Exclusive, enriched real-estate leads and the workspace to close them — for agents, investors, and teams.</p>
        </div>
        <div className="col">
          <h5>Product</h5>
          <a href="#deals">Deals &amp; Transactions</a>
          <a href="#how">How it works</a>
          <a href="#save">What it replaces</a>
          <a href="#pricing">Pricing</a>
          <a href="#teams">For teams</a>
        </div>
        <div className="col">
          <h5>Contact</h5>
          <address><S id="pin" size={16} sw={1.8} /><span>{CONTACT.address1}<br />{CONTACT.address2}</span></address>
          <a href={CONTACT.phoneHref}><S id="phone" size={16} sw={1.8} />{CONTACT.phone}</a>
          <a onClick={onContact} role="button" tabIndex={0} style={{ cursor: "pointer" }}><S id="mail" size={16} sw={1.8} />Contact us</a>
        </div>
      </div>
      <div className="footbar"><span>© 2026 Stratum Leads. All rights reserved.</span><span>Terms · Privacy</span></div>
    </div></footer>
  );
}

/* ============================ Sign-up workflow ============================ */
const PLAN_INFO = {
  Beta: { price: "$19/mo", tag: "All features as we ship them" },
  Launch: { price: "$49/mo", tag: "Start buying verified leads" },
  Scale: { price: "$149/mo", tag: "Higher volume and bid readiness" },
  Broker: { price: "Custom", tag: "Team access when seats are enabled" },
};

function OtpInput({ value, onChange, length = 6, autoFocus }) {
  const refs = React.useRef([]);
  React.useEffect(() => {if (autoFocus && refs.current[0]) refs.current[0].focus();}, [autoFocus]);
  const digits = Array.from({ length }, (_, i) => value[i] || "");
  const setAt = (i, raw) => {
    const d = raw.replace(/\D/g, "");
    if (d.length > 1) {
      const merged = (value.slice(0, i) + d).slice(0, length);
      onChange(merged);
      const f = Math.min(i + d.length, length - 1);
      if (refs.current[f]) refs.current[f].focus();
      return;
    }
    const arr = value.padEnd(length).split("");
    arr[i] = d;
    const joined = arr.join("").replace(/\s/g, "").slice(0, length);
    onChange(joined);
    if (d && i < length - 1 && refs.current[i + 1]) refs.current[i + 1].focus();
  };
  const onKey = (i, e) => {if (e.key === "Backspace" && !value[i] && i > 0 && refs.current[i - 1]) refs.current[i - 1].focus();};
  return (
    <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
      {digits.map((d, i) =>
      <input key={i} ref={(el) => refs.current[i] = el} value={d} inputMode="numeric" maxLength={i === 0 ? length : 1} aria-label={`Digit ${i + 1}`}
        onChange={(e) => setAt(i, e.target.value)} onKeyDown={(e) => onKey(i, e)}
        style={{ width: 46, height: 54, textAlign: "center", fontSize: 22, fontWeight: 800, fontFamily: "var(--font-mono)", borderRadius: "var(--radius-sm)", border: "1.5px solid " + (d ? "var(--accent)" : "var(--border)"), background: "var(--surface)", color: "var(--text)", outline: "none" }} />
      )}
    </div>);

}

function Resend({ onResend }) {
  const [secs, setSecs] = React.useState(30);
  React.useEffect(() => {if (secs <= 0) return;const t = setTimeout(() => setSecs((s) => s - 1), 1000);return () => clearTimeout(t);}, [secs]);
  if (secs > 0) return <span style={{ fontSize: 13, color: "var(--text-subtle)" }}>Resend code in {secs}s</span>;
  return <button onClick={() => {setSecs(30);onResend && onResend();}} style={{ border: "none", background: "transparent", color: "var(--accent)", fontSize: 13, fontWeight: 700, cursor: "pointer", padding: 0 }}>Resend code</button>;
}

const STEPS = ["Account", "Email", "Subscription", "Done"];
const US_STATES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"];

// Password input with a show/hide eye toggle. The design-system Field hard-codes its input padding
// and has no trailing slot, so we mirror its styling here (left lock icon, focus ring, hint/error)
// and add an eye button on the right that flips the input type between password and text.
function PasswordField({ label, value, onChange, error, hint, placeholder }) {
  const [show, setShow] = React.useState(false);
  const [focus, setFocus] = React.useState(false);
  React.useEffect(() => {refresh();});
  const controlStyle = {
    width: "100%", minHeight: "var(--control-h)", padding: "0 42px 0 38px",
    borderRadius: "var(--radius-sm)", border: "1px solid",
    borderColor: error ? "var(--danger)" : focus ? "var(--accent)" : "var(--border)",
    background: "var(--surface)", color: "var(--text)", fontFamily: "var(--font-sans)",
    fontSize: "var(--text-base)", outline: "none",
    boxShadow: focus ? "0 0 0 3px var(--focus-ring)" : "none",
    transition: "border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard)",
  };
  return (
    <label style={{ display: "grid", gap: 6 }}>
      {label && <span style={{ fontSize: "var(--text-sm)", fontWeight: "var(--weight-semibold)", color: "var(--text)" }}>{label}</span>}
      <span style={{ position: "relative", display: "block" }}>
        <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-subtle)", display: "grid", pointerEvents: "none" }}>{I("lock", { width: 16 })}</span>
        <input type={show ? "text" : "password"} value={value} onChange={onChange} placeholder={placeholder}
          style={controlStyle} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} />
        <button type="button" onClick={() => setShow((s) => !s)} tabIndex={-1}
          aria-label={show ? "Hide password" : "Show password"} title={show ? "Hide password" : "Show password"}
          style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)", display: "grid", placeItems: "center", width: 32, height: 32, border: "none", background: "transparent", color: "var(--text-subtle)", cursor: "pointer", borderRadius: "var(--radius-sm)", padding: 0 }}>
          {/* Render both icons once (hydrated at mount) and toggle visibility — avoids relying on a
              per-click lucide re-hydration. */}
          <span style={{ display: show ? "none" : "grid" }}>{I("eye", { width: 16 })}</span>
          <span style={{ display: show ? "grid" : "none" }}>{I("eye-off", { width: 16 })}</span>
        </button>
      </span>
      {(hint || error) && <span style={{ fontSize: "var(--text-xs)", color: error ? "var(--danger)" : "var(--text-muted)" }}>{error || hint}</span>}
    </label>
  );
}

// Standalone checkout kick-off. Reads the pending plan from localStorage (set at signup) so it works
// from every entry point: an immediate-session signup, the user landing back signed-in after they
// confirm their email (resume), and a returning user signing in with a plan still pending. Both
// success and cancel return to the apex, where the front-door script clears the pending flag.
async function beginCheckout() {
  if (!window.__sb) return { ok: false, error: "no-client" };
  const plan = (window.localStorage.getItem("stratum_pending_checkout") || "beta").toLowerCase();
  const { data: { session } } = await window.__sb.auth.getSession();
  if (!session) return { ok: false, error: "not-signed-in" };
  const origin = window.location.origin;
  const { data, error } = await window.__sb.functions.invoke("create-checkout-session", {
    body: {
      plan,
      success_url: origin + "/?checkout=success",
      cancel_url: origin + "/?checkout=cancelled",
    },
  });
  if (error || !data || !data.url) return { ok: false, error: "checkout-failed" };
  window.location.href = data.url;
  return { ok: true };
}

function SignupFlow({ plan, onClose, onSwitchToSignin }) {
  const [step, setStep] = React.useState(0); // 0 = account form, 1 = redirecting to checkout, 2 = confirm email
  const [form, setForm] = React.useState({ code: "", firstName: "", lastName: "", email: "", phone: "", mlsId: "", licenseState: "", password: "", agree: false });
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => {refresh();});
  React.useEffect(() => {const onKey = (e) => e.key === "Escape" && onClose();window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, []);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  // Kick the (already signed-in) user into Stripe Checkout for the chosen plan.
  async function goToCheckout() {
    window.localStorage.setItem("stratum_pending_checkout", (plan || "beta").toLowerCase());
    const res = await beginCheckout();
    if (!res.ok) {
      setErrors({ auth: res.error === "not-signed-in" ? "Please sign in to continue to checkout." : "Could not start checkout. Please try again." });
      setStep(0);
    }
  }

  const submitAccount = async () => {
    const err = {};
    // Invite gate — sign-ups are locked during beta. The REAL enforcement is the BEFORE INSERT
    // trigger on auth.users (migration 0045); the code below is only a pre-flight so the user gets
    // an inline "that code isn't valid" instead of the opaque "Database error saving new user"
    // GoTrue returns when the trigger raises. Never treat this check as the gate.
    if (!form.code.trim()) err.code = "Enter your invite code. Sign-ups are invite-only during beta.";
    if (!form.firstName.trim()) err.firstName = "Enter your first name.";
    if (!form.lastName.trim()) err.lastName = "Enter your last name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) err.email = "Enter a valid email address.";
    if (form.phone.replace(/\D/g, "").length < 10) err.phone = "Enter a valid phone number.";
    if (!form.mlsId.trim()) err.mlsId = "Enter your MLS agent number.";
    if (!form.licenseState) err.licenseState = "Select your license state.";
    if (form.password.length < 8) err.password = "Use at least 8 characters.";
    if (!form.agree) err.agree = "Please accept the terms to continue.";
    // Only spend a round-trip on the code once every local check passes.
    if (!Object.keys(err).length && window.__sb) {
      setBusy(true);
      const { data: codeOk, error: codeErr } = await window.__sb.rpc("check_invite_code", { p_code: form.code.trim() });
      setBusy(false);
      // On a network/RPC failure, say nothing and let the trigger be the judge — a flaky pre-flight
      // must never be the reason a valid invite is turned away.
      if (!codeErr && codeOk === false) err.code = "That invite code isn't valid. Sign-ups are invite-only during beta.";
    }
    setErrors(err);
    if (Object.keys(err).length) return;
    setBusy(true);
    // Real Supabase sign-up. The 0017 trigger provisions a tenant in the same transaction,
    // so create-checkout-session won't 403 on "no tenant". invite_code rides along in options.data
    // (→ raw_user_meta_data) where the 0045 trigger reads it.
    const { data, error } = await window.__sb.auth.signUp({
      email: form.email.trim(),
      password: form.password,
      options: { data: { full_name: (form.firstName.trim() + " " + form.lastName.trim()).trim(), first_name: form.firstName.trim(), last_name: form.lastName.trim(), phone: form.phone.trim(), mls_id: form.mlsId.trim(), license_state: form.licenseState, invite_code: form.code.trim() }, emailRedirectTo: window.location.origin + "/" },
    });
    setBusy(false);
    if (error) { setErrors({ auth: error.message }); return; }
    // Remember the chosen plan so checkout can resume after the user confirms their email and returns
    // signed-in (picked up by the front-door script + the resume effect in Site).
    window.localStorage.setItem("stratum_pending_checkout", (plan || "beta").toLowerCase());
    if (data && data.session) { setStep(1); goToCheckout(); }   // signed in immediately → straight to payment
    else { setStep(2); }                                        // project requires email confirmation first
  };

  const headerIcon = { 0: "user-plus", 1: "credit-card", 2: "mail-check" }[step];
  const activeStage = step === 0 ? 0 : step === 2 ? 1 : 2; // 0 account · 1 email confirm · 2 subscription

  const overlay = { position: "fixed", inset: 0, zIndex: 100, background: "rgba(16,22,38,0.62)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20, overflowY: "auto" };
  const cardStyle = { width: "min(468px, 100%)", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", overflow: "hidden", margin: "auto" };
  const bodyPad = { padding: "26px 30px 30px" };

  return (
    <div style={overlay} onClick={onClose}>
      <div style={cardStyle} onClick={(e) => e.stopPropagation()}>
        {/* Header + progress */}
        <div style={{ padding: "20px 30px 0", position: "relative" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
            <span style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: "var(--radius-md)", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(headerIcon, { width: 20 })}</span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800 }}>Create your account</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{plan ? `${plan} plan · ${PLAN_INFO[plan] ? PLAN_INFO[plan].price : ""}` : "Stratum Leads"}</div>
            </div>
          </div>
          {/* Stepper */}
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
            {STEPS.map((s, i) => {
              const done = i < activeStage;
              const on = i === activeStage;
              return (
                <React.Fragment key={s}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                    <span style={{ width: 22, height: 22, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: "50%", fontSize: 11, fontWeight: 800, background: done ? "var(--accent)" : on ? "var(--accent-soft)" : "var(--surface-sunken)", color: done ? "#fff" : on ? "var(--accent)" : "var(--text-subtle)", border: on ? "1.5px solid var(--accent)" : "none" }}>{done ? I("check", { width: 12 }) : i + 1}</span>
                    <span style={{ fontSize: 12, fontWeight: 700, color: on ? "var(--text)" : "var(--text-subtle)" }}>{s}</span>
                  </div>
                  {i < STEPS.length - 1 && <span style={{ flex: 1, height: 2, borderRadius: 2, background: i < activeStage ? "var(--accent)" : "var(--border)" }} />}
                </React.Fragment>);

            })}
          </div>
        </div>

        <div style={{ height: 1, background: "var(--border)", margin: "18px 0 0" }} />

        {/* Step 0 — Account */}
        {step === 0 &&
        <div style={bodyPad}>
            {plan && PLAN_INFO[plan] &&
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "12px 14px", borderRadius: "var(--radius-md)", background: "var(--surface-subtle)", border: "1px solid var(--border)", marginBottom: 18 }}>
                <div><strong style={{ fontSize: 14 }}>{plan}</strong><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{PLAN_INFO[plan].tag}</div></div>
                <strong style={{ fontSize: 15, fontFamily: "var(--font-mono)" }}>{PLAN_INFO[plan].price}</strong>
              </div>}
            <div style={{ display: "grid", gap: 14 }}>
              {/* TEMPORARY invite gate — remove with the code check in submitAccount when beta opens up. */}
              <Field label="Invite code" placeholder="Enter your invite code" icon={I("ticket", { width: 16 })} value={form.code} onChange={set("code")} error={errors.code} hint={!errors.code ? "Stratum Leads is invite-only during beta." : undefined} />
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="First name" placeholder="Jordan" icon={I("user", { width: 16 })} value={form.firstName} onChange={set("firstName")} error={errors.firstName} />
                <Field label="Last name" placeholder="Avery" value={form.lastName} onChange={set("lastName")} error={errors.lastName} />
              </div>
              <Field label="Work email" type="email" placeholder="you@brokerage.com" icon={I("mail", { width: 16 })} value={form.email} onChange={set("email")} error={errors.email} />
              <Field label="Phone number" type="tel" placeholder="(202) 555-0140" icon={I("phone", { width: 16 })} value={form.phone} onChange={set("phone")} error={errors.phone} />
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="MLS agent #" placeholder="e.g. 6120933" icon={I("id-card", { width: 16 })} value={form.mlsId} onChange={set("mlsId")} error={errors.mlsId} />
                <label style={{ display: "grid", gap: 6 }}>
                  <span style={{ fontSize: "var(--text-sm)", fontWeight: "var(--weight-semibold)" }}>License state</span>
                  <select value={form.licenseState} onChange={set("licenseState")} style={{ height: "var(--control-h)", padding: "0 10px", borderRadius: "var(--radius-sm)", border: "1px solid " + (errors.licenseState ? "var(--danger)" : "var(--border)"), background: "var(--surface)", color: form.licenseState ? "var(--text)" : "var(--text-subtle)", fontSize: 14, cursor: "pointer" }}>
                    <option value="">Select…</option>
                    {US_STATES.map((s) => <option key={s} value={s} style={{ color: "var(--text)" }}>{s}</option>)}
                  </select>
                  {errors.licenseState && <span style={{ fontSize: 12, color: "var(--danger)" }}>{errors.licenseState}</span>}
                </label>
              </div>
              <PasswordField label="Password" placeholder="At least 8 characters" value={form.password} onChange={set("password")} error={errors.password} hint={!errors.password ? "Use 8+ characters with a mix of letters and numbers." : undefined} />
              <div>
                <Checkbox checked={form.agree} onChange={(v) => setForm((f) => ({ ...f, agree: typeof v === "boolean" ? v : !f.agree }))} label="I agree to the Terms of Service and Privacy Policy." />
                {errors.agree && <div style={{ fontSize: 12, color: "var(--danger)", marginTop: 4 }}>{errors.agree}</div>}
              </div>
            </div>
            {errors.auth && <div style={{ fontSize: 12.5, color: "var(--danger)", marginTop: 12, padding: "8px 12px", borderRadius: "var(--radius-sm)", background: "var(--danger-soft, rgba(220,38,38,0.08))" }}>{errors.auth}</div>}
            <Button variant="primary" fullWidth iconRight={I("arrow-right")} onClick={submitAccount} disabled={busy} style={{ marginTop: 20 }}>{busy ? "Creating account…" : "Continue to payment"}</Button>
            <p style={{ margin: "14px 0 0", textAlign: "center", fontSize: 13, color: "var(--text-muted)" }}>Already have an account? <button onClick={onSwitchToSignin} style={{ border: "none", background: "transparent", color: "var(--accent)", fontWeight: 700, fontSize: 13, cursor: "pointer", padding: 0 }}>Sign in</button></p>
          </div>}


        {/* Step 1 — Redirecting to Stripe Checkout */}
        {step === 1 &&
        <div style={{ ...bodyPad, textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "10px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)" }}>{I("credit-card", { width: 30 })}</div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Taking you to secure checkout…</h3>
            <p style={{ margin: "0 0 20px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>You'll finish your {plan || "Beta"} subscription on Stripe's secure page, then land back in Stratum Leads.</p>
            {errors.auth && <p style={{ fontSize: 12.5, color: "var(--danger)", marginBottom: 14 }}>{errors.auth}</p>}
            <Button variant="secondary" onClick={goToCheckout}>Retry checkout</Button>
          </div>}


        {/* Step 2 — Confirm email (project requires email confirmation before sign-in) */}
        {step === 2 &&
        <div style={{ ...bodyPad, textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "10px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--success-soft)", color: "var(--success)" }}>{I("mail-check", { width: 30 })}</div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Confirm your email</h3>
            <p style={{ margin: "0 0 8px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>We sent a confirmation link to</p>
            <p style={{ margin: "0 0 18px", fontSize: 14, fontWeight: 700 }}>{form.email}</p>
            <p style={{ margin: "0 0 22px", fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.55 }}>Click the link to verify, then sign in to complete your {plan || "Beta"} subscription ({plan && PLAN_INFO[plan] ? PLAN_INFO[plan].price : ""}).</p>
            <Button variant="primary" fullWidth onClick={onSwitchToSignin}>Go to sign in</Button>
          </div>}

      </div>
    </div>);

}

function SignInFlow({ onClose, onSwitchToSignup }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({ email: "", password: "", remember: true });
  const [code, setCode] = React.useState("");
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => {refresh();});
  React.useEffect(() => {const onKey = (e) => e.key === "Escape" && onClose();window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, []);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submitCreds = async () => {
    const err = {};
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) err.email = "Enter a valid email address.";
    if (!form.password) err.password = "Enter your password.";
    setErrors(err);
    if (Object.keys(err).length > 0) return;
    if (!window.__sb) {setErrors({ auth: "Supabase client is not configured." });return;}
    setBusy(true);
    const { error } = await window.__sb.auth.signInWithPassword({ email: form.email, password: form.password });
    setBusy(false);
    if (error) {setErrors({ auth: error.message });return;}
    window.localStorage.setItem("STRATUM_USE_LIVE", "true");
    // Signed up but never paid? Resume checkout instead of dropping into the app.
    if (window.localStorage.getItem("stratum_pending_checkout")) {
      const res = await beginCheckout();
      if (res.ok) return;   // redirecting to Stripe
    }
    window.location.href = "/app/?use_live=true";
  };
  const verify = () => {
    if (code.length < 6) {setErrors({ code: "Enter the full 6-digit code." });return;}
    setErrors({});setStep(2);
  };

  const headerIcon = { 0: "log-in", 1: "shield-check", 2: "party-popper" }[step];
  const overlay = { position: "fixed", inset: 0, zIndex: 100, background: "rgba(16,22,38,0.62)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20, overflowY: "auto" };
  const cardStyle = { width: "min(440px, 100%)", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", overflow: "hidden", margin: "auto" };
  const bodyPad = { padding: "26px 30px 30px" };

  return (
    <div style={overlay} onClick={onClose}>
      <div style={cardStyle} onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "22px 30px 20px", position: "relative", borderBottom: "1px solid var(--border)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: "var(--radius-md)", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(headerIcon, { width: 20 })}</span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800 }}>{step === 2 ? "Signed in" : step === 1 ? "2-step verification" : "Welcome back"}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>Sign in to Stratum Leads</div>
            </div>
          </div>
        </div>

        {/* Step 0 — Credentials */}
        {step === 0 &&
        <div style={bodyPad}>
            <div style={{ display: "grid", gap: 14 }}>
              <Field label="Email" type="email" placeholder="you@brokerage.com" icon={I("mail", { width: 16 })} value={form.email} onChange={set("email")} error={errors.email} />
              <div>
                <Field label="Password" type="password" placeholder="Your password" icon={I("lock", { width: 16 })} value={form.password} onChange={set("password")} error={errors.password} />
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10 }}>
                  <Checkbox checked={form.remember} onChange={(v) => setForm((f) => ({ ...f, remember: typeof v === "boolean" ? v : !f.remember }))} label="Remember me" />
                  <a href="#" style={{ fontSize: 13, fontWeight: 700, color: "var(--accent)" }}>Forgot password?</a>
                </div>
              </div>
            </div>
            {errors.auth && <p role="alert" style={{ margin: "12px 0 0", padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "#fee2e2", color: "#991b1b", fontSize: 12.5, fontWeight: 700 }}>{errors.auth}</p>}
            <Button variant="primary" fullWidth iconRight={I("arrow-right")} onClick={submitCreds} disabled={busy} style={{ marginTop: 20 }}>{busy ? "Signing in…" : "Sign in"}</Button>
            <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "18px 0" }}>
              <span style={{ flex: 1, height: 1, background: "var(--border)" }} /><span style={{ fontSize: 12, color: "var(--text-subtle)" }}>OR</span><span style={{ flex: 1, height: 1, background: "var(--border)" }} />
            </div>
            <div style={{ display: "grid", gap: 8 }}>
              <Button variant="secondary" fullWidth icon={I("chrome")}>Continue with Google</Button>
              <Button variant="secondary" fullWidth icon={I("building-2")}>Continue with Microsoft</Button>
            </div>
            <p style={{ margin: "16px 0 0", textAlign: "center", fontSize: 13, color: "var(--text-muted)" }}>New to Stratum Leads? <button onClick={onSwitchToSignup} style={{ border: "none", background: "transparent", color: "var(--accent)", fontWeight: 700, fontSize: 13, cursor: "pointer", padding: 0 }}>Create account</button></p>
          </div>}


        {/* Step 1 — 2FA */}
        {step === 1 &&
        <div style={bodyPad}>
            <p style={{ margin: "0 0 4px", fontSize: 14, color: "var(--text)" }}>Enter the 6-digit code we sent to your registered device to finish signing in.</p>
            <p style={{ margin: "0 0 20px", fontSize: 13, color: "var(--text-muted)" }}>Protecting {form.email}</p>
            <OtpInput value={code} onChange={setCode} autoFocus />
            {errors.code && <p style={{ margin: "10px 0 0", textAlign: "center", fontSize: 12, color: "var(--danger)" }}>{errors.code}</p>}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, margin: "16px 0 0", fontSize: 13, color: "var(--text-muted)" }}>Didn't get it? <Resend /></div>
            <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", margin: "14px 0 20px", fontSize: 12, color: "var(--text-subtle)" }}>{I("info", { width: 13 })}Demo: enter any 6 digits.</div>
            <Button variant="primary" fullWidth iconRight={I("check")} onClick={verify} disabled={busy}>{busy ? "Verifying…" : "Verify & sign in"}</Button>
            <div style={{ marginTop: 16 }}><button onClick={() => {setErrors({});setStep(0);}} style={{ display: "inline-flex", alignItems: "center", gap: 5, border: "none", background: "transparent", color: "var(--text-muted)", fontSize: 13, fontWeight: 700, cursor: "pointer", padding: 0 }}>{I("arrow-left", { width: 14 })}Back</button></div>
          </div>}


        {/* Step 2 — Done */}
        {step === 2 &&
        <div style={{ ...bodyPad, textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "6px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--success-soft)", color: "var(--success)" }}>{I("check", { width: 30 })}</div>
            <h3 style={{ margin: "0 0 8px", fontSize: 20, fontWeight: 800 }}>Welcome back!</h3>
            <p style={{ margin: "0 0 22px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>You're verified and signed in. Pick up where you left off in your workspace.</p>
            <a href="/app/?use_live=true" style={{ textDecoration: "none" }}><Button variant="primary" fullWidth iconRight={I("arrow-right")}>Launch Stratum Leads</Button></a>
          </div>}

      </div>
    </div>);

}

/* ============================ Team-demo request ============================ */

// Store the demo request in Supabase (migration 0021). demo_requests is INSERT-only
// for the anon/authenticated roles — do NOT chain .select() after .insert(): there is
// no read policy, so reading the row back would error even when the insert succeeded.
async function submitDemoRequest(form) {
  if (!window.__sb) throw new Error("Supabase client is not configured");
  const { error } = await window.__sb.from("demo_requests").insert({
    name: form.name.trim(),
    email: form.email.trim(),
    phone: form.phone,
    brokerage: form.brokerage,
    team_size: form.teamSize,
    message: form.message ? form.message : null,
    source: "landing",
  });
  if (error) throw error;
}

function DemoRequestFlow({ onClose }) {
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", brokerage: "", teamSize: "1–5", message: "" });
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => {refresh();});
  React.useEffect(() => {const onKey = (e) => e.key === "Escape" && onClose();window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, []);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = async () => {
    const err = {};
    if (!form.name.trim()) err.name = "Enter your full name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) err.email = "Enter a valid email address.";
    if (form.phone.replace(/\D/g, "").length < 7) err.phone = "Enter a valid phone number.";
    setErrors(err);
    if (Object.keys(err).length) return;
    setBusy(true);
    try {
      await submitDemoRequest(form);
      setSent(true);
    } catch (e) {
      setErrors({ submit: "Couldn't send your request right now. Please try again." });
    }
    setBusy(false);
  };

  // Native select/textarea styled to match the design-system Field control.
  const controlStyle = {
    width: "100%", minHeight: "var(--control-h)", padding: "0 12px",
    borderRadius: "var(--radius-sm)", border: "1px solid var(--border)",
    background: "var(--surface)", color: "var(--text)", fontFamily: "var(--font-sans)",
    fontSize: "var(--text-base)", outline: "none",
  };
  const labelStyle = { fontSize: "var(--text-sm)", fontWeight: "var(--weight-semibold)", color: "var(--text)" };

  const overlay = { position: "fixed", inset: 0, zIndex: 100, background: "rgba(16,22,38,0.62)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20, overflowY: "auto" };
  const cardStyle = { width: "min(468px, 100%)", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", overflow: "hidden", margin: "auto" };
  const bodyPad = { padding: "26px 30px 30px" };

  return (
    <div style={overlay} onClick={onClose}>
      <div style={cardStyle} onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "22px 30px 20px", position: "relative", borderBottom: "1px solid var(--border)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: "var(--radius-md)", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(sent ? "mail-check" : "presentation", { width: 20 })}</span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800 }}>{sent ? "Request received" : "Book a team demo"}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>Stratum Leads for brokers &amp; teams</div>
            </div>
          </div>
        </div>

        {!sent &&
        <div style={bodyPad}>
            <div style={{ display: "grid", gap: 14 }}>
              <Field label="Full name" placeholder="Jordan Avery" icon={I("user", { width: 16 })} value={form.name} onChange={set("name")} error={errors.name} />
              <Field label="Work email" type="email" placeholder="you@brokerage.com" icon={I("mail", { width: 16 })} value={form.email} onChange={set("email")} error={errors.email} />
              <Field label="Phone" type="tel" placeholder="(555) 123-4567" icon={I("phone", { width: 16 })} value={form.phone} onChange={set("phone")} error={errors.phone} />
              <Field label="Brokerage / team name" placeholder="Avery Realty Group" icon={I("building-2", { width: 16 })} value={form.brokerage} onChange={set("brokerage")} />
              <label style={{ display: "grid", gap: 6 }}>
                <span style={labelStyle}>Team size</span>
                <select value={form.teamSize} onChange={set("teamSize")} style={controlStyle}>
                  {["1–5", "6–15", "16–40", "40+"].map((s) => <option key={s} value={s}>{s}</option>)}
                </select>
              </label>
              <label style={{ display: "grid", gap: 6 }}>
                <span style={labelStyle}>Message <span style={{ fontWeight: 400, color: "var(--text-subtle)" }}>(optional)</span></span>
                <textarea rows={3} placeholder="Tell us about your team and what you want to see." value={form.message} onChange={set("message")}
                  style={{ ...controlStyle, minHeight: 84, padding: "10px 12px", resize: "vertical", lineHeight: 1.5 }} />
              </label>
            </div>
            {errors.submit && <p role="alert" style={{ margin: "12px 0 0", padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "#fee2e2", color: "#991b1b", fontSize: 12.5, fontWeight: 700 }}>{errors.submit}</p>}
            <Button variant="primary" fullWidth iconRight={I("arrow-right")} onClick={submit} disabled={busy} style={{ marginTop: 20 }}>{busy ? "Sending…" : "Request a demo"}</Button>
          </div>}

        {sent &&
        <div style={{ ...bodyPad, textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "10px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--success-soft)", color: "var(--success)" }}>{I("check", { width: 30 })}</div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Thanks — our team will reach out shortly.</h3>
            <p style={{ margin: "0 0 22px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>We'll contact you at {form.email} to schedule your walkthrough.</p>
            <Button variant="primary" fullWidth onClick={onClose}>Done</Button>
          </div>}

      </div>
    </div>);

}

async function submitContactRequest(form) {
  if (!window.__sb) throw new Error("Supabase client is not configured");
  const { error } = await window.__sb.from("contact_requests").insert({
    department: form.department,
    name: form.name.trim(),
    email: form.email.trim(),
    phone: form.phone ? form.phone.trim() : null,
    message: form.message ? form.message : null,
    source: "landing",
  });
  if (error) throw error;
}

function ContactFlow({ onClose }) {
  const [form, setForm] = React.useState({ department: "", name: "", email: "", phone: "", message: "" });
  const [errors, setErrors] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => {refresh();});
  React.useEffect(() => {const onKey = (e) => e.key === "Escape" && onClose();window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, []);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = async () => {
    const err = {};
    if (!form.department) err.department = "Choose a department.";
    if (!form.name.trim()) err.name = "Enter your name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) err.email = "Enter a valid email address.";
    if (!form.message.trim()) err.message = "Add a short message.";
    setErrors(err);
    if (Object.keys(err).length) return;
    setBusy(true);
    try { await submitContactRequest(form); setSent(true); }
    catch (e) { setErrors({ submit: "Couldn't send your message right now. Please try again." }); }
    setBusy(false);
  };

  const controlStyle = { width: "100%", minHeight: "var(--control-h)", padding: "0 12px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: "var(--surface)", color: "var(--text)", fontFamily: "var(--font-sans)", fontSize: "var(--text-base)", outline: "none" };
  const labelStyle = { fontSize: "var(--text-sm)", fontWeight: "var(--weight-semibold)", color: "var(--text)" };
  const overlay = { position: "fixed", inset: 0, zIndex: 100, background: "rgba(16,22,38,0.62)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20, overflowY: "auto" };
  const cardStyle = { width: "min(468px, 100%)", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", overflow: "hidden", margin: "auto" };
  const bodyPad = { padding: "26px 30px 30px" };

  return (
    <div style={overlay} onClick={onClose}>
      <div style={cardStyle} onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "22px 30px 20px", position: "relative", borderBottom: "1px solid var(--border)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: "var(--radius-md)", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(sent ? "mail-check" : "mail", { width: 20 })}</span>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800 }}>{sent ? "Message received" : "Contact us"}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>We'll route it to the right team</div>
            </div>
          </div>
        </div>

        {!sent &&
        <div style={bodyPad}>
            <div style={{ display: "grid", gap: 14 }}>
              <label style={{ display: "grid", gap: 6 }}>
                <span style={labelStyle}>Department</span>
                <select value={form.department} onChange={set("department")} style={{ ...controlStyle, color: form.department ? "var(--text)" : "var(--text-subtle)", border: "1px solid " + (errors.department ? "var(--danger)" : "var(--border)"), cursor: "pointer" }}>
                  <option value="">Select a department…</option>
                  {["HR", "Accounting", "Support", "Security"].map((d) => <option key={d} value={d} style={{ color: "var(--text)" }}>{d}</option>)}
                </select>
                {errors.department && <span style={{ fontSize: 12, color: "var(--danger)" }}>{errors.department}</span>}
              </label>
              <Field label="Full name" placeholder="Jordan Avery" icon={I("user", { width: 16 })} value={form.name} onChange={set("name")} error={errors.name} />
              <Field label="Email" type="email" placeholder="you@company.com" icon={I("mail", { width: 16 })} value={form.email} onChange={set("email")} error={errors.email} />
              <Field label="Phone (optional)" type="tel" placeholder="(555) 123-4567" icon={I("phone", { width: 16 })} value={form.phone} onChange={set("phone")} />
              <label style={{ display: "grid", gap: 6 }}>
                <span style={labelStyle}>Message</span>
                <textarea rows={3} placeholder="How can we help?" value={form.message} onChange={set("message")}
                  style={{ ...controlStyle, minHeight: 84, padding: "10px 12px", resize: "vertical", lineHeight: 1.5, border: "1px solid " + (errors.message ? "var(--danger)" : "var(--border)") }} />
                {errors.message && <span style={{ fontSize: 12, color: "var(--danger)" }}>{errors.message}</span>}
              </label>
            </div>
            {errors.submit && <p role="alert" style={{ margin: "12px 0 0", padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "#fee2e2", color: "#991b1b", fontSize: 12.5, fontWeight: 700 }}>{errors.submit}</p>}
            <Button variant="primary" fullWidth iconRight={I("arrow-right")} onClick={submit} disabled={busy} style={{ marginTop: 20 }}>{busy ? "Sending…" : "Send message"}</Button>
          </div>}

        {sent &&
        <div style={{ ...bodyPad, textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "10px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--success-soft)", color: "var(--success)" }}>{I("check", { width: 30 })}</div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Thanks — we've got your message.</h3>
            <p style={{ margin: "0 0 22px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>Our {form.department} team will get back to you at {form.email}.</p>
            <Button variant="primary" fullWidth onClick={onClose}>Done</Button>
          </div>}

      </div>
    </div>);

}

function CheckoutResumeOverlay({ error, onDismiss }) {
  React.useEffect(() => {refresh();});
  const overlay = { position: "fixed", inset: 0, zIndex: 200, background: "rgba(16,22,38,0.72)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center", padding: 20 };
  const card = { width: "min(420px, 100%)", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", padding: 30, textAlign: "center" };
  return (
    <div style={overlay}>
      <div style={card}>
        <div style={{ width: 64, height: 64, margin: "4px auto 18px", display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)" }}>{I("credit-card", { width: 30 })}</div>
        {!error ?
          <div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Taking you to secure checkout…</h3>
            <p style={{ margin: 0, fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>Finishing your subscription on Stripe's secure page. One moment.</p>
          </div> :
          <div>
            <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 800 }}>Couldn't reach checkout</h3>
            <p style={{ margin: "0 0 20px", fontSize: 14, color: "var(--text-muted)", lineHeight: 1.55 }}>Something went wrong starting your subscription. Retry, or continue to your workspace and subscribe later.</p>
            <div style={{ display: "grid", gap: 8 }}>
              <Button variant="primary" fullWidth onClick={() => beginCheckout()}>Retry checkout</Button>
              <Button variant="secondary" fullWidth onClick={onDismiss}>Continue to workspace</Button>
            </div>
          </div>}
      </div>
    </div>);
}

function Site() {
  React.useEffect(() => {refresh();});
  const [signup, setSignup] = React.useState(null); // null | { plan }
  // Sign-in modal stays closed until the visitor clicks "Sign In" — never auto-opens.
  const [signin, setSignin] = React.useState(false);
  const [resume, setResume] = React.useState(null); // null | { error: bool }
  const [demo, setDemo] = React.useState(false);
  const [contact, setContact] = React.useState(false);
  // ---- Deep-linkable auth routes --------------------------------------------------------------
  // /signin and /signup are real URLs — Cloudflare Pages serves index.html for any unmatched path,
  // so no redirect rule is needed. They exist so the flows can be linked from email, docs, or a
  // future app host, instead of only being reachable by clicking a header button.
  //
  // The address bar and the modal are kept in sync BOTH ways: landing on /signup opens the modal,
  // and opening it from a button pushes the URL, so Back closes the modal rather than leaving the
  // site entirely.
  const syncPath = (url) => {
    try {
      if (window.location.pathname + window.location.search !== url) window.history.pushState({}, "", url);
    } catch (e) {}
  };
  const openSignup = (plan) => {
    setSignin(false);setDemo(false);setContact(false);
    const p = typeof plan === "string" ? plan : null;
    setSignup({ plan: p });
    syncPath(p ? "/signup?plan=" + encodeURIComponent(p) : "/signup");
  };
  const openSignin = () => {setSignup(null);setDemo(false);setContact(false);setSignin(true);syncPath("/signin");};
  const closeAuth = () => {setSignup(null);setSignin(false);syncPath("/");};

  // Apply the current path on load, and keep responding to Back/Forward.
  React.useEffect(() => {
    const applyPath = () => {
      const path = window.location.pathname.replace(/\/+$/, "") || "/";
      if (path === "/signup") {
        // Only accept a plan we actually sell. The value is rendered in the modal header, so an
        // unchecked ?plan= would let a shared link put arbitrary text inside your own signup
        // dialog ("…plan · claim your free leads"). React escapes it, so this is about not lending
        // the dialog to someone else's words, not about script injection.
        const asked = new URLSearchParams(window.location.search).get("plan");
        const plan = asked && Object.prototype.hasOwnProperty.call(PLAN_INFO, asked) ? asked : null;
        setSignin(false);setDemo(false);setContact(false);setSignup({ plan });
      } else if (path === "/signin") {
        setSignup(null);setDemo(false);setContact(false);setSignin(true);
      } else {
        setSignup(null);setSignin(false);
      }
    };
    applyPath();
    window.addEventListener("popstate", applyPath);
    return () => window.removeEventListener("popstate", applyPath);
  }, []);
  const openDemo = () => {setSignup(null);setSignin(false);setContact(false);setDemo(true);};
  const openContact = () => {setSignup(null);setSignin(false);setDemo(false);setContact(true);};

  // Resume an unfinished subscription. When the user confirms their email they land back here
  // signed-in with a pending plan; the front-door script defers the app-bounce for exactly this case,
  // and here we send them on to Stripe. Skipped when returning from a checkout (?checkout=...).
  React.useEffect(() => {
    if (!window.__sb) return;
    let pending = null;
    try { pending = window.localStorage.getItem("stratum_pending_checkout"); } catch (e) {}
    const co = new URLSearchParams(window.location.search).get("checkout");
    if (!pending || co) return;
    window.__sb.auth.getSession().then(async ({ data }) => {
      if (!(data && data.session)) return;
      setResume({ error: false });
      const res = await beginCheckout();
      if (!res.ok) setResume({ error: true });
    }).catch(() => {});
  }, []);

  const dismissResume = () => {
    try { window.localStorage.removeItem("stratum_pending_checkout"); } catch (e) {}
    window.localStorage.setItem("STRATUM_USE_LIVE", "true");
    window.location.href = "/app/?use_live=true";
  };

  return (
    <React.Fragment>
      <div className="page">
        <IconDefs />
        <h2 className="sronly">Stratum Leads — exclusive enriched real-estate leads, a project manager for every deal, tool-consolidation savings, and Hunter, Closer, and Rainmaker pricing.</h2>
        <Nav onSignup={openSignup} onSignin={openSignin} />
        <Hero onSignup={openSignup} onDemo={openDemo} />
        <PhotoBand />
        <SaveSection />
        <WhySection />
        <DealsSection />
        <HowSection />
        <TourSection />
        <CloseSection />
        <Pricing onSignup={openSignup} />
        <Teams onDemo={openDemo} />
        <Proof />
        <FinalCta onSignup={openSignup} onDemo={openDemo} />
        <Footer onContact={openContact} />
      </div>
      {signup && <SignupFlow plan={signup.plan} onClose={closeAuth} onSwitchToSignin={openSignin} />}
      {signin && <SignInFlow onClose={closeAuth} onSwitchToSignup={() => openSignup()} />}
      {demo && <DemoRequestFlow onClose={() => setDemo(false)} />}
      {contact && <ContactFlow onClose={() => setContact(false)} />}
      {resume && <CheckoutResumeOverlay error={resume.error} onDismiss={dismissResume} />}
    </React.Fragment>
  );
}

{ const __r = typeof document !== "undefined" && document.getElementById("root"); if (__r && !window.__rootMounted) { window.__rootMounted = true; ReactDOM.createRoot(__r).render(<Site />); refresh(); } }
