/* global React */
const { useState } = React;

// ───────── Tokens (subset, from MASTER.md §1) ─────────
const TOKENS = {
  light: {
    primary: "#0F172A",
    accent: "#15803D",
    accentBorder: "#15803D",
    onAccent: "#FFFFFF",
    background: "#F8FAFC",
    surface: "#FFFFFF",
    surfaceMuted: "#F1F5F9",
    border: "#E2E8F0",
    textPrimary: "#0F172A",
    textSecondary: "#475569",
    textTertiary: "#64748B",
    examMid: "#115E33",      // recommended-tier highlight
    examMidFill: "rgba(17,94,51,0.08)",
    info: "#0284C7",
    shadow: "0 8px 24px rgba(15,23,42,0.08)",
    shadowSoft: "0 1px 2px rgba(15,23,42,0.04)",
  },
  dark: {
    primary: "#F8FAFC",
    accent: "#34D399",
    accentBorder: "#34D399",
    onAccent: "#022C16",
    background: "#0B1120",
    surface: "#111827",
    surfaceMuted: "#1E293B",
    border: "#1F2937",
    textPrimary: "#F8FAFC",
    textSecondary: "#CBD5E1",
    textTertiary: "#94A3B8",
    examMid: "#10B981",
    examMidFill: "rgba(16,185,129,0.14)",
    info: "#38BDF8",
    shadow: "0 8px 24px rgba(0,0,0,0.45)",
    shadowSoft: "0 1px 2px rgba(0,0,0,0.4)",
  },
};

const SF = {
  // SF-Pro stack (no third-party fonts)
  text: '"SF Pro Text", -apple-system, "Helvetica Neue", Helvetica, Arial, "PingFang SC", sans-serif',
  display: '"SF Pro Display", -apple-system, "Helvetica Neue", Helvetica, Arial, "PingFang SC", sans-serif',
  rounded: '"SF Pro Rounded", "SF Pro Display", -apple-system, "Helvetica Neue", "PingFang SC", sans-serif',
  mono: '"SF Mono", ui-monospace, Menlo, Consolas, monospace',
};

// ───────── Status bar (iOS) ─────────
function StatusBar({ theme }) {
  const t = TOKENS[theme];
  return (
    <div style={{
      height: 54, padding: "16px 24px 0", display: "flex",
      justifyContent: "space-between", alignItems: "center",
      color: t.textPrimary, fontFamily: SF.text, fontSize: 15,
      fontWeight: 600, letterSpacing: 0.2,
    }}>
      <span style={{ fontVariantNumeric: "tabular-nums" }}>9:41</span>
      <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
        {/* signal */}
        <svg width="17" height="11" viewBox="0 0 17 11"><g fill={t.textPrimary}>
          <rect x="0" y="7" width="3" height="4" rx="0.5"/>
          <rect x="4.5" y="5" width="3" height="6" rx="0.5"/>
          <rect x="9" y="2.5" width="3" height="8.5" rx="0.5"/>
          <rect x="13.5" y="0" width="3" height="11" rx="0.5"/>
        </g></svg>
        {/* wifi */}
        <svg width="15" height="11" viewBox="0 0 15 11" fill={t.textPrimary}>
          <path d="M7.5 0C4.6 0 1.95 1.05 0 2.78l1.4 1.55C2.96 2.94 5.13 2.06 7.5 2.06c2.37 0 4.54.88 6.1 2.27L15 2.78C13.05 1.05 10.4 0 7.5 0zm0 3.7c-2 0-3.83.74-5.18 1.97l1.4 1.55c.97-.88 2.3-1.42 3.78-1.42 1.48 0 2.81.54 3.78 1.42l1.4-1.55C11.33 4.44 9.5 3.7 7.5 3.7zm0 3.7c-1.13 0-2.13.4-2.88 1.06L7.5 11l2.88-2.54A4.4 4.4 0 0 0 7.5 7.4z"/>
        </svg>
        {/* battery */}
        <svg width="27" height="12" viewBox="0 0 27 12">
          <rect x="0.5" y="0.5" width="22" height="11" rx="3" fill="none" stroke={t.textPrimary} strokeOpacity="0.4"/>
          <rect x="2" y="2" width="19" height="8" rx="1.5" fill={t.textPrimary}/>
          <rect x="23.5" y="4" width="2" height="4" rx="1" fill={t.textPrimary} fillOpacity="0.4"/>
        </svg>
      </div>
    </div>
  );
}

// ───────── Sheet handle ─────────
function SheetHandle({ theme }) {
  const t = TOKENS[theme];
  return (
    <div style={{ display: "flex", justifyContent: "center", padding: "6px 0 0" }}>
      <div style={{ width: 36, height: 5, borderRadius: 999, background: t.border }} />
    </div>
  );
}

// ───────── Close × (SF Symbol intent: xmark) ─────────
function CloseButton({ theme, anchor }) {
  const t = TOKENS[theme];
  return (
    <button
      data-anno={anchor}
      style={{
        appearance: "none", border: "none", background: t.surfaceMuted,
        width: 32, height: 32, borderRadius: 999,
        display: "flex", alignItems: "center", justifyContent: "center",
        cursor: "pointer", padding: 0,
      }}
      aria-label="关闭"
    >
      <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
        <path d="M1 1L12 12M12 1L1 12" stroke={t.textSecondary} strokeWidth="1.8" strokeLinecap="round"/>
      </svg>
    </button>
  );
}

// ───────── Product card ─────────
function ProductCard({ theme, selected, recommended, label, sub, price, period, badge, monthlyEq, onClick, anchor }) {
  const t = TOKENS[theme];
  // Visual weight (border + tint) is driven by `recommended`, not `selected`.
  // Selection only fills the radio. This keeps the year card visually anchored
  // while leaving default selection empty (anti dark pattern).
  const heavy = recommended;
  const borderColor = heavy ? t.examMid : t.border;
  return (
    <div
      data-anno={anchor}
      onClick={onClick}
      style={{
        background: heavy ? t.examMidFill : t.surface,
        border: `${heavy ? 2 : 1}px solid ${borderColor}`,
        borderRadius: 16,
        padding: heavy ? "15px 15px" : "16px 16px",
        boxShadow: heavy ? "none" : t.shadowSoft,
        display: "flex", alignItems: "center", gap: 12,
        cursor: "pointer", position: "relative",
      }}
    >
      {/* radio — reflects user choice only */}
      <div style={{
        width: 22, height: 22, borderRadius: 999, flexShrink: 0,
        border: `2px solid ${selected ? t.examMid : t.border}`,
        background: selected ? t.examMid : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        {selected && <div style={{ width: 8, height: 8, borderRadius: 999, background: theme === "dark" ? t.onAccent : "#fff" }} />}
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
            <span style={{
              fontFamily: SF.text, fontSize: 17, fontWeight: 600,
              color: t.textPrimary, letterSpacing: -0.1,
            }}>{label}</span>
            {badge && (
              <span style={{
                fontFamily: SF.text, fontSize: 11, fontWeight: 600,
                color: theme === "dark" ? t.onAccent : "#fff",
                background: t.examMid, padding: "2px 8px", borderRadius: 999,
                letterSpacing: 0.2,
              }}>{badge}</span>
            )}
          </div>
          <div style={{
            fontFamily: SF.rounded, fontSize: 17, fontWeight: 600,
            color: t.textPrimary, fontVariantNumeric: "tabular-nums",
            whiteSpace: "nowrap",
          }}>
            ¥{price}<span style={{ color: t.textTertiary, fontWeight: 500 }}> / {period}</span>
          </div>
        </div>
        <div style={{
          marginTop: 4, fontFamily: SF.text, fontSize: 13,
          color: t.textSecondary, display: "flex",
          justifyContent: "space-between", gap: 8,
        }}>
          <span>{sub}</span>
          {monthlyEq && (
            <span style={{ fontFamily: SF.rounded, color: t.textTertiary, fontVariantNumeric: "tabular-nums" }}>
              ≈ ¥{monthlyEq}/月
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

// ───────── Pricing source-of-truth (single map for CTA + disclosure) ─────────
const TIERS = {
  week:  { price: 9,  period: "周", trial: false },
  month: { price: 18, period: "月", trial: false },
  year:  { price: 98, period: "年", trial: true, trialDays: 3 },
};

// 4-state CTA reducer. `none` is the initial state; the other three mirror TIERS.
function ctaStateFor(tier) {
  switch (tier) {
    case null:
    case undefined:
      return { kind: "none",    label: "请选择订阅方案",    disabled: true };
    case "week":
      return { kind: "weekly",  label: "订阅 ¥9 / 周",       disabled: false };
    case "month":
      return { kind: "monthly", label: "订阅 ¥18 / 月",      disabled: false };
    case "year":
      return { kind: "yearly",  label: "开始 3 天免费试用",   disabled: false };
    default:
      throw new Error(`Unknown tier: ${tier}`);
  }
}

// Auto-renew disclosure body — tier-aware. Returns { headline, body, cancel }.
// `none` keeps the block visible (compliance) but copy is generic until selection.
function disclosureFor(tier) {
  const cancel = "可在 设置 › Apple ID › 订阅（Android：Google Play › 订阅）中随时关闭，关闭后当期不再扣费。";
  switch (tier) {
    case "year":
      return {
        headline: "自动续费说明",
        priceLabel: "¥98 / 年",
        body: "3 天试用结束后自动按 [PRICE] 续费。续费前 24 小时通过邮件与 App 推送提醒。",
        cancel,
      };
    case "month":
      return {
        headline: "自动续费说明",
        priceLabel: "¥18 / 月",
        body: "订阅期满后自动按 [PRICE] 续费。续费前 24 小时通过邮件与 App 推送提醒。",
        cancel,
      };
    case "week":
      return {
        headline: "自动续费说明",
        priceLabel: "¥9 / 周",
        body: "订阅期满后自动按 [PRICE] 续费。续费前 24 小时通过邮件与 App 推送提醒。",
        cancel,
      };
    case null:
    case undefined:
    default:
      return {
        headline: "自动续费说明",
        priceLabel: null,
        body: "订阅期满后将自动续费当前所选方案。续费前 24 小时通过邮件与 App 推送提醒。",
        cancel,
      };
  }
}

// ───────── Paywall surface ─────────
function Paywall({ theme = "light", showAnno = false }) {
  const t = TOKENS[theme];
  const [selected, setSelected] = useState(null); // no default — anti-dark-pattern

  const cta = ctaStateFor(selected);
  const disclosure = disclosureFor(selected);

  return (
    <div style={{
      width: 393, height: 852, background: t.background,
      color: t.textPrimary, fontFamily: SF.text,
      position: "relative", overflow: "hidden",
      display: "flex", flexDirection: "column",
    }}>
      <StatusBar theme={theme} />
      <SheetHandle theme={theme} />

      <div style={{ padding: "8px 20px 0", flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
        {/* Close (own row, left) */}
        <div style={{ padding: "8px 0 12px" }}>
          <CloseButton theme={theme} anchor="A1" />
        </div>

        {/* Parent-supervision banner — full-width, own row */}
        <div data-anno="C4a" style={{
          width: "100%",
          padding: "10px 12px",
          background: t.surfaceMuted,
          borderRadius: 10,
          fontFamily: SF.text, fontSize: 12.5, lineHeight: 1.4,
          color: t.textSecondary,
          display: "flex", alignItems: "center", gap: 8,
          marginBottom: 14,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
            <circle cx="7" cy="7" r="6" stroke={t.textTertiary} strokeWidth="1.2"/>
            <path d="M7 4v3.5M7 9.7v0.3" stroke={t.textTertiary} strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
          <span>建议在家长指导下开通订阅</span>
        </div>

        {/* Title block */}
        <div style={{ paddingBottom: 14 }}>
          <div data-anno="A1t" style={{
            fontFamily: SF.display, fontSize: 26, fontWeight: 700,
            lineHeight: 1.18, color: t.textPrimary, letterSpacing: -0.4,
          }}>
            把中考体测<br />沉进日常练习
          </div>
          <div style={{
            marginTop: 8, fontFamily: SF.text, fontSize: 14,
            color: t.textSecondary, lineHeight: 1.45,
          }}>
            9 省中考标准 · 实时分数对照 · 隐私本地
          </div>
        </div>

        {/* Product cards */}
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <ProductCard
            theme={theme}
            anchor="A1p"
            selected={selected === "week"}
            onClick={() => setSelected("week")}
            label="周订阅"
            sub="灵活短期备考"
            price="9"
            period="周"
          />
          <ProductCard
            theme={theme}
            anchor="A1p"
            selected={selected === "month"}
            onClick={() => setSelected("month")}
            label="月订阅"
            sub="一个完整冲刺月"
            price="18"
            period="月"
          />
          <ProductCard
            theme={theme}
            anchor="A1p"
            selected={selected === "year"}
            recommended
            onClick={() => setSelected("year")}
            label="年订阅"
            sub="3 天免费试用"
            price="98"
            period="年"
            badge="推荐"
            monthlyEq="8.17"
          />
        </div>

        {/* Auto-renew disclosure block — body-size, tier-aware */}
        <div data-anno="C3" style={{
          marginTop: 14, padding: "12px 14px",
          background: t.surfaceMuted, borderRadius: 12,
          fontFamily: SF.text, fontSize: 13, lineHeight: 1.55,
          color: t.textPrimary,
        }}>
          <div style={{ fontWeight: 600, marginBottom: 4, fontSize: 13 }}>
            {disclosure.headline}
          </div>
          <div style={{ color: t.textSecondary }}>
            {disclosure.body.split("[PRICE]").map((seg, i, arr) => (
              <React.Fragment key={i}>
                {seg}
                {i < arr.length - 1 && disclosure.priceLabel && (
                  <span style={{ fontFamily: SF.rounded, color: t.textPrimary, fontWeight: 600 }}>
                    {disclosure.priceLabel}
                  </span>
                )}
              </React.Fragment>
            ))}
            <span data-anno="C2b C3c" style={{ display: "block", marginTop: 4 }}>
              {disclosure.cancel}
            </span>
          </div>
        </div>

        {/* Parent confirm gate */}
        <div data-anno="C4b" style={{
          marginTop: 10,
          display: "flex", alignItems: "flex-start", gap: 10,
          fontFamily: SF.text, fontSize: 12.5, color: t.textSecondary,
          lineHeight: 1.5,
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0, marginTop: 2 }}>
            <path d="M8 1.5L2 4v4c0 3.5 2.5 5.7 6 6.5 3.5-.8 6-3 6-6.5V4l-6-2.5z"
              fill="none" stroke={t.info} strokeWidth="1.4"/>
            <path d="M5.5 8l1.8 1.8L10.5 6.5" fill="none" stroke={t.info} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span>
            首次开通需家长确认：<b style={{ color: t.textPrimary, fontWeight: 600 }}>短信验证码 / 身份证末 4 位 / 家长 PIN</b>，三选一。
          </span>
        </div>

        {/* CTA — driven by ctaStateFor(selected), 4 states */}
        <button data-anno="A1c" disabled={cta.disabled} style={{
          marginTop: 14,
          appearance: "none", border: "none",
          cursor: cta.disabled ? "not-allowed" : "pointer",
          width: "100%", height: 52, borderRadius: 14,
          background: cta.disabled ? t.surfaceMuted : t.accent,
          color: cta.disabled ? t.textTertiary : t.onAccent,
          fontFamily: SF.text, fontSize: 17, fontWeight: 600,
          letterSpacing: 0.1,
          fontVariantNumeric: "tabular-nums",
          boxShadow: cta.disabled ? "none" : t.shadow,
          transition: "background 160ms ease, color 160ms ease",
        }}>
          {cta.label}
        </button>

        {/* Restore as ghost button */}
        <button data-anno="A2" style={{
          marginTop: 8,
          appearance: "none", border: "none", background: "transparent",
          width: "100%", height: 36, cursor: "pointer",
          color: t.accent, fontFamily: SF.text, fontSize: 15, fontWeight: 500,
          display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
        }}>
          <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
            <path d="M11 6.5a4.5 4.5 0 1 1-1.3-3.18M11 1v3h-3" stroke={t.accent} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          恢复购买
        </button>

        {/* Footer links */}
        <div data-anno="A1f" style={{
          marginTop: "auto",
          padding: "10px 0 18px",
          display: "flex", justifyContent: "center",
          gap: 0, fontFamily: SF.text, fontSize: 12,
          color: t.textTertiary,
        }}>
          <FooterLink theme={theme}>用户协议</FooterLink>
          <Sep theme={theme} />
          <FooterLink theme={theme}>隐私政策</FooterLink>
          <Sep theme={theme} />
          <FooterLink theme={theme}>联系开发者</FooterLink>
        </div>

        {/* Home indicator */}
        <div style={{ display: "flex", justifyContent: "center", paddingBottom: 8 }}>
          <div style={{ width: 134, height: 5, borderRadius: 999, background: t.textPrimary, opacity: 0.85 }} />
        </div>
      </div>

      {showAnno && <AnnotationOverlay theme={theme} />}
    </div>
  );
}

function Sep({ theme }) {
  const t = TOKENS[theme];
  return <span style={{ padding: "0 10px", color: t.border }}>·</span>;
}
function FooterLink({ theme, children }) {
  const t = TOKENS[theme];
  return (
    <span style={{
      color: t.textSecondary, textDecoration: "none",
      fontWeight: 500, cursor: "pointer",
    }}>{children}</span>
  );
}

// ───────── Annotation overlay (compliance map) ─────────
const ANNOTATIONS = [
  { id: "A1", x: 16,  y: 124, label: "iOS 3.1.2(a)", note: "Title + 三档价格 + 周期 视觉层级高于 CTA；Close × 始终可见 top-left", color: "#0284C7" },
  { id: "A2", x: 16,  y: 695, label: "iOS 3.1.2",    note: "Restore Purchases ghost button", color: "#0284C7" },
  { id: "C2", x: 16,  y: 528, label: "Google Play",  note: "Free-trial → paid 转换 + Play 内取消路径", color: "#7C3AED" },
  { id: "C3", x: 16,  y: 488, label: "上海消保委",   note: "「自动续费」字号 ≥ 正文（13pt）+ 24h 续费前提醒文案", color: "#B45309" },
  { id: "C4", x: 16,  y: 612, label: "未成年人保护", note: "家长确认（SMS / 身份证末 4 / PIN）+ 顶部家长指导提示", color: "#15803D" },
];

function AnnotationOverlay() {
  return null; // overlay drawn in canvas, not on the device, to avoid noise
}

// expose
window.Paywall = Paywall;
window.PaywallTokens = TOKENS;
window.PaywallAnnotations = ANNOTATIONS;
