/* =========================================================================
   TAXR — Paywall · Checkout · Hint shop
   =========================================================================
   CREEM URLS — create products in Creem dashboard then replace these:
   https://creem.io/product/prod_XXXXXXXXXXXXXXXXXXXXXXXXX
   ========================================================================= */
const TAXR_CREEM = {
  full:    "https://creem.io/product/prod_2q69SIfcmlhaRCJZ5dYGBr", // $39 full course
  m1:      "https://creem.io/product/prod_4nMbnmtTpeSS1J89OuVZ3z", // $14.99 Module 1
  m2:      "https://creem.io/product/prod_7VXosbP7fupiCcQMFQaWDX", // $14.99 Module 2
  m3:      "https://creem.io/product/prod_1HoCPhzOa0e6VjPLWtjN04", // $14.99 Module 3
  m2m3:    "https://creem.io/product/prod_5bmXWmepCMoOqSpEdkB5Le", // $24.99 Modules 2+3 bundle
  fish25:  "https://creem.io/product/prod_7Xmu6dvKCrBoMtYnwkdttu", // $4.99 — 25 hints
  fish75:  "https://creem.io/product/prod_5PpQRx5fOANFKfW77Xyoks", // $9.99 — 75 hints
};

/* UnlockCard — shows the right purchase path based on where the user is */
function UnlockCard({ nav, moduleId, account, progress }) {
  const D = window.TAXR;
  const mid = moduleId || "m1";
  const m1Passed = (progress && (progress.tests || {}).m1 >= 70);
  const bundle = D.pricing.bundles.m2m3;

  // After M1 is passed and user hits M2 paywall → offer bundle prominently
  const showBundle = mid === "m2" && m1Passed;

  return (
    <div className="card pop" style={{ maxWidth: 480, width: "100%", padding: 32, textAlign: "center", boxShadow: "var(--shadow-lg)", background: "var(--surface)" }} key="unlock">
      <span style={{ width: 56, height: 56, borderRadius: 15, display: "grid", placeItems: "center", margin: "0 auto 18px", background: "var(--amber-soft)", color: "var(--amber)" }}>
        <Icon name="lock" size={26} />
      </span>

      {showBundle ? (
        <>
          <Eyebrow green style={{ justifyContent: "center", marginBottom: 12 }}>Module 1 complete — great work</Eyebrow>
          <h3 className="display" style={{ fontSize: 28 }}>Ready for <span className="it">Module 2?</span></h3>
          <p className="fs-15 t-muted lh-rel" style={{ margin: "14px auto 24px", maxWidth: 360 }}>
            Keep the momentum. Grab Module 2 on its own, or bundle it with Module 3 and save ${bundle.saving}.
          </p>
          <div className="col gap-12">
            <Button block size="lg" arrow onClick={() => nav("checkout", { bundle: "m2m3" })}
              style={{ background: "var(--amber)", borderColor: "var(--amber)" }}>
              Modules 2 & 3 bundle · ${bundle.price} <span style={{ opacity: .65, fontSize: ".82em" }}>save ${bundle.saving}</span>
            </Button>
            <Button block variant="ghost" onClick={() => nav("checkout", { moduleId: "m2" })}>Just Module 2 · $14.99</Button>
            <Button block variant="ghost" onClick={() => nav("checkout", { plan: "full" })}>Full course · $39</Button>
          </div>
        </>
      ) : (
        <>
          <Eyebrow green style={{ justifyContent: "center", marginBottom: 12 }}>You finished the free lessons</Eyebrow>
          <h3 className="display" style={{ fontSize: 30 }}>Keep going to <span className="it">EA-ready.</span></h3>
          <p className="fs-15 t-muted lh-rel" style={{ margin: "14px auto 24px", maxWidth: 340 }}>
            You've seen how Taxr teaches. Unlock the rest of Module 1 — and the other 17 modules — whenever you're ready.
          </p>
          <div className="col gap-12">
            <Button block size="lg" arrow onClick={() => nav("checkout", { plan: "full" })}>Unlock full course · $39</Button>
            <Button block variant="ghost" onClick={() => nav("checkout", { moduleId: mid })}>Just this module · $14.99</Button>
          </div>
        </>
      )}

      <div className="row center gap-12" style={{ marginTop: 18 }}>
        <span className="mono fs-13 t-dim">One-time · lifetime access · no subscription</span>
      </div>
    </div>
  );
}

/* Full paywall page */
function Paywall({ nav, params, account, progress }) {
  return (
    <div className="wrap col center grid-tex" style={{ minHeight: "82vh", padding: "60px 32px", textAlign: "center" }}>
      <span style={{ fontSize: 60 }}>🐧</span>
      <Eyebrow green style={{ justifyContent: "center", margin: "18px 0 12px" }}>Free preview complete</Eyebrow>
      <h1 className="display" style={{ fontSize: 52, maxWidth: 680 }}>That's the free taste. <span className="it">Ready for the rest?</span></h1>
      <p className="fs-18 t-muted lh-rel" style={{ marginTop: 18, maxWidth: 500 }}>
        You worked through the opening lessons of Module 1. The full course takes you all the way to Enrolled Agent — 94 lessons, 18 tests, every flashcard.
      </p>
      <div style={{ marginTop: 34, width: "100%", maxWidth: 480 }}>{UnlockCard({ nav, moduleId: params.moduleId, account, progress })}</div>
    </div>
  );
}

/* Checkout — redirects to Creem, then unlocks on return */
function Checkout({ nav, params, account, onPurchase, onBuyHints }) {
  const D = window.TAXR;

  let item;
  if (params.plan === "full") {
    item = { kind: "full", creemKey: "full", name: "Taxr — Full course", price: 39, sub: "All 18 modules · lifetime access",
      bullets: ["All 3 phases · 94 lessons", "18 module tests + practice exams", "Flashcards for every module", "10 starter hints included", "Free content updates each tax year"] };
  } else if (params.bundle) {
    const b = D.pricing.bundles[params.bundle];
    item = { kind: "bundle", bundleId: params.bundle, creemKey: params.bundle, name: b.label, price: b.price,
      sub: b.modules.length + " modules · lifetime access",
      bullets: b.modules.map((mid) => {
        const m = D.phases.flatMap((p) => p.modules).find((x) => x.id === mid);
        return "Module " + m.n + " — " + m.title;
      }).concat(["Every lesson + test + flashcards", "Lifetime access", "Save $" + b.saving + " vs buying separately"]) };
  } else if (params.hints) {
    const p = D.pricing.hintPacks.find((h) => h.id === params.hints);
    item = { kind: "hints", creemKey: p.id, name: p.count + " hints", price: p.price, sub: "Pip's nudges for tricky questions",
      bullets: [p.count + " hints added to your balance", "Never expire", "Use on any module test"] };
  } else {
    const mod = D.phases.flatMap((p) => p.modules).find((m) => m.id === (params.moduleId || "m1"));
    item = { kind: "module", moduleId: mod.id, creemKey: mod.id, name: "Module " + mod.n + " — " + mod.title, price: 14.99, sub: mod.lessons + " lessons · lifetime access",
      bullets: ["Every lesson in this module", "The module test + flashcards", "Lifetime access", "Upgrade to full course anytime"] };
  }

  const creemUrl = TAXR_CREEM[item.creemKey];
  const launching = !creemUrl;

  function pay() {
    if (launching) return;
    // Require Waddl3 ID for module/course purchases so the webhook can record the unlock
    if (account.guest && item.kind !== "hints") {
      nav("auth", { mode: "signup", returnTo: "checkout", returnParams: params });
      return;
    }
    const returnParam = item.kind === "full" ? "full"
      : item.kind === "bundle" ? "bundle_" + item.bundleId
      : item.kind === "module" ? "mod_" + item.moduleId
      : "hints_" + params.hints;
    const returnUrl = encodeURIComponent(window.location.href.split("?")[0] + "?taxr_paid=" + returnParam);
    const url = account.email ? creemUrl + "?prefilled_email=" + encodeURIComponent(account.email) + "&success_url=" + returnUrl : creemUrl + "?success_url=" + returnUrl;
    window.location.href = url;
  }

  return (
    <div className="wrap" style={{ padding: "30px 32px 80px", maxWidth: 920, margin: "0 auto" }}>
      <button className="row gap-8 fs-14 t-dim" onClick={() => nav("dashboard")} style={{ marginBottom: 24 }}>
        <Icon name="back" size={16} /> Cancel
      </button>
      <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 28, alignItems: "start" }}>

        {/* checkout CTA */}
        <div className="card card-pad" style={{ padding: 32 }}>
          <h1 className="serif" style={{ fontSize: 28, marginBottom: 6 }}>Checkout</h1>
          <p className="fs-14 t-muted" style={{ marginBottom: 28 }}>
            Secure payment via <strong>Creem</strong>. One-time charge — no subscription.
          </p>

          {launching ? (
            <div style={{ textAlign: "center", padding: "24px 0" }}>
              <span style={{ fontSize: 40 }}>🐧</span>
              <p className="fs-16 t-muted" style={{ marginTop: 14, lineHeight: 1.6 }}>
                Payments for Taxr are <strong>launching soon</strong>.<br />
                Check back shortly — or{" "}
                <a href="/account" className="t-blue" target="_blank" rel="noopener">sign up for Waddl3 ID</a>{" "}
                to be notified.
              </p>
            </div>
          ) : account.guest && item.kind !== "hints" ? (
            <div style={{ textAlign: "center" }}>
              <div className="card" style={{ padding: "18px 20px", marginBottom: 20, background: "var(--blue-soft)", borderColor: "rgba(96,165,250,0.25)" }}>
                <p className="fs-14" style={{ color: "var(--blue-bright)", lineHeight: 1.6, marginBottom: 14 }}>
                  <strong>Sign in to purchase.</strong><br />
                  A Waddl3 ID links your purchase to your account so access is never lost.
                </p>
                <Button block onClick={() => nav("auth", { mode: "signup", returnTo: "checkout", returnParams: params })}>
                  Create free account → then buy
                </Button>
              </div>
              <button className="fs-13 t-dim" onClick={() => nav("auth", { mode: "login", returnTo: "checkout", returnParams: params })}>
                Already have an account? Sign in
              </button>
            </div>
          ) : (
            <>
              <Button block size="lg" onClick={pay} style={{ marginBottom: 16 }}>
                Pay ${item.price.toFixed(2)} via Creem →
              </Button>
              <p className="mono fs-13 t-dim center" style={{ justifyContent: "center", gap: 8 }}>
                <Icon name="lock" size={13} /> Secured by Creem · you'll be redirected
              </p>
            </>
          )}
        </div>

        {/* order summary */}
        <div className="card card-pad" style={{ background: "var(--surface)", padding: 30 }}>
          <span className="mono fs-13 t-dim upper">Order summary</span>
          <div className="row spread" style={{ alignItems: "flex-start", margin: "16px 0 8px" }}>
            <div className="col" style={{ gap: 4, maxWidth: 200 }}>
              <span className="serif" style={{ fontSize: 19, lineHeight: 1.2 }}>{item.name}</span>
              <span className="fs-13 t-muted">{item.sub}</span>
            </div>
            <span className="serif" style={{ fontSize: 24 }}>${item.price}</span>
          </div>
          <div className="hr" style={{ margin: "18px 0" }} />
          <div className="col gap-12" style={{ marginBottom: 20 }}>
            {item.bullets.map((b) => (
              <div key={b} className="row gap-12">
                <Icon name="check" size={16} style={{ color: "var(--green)", flex: "none", marginTop: 2 }} />
                <span className="fs-14 t-muted">{b}</span>
              </div>
            ))}
          </div>
          <div className="hr" style={{ margin: "0 0 16px" }} />
          <div className="row spread">
            <span className="fs-15" style={{ fontWeight: 600 }}>Total</span>
            <span className="serif" style={{ fontSize: 22 }}>${item.price.toFixed(2)}</span>
          </div>
          {item.kind === "module" && (
            <button className="row center gap-8 fs-13 t-blue" style={{ width: "100%", marginTop: 18, justifyContent: "center" }} onClick={() => nav("checkout", { plan: "full" })}>
              <Icon name="spark" size={14} /> Get all 18 modules for $39 instead
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

/* Hint shop modal */
function HintShop({ onClose, nav }) {
  const D = window.TAXR;
  return (
    <Modal onClose={onClose} max={460}>
      <div style={{ padding: 30 }}>
        <div className="row spread" style={{ marginBottom: 18 }}>
          <div className="row gap-12">
            <span style={{ width: 42, height: 42, borderRadius: 12, display: "grid", placeItems: "center", background: "var(--amber-soft)", color: "var(--amber)" }}><Icon name="fish" size={20} /></span>
            <div className="col"><span className="serif" style={{ fontSize: 20 }}>Top up hints</span><span className="fs-13 t-muted">Pip's nudges, whenever you're stuck.</span></div>
          </div>
          <button onClick={onClose} className="t-dim"><Icon name="x" size={20} /></button>
        </div>
        <div className="col gap-12">
          {D.pricing.hintPacks.map((p) => (
            <button key={p.id} className="card card-hover row spread" onClick={() => { onClose(); nav("checkout", { hints: p.id }); }}
              style={{ padding: "18px 20px", borderColor: p.best ? "rgba(231,179,92,0.4)" : "var(--line)", alignItems: "center" }}>
              <div className="row gap-14">
                <span className="row gap-8" style={{ color: "var(--amber)" }}><Icon name="fish" size={18} /><span className="serif" style={{ fontSize: 26, color: "var(--text)" }}>{p.count}</span></span>
                <div className="col" style={{ alignItems: "flex-start" }}>
                  <span className="fs-15" style={{ fontWeight: 600 }}>{p.count} hints {p.best && <Badge kind="amber" style={{ marginLeft: 6 }}>Best value</Badge>}</span>
                  <span className="fs-13 t-muted">{p.blurb}</span>
                </div>
              </div>
              <span className="serif" style={{ fontSize: 22 }}>${p.price}</span>
            </button>
          ))}
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { UnlockCard, Paywall, Checkout, HintShop });
