// ============================================
// Reliq — Signup page
// Public route: /signup
// Reads preserved preview scan context from localStorage.
// After mock signup, redirects to: payment (pricing trial), scan result
// (free-scan flow), or dashboard (direct signup / auth-guard redirect).
// ============================================

// ── localStorage keys ─────────────────────────────────────────────────────────
// Preview context keys — must match free-scan.jsx and reliq-state.jsx.
const SU_SCAN_ID = "reliq_preview_scan_id";
const SU_SOURCE  = "reliq_signup_source";
// Note: the preview redirect is now in "reliq_preview_pending_redirect" (Step 3).
// Auth redirect is in "reliq_auth_pending_redirect", managed by reliqAuth.
// Neither is read here directly — routing uses dedicated helpers in onAuthSuccess.

const getPreviewContext = () => {
  try {
    return {
      scanId: localStorage.getItem(SU_SCAN_ID) || null,
      source: localStorage.getItem(SU_SOURCE)  || null,
      // redirect removed: free-scan flow uses a hardcoded destination; auth-guard
      // redirects are read via reliqAuth.getPendingRedirect() in onAuthSuccess.
    };
  } catch (_) {
    return { scanId: null, source: null };
  }
};

// Delegate to the centralised helper. The local fallback handles the rare case
// where reliq-state.jsx hasn't finished evaluating (should never occur in prod).
const clearPreviewCtx = () => {
  if (window.reliqSubscription) {
    window.reliqSubscription.clearPreviewContext();
  } else {
    try {
      localStorage.removeItem(SU_SCAN_ID);
      localStorage.removeItem(SU_SOURCE);
      localStorage.removeItem("reliq_preview_pending_redirect"); // new canonical key
      localStorage.removeItem("reliq_pending_redirect");         // legacy fallback
    } catch (_) {}
  }
};

// ── Pricing trial context — read from URL hash query params ───────────────────
// Hash looks like: #/signup?plan=starter&trial=7d&source=pricing
// We parse the query string out of the hash (after the ?) at mount time.
const getTrialContext = () => {
  try {
    const hash = window.location.hash;
    const qi = hash.indexOf("?");
    if (qi < 0) return null;
    const p = new URLSearchParams(hash.slice(qi + 1));
    const plan   = p.get("plan");
    const source = p.get("source");
    const trial  = p.get("trial");
    if (source === "pricing" && plan) return { plan, trial: trial || "7d" };
  } catch (_) {}
  // Fall back to localStorage (set by startTrial() in landing.jsx)
  try {
    const plan   = localStorage.getItem("reliq_trial_plan");
    const source = localStorage.getItem("reliq_trial_source");
    if (source === "pricing" && plan) return { plan, trial: "7d" };
  } catch (_) {}
  return null;
};

const TRIAL_PLAN_NAMES = { starter: "Starter", pro: "Pro", team: "Team" };

// ── Spinner icon ──────────────────────────────────────────────────────────────
const SpinIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24"
       style={{ animation:"spin 1s linear infinite", flexShrink:0 }}>
    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2.5"
            fill="none" strokeDasharray="40 60" strokeLinecap="round" />
  </svg>
);

// ── GitHub OAuth mock ──────────────────────────────────────────────────────────
// Replace this function body with a real window.open OAuth popup when auth is wired.
const mockGithubOAuth = () => new Promise((resolve) => {
  setTimeout(() => resolve({ ok: true }), 1700);
});

// ── Email/password mock signup ────────────────────────────────────────────────
const mockEmailSignup = (email) => new Promise((resolve, reject) => {
  if (!email || !email.includes("@")) {
    setTimeout(() => reject(new Error("Enter a valid email address.")), 300);
    return;
  }
  setTimeout(() => resolve({ ok: true }), 1400);
});

// ── Signup component ──────────────────────────────────────────────────────────
const Signup = ({ go }) => {
  const ctx      = React.useRef(getPreviewContext());
  const trialCtx = React.useRef(getTrialContext()); // null if not from pricing

  const isPricingTrial = !!trialCtx.current;
  const trialPlan      = isPricingTrial ? trialCtx.current.plan : null;
  const trialPlanName  = TRIAL_PLAN_NAMES[trialPlan] || trialPlan;

  const [email,          setEmail]          = React.useState("");
  const [password,       setPassword]       = React.useState("");
  const [fieldErrors,    setFieldErrors]    = React.useState({});
  const [emailLoading,   setEmailLoading]   = React.useState(false);
  const [emailError,     setEmailError]     = React.useState(null);
  const [githubLoading,  setGithubLoading]  = React.useState(false);
  const [githubError,    setGithubError]    = React.useState(null);

  // Client-side field validation (uses reliqValidate if available)
  const validateField = (field, value) => {
    if (!window.reliqValidate) return null;
    if (field === "email")    return window.reliqValidate.email(value);
    if (field === "password") return window.reliqValidate.password(value, 8);
    return null;
  };
  const onBlurField = (field, value) => {
    const err = validateField(field, value);
    setFieldErrors(prev => ({ ...prev, [field]: err }));
  };
  const validateAll = () => {
    const errs = {};
    const eErr = validateField("email", email);
    const pErr = validateField("password", password);
    if (eErr) errs.email = eErr;
    if (pErr) errs.password = pErr;
    setFieldErrors(errs);
    return Object.keys(errs).length === 0;
  };

  // After successful auth:
  //   • Pricing trial flow → set pending_payment state, route to payment step
  //   • Free-scan flow → route to preview scan result (scan/scn_2k8x)
  //   • Auth-guard redirect → use reliqAuth.getPendingRedirect() (auth redirect key)
  //   • Direct signup → route to dashboard
  //
  // provider = "email" | "github"
  // GitHub auth verifies identity only — it does NOT activate the trial.
  // Trial becomes active only after payment method is successfully added.
  const onAuthSuccess = (name, userEmail, provider = "email") => {
    if (window.reliqAuth) window.reliqAuth.signIn({ name, email: userEmail });
    if (isPricingTrial) {
      // Write pending trial state — trial is NOT yet active
      if (window.reliqSubscription) {
        window.reliqSubscription.setPendingPayment(trialPlan, provider);
      } else {
        // Fallback if reliq-state.jsx hasn't loaded
        try {
          localStorage.setItem("reliq_auth_provider",           provider);
          localStorage.setItem("reliq_selected_plan",           trialPlan);
          localStorage.setItem("reliq_payment_method_required", "true");
          localStorage.setItem("reliq_payment_method_added",    "false");
          localStorage.setItem("reliq_trial_status",            "pending_payment");
          localStorage.setItem("reliq_subscription_status",     "incomplete");
        } catch (_) {}
      }
      // Clear any stale auth redirect — user is heading to payment, then dashboard.
      if (window.reliqAuth) window.reliqAuth.clearPendingRedirect();
      go("payment?plan=" + trialPlan + "&trial=7d");
    } else {
      // Non-trial signup — resolve destination by flow type.
      // free-scan: always route to the preview scan result; source is reliable
      //   even if the auth guard ran and populated reliq_auth_pending_redirect.
      // auth-guard redirect: read via reliqAuth.getPendingRedirect() which reads
      //   reliq_auth_pending_redirect first, then falls back to the legacy key.
      // direct signup: no auth redirect stored → dashboard.
      const fromFreeScan = ctx.current.source === "free-scan";
      let dest;
      if (fromFreeScan) {
        dest = "scan/scn_2k8x";
      } else {
        const authRedirect = window.reliqAuth ? window.reliqAuth.getPendingRedirect() : null;
        dest = authRedirect || "dashboard";
      }
      clearPreviewCtx();
      if (window.reliqAuth) window.reliqAuth.clearPendingRedirect();
      go(dest);
    }
  };

  // ── Email signup ────────────────────────────────────────────────────────────
  const handleEmailSubmit = async (e) => {
    e.preventDefault();
    if (emailLoading) return;
    // Run client-side validation first — show all errors before hitting the mock API
    if (!validateAll()) return;
    setEmailError(null);
    setEmailLoading(true);
    try {
      await mockEmailSignup(email);
      const name = email.split("@")[0].replace(/[._]/g, " ").replace(/\b\w/g, c => c.toUpperCase());
      onAuthSuccess(name, email, "email");
    } catch (err) {
      setEmailError(err.message || "Something went wrong. Please try again.");
      setEmailLoading(false);
    }
  };

  // ── GitHub signup ───────────────────────────────────────────────────────────
  // GitHub confirms identity only. Paid plan access is gated on payment method.
  const handleGithub = async () => {
    if (githubLoading) return;
    setGithubError(null);
    setGithubLoading(true);
    try {
      await mockGithubOAuth();
      onAuthSuccess("GitHub User", "github@user.dev", "github");
    } catch (_) {
      setGithubError("Could not connect GitHub. Please try again.");
      setGithubLoading(false);
    }
  };

  const fromFreeScan = !isPricingTrial && ctx.current.source === "free-scan";

  // ── Field style ─────────────────────────────────────────────────────────────
  const fieldStyle = {
    display:"flex", flexDirection:"column", gap:6, marginBottom:14,
  };
  const labelStyle = {
    fontFamily:"var(--font-mono)", fontSize:10.5,
    letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)",
  };
  const inputStyle = {
    background:"var(--bg-1)", border:"1px solid var(--line-2)",
    borderRadius:"var(--r-sm)", padding:"10px 12px",
    fontSize:13.5, color:"var(--fg-0)", outline:"none",
    width:"100%", transition:"border-color .12s",
    fontFamily:"var(--font-sans)",
  };

  return (
    <LandingLayout go={go} pageTitle="Create account">
      <div style={{ maxWidth:420, margin:"0 auto" }}>

        {/* Header */}
        <div style={{ textAlign:"center", marginBottom:32 }}>
          <div style={{ margin:"0 auto 22px", display:"inline-block" }}>
            <img className="brand-logo brand-logo-light" src="assets/reliq-logo-dark.png"  alt="Reliq" style={{ height:28 }} />
            <img className="brand-logo brand-logo-dark"  src="assets/reliq-logo-light.png" alt="Reliq" style={{ height:28 }} />
          </div>
          <h1 style={{
            fontFamily:"var(--font-display)", fontSize:26, fontWeight:600,
            letterSpacing:"-0.02em", margin:"0 0 10px",
          }}>
            {isPricingTrial
              ? `Start your 7-day ${trialPlanName} trial`
              : "Create your Reliq account"
            }
          </h1>
          <p style={{ color:"var(--fg-2)", fontSize:14, lineHeight:1.6, margin:0 }}>
            {isPricingTrial
              ? "Create your Reliq account and add a payment method to start your trial."
              : fromFreeScan
                ? "Unlock your full scan report, fix plan, PDF export, and re-scan history."
                : "Start checking your apps for store-policy issues before you submit."
            }
          </p>
        </div>

        {/* Pricing trial plan chip */}
        {isPricingTrial && (
          <div style={{
            display:"flex", alignItems:"center", gap:12,
            padding:"12px 16px", borderRadius:"var(--r-md)", marginBottom:22,
            background:"var(--bg-2)", border:"1px solid var(--line-2)",
          }}>
            <Icon name="bolt" size={15} style={{ color:"var(--teal)", flexShrink:0 }} />
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:500, color:"var(--fg-0)" }}>
                {trialPlanName} plan · 7-day trial
              </div>
              <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:1 }}>
                Payment method required — you won't be charged for 7 days.
              </div>
            </div>
          </div>
        )}

        {/* Preview scan context banner (free-scan flow only) */}
        {fromFreeScan && ctx.current.scanId && (
          <div style={{
            display:"flex", alignItems:"center", gap:12,
            padding:"12px 16px", borderRadius:"var(--r-md)", marginBottom:22,
            background:"var(--teal-bg)", border:"1px solid var(--line-3)",
          }}>
            <Icon name="check-circle" size={16} style={{ color:"var(--teal)", flexShrink:0 }} />
            <div>
              <div style={{ fontSize:13, fontWeight:500 }}>Your preview scan is saved.</div>
              <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:1 }}>
                Sign up to unlock the full report instantly.
              </div>
            </div>
          </div>
        )}

        {/* GitHub button */}
        <button
          className="btn btn-lg"
          onClick={handleGithub}
          disabled={githubLoading || emailLoading}
          style={{
            width:"100%", justifyContent:"center", marginBottom:6,
            opacity: (githubLoading || emailLoading) ? 0.7 : 1,
            cursor:  (githubLoading || emailLoading) ? "not-allowed" : "pointer",
          }}
        >
          {githubLoading
            ? <><SpinIcon /> Connecting GitHub…</>
            : <><Icon name="github" size={15} /> Continue with GitHub</>
          }
        </button>

        {githubError && (
          <div style={{
            padding:"9px 14px", borderRadius:8, marginBottom:10,
            background:"var(--red-bg)", border:"1px solid rgba(239,68,68,0.25)",
            color:"var(--red)", fontSize:13,
            display:"flex", alignItems:"center", gap:8,
          }}>
            <Icon name="alert" size={13} /> {githubError}
          </div>
        )}

        {/* Divider */}
        <div style={{
          display:"flex", alignItems:"center", gap:12,
          margin:"18px 0",
          fontFamily:"var(--font-mono)", fontSize:11,
          color:"var(--fg-3)", letterSpacing:"0.1em", textTransform:"uppercase",
        }}>
          <div style={{ flex:1, height:1, background:"var(--line-1)" }} />
          or sign up with email
          <div style={{ flex:1, height:1, background:"var(--line-1)" }} />
        </div>

        {/* Email form */}
        <form onSubmit={handleEmailSubmit} noValidate>
          <div style={fieldStyle}>
            <label style={labelStyle} htmlFor="su-email">Email</label>
            <input
              id="su-email"
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={e => { setEmail(e.target.value); if (fieldErrors.email) setFieldErrors(p => ({...p, email:null})); }}
              disabled={emailLoading || githubLoading}
              aria-invalid={!!fieldErrors.email}
              aria-describedby={fieldErrors.email ? "su-email-err" : undefined}
              style={{
                ...inputStyle,
                borderColor: fieldErrors.email ? "var(--red)" : undefined,
                ...(emailLoading || githubLoading ? { opacity:0.6 } : {}),
              }}
              onFocus={e => { if (!fieldErrors.email) e.target.style.borderColor = "var(--teal)"; }}
              onBlur={e  => { onBlurField("email", e.target.value); e.target.style.borderColor = fieldErrors.email ? "var(--red)" : "var(--line-2)"; }}
            />
            {fieldErrors.email && (
              <span id="su-email-err" style={{fontSize:12, color:"var(--red)", marginTop:2, display:"flex", alignItems:"center", gap:4}}>
                <Icon name="alert" size={11} /> {fieldErrors.email}
              </span>
            )}
          </div>

          <div style={fieldStyle}>
            <label style={labelStyle} htmlFor="su-password">Password</label>
            <input
              id="su-password"
              type="password"
              placeholder="8+ characters"
              value={password}
              onChange={e => { setPassword(e.target.value); if (fieldErrors.password) setFieldErrors(p => ({...p, password:null})); }}
              disabled={emailLoading || githubLoading}
              aria-invalid={!!fieldErrors.password}
              aria-describedby={fieldErrors.password ? "su-pass-err" : undefined}
              style={{
                ...inputStyle,
                borderColor: fieldErrors.password ? "var(--red)" : undefined,
                ...(emailLoading || githubLoading ? { opacity:0.6 } : {}),
              }}
              onFocus={e => { if (!fieldErrors.password) e.target.style.borderColor = "var(--teal)"; }}
              onBlur={e  => { onBlurField("password", e.target.value); e.target.style.borderColor = fieldErrors.password ? "var(--red)" : "var(--line-2)"; }}
            />
            {fieldErrors.password && (
              <span id="su-pass-err" style={{fontSize:12, color:"var(--red)", marginTop:2, display:"flex", alignItems:"center", gap:4}}>
                <Icon name="alert" size={11} /> {fieldErrors.password}
              </span>
            )}
          </div>

          {emailError && (
            <div style={{
              padding:"9px 14px", borderRadius:8, marginBottom:12,
              background:"var(--red-bg)", border:"1px solid rgba(239,68,68,0.25)",
              color:"var(--red)", fontSize:13,
              display:"flex", alignItems:"center", gap:8,
            }}>
              <Icon name="alert" size={13} /> {emailError}
            </div>
          )}

          <button
            type="submit"
            className="btn btn-primary btn-lg"
            disabled={emailLoading || githubLoading}
            style={{
              width:"100%", justifyContent:"center", marginTop:4,
              opacity: (emailLoading || githubLoading) ? 0.7 : 1,
              cursor:  (emailLoading || githubLoading) ? "not-allowed" : "pointer",
            }}
            aria-label={isPricingTrial ? `Continue to ${trialPlanName} trial` : "Create account"}
          >
            {emailLoading
              ? <><SpinIcon /> Creating account…</>
              : isPricingTrial
                ? <>Continue to trial <Icon name="arrow-right" size={14} /></>
                : <>Create account <Icon name="arrow-right" size={14} /></>
            }
          </button>
        </form>

        {/* Trust note — differs by flow */}
        <div style={{
          marginTop:20, textAlign:"center",
          fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)",
        }}>
          {isPricingTrial
            ? "Payment method required. You won't be charged until your 7-day trial ends."
            : "No credit card required to start."
          }
        </div>

        {/* Sign-in link */}
        <div style={{
          marginTop:14, textAlign:"center", fontSize:13, color:"var(--fg-2)",
        }}>
          Already have an account?{" "}
          <span
            style={{ color:"var(--teal)", cursor:"pointer", fontWeight:500 }}
            onClick={() => go("/signin")}
          >
            Sign in
          </span>
        </div>

      </div>
    </LandingLayout>
  );
};

Object.assign(window, { Signup });
