// Landing page — Market-Options
function Landing({ onNavigate }) {
  // A signed-in visitor who lands here (typed the root URL, clicked the
  // brand mark, etc.) should see "Open console" instead of "Sign in" /
  // "Get API key" — otherwise the page looks as if their session expired.
  const signedIn = !!(window.Auth && Auth.isAuthed());

  const scrollToSection = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  // Docs is part of the signed-in console — send guests to sign up first.
  const openDocs = () => onNavigate(signedIn ? "docs" : "signup");
  return (
    <div className="landing">
      <nav className="landing-nav">
        <Brand />
        <div className="links">
          <a style={{ cursor: "pointer" }} onClick={() => scrollToSection("endpoints")}>Endpoints</a>
          <a style={{ cursor: "pointer" }} onClick={() => scrollToSection("pricing")}>Pricing</a>
          <a style={{ cursor: "pointer" }} onClick={openDocs}>Docs</a>
        </div>
        <div className="cta">
          {signedIn ? (
            <button className="btn btn-primary" onClick={() => onNavigate("dashboard")}>
              Open console <Icon.ArrowRight style={{ width: 14, height: 14 }} />
            </button>
          ) : (
            <>
              <button className="btn btn-ghost" onClick={() => onNavigate("login")}>Sign in</button>
              <button className="btn btn-primary" onClick={() => onNavigate("signup")}>
                Get API key <Icon.ArrowRight style={{ width: 14, height: 14 }} />
              </button>
            </>
          )}
        </div>
      </nav>

      {/* HERO */}
      <section className="hero">
        <div className="hero-grid-bg" />
        <div className="hero-inner">
          <div>
            <span className="status-pill">
              <span className="dot" /> $20/mo · about 80% cheaper than the big providers
            </span>
            <h1>
              Options data,<br />
              <em>$20/month</em>{" "}
              <span style={{
                fontSize: "0.45em",
                fontWeight: 400,
                color: "var(--muted)",
                letterSpacing: 0,
                verticalAlign: "0.35em",
                marginLeft: 8,
                fontFamily: "var(--ff-mono)",
              }}>
                (others charge $99)
              </span>
            </h1>
            <p className="hero-sub">
              Professional US options data — expirations, strikes, greeks, IV — at
              $20/month instead of $99. Data is delayed up to 60 seconds, which
              is what keeps the price low. If your strategy doesn't need
              sub-second quotes, you save about 80% and get the same data the
              bigger names sell.
            </p>
            <div className="hero-actions">
              {signedIn ? (
                <button className="btn btn-primary" onClick={() => onNavigate("dashboard")}>
                  Open console <Icon.ArrowRight style={{ width: 14, height: 14 }} />
                </button>
              ) : (
                <button className="btn btn-primary" onClick={() => onNavigate("signup")}>
                  Start your 3-day Pro trial <Icon.ArrowRight style={{ width: 14, height: 14 }} />
                </button>
              )}
              <button className="btn" onClick={openDocs}>
                <Icon.Docs style={{ width: 14, height: 14 }} /> Read the docs
              </button>
            </div>
            <div className="trust-line">
              <span>5 options endpoints</span>
              <span className="sep">•</span>
              <span>3-day Pro trial — no card required</span>
              <span className="sep">•</span>
              <span>API-key auth</span>
              <span className="sep">•</span>
              <span>Usage analytics built in</span>
            </div>
          </div>

          {/* Terminal demo */}
          <HeroTerminal />
        </div>
      </section>

      {/* Endpoints overview */}
      <section className="section" id="endpoints">
        <div className="section-inner">
          <span className="eyebrow">Endpoints</span>
          <h2>Five endpoints. <em>Every contract.</em></h2>
          <p className="lead">
            From discovery to execution-ready quotes. Compose them as you go — no SDK lock-in,
            stable JSON contracts, deterministic field ordering.
          </p>
          <div className="endpoint-strip">
            <EndpointCard num="01" tag="GET" name="/options/expirations" icon={<Icon.Calendar style={{ width: 22, height: 22 }} />}
              desc="List all expiration dates for an underlying, including weeklies, monthlies, and LEAPS." />
            <EndpointCard num="02" tag="GET" name="/options/strikes" icon={<Icon.Chart style={{ width: 22, height: 22 }} />}
              desc="List every listed strike price for an underlying, grouped by expiration — drives strike pickers." />
            <EndpointCard num="03" tag="GET" name="/options/lookup" icon={<Icon.Magnify style={{ width: 22, height: 22 }} />}
              desc="Resolve a human-readable contract string into a canonical OSI symbol — fuzzy and forgiving." />
            <EndpointCard num="04" tag="GET" name="/options/chain" icon={<Icon.ChainLink style={{ width: 22, height: 22 }} />}
              desc="Full chain with strikes, greeks, OI, volume, IV — filter by moneyness, delta, or DTE." />
            <EndpointCard num="05" tag="GET" name="/options/quotes" icon={<Icon.Quote style={{ width: 22, height: 22 }} />}
              desc="Bid/ask/last on one or many contracts. Snapshot pricing, fast JSON." />
          </div>
        </div>
      </section>

      {/* Features */}
      <section className="section">
        <div className="section-inner">
          <span className="eyebrow">Why $20 works</span>
          <h2>Delayed data,<br /><em>honestly priced.</em></h2>
          <div className="grid g-3" style={{ gap: 18 }}>
            <Feature icon={<Icon.Bolt style={{ width: 18, height: 18 }} />}
              title="1/5 the price" body="Pro is $20/month — about a fifth of what the big providers charge for the same options data. The trade-off is data delay, fully disclosed below." />
            <Feature icon={<Icon.Clock style={{ width: 18, height: 18 }} />}
              title="Up to 1-minute delay" body="Quotes can be delayed by up to 60 seconds. Fast enough for research, signals, backtests, and dashboards — not for sub-second arbitrage." />
            <Feature icon={<Icon.Globe style={{ width: 18, height: 18 }} />}
              title="Top 100 underlyings" body="SPY, QQQ, IWM, all major sector ETFs, every mega-cap tech name, popular financials and consumer — the 100 tickers that drive ~95% of US options volume." />
            <Feature icon={<Icon.Stack style={{ width: 18, height: 18 }} />}
              title="Plain JSON, no SDK" body="GET requests, query params, JSON responses. Same shape across all five endpoints. Stable v1 schemas, no client library required." />
            <Feature icon={<Icon.Shield style={{ width: 18, height: 18 }} />}
              title="API-key auth" body="Pass your key as ?apiKey=… in the URL (Polygon-style) or in the x-api-key header. Rotate or revoke any time from the dashboard." />
            <Feature icon={<Icon.Chart style={{ width: 18, height: 18 }} />}
              title="Usage analytics" body="Per-key credit counts, p95 latency, error rates, daily quota — all in your dashboard. No third-party tracking required." />
          </div>
        </div>
      </section>

      {/* Code preview */}
      <section className="section">
        <div className="section-inner" style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 48, alignItems: "center" }}>
          <div>
            <span className="eyebrow">DX</span>
            <h2>Curl on the left.<br /><em>Production on the right.</em></h2>
            <p className="lead" style={{ marginBottom: 16 }}>
              The example you copy from the docs is the live API. Plain JSON, stable
              v1 schema, no SDK lock-in. The bullets below are real guarantees.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, color: "var(--text-dim)", fontSize: 14, lineHeight: 2 }}>
              <li><Icon.Check style={{ width: 13, height: 13, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> API key in the URL or header — your choice.</li>
              <li><Icon.Check style={{ width: 13, height: 13, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> Credit + rate-limit headers on every response.</li>
              <li><Icon.Check style={{ width: 13, height: 13, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> Errors carry a stable <code className="mono" style={{ color: "var(--amber)" }}>code</code> and <code className="mono" style={{ color: "var(--amber)" }}>hint</code>.</li>
              <li><Icon.Check style={{ width: 13, height: 13, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> <code className="mono" style={{ color: "var(--amber)" }}>X-Credits-Used</code> header shows exactly what each call cost.</li>
              <li><Icon.Check style={{ width: 13, height: 13, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> ISO-8601 timestamps. Always UTC.</li>
            </ul>
          </div>
          <CodeBlock
            tabs={[
              { id: "curl", label: "curl", code: H.curl(
`curl "${window.location.origin}/api/v1/options/chain?underlying=AAPL&apiKey=sk_live_•••"`) },
              { id: "js", label: "node.js", code: H.js(
`const KEY = process.env.MARKET_OPTIONS_KEY;
const res = await fetch(
  "${window.location.origin}/api/v1/options/chain?underlying=AAPL&apiKey=" + KEY
);
const chain = await res.json();

// columnar: index i across the arrays is one contract
console.log(chain.optionSymbol.length);`) },
              { id: "py", label: "python", code: H.py(
`import os, requests

res = requests.get(
    "${window.location.origin}/api/v1/options/chain",
    params={"underlying": "AAPL", "apiKey": os.environ["MARKET_OPTIONS_KEY"]},
)
print(len(res.json()["optionSymbol"]))`) },
            ]}
          />
        </div>
      </section>

      {/* Pricing strip */}
      <section className="section" id="pricing" style={{ borderBottom: 0 }}>
        <div className="section-inner">
          <span className="eyebrow">Pricing</span>
          <h2>$20, not $99. <em>Same data.</em></h2>
          <p className="lead" style={{ maxWidth: 720 }}>
            Professional options data with up to a 60-second delay. If your
            strategy doesn't need sub-second quotes — research, signals,
            backtests, dashboards — you save about 80% versus the big
            providers. New accounts get a 3-day Pro trial automatically —
            no card required.
          </p>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18,
            marginTop: 32, maxWidth: 720, marginLeft: "auto", marginRight: "auto",
          }}>
            <PricingTier onNavigate={onNavigate} signedIn={signedIn} name="Free" price="$0" sub="1,000 credits / day" features={[
              "1,000 credits / day",
              "60 credits / minute burst",
              "All 5 options endpoints",
              "Top 100 underlyings",
              "Up to 60s data delay",
              "Community support",
            ]} />
            <PricingTier onNavigate={onNavigate} signedIn={signedIn} name="Pro" price="$20" sub="10,000 credits / minute · 3-day trial" highlight features={[
              "10,000 credits / minute",
              "Unlimited daily credits",
              "All 5 options endpoints",
              "Top 100 underlyings",
              "Up to 60s data delay",
              "Usage analytics",
              "Email support",
            ]} />
          </div>
          <p style={{
            marginTop: 18, textAlign: "center", fontSize: 12.5,
            color: "var(--muted)", fontFamily: "var(--ff-mono)",
          }}>
            Need sub-second data or off-list tickers? This isn't the right
            fit — try one of the big providers direct.
          </p>
        </div>
      </section>

      <footer style={{ padding: "32px 48px", borderTop: "1px solid var(--border-soft)", display: "flex", alignItems: "center", color: "var(--muted)", fontSize: 12, fontFamily: "var(--ff-mono)" }}>
        <Brand small />
        <span style={{ marginLeft: "auto" }}>© 2026 Market-Options — Not investment advice.</span>
      </footer>
    </div>
  );
}

function HeroTerminal() {
  return (
    <div className="hero-terminal">
      <div className="terminal-bar">
        <div className="tl-lights"><span /><span /><span /></div>
        <span style={{ marginLeft: 6 }}>~/market-options — chain.js — node v22</span>
        <span style={{ marginLeft: "auto", color: "var(--green)" }}>● live</span>
      </div>
      <div style={{ padding: "16px 18px", fontFamily: "var(--ff-mono)", fontSize: 12.5, lineHeight: 1.7 }}>
        <div style={{ color: "var(--muted)" }}>$ <span style={{ color: "var(--text)" }}>node chain.js</span></div>
        <div style={{ color: "var(--faint)" }}>// SPY chain · 2026-06-19 · ±5% moneyness</div>
        <table style={{ width: "100%", marginTop: 10, borderCollapse: "collapse", fontSize: 11.5 }}>
          <thead>
            <tr style={{ color: "var(--muted)", textAlign: "right" }}>
              <th style={{ textAlign: "left", padding: "4px 8px 4px 0", fontWeight: 500 }}>strike</th>
              <th style={{ padding: "4px 6px", fontWeight: 500 }}>side</th>
              <th style={{ padding: "4px 6px", fontWeight: 500 }}>bid</th>
              <th style={{ padding: "4px 6px", fontWeight: 500 }}>ask</th>
              <th style={{ padding: "4px 6px", fontWeight: 500 }}>Δ</th>
              <th style={{ padding: "4px 6px", fontWeight: 500 }}>IV</th>
              <th style={{ padding: "4px 6px 4px 6px", fontWeight: 500 }}>OI</th>
            </tr>
          </thead>
          <tbody>
            {[
              ["530", "C", "8.14", "8.18", "0.72", "16.4%", "12,418", "up"],
              ["540", "C", "3.97", "4.01", "0.58", "15.9%", "31,902", "up"],
              ["545", "C", "2.21", "2.24", "0.49", "15.7%", "47,113", "up"],
              ["550", "P", "1.84", "1.87", "-0.40", "16.1%", "52,007", "down"],
              ["555", "P", "3.62", "3.66", "-0.51", "16.5%", "29,431", "down"],
              ["560", "P", "6.18", "6.22", "-0.63", "17.0%", "18,224", "down"],
            ].map((r, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--border-soft)" }}>
                <td style={{ padding: "5px 8px 5px 0", color: "var(--text)" }}>${r[0]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px", color: r[1] === "C" ? "var(--green)" : "var(--red)" }}>{r[1]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px" }}>{r[2]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px" }}>{r[3]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px", color: r[1] === "C" ? "var(--green)" : "var(--red)" }}>{r[4]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px", color: "var(--amber)" }}>{r[5]}</td>
                <td style={{ textAlign: "right", padding: "5px 6px 5px 6px", color: "var(--muted)" }}>{r[6]}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{ marginTop: 12, color: "var(--muted)" }}>
          <span style={{ color: "var(--green)" }}>✓</span> 38 contracts · 142ms · 38 credits
        </div>
        <div style={{ marginTop: 4, color: "var(--muted)" }}>$ <span style={{ color: "var(--text)" }}>_</span></div>
      </div>
    </div>
  );
}

function EndpointCard({ num, tag, name, desc, icon }) {
  return (
    <div className="col">
      <div className="row" style={{ justifyContent: "space-between" }}>
        <span className="num">{num}</span>
        <span style={{ color: "var(--muted)" }}>{icon}</span>
      </div>
      <h4>
        <Tag kind="get">{tag}</Tag>
      </h4>
      <div className="mono" style={{ fontSize: 14, color: "var(--text)", margin: "4px 0 10px" }}>{name}</div>
      <p>{desc}</p>
    </div>
  );
}

function Feature({ icon, title, body }) {
  return (
    <div className="feature-card">
      <div className="ico-wrap">{icon}</div>
      <h3>{title}</h3>
      <p>{body}</p>
    </div>
  );
}

function PricingTier({ name, price, sub, features, highlight, onNavigate, signedIn }) {
  // Signed-in visitors are already past the signup step — route them to the
  // billing page (where they actually pick / change a plan) instead of back
  // through signup, which would just immediately bounce them to the dashboard.
  const cta = signedIn
    ? { label: "Manage in billing", target: "billing" }
    : { label: highlight ? "Start 3-day Pro trial" : "Choose plan", target: "signup" };
  return (
    <div className="feature-card" style={highlight ? { borderColor: "var(--green)", boxShadow: "0 0 0 1px var(--green) inset" } : null}>
      <div className="row" style={{ justifyContent: "space-between" }}>
        <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.1em" }}>{name}</span>
        {highlight && <Tag kind="get">Most popular</Tag>}
      </div>
      <div style={{ fontSize: 36, letterSpacing: "-0.025em", fontWeight: 600, marginTop: 16 }}>
        {price} <span style={{ fontSize: 13, color: "var(--muted)", fontWeight: 400, fontFamily: "var(--ff-mono)" }}>/ mo</span>
      </div>
      <div className="mono" style={{ color: "var(--muted)", fontSize: 12, marginTop: 2, marginBottom: 18 }}>{sub}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, color: "var(--text-dim)", fontSize: 13.5, lineHeight: 1.9 }}>
        {features.map((f, i) => (
          <li key={i}>
            <Icon.Check style={{ width: 12, height: 12, color: "var(--green)", verticalAlign: "-1px", marginRight: 8 }} /> {f}
          </li>
        ))}
      </ul>
      <button
        className={`btn ${highlight ? "btn-primary" : ""}`}
        style={{ marginTop: 20, width: "100%", justifyContent: "center" }}
        onClick={() => onNavigate && onNavigate(cta.target)}
      >
        {cta.label}
      </button>
    </div>
  );
}

Object.assign(window, { Landing });
