// economy.jsx — Pricing & GoT economy: 3-audience reference
//
// Content distilled from:
//   - GoT-Token-Economy-PRD.md v3.0.0 (2026-01-15) — locked numbers
//   - Memory: Smart API Router narrative + GoT rebate framing (post-PRD)
//
// Three audience tabs:
//   • Users — what you pay, what you get
//   • OEM Partners — why GoT aligns with selling silicon
//   • Creators — how earning works through the marketplace
//
// PLACEHOLDERS (3 unresolved gaps marked clearly inline):
//   1. GoT rebate mechanic — real mechanism vs narrative framing
//   2. Acer 4,500 GoT/月 fixed vs rebate — additive or substitutive
//   3. $8.9 Plus tier monthly GoT allocation — TBD in PRD v3.0

const { useState: useStateE } = React;

const ECON_VERSION = "v3.0 + addenda · Draft";
const ECON_UPDATED = "May 2026 (PRD: Jan 2026)";

// ─────────────────────────────────────────────────── Tabs (mirrors rules.jsx)
function EconTabs({ value, options, onChange }) {
  return (
    <div className="row" style={{
      borderBottom: "1px solid var(--line)",
      gap: 4, marginTop: 16, marginBottom: 32,
    }}>
      {options.map(o => (
        <button key={o.id} className="unstyled" onClick={() => onChange(o.id)}
          style={{
            padding: "12px 16px",
            font: "500 14px/1 var(--font-sans)",
            color: value === o.id ? "var(--ink)" : "var(--ink-3)",
            borderBottom: value === o.id ? "2px solid var(--accent)" : "2px solid transparent",
            marginBottom: -1, cursor: "pointer", background: "transparent",
          }}>
          <div>{o.label}</div>
          <div style={{ font: "400 11px/1.4 var(--font-sans)", color: "var(--ink-4)", marginTop: 4 }}>
            {o.subtitle}
          </div>
        </button>
      ))}
    </div>
  );
}

function ESection({ id, title, kicker, children }) {
  return (
    <section id={id} style={{ marginBottom: 40, scrollMarginTop: 80 }}>
      {kicker && (
        <div style={{
          font: "500 11px/1 var(--font-mono)", color: "var(--ink-3)",
          textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8,
        }}>{kicker}</div>
      )}
      <h2 style={{
        font: "600 22px/1.3 var(--font-display)", color: "var(--ink)",
        margin: "0 0 16px 0",
      }}>{title}</h2>
      <div style={{ font: "400 15px/1.6 var(--font-sans)", color: "var(--ink-1)" }}>
        {children}
      </div>
    </section>
  );
}

function ENote({ tone = "info", children }) {
  const tones = {
    info:    { bg: "var(--bg-muted)", border: "var(--line)", ink: "var(--ink-2)" },
    warn:    { bg: "var(--amber-50)", border: "var(--amber-100)", ink: "var(--amber-700)" },
    success: { bg: "var(--green-50)", border: "var(--green-100)", ink: "var(--green-700)" },
    open:    { bg: "var(--bg-sunken)", border: "var(--line-strong)", ink: "var(--ink-3)" },
    tbd:     { bg: "var(--amber-50)", border: "var(--amber-100)", ink: "var(--amber-700)" },
  };
  const t = tones[tone] || tones.info;
  return (
    <div style={{
      background: t.bg, border: `1px solid ${t.border}`, color: t.ink,
      padding: "12px 14px", borderRadius: "var(--r-3)", margin: "12px 0",
      font: "400 14px/1.55 var(--font-sans)",
    }}>{children}</div>
  );
}

function ETable({ headers, rows }) {
  return (
    <div style={{ overflowX: "auto", margin: "12px 0" }}>
      <table style={{
        width: "100%", borderCollapse: "collapse",
        font: "400 14px/1.5 var(--font-sans)",
      }}>
        <thead>
          <tr>
            {headers.map((h, i) => (
              <th key={i} style={{
                textAlign: "left", padding: "10px 12px",
                borderBottom: "1px solid var(--line-strong)",
                font: "600 12px/1.4 var(--font-sans)",
                color: "var(--ink-3)", textTransform: "uppercase",
                letterSpacing: "0.04em",
              }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, ri) => (
            <tr key={ri}>
              {row.map((cell, ci) => (
                <td key={ci} style={{
                  padding: "10px 12px", verticalAlign: "top",
                  borderBottom: "1px solid var(--line-soft)",
                  color: "var(--ink-1)",
                }}>{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// Pricing tier card
function TierCard({ name, price, sub, highlight, features }) {
  return (
    <div style={{
      flex: "1 1 240px", minWidth: 240,
      border: highlight ? "2px solid var(--accent)" : "1px solid var(--line-strong)",
      borderRadius: "var(--r-4)", padding: "20px 18px",
      background: "var(--surface)",
    }}>
      <div style={{ font: "500 12px/1 var(--font-mono)", color: "var(--ink-3)",
        textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>
        {name}
      </div>
      <div style={{ font: "700 26px/1.1 var(--font-display)", color: "var(--ink)" }}>
        {price}
      </div>
      <div style={{ font: "400 13px/1.4 var(--font-sans)", color: "var(--ink-3)", marginBottom: 14 }}>
        {sub}
      </div>
      <ul style={{ paddingLeft: 18, margin: 0, font: "400 14px/1.55 var(--font-sans)", color: "var(--ink-1)" }}>
        {features.map((f, i) => <li key={i} style={{ marginBottom: 4 }}>{f}</li>)}
      </ul>
    </div>
  );
}

// ─────────────────────────────────────────────────── Audience: Users
function UserEcon() {
  return (
    <div>
      <ESection kicker="Three plans" title="What you pay, what you get">
        <div className="row" style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
          <TierCard
            name="Free"
            price="$0"
            sub="One-time 500 GoT to try IrisGo end-to-end."
            features={[
              "500 GoT-Free at signup (one-time)",
              "+100 GoT-Free per friend you refer (up to 5/month)",
              "Fast tier features only",
              "No card required",
            ]} />
          <TierCard
            name="IrisGo Plus"
            price="$8.9 / mo"
            sub="Bundled with select OEM devices (Acer launch partner)."
            features={[
              "Monthly GoT allocation — TBD",
              "Acer 1-year bundle: 4,500 GoT-Free / month",
              "Fast + select Pro features",
              "Pre-installed on partner devices",
            ]} />
          <TierCard
            name="IrisGo Pro"
            price="$14.9 / mo"
            highlight
            sub="Power-user tier. Cheaper than ChatGPT Plus, more headroom."
            features={[
              "10,000 GoT-Paid + 250 GoT-Free per month",
              "All Pro tier features unlocked",
              "GoT-Paid is transferable & accumulates",
              "Image generation included",
            ]} />
        </div>
        <ENote tone="tbd">
          <b>Open while we finalize:</b> the exact GoT allocation for the standalone $8.9 Plus tier (PRD v3.0 has it as TBD pending OEM-cohort data). We will publish the number alongside the public payment-gateway launch.
        </ENote>
      </ESection>

      <ESection kicker="The unit" title="What is a GoT?">
        <p><b>GoT — Grains of Thought.</b> One GoT is the cost of one well-defined unit of agent work. Not a raw API token, not a character count — a complete piece of value: a translation, a Web summary, an explanation, one image, one Deep Research run.</p>
        <p>We chose this abstraction so you don't have to think in tokens. Token costs change every quarter; what stays steady is "how much agent work you got done this month."</p>
        <p><b>1 GoT ≈ $0.002 USD.</b> The retail face value of your subscription's GoT allocation always exceeds what you paid — that gap is your margin against pay-as-you-go API pricing.</p>
      </ESection>

      <ESection kicker="Two wallets" title="GoT-Free and GoT-Paid behave differently">
        <ETable
          headers={["Trait", "GoT-Free", "GoT-Paid"]}
          rows={[
            ["How you get them", "Signup, referrals, OEM bundle, monthly Pro top-up", "By paying — included in Pro, or top-ups"],
            ["Transferable to other users", "No", "Yes (with cooldowns and caps)"],
            ["Where they apply", "Fast tier features", "Both Fast and Pro tier features"],
            ["Spend order", "Spent first", "Spent only after Free runs out"],
            ["Carries over month-to-month", "No (one-time or monthly refresh)", "Yes — accumulates"],
          ]} />
        <p><b>Pro features (e.g. Deep Research Pro, image generation) require GoT-Paid by design.</b> If you're on Free and try a Pro feature, we prompt you to upgrade rather than silently fail.</p>
      </ESection>

      <ESection kicker="What things cost" title="Per-feature GoT pricing">
        <ETable
          headers={["Feature", "Fast (Free or Paid)", "Pro (Paid only)"]}
          rows={[
            ["Translation", "0 GoT", "—"],
            ["Grammar", "5 GoT", "25 GoT"],
            ["Explanation", "8 GoT", "35 GoT"],
            ["Web Summary", "30 GoT", "100 GoT"],
            ["Image generation (prompt)", "2 GoT", "—"],
            ["Image generation (output)", "—", "80 GoT / image"],
            ["Deep Research Lite", "120 GoT", "—"],
            ["Deep Research Pro", "—", "500–1,000 GoT"],
          ]} />
        <p>Translation is free because we use a near-zero-cost provider for it. Everything else gets passed through Smart Router (next section), which decides — per request — whether to run on your device or in the cloud, transparently.</p>
      </ESection>

      <ESection kicker="Earning more" title="Referrals and ways to top up GoT-Free">
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li><b>Refer a friend:</b> +100 GoT-Free for both of you. Up to 5 referrals/month — capped to deter farming.</li>
          <li><b>Anti-abuse:</b> referees must complete one real task before reward unlocks; new accounts wait 7 days before they can refer; same IP/device caps.</li>
          <li><b>OEM bundle:</b> if your device shipped with IrisGo (e.g., Acer launch), you get a monthly GoT-Free allocation for the bundle term — no payment needed.</li>
          <li><b>Annotation reward (Helix):</b> if you opt into the Data Annotation Network, contributing labels earns GoT-Free.</li>
        </ul>
      </ESection>

      <ESection kicker="Running out, refunding, and transfers" title="The edge cases">
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li><b>Out of GoT mid-task?</b> We never silently fail or charge a hidden card. We pause the task and surface the upgrade choice.</li>
          <li><b>Refund window:</b> 7 days for first purchases; pro-rated for subscription cancellations.</li>
          <li><b>Transfer GoT-Paid:</b> to any IrisGo account. 5–10 minute reversal window. Daily cap 2,000; monthly 10,000. New accounts (under 7 days) are limited to 500/day in.</li>
          <li><b>Cash payout:</b> not in V1 — GoT stays in the ecosystem until volume justifies the tax/KYC plumbing for cash conversion. Roadmap target: post-100K MAU.</li>
        </ul>
      </ESection>
    </div>
  );
}

// ─────────────────────────────────────────────────── Audience: OEM Partners
function OEMEcon() {
  return (
    <div>
      <ESection kicker="The thesis" title="Your silicon becomes recurring user-felt value">
        <p>Your customer ships with our agent. Our agent runs work in two places: locally (on your NPU + iGPU) when it can, and in the cloud when it must. Smart Router makes the decision per request.</p>
        <p>Every request that runs locally is one our cloud didn't pay for. The savings are real, and we share them with the user as <b>GoT rebate</b> — their balance grows when their device does the work.</p>
        <p style={{ font: "500 16px/1.5 var(--font-sans)", color: "var(--iris-700)", margin: "20px 0", padding: "16px 18px",
          borderLeft: "3px solid var(--accent)", background: "var(--accent-soft)" }}>
          Your silicon is no longer just a spec sheet. It becomes a recurring source of value the user feels every week.
        </p>
      </ESection>

      <ESection kicker="Smart API Router" title="Three-tier routing decision (per request)">
        <ETable
          headers={["Tier", "Triggers when…", "Where it runs", "Implication for you"]}
          rows={[
            ["Local-eligible", "Task fits NPU/iGPU capability and latency budget", "On-device", "Highest silicon utilization. Drives GoT rebate."],
            ["Privacy-required", "Sensitive content (medical, financial, personal docs) detected", "On-device, mandatory", "Privacy story that competing cloud-only assistants can't match."],
            ["Cost-latency optimal", "Task exceeds local capacity OR cloud is faster/cheaper for this specific request", "Cloud (Anthropic / OpenAI / Gemini, routed)", "Always-best-tool-for-the-job. We absorb the cost variance."],
          ]} />
        <p>Co-engineered with <b>Intel Superbuilder</b> SW stacks — we're tuning routing thresholds against actual NPU + iGPU capacity per CPU generation, not generic benchmarks.</p>
      </ESection>

      <ESection kicker="The bundle structure" title="Acer launch partner reference (1-year free trial, 100K device target)">
        <ETable
          headers={["Slot", "Spec", "Notes"]}
          rows={[
            ["Trial term", "12 months from device activation", "Set at the OEM contract level."],
            ["Monthly allocation", "4,500 GoT-Free / month", "PRD v3.0 baseline. Per OEM negotiation."],
            ["Annual face value", "~$108 USD per user / year", "At 1 GoT = $0.002 list price."],
            ["Cost ceiling", "~$60 USD per user / year", "Targeted via Smart Router local-first routing."],
            ["Conversion target", "10–15% trial → Pro at month 12", "Modeled in PRD; tracked by cohort."],
          ]} />
        <ENote tone="tbd">
          <b>Open while we finalize:</b> whether the 4,500/month fixed allocation persists alongside the GoT rebate (rebate-on-top model), or whether the bundle transitions to a base-plus-rebate model (smaller fixed floor + variable rebate keyed to local execution rate). Either way the user-facing face value will not decrease — we will publish the chosen model before any device ships under it.
        </ENote>
      </ESection>

      <ESection kicker="Three-way alignment" title="Why this works for everyone at once">
        <ETable
          headers={["Stakeholder", "What they get from local-first routing"]}
          rows={[
            ["End user", "Faster responses, privacy by default, GoT balance grows the more their device works."],
            ["OEM (you)", "Silicon is a recurring value driver, not a one-time spec. Differentiation against cloud-only assistants."],
            ["IrisGo", "Lower cloud-token cost-of-revenue; margin expands as local-execution rate climbs."],
          ]} />
        <p>None of these are zero-sum. The variable everyone wants to maximize is the same: <em>local execution rate</em>.</p>
      </ESection>

      <ESection kicker="Bundle commercial model" title="What we ask of you, what we don't">
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li><b>We do not take a cut of your hardware sale.</b> No marketplace skim, no per-device royalty.</li>
          <li><b>You bundle the trial term;</b> conversion economics post-trial flow to whichever tier the user chooses.</li>
          <li><b>You get co-marketing</b> at the bundle layer — IrisGo Plus at $8.9 / Pro at $14.9 — your brand is the entry surface.</li>
          <li><b>Your customer support stays on the device;</b> AI-feature support is on us.</li>
        </ul>
      </ESection>

      <ESection kicker="What ships when" title="Sequencing for OEM rollout">
        <ETable
          headers={["Milestone", "What lands", "Who has to be ready"]}
          rows={[
            ["Smart Router GA", "Three-tier decision live; telemetry per-request", "IrisGo + OEM device"],
            ["Payment gateway open", "Free / Plus / Pro tiers selectable; subscriptions billable", "IrisGo + payment processor"],
            ["Acer bundle activation", "Per-device entitlement on first boot", "Acer + IrisGo provisioning"],
            ["GoT rebate live", "Local-execution → wallet credit pipeline", "TBD — instrumentation pending"],
            ["Conversion analytics", "Trial-to-paid cohort dashboards", "IrisGo data team"],
          ]} />
      </ESection>
    </div>
  );
}

// ─────────────────────────────────────────────────── Audience: Creators
function CreatorEcon() {
  return (
    <div>
      <ESection kicker="What this page covers" title="GoT, from the creator's side">
        <p>If you're publishing a Skill on IrisGo Marketplace, this is how money moves from the user, to us, to you. The marketplace policy details — onboarding, review, ranking — live on the <a href="#" onClick={(e) => { e.preventDefault(); window.__driveRoute && window.__driveRoute({name:"rules"}); }} style={{ color: "var(--iris-700)" }}>Rules page</a>. This page is just the economy layer.</p>
      </ESection>

      <ESection kicker="The four GoT use cases" title="Where GoT actually flows">
        <ETable
          headers={["Use case", "Direction", "Notes"]}
          rows={[
            ["Skill payment", "User → IrisGo → Creator", "User pays GoT-Paid for a paid skill. We take the platform fee, you keep the rest."],
            ["NPU rebate", "IrisGo → User", "When local execution saves cloud cost, the user's wallet grows. Doesn't touch creator share."],
            ["Annotation reward (Helix)", "IrisGo → User", "Users earning GoT-Free for opt-in data labeling. Independent of skills."],
            ["Referral bonus", "Mutual: Referrer ↔ Referee", "+100 GoT-Free both sides per accepted referral."],
          ]} />
      </ESection>

      <ESection kicker="Take rate" title="Your share of paid skill revenue">
        <ETable
          headers={["Period", "Platform fee", "Creator keeps"]}
          rows={[
            ["Year 1", "0%", "100%"],
            ["Year 2 (standard)", "15%", "85%"],
            ["Year 2 — first 100 verified creators", "5% (grandfathered)", "95% (Year 2 only)"],
            ["Year 3 onward", "30%", "70%"],
            ["AI App partner tier", "5% (BD-negotiated)", "95% — you bring your own infra"],
            ["Sensitive opt-out tier", "20%", "80% — self-hosted, no CAE auto-injection"],
          ]} />
        <ENote tone="success">
          Take-rate changes get at least 6 months' advance notice. We won't move the goalposts on you between billing cycles.
        </ENote>
      </ESection>

      <ESection kicker="Pricing your skill" title="The five pricing models you can pick from">
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li><b>Free</b> — 0 GoT. You disclose how the skill is funded (ads, data, donation, OSS).</li>
          <li><b>One-time purchase</b> — fixed GoT for perpetual access.</li>
          <li><b>Subscription</b> — monthly or yearly GoT, your choice.</li>
          <li><b>Metered (per-use)</b> — GoT per execution. You declare a per-use cap so users aren't surprised.</li>
          <li><b>Freemium</b> — both tiers within the same skill.</li>
        </ul>
        <p>We do not enforce minimum pricing. We do enforce honest disclosure at the install screen — what permissions you ask for, what data leaves the device, how it's monetized.</p>
      </ESection>

      <ESection kicker="From GoT to cash" title="Closed-loop now, payout later">
        <p>Today (V1) GoT stays inside the ecosystem. Earned GoT can be:</p>
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li>Spent on other skills, image generation, Deep Research Pro</li>
          <li>Held in your wallet (GoT-Paid accumulates indefinitely)</li>
          <li>Transferred to other IrisGo accounts (with caps & cooldowns; see the user tab)</li>
        </ul>
        <p><b>Cash payout</b> opens after the platform crosses ~100K MAU and we have the tax/KYC plumbing in place (1099 in the US, 二代健保 in Taiwan, equivalents elsewhere). Until then, you're earning a real asset that compounds inside a real economy — just not yet a wire transfer.</p>
        <ENote tone="open">
          <b>Open:</b> the exact "first 100 verified creators" definition for the Year 2 grandfather (first-come vs revenue-threshold) is still being worked out. We will publish the rule before Year 1 ends.
        </ENote>
      </ESection>

      <ESection kicker="Smart Router and your skill" title="What the routing layer means for you">
        <p>When a user invokes your skill, Smart Router decides where the underlying model call runs. You don't pick the model — we do, dynamically, against the policy you set in your manifest:</p>
        <ul style={{ paddingLeft: 20, margin: "8px 0" }}>
          <li><b>Default:</b> we route locally when capable, cloud otherwise. Lowest cost, fastest typical response.</li>
          <li><b>Pinned cloud (e.g., Claude Opus only):</b> use when your skill genuinely needs a frontier model. Higher GoT cost passed to the user, transparent in the install dialog.</li>
          <li><b>Pinned local-only:</b> use when the skill is privacy-critical and must never leave the device.</li>
        </ul>
        <p>The router does not change your earnings. It changes our cost-of-revenue per call, which is why local-first routing is what makes the whole take-rate-zero-Y1 strategy survivable.</p>
      </ESection>
    </div>
  );
}

// ─────────────────────────────────────────────────── Main screen
function EconomyScreen({ onNav }) {
  const [tab, setTab] = useStateE("user");

  const tabs = [
    { id: "user",     label: "Users",      subtitle: "What you pay, what you get" },
    { id: "oem",      label: "OEM Partners", subtitle: "Why this aligns selling silicon" },
    { id: "creator",  label: "Creators",   subtitle: "How earning GoT works" },
  ];

  let body = null;
  if (tab === "user") body = <UserEcon />;
  else if (tab === "oem") body = <OEMEcon />;
  else if (tab === "creator") body = <CreatorEcon />;

  return (
    <main style={{ maxWidth: 880, margin: "0 auto", padding: "32px 24px 80px" }}>
      <div style={{ marginBottom: 8 }}>
        <span style={{
          font: "500 11px/1 var(--font-mono)", color: "var(--ink-3)",
          textTransform: "uppercase", letterSpacing: "0.08em",
        }}>Pricing & GoT economy · {ECON_VERSION} · Updated {ECON_UPDATED}</span>
      </div>
      <h1 style={{
        font: "700 32px/1.2 var(--font-display)", color: "var(--ink)",
        margin: "0 0 12px 0",
      }}>The IrisGo economy, in one place</h1>
      <p style={{ font: "400 16px/1.55 var(--font-sans)", color: "var(--ink-2)", margin: 0 }}>
        Pricing, the GoT unit, the wallet model, and how creators and OEM partners
        plug into all of it. Three audiences, one source of truth — open items
        flagged inline so you know what's locked and what we're still finalizing.
      </p>

      <EconTabs value={tab} options={tabs} onChange={setTab} />
      {body}

      <div style={{
        marginTop: 48, paddingTop: 24, borderTop: "1px solid var(--line)",
        font: "400 13px/1.6 var(--font-sans)", color: "var(--ink-3)",
      }}>
        Source: <code style={{ font: "500 12px/1 var(--font-mono)" }}>GoT-Token-Economy-PRD.md v3.0.0</code> (Jan 2026) plus addenda from Smart Router and Intel Superbuilder narratives. <a href="#" onClick={(e) => { e.preventDefault(); onNav && onNav("rules"); }} style={{ color: "var(--iris-700)" }}>Marketplace Rules page</a> covers everything outside the economy layer. Numbers and policies marked TBD will be finalized before the public payment-gateway launch. — IrisGo
      </div>
    </main>
  );
}

window.EconomyScreen = EconomyScreen;
