const { useState, useEffect, useMemo, useRef } = React;

/* Auth — Registration flow (multi-step) + Login */

function AuthShell({ children, side }) {
  return (
    <div className="auth-shell">
      <div className="auth-main">
        <div className="auth-top">
          <Logo size="md"/>
          <div className="dim" style={{ fontSize: 12 }}>Need help? <a href="#">support@contactiq.io</a></div>
        </div>
        <div className="auth-body">
          <div className="auth-card">
            {children}
          </div>
        </div>
        <div className="auth-foot dim">© 2026 AI.CONTACTIQ — your data only, never sold.</div>
      </div>
      <aside className="auth-side">
        {side}
      </aside>
    </div>
  );
}

function AuthSideTrial() {
  return (
    <div className="auth-side-card">
      <div className="eyebrow" style={{ color: "var(--deck-accent)" }}>14-DAY FREE TRIAL</div>
      <h2 className="auth-side-h">Read every building<br/>you visit, instantly.</h2>
      <ul className="auth-side-feats">
        <li><I.Check style={{ color: "var(--deck-accent)" }}/> Unlimited lookups for 14 days</li>
        <li><I.Check style={{ color: "var(--deck-accent)" }}/> $5/mo after — cancel anytime, no questions</li>
        <li><I.Check style={{ color: "var(--deck-accent)" }}/> Works in Chrome, Firefox, Edge, Safari</li>
        <li><I.Check style={{ color: "var(--deck-accent)" }}/> Corporate email only — keeps the data serious</li>
      </ul>
    </div>
  );
}

/* ── Registration: a 3-step wizard ────────────────────────────────── */
function RegisterPage({ go, setUser }) {
  const [step, setStep] = useState(1);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    name: "",
    email: "",
    company: "",
    password: "",
    showPw: false,
    agree: false,
  });
  const [errors, setErrors] = useState({});

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Client-side blocklist mirrors the server-side `is_corporate_email` RPC —
  // we still re-check on the server (in signUp) for safety.
  const CONSUMER_DOMAINS = new Set([
    "gmail.com", "googlemail.com", "yahoo.com", "yahoo.co.uk", "ymail.com",
    "hotmail.com", "hotmail.co.uk", "outlook.com", "live.com", "msn.com",
    "icloud.com", "me.com", "mac.com", "aol.com", "protonmail.com", "proton.me",
    "yandex.com", "mail.com", "gmx.com", "zoho.com", "fastmail.com",
    "qq.com", "163.com", "126.com",
  ]);
  const isConsumerEmail = (e) => {
    const dom = (e.split("@")[1] || "").toLowerCase();
    return CONSUMER_DOMAINS.has(dom);
  };

  const validateStep1 = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.company.trim()) e.company = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = "That doesn't look like an email";
    else if (isConsumerEmail(form.email)) e.email = "Use your corporate email — we don't accept consumer addresses";
    if (!form.password) e.password = "Required";
    else if (form.password.length < 8) e.password = "8 characters or more";
    if (!form.agree) e.agree = "You'll need to agree.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  // Real signup: create the auth.users row, which fires our trigger that
  // creates profile + trial subscription. Errors surface inline on Step 1.
  const submitStep1 = async () => {
    if (!validateStep1()) return;
    if (!window.ContactIQ) { setStep(2); return; } // preview mode
    setSubmitting(true);
    try {
      await window.ContactIQ.signUp({
        email:     form.email.trim(),
        password:  form.password,
        full_name: form.name.trim(),
        company:   form.company.trim(),
      });
      setUser(u => ({ ...u, name: form.name, email: form.email, company: form.company || "—" }));
      setStep(2);
    } catch (err) {
      setErrors({ email: err.message || String(err) });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <AuthShell side={<AuthSideTrial/>}>
      <div className="auth-stepper">
        <Step n="1" cur={step} label="Your details"/>
        <Step n="2" cur={step} label="Payment"/>
        <Step n="3" cur={step} label="Install"/>
      </div>

      {step === 1 && (
        <>
          <h1 className="auth-h">Create your account</h1>
          <p className="auth-sub">14-day free trial. Corporate email &amp; card on file required — we don't bill you until day 15.</p>

          <div className="auth-form">
            <div className="auth-row">
              <div className="field" style={{ flex: 1 }}>
                <label className="label">Full name</label>
                <input className="input" value={form.name} onChange={e => update("name", e.target.value)} placeholder="Maya Chen"/>
                {errors.name && <span className="err">{errors.name}</span>}
              </div>
              <div className="field" style={{ flex: 1 }}>
                <label className="label">Company</label>
                <input className="input" value={form.company} onChange={e => update("company", e.target.value)} placeholder="Candor Brokers"/>
                {errors.company && <span className="err">{errors.company}</span>}
              </div>
            </div>

            <div className="field">
              <label className="label">Corporate email</label>
              <input className="input" type="email" value={form.email} onChange={e => update("email", e.target.value)} placeholder="you@yourcompany.com"/>
              {errors.email
                ? <span className="err">{errors.email}</span>
                : <span className="help">No gmail / yahoo / icloud. Your company domain only.</span>}
            </div>

            <div className="field">
              <label className="label">Password</label>
              <div className="auth-pw">
                <input
                  className="input"
                  type={form.showPw ? "text" : "password"}
                  value={form.password}
                  onChange={e => update("password", e.target.value)}
                  placeholder="8+ characters"
                />
                <button type="button" className="auth-pw-toggle" onClick={() => update("showPw", !form.showPw)}>
                  <I.Eye/>
                </button>
              </div>
              {errors.password
                ? <span className="err">{errors.password}</span>
                : <span className="help">Must be at least 8 characters. We hash with bcrypt — we can't see it.</span>}
            </div>

            <label className="auth-check">
              <input type="checkbox" checked={form.agree} onChange={e => update("agree", e.target.checked)}/>
              <span>I agree to the <a href="#">Terms</a> &amp; <a href="#">Privacy Policy</a>.</span>
            </label>
            {errors.agree && <span className="err">{errors.agree}</span>}

            <button
              className="btn primary lg full"
              disabled={submitting}
              onClick={submitStep1}
            >
              {submitting ? "Creating account…" : <>Create account — start trial <I.ChevR/></>}
            </button>

            <div className="auth-alt">
              Already have an account? <a onClick={() => go("login")}>Sign in</a>
            </div>
          </div>
        </>
      )}

      {step === 2 && (
        <PaymentStep
          onPaid={() => { setUser(u => ({ ...u, plan: "trial", paymentMethod: "google_pay" })); setStep(3); }}
          onBack={() => setStep(1)}
        />
      )}

      {step === 3 && (
        <>
          <h1 className="auth-h">Install the extension</h1>
          <p className="auth-sub">Last step. Pick your browser — takes about 30 seconds.</p>

          <div className="auth-browsers">
            {[
              { k: "chrome",  el: <Browser.Chrome/>,  name: "Chrome",  store: "Chrome Web Store" },
              { k: "firefox", el: <Browser.Firefox/>, name: "Firefox", store: "Firefox Add-ons" },
              { k: "edge",    el: <Browser.Edge/>,    name: "Edge",    store: "Edge Add-ons" },
              { k: "safari",  el: <Browser.Safari/>,  name: "Safari",  store: "Mac App Store" },
            ].map(b => (
              <button key={b.k} className="auth-browser-card">
                <div className="auth-browser-icon">{b.el}</div>
                <div className="col" style={{ gap: 2, alignItems: "flex-start" }}>
                  <span style={{ fontWeight: 600, fontSize: 13 }}>Add to {b.name}</span>
                  <span className="dim mono" style={{ fontSize: 10 }}>{b.store}</span>
                </div>
                <I.Open style={{ marginLeft: "auto", color: "var(--fg-3)" }}/>
              </button>
            ))}
          </div>

          <div className="auth-install-help">
            <I.Sparkle style={{ color: "var(--accent)", flexShrink: 0 }}/>
            <div>
              <div style={{ fontWeight: 600, fontSize: 12 }}>Already installed?</div>
              <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>
                Click the ContactIQ icon in your toolbar and sign in with the credentials you just created.
              </div>
            </div>
          </div>

          <div className="auth-row" style={{ gap: 8, marginTop: 14 }}>
            <button className="btn primary lg full" onClick={() => go("dashboard")}>
              Open my dashboard <I.ChevR/>
            </button>
          </div>

          <button className="btn ghost sm" style={{ alignSelf: "center", marginTop: 6 }} onClick={() => go("dashboard")}>
            I'll install later — take me to my dashboard
          </button>
        </>
      )}
    </AuthShell>
  );
}

function Step({ n, cur, label }) {
  const state = +n < cur ? "done" : +n === cur ? "cur" : "todo";
  return (
    <div className={"step " + state}>
      <span className="step-num">{state === "done" ? <I.Check/> : n}</span>
      <span className="step-lbl">{label}</span>
    </div>
  );
}

/* ── Payment step: Stripe Checkout (Google Pay supported in Stripe) ─ */
function PaymentStep({ onPaid, onBack }) {
  // phase: idle | redirecting | sheet | processing | done
  // "redirecting" = real Stripe Checkout path; the iframe-mock states are kept
  // for preview/no-Stripe-key environments.
  const [phase, setPhase] = useState("idle");
  const [stripeError, setStripeError] = useState(null);

  // If returning from a successful Stripe Checkout, ?billing=ok in the URL,
  // jump straight to step 3 (install).
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("billing") === "ok") {
      // strip the param so reload doesn't re-trigger
      params.delete("billing");
      const qs = params.toString();
      window.history.replaceState({}, "",
        window.location.pathname + (qs ? "?" + qs : ""));
      onPaid();
    }
  }, []);

  // Try Stripe first; fall back to the mocked Google Pay sheet so the
  // prototype is still usable before edge-function keys are configured.
  const startCheckout = async () => {
    setStripeError(null);
    setPhase("redirecting");
    try {
      const url = await window.ContactIQ.startStripeCheckout();
      window.location.assign(url);
    } catch (err) {
      // Stripe not configured → drop into the mocked sheet so the user can
      // still complete the flow visually. The error is shown subtly.
      console.warn("[ContactIQ] stripe checkout failed, using mock", err);
      setStripeError(err.message || String(err));
      setPhase("sheet");
    }
  };

  // After Google Pay sheet "accept" in mock mode, show processing then done
  useEffect(() => {
    if (phase === "processing") {
      const t = setTimeout(() => setPhase("done"), 1400);
      return () => clearTimeout(t);
    }
    if (phase === "done") {
      const t = setTimeout(onPaid, 900);
      return () => clearTimeout(t);
    }
  }, [phase]);

  return (
    <>
      <h1 className="auth-h">Add your card</h1>
      <p className="auth-sub">
        Card on file is required to start your trial. We don't charge anything for 14 days — you can
        cancel from your billing page anytime before <span className="mono" style={{ color: "var(--fg-1)", fontWeight: 600 }}>Jun 8, 2026</span> and never see a charge.
      </p>

      <div className="auth-trial-card">
        <div className="auth-trial-row">
          <span className="dim">Plan</span>
          <span style={{ fontWeight: 600 }}>ContactIQ Extension</span>
        </div>
        <div className="auth-trial-row">
          <span className="dim">Trial</span>
          <span>14 days · free</span>
        </div>
        <div className="auth-trial-row">
          <span className="dim">Then</span>
          <span><span className="mono" style={{ fontWeight: 600 }}>$5.00</span> / month</span>
        </div>
        <div className="auth-trial-row">
          <span className="dim">First charge</span>
          <span className="mono">Jun 8, 2026</span>
        </div>
      </div>

      <button
        className="gpay-btn"
        onClick={startCheckout}
        disabled={phase !== "idle"}
      >
        <GoogleG size={20}/>
        <span>{phase === "redirecting" ? "Opening Stripe…" : "Pay"}</span>
      </button>

      <div className="auth-alt dim" style={{ fontSize: 11 }}>
        $0.00 today · $5.00/mo starting Jun 8, 2026 · cancel anytime
      </div>
      {stripeError && (
        <div className="auth-alt" style={{ fontSize: 10.5, color: "var(--amber)" }}>
          Stripe not configured — showing demo sheet. ({stripeError})
        </div>
      )}

      <div className="auth-row" style={{ gap: 8, marginTop: 4 }}>
        <button className="btn lg ghost" onClick={onBack}>Back</button>
      </div>

      {/* Google Pay sheet overlay */}
      {phase !== "idle" && (
        <div className="gpay-overlay" onClick={() => phase === "sheet" && setPhase("idle")}>
          <div className="gpay-sheet" onClick={e => e.stopPropagation()}>
            <div className="gpay-sheet-head">
              <GoogleG size={18}/>
              <span style={{ fontWeight: 500 }}>Pay</span>
              <button className="gpay-x" onClick={() => phase === "sheet" && setPhase("idle")}><I.X/></button>
            </div>

            {phase === "sheet" && (
              <>
                <div className="gpay-merchant">
                  <Logo/>
                  <div className="col" style={{ gap: 0 }}>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>AI.CONTACTIQ Extension</span>
                    <span className="dim" style={{ fontSize: 11 }}>14-day free trial · then $5.00/mo</span>
                  </div>
                </div>
                <div className="gpay-divider"/>
                <div className="gpay-row">
                  <span className="dim" style={{ fontSize: 11 }}>Payment method</span>
                  <div className="gpay-card">
                    <div className="gpay-card-icon">VISA</div>
                    <div className="col" style={{ gap: 0, flex: 1 }}>
                      <span style={{ fontSize: 13, fontWeight: 500 }}>Visa •••• 4242</span>
                      <span className="dim" style={{ fontSize: 11 }}>maya@candorbrokers.com</span>
                    </div>
                    <I.Chev/>
                  </div>
                </div>
                <div className="gpay-divider"/>
                <div className="gpay-row" style={{ display: "flex", justifyContent: "space-between" }}>
                  <span className="dim" style={{ fontSize: 12 }}>Total today</span>
                  <span className="mono" style={{ fontWeight: 700, fontSize: 14 }}>$0.00</span>
                </div>
                <div className="gpay-row" style={{ display: "flex", justifyContent: "space-between" }}>
                  <span className="dim" style={{ fontSize: 12 }}>After trial (Jun 8)</span>
                  <span className="mono" style={{ fontWeight: 500, fontSize: 13 }}>$5.00/mo</span>
                </div>
                <button className="gpay-confirm" onClick={() => setPhase("processing")}>
                  <GoogleG size={18}/> Pay
                </button>
                <div className="dim" style={{ fontSize: 10, textAlign: "center", marginTop: 8 }}>
                  Encrypted &amp; tokenized · By tapping Pay you agree to ContactIQ's terms.
                </div>
              </>
            )}

            {phase === "processing" && (
              <div className="gpay-processing">
                <div className="gpay-spinner"/>
                <div style={{ fontWeight: 500 }}>Authorizing…</div>
                <div className="dim" style={{ fontSize: 11 }}>Confirming with your bank</div>
              </div>
            )}

            {phase === "done" && (
              <div className="gpay-processing">
                <div className="gpay-check"><I.Check style={{ width: 28, height: 28 }}/></div>
                <div style={{ fontWeight: 600 }}>You're set</div>
                <div className="dim" style={{ fontSize: 11 }}>Trial active until Jun 8 · then $5.00/mo</div>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

/* ── Login ─────────────────────────────────────────────────────── */
function LoginPage({ go }) {
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const [magicSent, setMagicSent] = useState(false);

  const doSignIn = async () => {
    setErr(null); setBusy(true);
    try {
      if (!window.ContactIQ) { go("dashboard"); return; }
      await window.ContactIQ.signIn({ email: email.trim(), password: pw });
      go("dashboard");
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  };

  const doMagicLink = async () => {
    setErr(null); setMagicSent(false); setBusy(true);
    try {
      if (!email.trim()) throw new Error("Enter your email first");
      if (!window.ContactIQ) { go("dashboard"); return; }
      await window.ContactIQ.signInMagicLink(email.trim());
      setMagicSent(true);
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  };

  return (
    <AuthShell side={<AuthSideTrial quote={false}/>}>
      <h1 className="auth-h">Sign in</h1>
      <p className="auth-sub">Welcome back. We'll pick up where you left off.</p>

      <div className="auth-form">
        <div className="field">
          <label className="label">Work email</label>
          <input
            className="input"
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="you@yourcompany.com"
            onKeyDown={e => { if (e.key === "Enter") doSignIn(); }}
          />
        </div>
        <div className="field">
          <div className="row" style={{ justifyContent: "space-between" }}>
            <label className="label">Password</label>
            <a className="help" style={{ color: "var(--accent)" }} href="#"
               onClick={e => { e.preventDefault(); doMagicLink(); }}>Forgot?</a>
          </div>
          <div className="auth-pw">
            <input
              className="input"
              type={showPw ? "text" : "password"}
              value={pw}
              onChange={e => setPw(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") doSignIn(); }}
            />
            <button type="button" className="auth-pw-toggle" onClick={() => setShowPw(!showPw)}>
              <I.Eye/>
            </button>
          </div>
        </div>

        {err && <div className="err" style={{ marginTop: -6 }}>{err}</div>}
        {magicSent && (
          <div className="auth-install-help" style={{ marginTop: -6 }}>
            <I.Mail style={{ color: "var(--accent)" }}/>
            <div>
              <div style={{ fontWeight: 600, fontSize: 12 }}>Magic link sent</div>
              <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>
                Check {email} — click the link to finish signing in.
              </div>
            </div>
          </div>
        )}

        <button className="btn primary lg full" disabled={busy} onClick={doSignIn}>
          {busy ? "Signing in…" : <>Sign in <I.ChevR/></>}
        </button>

        <div className="auth-divider"><span>or</span></div>
        <button className="btn lg full" disabled={busy} onClick={doMagicLink}>
          <I.Mail/> Email me a magic link
        </button>

        <div className="auth-alt">
          New to ContactIQ? <a onClick={() => go("signup")}>Create an account</a>
        </div>
      </div>
    </AuthShell>
  );
}

window.RegisterPage = RegisterPage;
window.LoginPage = LoginPage;
