/* Pricing — Free vs Pro with detailed comparison + per-row mockups */

const CompareMockups = {
  snapshot: (() => {
    // DB publishes a snapshot every 30s: S1, S2, S3, S4. Pro serves the
    // current-tick snapshot, so its pill tracks S1..S4 exactly.
    // FREE refreshes every 60s, not every 30s, and at each refresh it
    // locks in the prior snapshot. Across the four 30s ticks that means
    // FREE holds S0 for two ticks, then S1 for two ticks - so by the
    // time DB lands the rug on S4, FREE is still serving S1 and misses
    // it entirely. S0 is a synthetic "one snapshot before S1" frame so
    // the first two cells carry a real value instead of a placeholder.
    const SNAPS = [
      { id: "S0", v: "$1.2428" },            // virtual prior frame
      { id: "S1", v: "$1.2424" },
      { id: "S2", v: "$1.2423" },
      { id: "S3", v: "$1.2423" },
      { id: "S4", v: "$0.0000022388", rug: true },
    ];
    const TICK_LABELS = ["t−90s", "t−60s", "t−30s", "t (now)"];
    // Per-tick mapping (index matches TICK_LABELS):
    //   DB:   S1, S2, S3, S4  (new snapshot each 30s tick)
    //   PRO:  S1, S2, S3, S4  (same-tick snapshot)
    //   FREE: S0, S0, S1, S1  (60s refresh; holds previous snapshot)
    const DB_ROW   = [SNAPS[1], SNAPS[2], SNAPS[3], SNAPS[4]];
    const PRO_ROW  = DB_ROW;
    const FREE_ROW = [
      { ...SNAPS[0], refresh: true },
      { ...SNAPS[0], held: true },
      { ...SNAPS[1], refresh: true },
      { ...SNAPS[1], held: true },
    ];
    return () => (
      <div className="snap-grid">
        {/* axis */}
        <div className="snap-cell label axis"/>
        {TICK_LABELS.map((tick, i) => (
          <div key={"ax"+i} className={"snap-cell axis" + (i === 3 ? " now" : "")}>
            <span className="snap-t mono">{tick}</span>
            {i === 3 && <span className="snap-now mono">LIVE</span>}
          </div>
        ))}

        {/* DB row */}
        <div className="snap-cell label db">
          <span className="snap-tag">DB</span>
          <span className="snap-sub mono">new snapshot<br/>every 30 seconds</span>
        </div>
        {DB_ROW.map((s, i) => (
          <div key={"db"+i} className={"snap-cell db sid-" + s.id + (s.rug ? " rug" : "")}>
            <span className={"snap-id mono" + (s.rug ? " rug" : "")} data-sid={s.id}>{s.id}</span>
            <span className={"snap-v mono" + (s.rug ? " rug" : "")}>{s.v}</span>
            {s.rug && <span className="snap-note mono rug">rug printed</span>}
          </div>
        ))}

        {/* PRO row */}
        <div className="snap-cell label pro">
          <span className="snap-tag pro">PRO</span>
          <span className="snap-sub mono">serves the same-tick<br/>snapshot</span>
        </div>
        {PRO_ROW.map((s, i) => (
          <div key={"pr"+i} className={"snap-cell pro sid-" + s.id + (s.rug ? " fresh" : "")}>
            <span className={"snap-id mono pro" + (s.rug ? " fresh" : "")} data-sid={s.id}>{s.id}</span>
            <span className={"snap-v mono" + (s.rug ? " rug" : "")}>{s.v}</span>
            {s.rug && <span className="snap-note mono fresh">FRESH · rug caught</span>}
          </div>
        ))}

        {/* FREE row */}
        <div className="snap-cell label free">
          <span className="snap-tag free">FREE</span>
          <ul className="snap-bullets mono">
            <li><span className="snap-x">×</span> 60-second refresh</li>
            <li><span className="snap-x">×</span> reads the <strong>prior</strong> snapshot</li>
          </ul>
        </div>
        {FREE_ROW.map((s, i) => {
          const isLive = i === 3;
          return (
            <div key={"fr"+i} className={"snap-cell free sid-" + s.id + (s.held ? " held" : "") + (isLive ? " stale" : "")}>
              <span className={"snap-id mono free" + (isLive ? " stale" : "")} data-sid={s.id}>{s.id}</span>
              <span className="snap-v mono">{s.v}</span>
              {isLive
                ? <span className="snap-note mono stale">STALE · rug invisible</span>
                : <span className="snap-note mono hold">{s.refresh ? "refreshed" : "held"}</span>}
            </div>
          );
        })}
      </div>
    );
  })(),

  telegram: () => (
    <div className="tg-compare">
      <div className="tg-card free">
        <div className="tg-card-head">
          <span className="tg-tag">FREE</span>
          <span className="tg-tag-sub mono">no push channel</span>
        </div>
        <div className="tg-card-body empty">
          <div className="tg-x">
            <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
              <path d="M3 3l10 10M13 3L3 13" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
          </div>
          <div className="tg-empty-text mono">
            Web surface only. Opportunities are only surfaced while your tab is open — close the browser and every spike, entry, and execution report disappears until you come back.
          </div>
        </div>
      </div>
      <div className="tg-card pro">
        <div className="tg-card-head">
          <span className="tg-tag pro">PRO</span>
          <span className="tg-tag-sub mono">personal bot · per-user thresholds · realtime push</span>
        </div>
        <div className="tg-card-body">
          <div className="tg-chat">
            <div className="tg-bot-line mono">
              <span className="tg-dot"/> @your_w3m_bot · DM
            </div>
            <div className="tg-msg spike">
              <div className="tg-msg-head mono">[AUTO] [SPIKE 30s | ≥30.00%]  <strong>DOT</strong>  −100.00%</div>
              <div className="tg-msg-row mono"><span className="k">Source</span><span className="v">uniswap:eth</span></div>
              <div className="tg-msg-row mono"><span className="k">Buy drop</span><span className="v down">100.00%</span></div>
              <div className="tg-msg-row mono"><span className="k">Prev → now</span><span className="v">$1.2424 → $2.24e-6</span></div>
              <div className="tg-msg-foot mono">pool 0x68d466…436da6 · 03:55:51 UTC</div>
            </div>
            <div className="tg-msg entry">
              <div className="tg-msg-head mono">[ENTRY]  <strong>rETH</strong>  +8.85%</div>
              <div className="tg-msg-row mono"><span className="k">Buy</span><span className="v">uniswap:eth · $2,474.74</span></div>
              <div className="tg-msg-row mono"><span className="k">Sell</span><span className="v">katana:ronin · $2,693.70</span></div>
              <div className="tg-msg-foot mono">16:23:45 UTC</div>
            </div>
            <div className="tg-threads mono">
              thread routing · <strong>#spikes</strong> · <strong>#new-entries</strong> · <strong>#executions</strong>
            </div>
          </div>
        </div>
      </div>
    </div>
  ),

  controls: (() => {
    const THRESHOLD_ROWS = {
      free: [
        { k: "SPIKE %",  v: "30.00" },
        { k: "WINDOW",   v: "30s" },
        { k: "ENTRY %",  v: "1.00" },
      ],
      pro: [
        { k: "SPIKE %",  v: "15.00", edit: true },
        { k: "WINDOW",   v: "1m",    edit: true },
        { k: "ENTRY %",  v: "0.50",  edit: true },
      ],
    };
    const FILTER_ROWS = {
      free: [
        { label: "all routes", on: true, locked: true },
        { label: "from · —",   locked: true },
        { label: "to · —",     locked: true },
        { label: "chain · —",  locked: true },
      ],
      pro: [
        { label: "from · binance", on: true },
        { label: "to · arbitrum",  on: true },
        { label: "chain · eth · base · sol", on: true },
        { label: "spread ≥ 0.50%" },
        { label: "bridge ETA ≤ 5m" },
        { label: "kind: spot, perp basis, DEX-DEX" },
      ],
    };
    const Column = ({ tier, locked, thresholds, filters }) => (
      <div className={"controls-card " + (tier === "pro" ? "pro" : "free")}>
        <div className="controls-head">
          <span className={"controls-tag " + (tier === "pro" ? "pro" : "")}>{tier.toUpperCase()}</span>
          <span className="controls-tag-sub mono">{locked ? "locked defaults" : "per-user overrides"}</span>
        </div>
        <div className="controls-block">
          <div className="controls-block-title mono">Thresholds</div>
          <div className="controls-rows">
            {thresholds.map((r, i) => (
              <div key={i} className={"controls-row" + (locked ? " locked" : "")}>
                <span className="k mono">{r.k}</span>
                <span className="v mono">{r.v}</span>
                <span className={"state mono" + (r.edit ? " edit" : " lock")}>
                  {locked ? "locked" : (r.edit ? "edit" : "—")}
                </span>
              </div>
            ))}
          </div>
        </div>
        <div className="controls-block">
          <div className="controls-block-title mono">Opportunity filters</div>
          <div className="controls-pills">
            {filters.map((f, i) => (
              <span key={i} className={
                "controls-pill" +
                (f.on ? " on" : "") +
                (f.locked ? " locked" : "") +
                (tier === "pro" ? " pro" : "")
              }>{f.label}</span>
            ))}
          </div>
        </div>
      </div>
    );
    return () => (
      <div className="controls-compare">
        <Column tier="free" locked thresholds={THRESHOLD_ROWS.free} filters={FILTER_ROWS.free}/>
        <Column tier="pro"  thresholds={THRESHOLD_ROWS.pro}  filters={FILTER_ROWS.pro}/>
      </div>
    );
  })(),

  bridge: () => (
    <div className="bridge-compare">
      <div className="bridge-card free">
        <div className="bridge-head">
          <span className="bridge-tag">FREE</span>
          <span className="bridge-tag-sub mono">cross-chain row flagged · no quote</span>
        </div>
        <div className="bridge-body">
          <div className="bridge-route mono">
            <span className="chain">eth</span>
            <span className="arrow">→</span>
            <span className="chain">arbitrum</span>
          </div>
          <div className="bridge-warning mono">
            <span className="warn-tag">NEEDS BRIDGE</span>
            <span className="warn-text">route exists — quote hidden</span>
          </div>
          <div className="bridge-kv-grid">
            {[
              { k: "fee", v: "?" },
              { k: "eta", v: "?" },
              { k: "pool TVL", v: "?" },
              { k: "credit", v: "?" },
            ].map((f, i) => (
              <div key={i} className="bridge-kv locked">
                <span className="k mono">{f.k}</span>
                <span className="v mono">{f.v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="bridge-card pro">
        <div className="bridge-head">
          <span className="bridge-tag pro">PRO</span>
          <span className="bridge-tag-sub mono">stargate v2 · layerzero · live poll 30s</span>
        </div>
        <div className="bridge-body">
          <div className="bridge-route mono">
            <span className="chain">eth</span>
            <span className="arrow pro">→</span>
            <span className="chain">arbitrum</span>
            <span className="via mono">via Stargate V2</span>
          </div>
          <div className="bridge-status mono">
            <span className="status-dot active"/>
            <span className="status-label">route active · OFT credit healthy</span>
          </div>
          <div className="bridge-kv-grid">
            {[
              { k: "fee_usd",     v: "$0.82" },
              { k: "eta",         v: "4m 12s" },
              { k: "pool TVL",    v: "$12.4M" },
              { k: "credit",      v: "2,148 USDC" },
              { k: "gas",         v: "$0.17" },
              { k: "net spread",  v: "+3.12%", accent: true },
            ].map((f, i) => (
              <div key={i} className={"bridge-kv pro" + (f.accent ? " accent" : "")}>
                <span className="k mono">{f.k}</span>
                <span className="v mono">{f.v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  ),

  _bridgeOld: () => (
    <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10}}>
      <div style={{
        border: "1px solid var(--hairline)",
        borderRadius: 6,
        padding: 12,
        background: "var(--bg-sunken)",
        display: "flex",
        flexDirection: "column",
        gap: 8,
      }}>
        <div className="mono" style={{fontSize: 9.5, color: "var(--fg-4)", letterSpacing: "0.08em"}}>FREE</div>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr auto 1fr",
          gap: 8, alignItems: "center",
        }}>
          <span className="mono" style={{fontSize: 11, color: "var(--fg-2)"}}>eth</span>
          <span className="mockup-badge red">NEEDS BRIDGE</span>
          <span className="mono" style={{fontSize: 11, color: "var(--fg-2)", textAlign: "right"}}>arb</span>
        </div>
        <div className="mono" style={{fontSize: 9, color: "var(--fg-4)", textAlign: "center"}}>fee · ? · eta · ?</div>
      </div>
      <div style={{
        border: "1px solid var(--hairline)",
        borderRadius: 6,
        padding: 12,
        background: "var(--bg-elev)",
        display: "flex",
        flexDirection: "column",
        gap: 8,
      }}>
        <div className="mono" style={{fontSize: 9.5, color: "var(--fg-4)", letterSpacing: "0.08em"}}>PRO</div>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr auto 1fr",
          gap: 8, alignItems: "center",
        }}>
          <span className="mono" style={{fontSize: 11, color: "var(--fg)"}}>eth</span>
          <svg width="40" height="12" viewBox="0 0 40 12" fill="none">
            <path d="M2 6h36m0 0l-4-3m4 3l-4 3" stroke="var(--accent)" strokeWidth="1.3"/>
          </svg>
          <span className="mono" style={{fontSize: 11, color: "var(--fg)", textAlign: "right"}}>arb</span>
        </div>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
          gap: 6,
          paddingTop: 4,
          borderTop: "1px dashed var(--hairline)",
        }}>
          <div>
            <div className="mono" style={{fontSize: 8.5, color: "var(--fg-4)"}}>VIA</div>
            <div className="mono" style={{fontSize: 10, color: "var(--fg)"}}>across</div>
          </div>
          <div>
            <div className="mono" style={{fontSize: 8.5, color: "var(--fg-4)"}}>FEE</div>
            <div className="mono" style={{fontSize: 10, color: "var(--accent-ink)"}}>$0.82</div>
          </div>
          <div>
            <div className="mono" style={{fontSize: 8.5, color: "var(--fg-4)"}}>ETA</div>
            <div className="mono" style={{fontSize: 10, color: "var(--fg)"}}>4m 12s</div>
          </div>
        </div>
      </div>
    </div>
  ),
};

const COMPARE = [
  {
    id: "snapshot",
    label: "Snapshot freshness",
    sub: "Every surface on the site reads from this.",
    free: { head: "1-minute cadence + 1-minute delay", detail: "serves the prior snapshot (lag n−1)" },
    pro:  { head: "30-second cadence + realtime price", detail: "serves the most recent snapshot" },
  },
  {
    id: "telegram",
    label: "Personal Telegram alerts",
    sub: "Spikes, new entries, execution reports — pushed to your own chat 24/7.",
    free: { head: "Web surface only", detail: "no push — events vanish once the tab closes" },
    pro:  { head: "Personal bot · thread-routed", detail: "spike / entry / execution reports with per-user thresholds" },
  },
  {
    id: "controls",
    label: "Per-user filters & thresholds",
    sub: "Pick which opportunities fire an alert and which even show up on your board.",
    free: { head: "Locked defaults", detail: "1.00% entry · 30s/30% spike · all routes" },
    pro:  { head: "Fully editable", detail: "your own spike/entry %, window, venue & chain filters" },
  },
  {
    id: "bridge",
    label: "Bridge quote & status",
    sub: "Live fee, ETA, pool TVL and OFT credit on every cross-chain opportunity.",
    free: { head: "\"NEEDS BRIDGE\" flag only", detail: "cross-chain rows get a red tag, no quote" },
    pro:  { head: "Live Bridge Route", detail: "fee_usd · ETA · pool TVL · credit · route status" },
  },
];

const Tier = ({ pro, compact = false }) => {
  if (pro) {
    return (
      <div className="tier pro">
        <span className="name">Pro</span>
        <div className="price">
          <span className="num">$0.0693</span>
          <span className="was">$99.9</span>
          <span className="unit">/ hour · 50% off</span>
        </div>
        <div className="sub">Pay for any length with x402 USDC on Base. Cancel by simply not paying next cycle — no auto-renew lock-in.</div>
        <a href="/mypage#billing" className="btn btn-primary tier-cta">
          Subscribe with USDC
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3 7h8m0 0L7 3m4 4L7 11" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </a>
        <div style={{display: "flex", flexDirection: "column", gap: 10}}>
          {[
            "30-second cadence + realtime price",
            "Personalized Telegram alerts",
            "Full % + window thresholds",
            "From / to filters & routing",
            "Live bridge fees & ETA",
            "Priority support",
          ].map((f, i) => (
            <div key={i} className="mono" style={{fontSize: 12.5, display: "flex", gap: 8, alignItems: "center"}}>
              <span style={{color: "var(--accent)"}}>✓</span>
              <span>{f}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return (
    <div className="tier">
      <span className="name">Free</span>
      <div className="price">
        <span className="num">$0</span>
        <span className="unit">/ forever</span>
      </div>
      <div className="sub">Full read access to the opportunity book, with a 1-minute cadence + 1-minute delay and default thresholds.</div>
      <a href="/arbitrage" className="btn btn-ghost tier-cta">Launch dashboard</a>
      <div style={{display: "flex", flexDirection: "column", gap: 10}}>
        {[
          "1-minute snapshot freshness + 1-minute delay",
          "Opportunities, New Entries, Spikes — read",
          "Default thresholds",
          "'Needs bridge' flag (no quote)",
          "Web-only",
        ].map((f, i) => (
          <div key={i} className="mono" style={{fontSize: 12.5, display: "flex", gap: 8, alignItems: "center", color: "var(--fg-2)"}}>
            <span style={{color: "var(--fg-4)"}}>○</span>
            <span>{f}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const AccordionItem = ({ row, Mock, index }) => {
  const [open, setOpen] = React.useState(index === 0 || index === 1);
  return (
    <div className={"acc-item " + (open ? "open" : "")}>
      <button className="acc-head" onClick={() => setOpen(o => !o)} aria-expanded={open}>
        <div className="acc-left">
          <span className="acc-num">{String(index + 1).padStart(2, "0")}</span>
          <div className="acc-title">
            <div className="acc-label">{row.label}</div>
            <div className="acc-sub">{row.sub}</div>
          </div>
        </div>
        <div className="acc-right">
          <div className="acc-summary">
            <span className="acc-pill free"><b>Free</b><span>{row.free.head}</span></span>
            <span className="acc-arrow">
              <svg width="12" height="10" viewBox="0 0 12 10" fill="none"><path d="M1 5h10m0 0L7 1m4 4L7 9" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </span>
            <span className="acc-pill pro"><b>Pro</b><span>{row.pro.head}</span></span>
          </div>
          <span className="acc-chev" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M3 5l4 4 4-4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </span>
        </div>
      </button>
      <div className="acc-body">
        <div className="acc-body-inner">
          <div className="acc-grid">
            <div className="acc-col">
              <div className="acc-col-head"><span className="acc-col-tag">Free</span><span className="acc-col-head-text">{row.free.head}</span></div>
              <div className="acc-col-detail">{row.free.detail}</div>
            </div>
            <div className="acc-col pro">
              <div className="acc-col-head"><span className="acc-col-tag pro">Pro</span><span className="acc-col-head-text">{row.pro.head}</span></div>
              <div className="acc-col-detail">{row.pro.detail}</div>
            </div>
          </div>
          {Mock && <div className="acc-mock"><Mock/></div>}
        </div>
      </div>
    </div>
  );
};

const Pricing = () => {
  return (
    <section id="pricing">
      <div className="container">
        <div className="pricing-head">
          <div>
            <div className="eyebrow"><span className="dot"/>Pricing</div>
            <h2 className="section-title" style={{marginTop: 14}}>
              Launch price.<br/>Pay by the day, not the year.
            </h2>
          </div>
          <div>
            <div className="price-banner">
              <b>−50% launch</b>
              <span>$99.9 → $49.9 / month · $0.0693 / hour · x402 on Base · USDC</span>
            </div>
            <p className="lede" style={{fontSize: 16, marginTop: 8}}>
              Pick any duration. web3map settles via the x402 payment
              protocol — you pay for exactly the window you want.
            </p>
          </div>
        </div>

        <div className="tier-grid">
          <Tier/>
          <Tier pro/>
        </div>

        <div className="compare-intro">
          <div className="eyebrow"><span className="dot"/>Free vs Pro</div>
          <h3 className="compare-title">
            What you get when you upgrade.
          </h3>
          <p className="compare-lede">
            Five features, side by side. Click any row for the full picture.
          </p>
        </div>

        <div className="compare-accordion">
          {COMPARE.map((row, i) => {
            const Mock = CompareMockups[row.id];
            const [open, setOpen] = [null, null]; // placeholder — use AccordionItem
            return (
              <AccordionItem key={row.id} row={row} Mock={Mock} index={i}/>
            );
          })}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Pricing });
