/* Stripe checkout - a separate payment page (#/checkout) + success page (#/success).
   Flow (Stripe-hosted Checkout): the page asks our backend to create a Checkout
   Session, then redirects the browser to Stripe's secure hosted page. No card
   data and no API keys ever touch the client. Backend lives in /api (server.js). */

// Where the serverless API is reachable. Defaults to same-origin /api (server.js).
// Override for a split deploy: window.IDEAL_OFFER_API = "https://api.example.com/api".
const API_BASE = (typeof window !== "undefined" && window.IDEAL_OFFER_API) || "/api";

const COURSE_OFFER = {
  name: "The Course",
  price: "$39",
  currency: "CAD",
  per: "one-time · lifetime access",
  includes: [
    "All 6 modules - the complete path",
    "Every worksheet, script & template",
    "Resume, LinkedIn & interview playbooks",
    "Lifetime access + free updates",
  ],
};

// The curriculum, pulled from the single source of truth so it never drifts.
const PAY_ICONS = { "module-1": "target", "module-2": "doc", "module-3": "globe", "module-4": "chat", "module-5": "code", "module-6": "badge" };
const PAY_MODS = (typeof MODULES_DATA !== "undefined" ? MODULES_DATA : []).map((m) => ({
  id: m.id, n: m.n, name: m.track, desc: m.title, icon: PAY_ICONS[m.id] || "doc",
}));

function Checkout() {
  const user = useUser();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [pending, setPending] = useState(false);   // waiting on Google sign-in
  const [showGoogle, setShowGoogle] = useState(false); // fallback button revealed

  // already purchased? there's nothing to buy - send them to the course.
  const owns = !!(user && user.paid);
  useEffect(() => { if (owns) window.navigate("/learn/module-1", { replace: true }); }, [owns]);

  const startCheckout = async () => {
    setError(null);
    const signedIn = typeof readUser === "function" ? readUser() : null;
    if (!signedIn || !signedIn.token) { setError("Please sign in to enroll."); return; }
    setLoading(true);
    try {
      const res = await fetch(API_BASE + "/create-checkout-session", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: "Bearer " + signedIn.token },
        body: JSON.stringify({ plan: "course" }),
      });
      const data = await res.json().catch(() => ({}));
      // Server refuses to charge an existing owner — treat it as "already enrolled".
      if (res.status === 409 || data.alreadyPaid) {
        const cur = typeof readUser === "function" ? readUser() : null;
        if (cur) writeUser({ ...cur, paid: true });
        window.navigate("/learn/module-1", { replace: true });
        return;
      }
      if (!res.ok || !data.url) throw new Error(data.error || "Could not start checkout. Please try again.");
      window.location = data.url; // hand off to Stripe's hosted checkout
    } catch (err) {
      setError(err.message || "Something went wrong starting checkout.");
      setLoading(false);
    }
  };

  // Colorful "Get the course" is always shown. If the visitor isn't signed in yet,
  // the click opens Google sign-in first; once signed in, this effect continues.
  // The sign-in response has no purchase status, so we confirm the account doesn't
  // already own the course BEFORE creating a payment (prevents charging a returning
  // owner who was signed out when they clicked pay).
  useEffect(() => {
    if (!(pending && user && user.token)) return;
    let alive = true;
    (async () => {
      try {
        const r = await fetch(API_BASE + "/me", { headers: { Authorization: "Bearer " + user.token } });
        const d = await r.json().catch(() => ({}));
        if (!alive) return;
        if (d && d.paid) {
          const cur = typeof readUser === "function" ? readUser() : null;
          if (cur) writeUser({ ...cur, paid: true });
          setPending(false);
          window.navigate("/learn/module-1", { replace: true });
          return;
        }
      } catch (e) { /* fall through — the server still refuses to double-charge */ }
      if (!alive) return;
      setPending(false);
      startCheckout();
    })();
    return () => { alive = false; };
  }, [pending, user]);

  const onEnroll = () => {
    setError(null);
    const signedIn = typeof readUser === "function" ? readUser() : null;
    if (signedIn && signedIn.token) { startCheckout(); return; }
    setPending(true);
    const started = typeof signInWithGoogle === "function" && signInWithGoogle({
      onError: (m) => { setPending(false); setError(m); },
      onUnavailable: () => setShowGoogle(true), // popup blocked → reveal standard button
    });
    if (!started) { setPending(false); setShowGoogle(true); }
  };

  if (owns) return (
    <main className="po-pay">
      <div className="wrap po-pay-wrap"><p className="po-pay-confirming mono">You already own the course - taking you to the modules…</p></div>
    </main>
  );

  return (
    <main className="po-pay">
      <div className="wrap po-pay-wrap">
        <a className="po-pay-back" href="/">
          <Icon name="arrow" size={15} style={{ transform: "rotate(180deg)" }} /> Back to site
        </a>
        <div className="po-pay-grid">
          <div className="po-pay-intro reveal">
            <span className="eyebrow"><Icon name="badge" size={15} /> Enroll</span>
            <h1>The whole playbook, start to offer.</h1>
            <p>One $39 payment unlocks all six modules end-to-end - from seeing the hiring machine to negotiating and signing. Module 1 is the free preview; this is everything after it.</p>

            <div className="po-pay-curric">
              <span className="po-pay-curric-h mono">What you unlock · 6 modules</span>
              <ol className="po-pay-mods">
                {PAY_MODS.map((m) => (
                  <li key={m.id}>
                    <a className="po-pay-mod" href={"/learn/" + m.id} title={"Preview " + m.n + " · " + m.name}>
                      <span className="po-pay-mod-ic"><Icon name={m.icon} size={16} /></span>
                      <div className="po-pay-mod-txt">
                        <b><span className="mono">{m.n}</span> {m.name}</b>
                        <span>{m.desc}</span>
                      </div>
                      <span className="po-pay-mod-go" aria-hidden="true"><Icon name="arrow" size={15} /></span>
                    </a>
                  </li>
                ))}
              </ol>
            </div>

            <ul className="po-pay-incl">
              {COURSE_OFFER.includes.map((x) => (
                <li key={x}><Icon name="check" size={16} stroke={2.6} /><span>{x}</span></li>
              ))}
            </ul>
          </div>

          <div className="po-pay-card card reveal">
            <span className="po-pay-tag mono">beHired - {COURSE_OFFER.name}</span>
            <div className="po-pay-price">
              <b>{COURSE_OFFER.price}</b>
              <span className="po-pay-cur">{COURSE_OFFER.currency}<em>{COURSE_OFFER.per}</em></span>
            </div>
            <ul className="po-pay-card-feats">
              <li><Icon name="check" size={14} stroke={2.8} /> All 6 modules, forever</li>
              <li><Icon name="check" size={14} stroke={2.8} /> Every template & script</li>
              <li><Icon name="check" size={14} stroke={2.8} /> 30-day money-back guarantee</li>
            </ul>
            <button className="btn btn-primary po-pay-btn" onClick={onEnroll} disabled={loading || pending}>
              {loading
                ? <>Starting secure checkout…</>
                : pending
                  ? <>Connecting Google sign-in…</>
                  : <>Get the course - {COURSE_OFFER.price} {COURSE_OFFER.currency} <Icon name="arrow" size={17} /></>}
            </button>
            {user ? (
              <p className="po-pay-as mono"><Icon name="check" size={12} stroke={2.8} /> Signed in as {user.email}</p>
            ) : (
              <p className="po-pay-signin-note"><Icon name="user" size={14} /> You'll sign in with Google, then go straight to secure checkout - your purchase stays tied to your account.</p>
            )}
            {showGoogle && !user && (
              <div className="po-pay-signin">
                {(typeof GOOGLE_CONFIGURED !== "undefined" && GOOGLE_CONFIGURED)
                  ? <><p className="po-pay-signin-note mono">Continue with Google to enroll:</p><GoogleButton onError={setError} /></>
                  : <a className="btn btn-ghost po-pay-btn" href="/signup"><Icon name="user" size={16} /> Sign in to continue</a>}
              </div>
            )}
            {error && <p className="po-pay-error" role="alert"><Icon name="bolt" size={14} /> {error}</p>}
            <p className="po-pay-secure mono"><Icon name="badge" size={13} /> Secured by Stripe · cards, Apple&nbsp;Pay &amp; Google&nbsp;Pay</p>
            <p className="po-pay-legal">By purchasing you agree to our <a href="/terms">Terms</a> &amp; <a href="/refund">Refund Policy</a>. See our <a href="/privacy">Privacy Policy</a>.</p>
          </div>
        </div>
      </div>
    </main>
  );
}

function CheckoutSuccess() {
  const [state, setState] = useState({ loading: true, ok: false, unconfirmed: false, email: null });

  useEffect(() => {
    const sessionId = new URLSearchParams(window.location.search || "").get("session_id");
    if (!sessionId) { setState({ loading: false, ok: true, unconfirmed: false, email: null }); return; }

    // If signed in, verify + mark the account paid (unlocks content, hides Enroll CTAs).
    const u = typeof readUser === "function" ? readUser() : null;
    if (u && u.token) {
      fetch(API_BASE + "/confirm-purchase", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: "Bearer " + u.token },
        body: JSON.stringify({ sessionId }),
      })
        .then((r) => r.json())
        .then((d) => {
          if (d && d.paid) { const cur = readUser(); if (cur) writeUser({ ...cur, paid: true }); }
          setState({ loading: false, ok: true, unconfirmed: false, email: (cur => cur && cur.email)(readUser()) });
        })
        .catch(() => setState({ loading: false, ok: true, unconfirmed: false, email: null }));
      return;
    }

    fetch(API_BASE + "/session-status?session_id=" + encodeURIComponent(sessionId))
      .then((r) => r.json())
      .then((d) => {
        const paid = d.payment_status === "paid" || d.status === "complete";
        setState({ loading: false, ok: paid, unconfirmed: !paid, email: d.email || null });
      })
      // Don't hold the thank-you hostage to a status hiccup - assume success on the redirect.
      .catch(() => setState({ loading: false, ok: true, unconfirmed: false, email: null }));
  }, []);

  return (
    <main className="po-pay">
      <div className="wrap po-pay-wrap">
        <div className="po-pay-done card reveal">
          {state.loading ? (
            <p className="mono po-pay-confirming">Confirming your payment…</p>
          ) : state.ok ? (
            <>
              <span className="po-pay-check"><Icon name="check" size={30} stroke={2.6} /></span>
              <h1>You’re in.</h1>
              <p>{state.email ? <>A receipt is on its way to <b>{state.email}</b>. </> : null}Your enrollment is confirmed - every module is unlocked.</p>
              <a className="btn btn-primary" href="/learn/module-1">Start with Module 1 <Icon name="arrow" size={17} /></a>
            </>
          ) : (
            <>
              <span className="po-pay-check po-pay-check-wait"><Icon name="bolt" size={28} /></span>
              <h1>Almost there</h1>
              <p>Your payment is still processing. It’ll confirm shortly - check your email for a receipt. If anything looks off, reach us and we’ll sort it out.</p>
              <a className="btn btn-ghost" href="/checkout">Back to checkout</a>
            </>
          )}
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { Checkout, CheckoutSuccess });
