// Paywall (in-app, faux Stripe) — also handles signup + login.
// Renders when the user enters the dashboard while signed out (signup/login)
// or signed in but not yet paid (pay only).

const { useState: useStateGate } = React;

// ===== Paywall ($7/month) — merged signup + payment =====
// If the user isn't signed in (no session prop), the form also collects
// email + password and creates a Supabase account on submit before
// marking them as paid. Returning users can toggle to a Log-in view.
const Paywall = ({ onUnlock, onBack, session }) => {
  const isSignedIn = !!session;
  // If the URL has a "login=1" or auth-callback marker, prefer the login
  // tab so users coming back from the email confirmation link don't see
  // an empty signup form.
  const _wantsLogin = (() => {
    if (typeof window === "undefined") return false;
    const s = window.location.search || "";
    const h = window.location.hash || "";
    return s.includes("login=1") || s.includes("type=signup") || h.includes("type=signup") || h.includes("confirmed");
  })();
  const [mode, setMode] = useStateGate(
    isSignedIn ? "pay" : (_wantsLogin ? "login" : "signup")
  ); // "signup" | "login" | "pay"
  const [name, setName] = useStateGate("");
  const [email, setEmail] = useStateGate("");
  const [password, setPassword] = useStateGate("");
  const [card, setCard] = useStateGate("");
  const [exp, setExp] = useStateGate("");
  const [cvc, setCvc] = useStateGate("");
  const [processing, setProcessing] = useStateGate(false);
  const [err, setErr] = useStateGate("");
  const [info, setInfo] = useStateGate("");

  const supaConfigured =
    typeof window.SUPABASE_CONFIGURED === "function" && window.SUPABASE_CONFIGURED();

  const prefillDemo = () => {
    // Fill name + card info, leave email/password for the user.
    setName("Jamie Rivera");
    setCard("4242 4242 4242 4242");
    setExp("12/28");
    setCvc("123");
  };

  const switchMode = (m) => {
    setMode(m);
    setErr("");
    setInfo("");
  };

  const forgotPassword = async () => {
    setErr(""); setInfo("");
    const sb = window.getSupabase && window.getSupabase();
    if (!sb) { setErr("Supabase not configured."); return; }
    if (!email.trim()) { setErr("Enter your email above first."); return; }
    try {
      const { error } = await sb.auth.resetPasswordForEmail(email.trim());
      if (error) throw error;
      setInfo("If that email exists, a reset link is on its way.");
    } catch (e) {
      setErr((e && e.message) || "Could not send reset email.");
    }
  };

  const pay = async (e) => {
    e.preventDefault();
    setErr(""); setInfo("");
    const sb = window.getSupabase && window.getSupabase();

    // ---- LOGIN mode: just authenticate, then paywall component will be re-rendered with session ----
    if (mode === "login") {
      if (!sb) { setErr("Supabase not configured yet."); return; }
      if (!email.trim() || !password) { setErr("Email and password required."); return; }
      setProcessing(true);
      try {
        const { error } = await sb.auth.signInWithPassword({ email: email.trim(), password });
        if (error) throw error;
        // App will detect new session via onAuthStateChange and re-render us.
        // If the user is already paid, App will skip past us to the dashboard.
      } catch (ex) {
        setErr((ex && ex.message) || "Could not log in.");
      } finally {
        setProcessing(false);
      }
      return;
    }

    // ---- SIGNUP and PAY both require name + card details ----
    if (!name.trim()) { setErr("Add the name on the card."); return; }

    // Card validation — required before we'll let signup or pay through.
    const cardDigits = (card || "").replace(/\D/g, "");
    if (cardDigits.length < 13 || cardDigits.length > 19) {
      setErr("Enter a valid card number.");
      return;
    }
    if (!/^\d{2}\/\d{2}$/.test((exp || "").trim())) {
      setErr("Expiry must be in MM/YY format.");
      return;
    }
    if (!/^\d{3,4}$/.test((cvc || "").trim())) {
      setErr("CVC must be 3 or 4 digits.");
      return;
    }

    // ---- SIGNUP mode: create account first, then mark paid ----
    if (mode === "signup") {
      if (!sb) { setErr("Supabase not configured yet."); return; }
      if (!email.trim() || !password) { setErr("Email and password required."); return; }
      if (password.length < 6) { setErr("Password must be at least 6 characters."); return; }
      setProcessing(true);
      try {
        const { data, error } = await sb.auth.signUp({
          email: email.trim(),
          password,
          options: {
            data: { name: name.trim() },
            // After clicking the confirm link, return to the dashboard
            // route with a "login=1" flag so the form defaults to the
            // login tab. Don't append a hash — Supabase appends its
            // own auth tokens to the hash, and overlapping fragments
            // confuse the URL parser.
            emailRedirectTo: window.location.origin + "/?dashboard=1&login=1",
          },
        });
        if (error) throw error;
        // Card was already validated above — mark them paid locally now
        // so we don't ask again after they confirm + sign in. The next
        // time they're authenticated, App.jsx will sync this flag to
        // their profiles row.
        try { localStorage.setItem("pp_paid", "1"); } catch (_) {}
        try { localStorage.setItem("pp_name", name.trim()); } catch (_) {}
        if (!data.session) {
          // Email confirmation is on. Tell the user — but their trial is
          // already set up; they just need to confirm and log in.
          setProcessing(false);
          setInfo("Trial set up! Check your inbox to confirm your email, then sign in to access your dashboard.");
          return;
        }
        // Otherwise we have a session already — fall through to the paid step.
      } catch (ex) {
        setProcessing(false);
        setErr((ex && ex.message) || "Could not create account.");
        return;
      }
    }

    // ---- Mark paid (faux Stripe) ----
    if (!processing) setProcessing(true);
    setTimeout(() => {
      try { localStorage.setItem("pp_paid", "1"); } catch (_) {}
      try { localStorage.setItem("pp_name", name.trim()); } catch (_) {}
      onUnlock();
    }, 1100);
  };

  return (
    <div className="paywall-shell">
      <div className="paywall-grid">
        {/* Left: pitch */}
        <div className="paywall-pitch">
          <a onClick={onBack} className="paywall-back">← back to reading</a>
          <h1 className="paywall-h1">
            Your numbers, your stack, <em>all in one place.</em>
          </h1>
          <p className="paywall-lede">
            The Index and Weekly Reader stay free forever. The Dashboard — where Splat reads your labs, tracks your stack and nudges you at the right moment — is $7/mo. Cancel anytime from settings.
          </p>

          <ul className="paywall-list">
            <li><span className="tick">✓</span> Personal stack tracker · doses, timing, streaks</li>
            <li><span className="tick">✓</span> Biomarker trends · upload a PDF, Splat reads it</li>
            <li><span className="tick">✓</span> 8-week cycle timeline · taper, wash, repeat</li>
            <li><span className="tick">✓</span> Supply tracker · "you have 6 days of Mots-C left"</li>
            <li><span className="tick">✓</span> The floating Splat, nudging in context</li>
          </ul>

          <div className="paywall-splat-quote">
            <Splat size={54} expression="reading" />
            <div>
              <div className="from">Splat, probably:</div>
              <p>"i read 2,000+ papers so you don't have to. seven bucks feels fair, right?"</p>
            </div>
          </div>
        </div>

        {/* Right: checkout */}
        <div className="paywall-card">
          <div className="paywall-price-row">
            <div>
              <div className="paywall-price">
                $7<span className="slash">/mo</span>
              </div>
              <div className="mono" style={{ color: "var(--muted)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase" }}>
                7-day free trial · cancel anytime
              </div>
            </div>
            <span className="pill green">● 4,218 members</span>
          </div>

          <div className="paywall-line-items">
            <div className="paywall-line">
              <span>PeptidePal Dashboard · monthly</span>
              <span className="mono">$7.00</span>
            </div>
            <div className="paywall-line">
              <span>Splat's Tips (included)</span>
              <span className="mono" style={{ color: "var(--splat-deep)" }}>free</span>
            </div>
            <div className="paywall-line total">
              <span>Due today</span>
              <span className="mono">$0.00</span>
            </div>
            <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.06em", marginTop: 4 }}>
              $7.00 will be charged after your 7-day trial ends.
            </div>
          </div>

          {isSignedIn && (
            <div style={{
              background: "var(--splat-soft)",
              border: "1px solid var(--splat-deep)",
              borderRadius: 12,
              padding: "10px 14px",
              fontSize: 13,
              marginBottom: 16,
              display: "flex",
              alignItems: "center",
              gap: 10,
              color: "var(--splat-deep)",
            }}>
              <span style={{ fontSize: 16 }}>✓</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>You're signed in{session && session.user && session.user.email ? ` as ${session.user.email}` : ""}.</div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-2)", marginTop: 2 }}>
                  One last step — confirm your card to start your free trial.
                </div>
              </div>
            </div>
          )}

          {!isSignedIn && (
            <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
              <button type="button" onClick={() => switchMode("signup")}
                style={{
                  flex: 1, padding: "10px 12px",
                  background: mode === "signup" ? "var(--ink)" : "transparent",
                  color: mode === "signup" ? "var(--cream)" : "var(--ink)",
                  border: "1.5px solid var(--ink)", borderRadius: 999,
                  fontFamily: "var(--mono)", fontSize: 11, textTransform: "uppercase",
                  letterSpacing: "0.12em", cursor: "pointer",
                }}>New · Start trial</button>
              <button type="button" onClick={() => switchMode("login")}
                style={{
                  flex: 1, padding: "10px 12px",
                  background: mode === "login" ? "var(--ink)" : "transparent",
                  color: mode === "login" ? "var(--cream)" : "var(--ink)",
                  border: "1.5px solid var(--ink)", borderRadius: 999,
                  fontFamily: "var(--mono)", fontSize: 11, textTransform: "uppercase",
                  letterSpacing: "0.12em", cursor: "pointer",
                }}>Already a member</button>
            </div>
          )}

          {!supaConfigured && (
            <div style={{ background: "var(--cream-2)", border: "1px dashed var(--ink)", borderRadius: 12, padding: "10px 14px", fontSize: 12, marginBottom: 14, fontFamily: "var(--mono)", lineHeight: 1.5 }}>
              ※ Supabase not configured yet — paste your project credentials into <code>src/supabase.js</code>.
            </div>
          )}

          <form onSubmit={pay} className="paywall-form">
            {mode === "signup" && (
              <>
                <label className="paywall-lbl">Email</label>
                <input
                  className="paywall-input"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email"
                  required
                />
                <label className="paywall-lbl" style={{ marginTop: 4 }}>Password</label>
                <input
                  className="paywall-input"
                  type="password"
                  placeholder="at least 6 characters"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="new-password"
                  minLength={6}
                  required
                />
                <div style={{ height: 1, background: "var(--line)", margin: "12px 0 4px" }} />
              </>
            )}

            {mode === "login" && (
              <>
                <label className="paywall-lbl">Email</label>
                <input
                  className="paywall-input"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email"
                  required
                />
                <label className="paywall-lbl" style={{ marginTop: 4 }}>Password</label>
                <input
                  className="paywall-input"
                  type="password"
                  placeholder="your password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="current-password"
                  required
                />
                <button type="button" onClick={forgotPassword}
                  style={{ alignSelf: "flex-start", background: "transparent", border: 0, padding: 0, marginTop: 4, color: "var(--splat-deep)", fontFamily: "var(--mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", cursor: "pointer" }}>
                  Forgot password?
                </button>
              </>
            )}

            {mode !== "login" && (
              <>
                <label className="paywall-lbl" style={{ marginTop: mode === "signup" ? 4 : 0 }}>Name on card</label>
                <input
                  className="paywall-input"
                  placeholder="Jamie Rivera"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                />
                <label className="paywall-lbl" style={{ marginTop: 4 }}>Card number</label>
                <input
                  className="paywall-input"
                  placeholder="1234 5678 9012 3456"
                  value={card}
                  onChange={(e) => setCard(e.target.value)}
                  inputMode="numeric"
                  maxLength={19}
                />
                <div className="paywall-row-2">
                  <div>
                    <label className="paywall-lbl">Expires</label>
                    <input className="paywall-input" placeholder="MM/YY" value={exp} onChange={(e) => setExp(e.target.value)} maxLength={5} />
                  </div>
                  <div>
                    <label className="paywall-lbl">CVC</label>
                    <input className="paywall-input" placeholder="123" value={cvc} onChange={(e) => setCvc(e.target.value)} maxLength={4} />
                  </div>
                </div>

                <button type="button" className="paywall-demo" onClick={prefillDemo}>
                  ※ autofill demo card (this is a mockup)
                </button>
              </>
            )}

            {err && (
              <div style={{ background: "rgba(242,107,74,0.12)", border: "1px solid #F26B4A", color: "#8C3821", borderRadius: 10, padding: "8px 12px", fontFamily: "var(--mono)", fontSize: 12, marginTop: 6 }}>
                {err}
              </div>
            )}
            {info && (
              <div style={{ background: "var(--cream-2)", border: "1px solid var(--line)", color: "var(--ink)", borderRadius: 10, padding: "8px 12px", fontFamily: "var(--mono)", fontSize: 12, marginTop: 6 }}>
                {info}
              </div>
            )}

            <button type="submit" className="btn primary paywall-submit" disabled={processing}>
              {processing ? (
                <><span className="typing-dots"><span /><span /><span /></span>{" "}
                {mode === "login" ? "signing in…" : mode === "signup" ? "creating your trial…" : "starting your trial…"}</>
              ) : (
                <>{mode === "login" ? "Log in →" : mode === "signup" ? "Create account & start trial →" : "Start 7-day free trial →"}</>
              )}
            </button>
            <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.04em", textAlign: "center", marginTop: 10, display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
              <span>🔒 Secured by</span>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 25" width="38" height="16" aria-label="Stripe" style={{ display: "inline-block", verticalAlign: "middle" }}>
                <path fill="#635BFF" d="M59.64 14.28h-8.06c.19 1.93 1.6 2.55 3.2 2.55 1.64 0 2.96-.37 4.05-.95v3.32a8.33 8.33 0 0 1-4.56 1.1c-4.01 0-6.83-2.5-6.83-7.48 0-4.19 2.39-7.52 6.3-7.52 3.92 0 5.96 3.28 5.96 7.5 0 .4-.04 1.26-.06 1.48zm-5.92-5.62c-1.03 0-2.17.73-2.17 2.58h4.25c0-1.85-1.07-2.58-2.08-2.58zM40.95 20.3c-1.44 0-2.32-.6-2.91-1.04l-.02 4.63-4.12.87V5.57h3.76l.08 1.02a4.7 4.7 0 0 1 3.23-1.2c2.9 0 5.62 2.6 5.62 7.4 0 5.23-2.7 7.5-5.64 7.5zM40 9.1c-.95 0-1.54.34-1.97.81l.02 6.12c.4.44.98.78 1.95.78 1.52 0 2.54-1.65 2.54-3.87 0-2.15-1.04-3.84-2.54-3.84zM28.24 5.57h4.13v14.44h-4.13V5.57zm0-4.7L32.37 0v3.36l-4.13.88V.88zm-4.32 9.35v9.79H19.8V5.57h3.7l.12 1.22c1-1.77 3.07-1.41 3.62-1.22v3.79c-.52-.17-2.29-.43-3.32.86zm-8.55 4.72c0 2.43 2.6 1.68 3.12 1.46v3.36c-.55.3-1.54.54-2.89.54a4.15 4.15 0 0 1-4.27-4.24l.01-13.17 4.02-.86v3.54h3.14V9.1h-3.13v5.85zm-4.91.7c0 2.97-2.31 4.66-5.73 4.66a11.2 11.2 0 0 1-4.46-.93v-3.93c1.38.75 3.1 1.31 4.46 1.31.92 0 1.53-.24 1.53-1C6.26 13.77 0 14.51 0 9.95 0 7.04 2.28 5.3 5.62 5.3c1.36 0 2.72.2 4.09.75v3.88a9.23 9.23 0 0 0-4.1-1.06c-.86 0-1.44.25-1.44.9 0 1.76 6.29.92 6.29 5.88z"/>
              </svg>
              <span>· no commitment · cancel from settings</span>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Paywall });
