// login.jsx — Login / sign-up screen

const PLAN_META = {
  starter: {
    label: "Starter",
    monthly: 19, annual: 15,
    desc: "Solo traders & single-person businesses.",
    features: ["Unlimited bookings", "3 service types", "1 staff member", "Stripe or PayPal payments", "Email confirmations & reminders", "Gift vouchers & session packages", "Mobile admin app"],
  },
  professional: {
    label: "Professional",
    monthly: 39, annual: 29,
    desc: "Salons, studios & small teams.",
    features: ["Everything in Starter", "Unlimited services & 5 staff", "Deposits & coupon codes", "Memberships & recurring plans", "SMS, WhatsApp & calendar sync", "Custom branded booking page", "Advanced analytics"],
    popular: true,
  },
  business: {
    label: "Business",
    monthly: 79, annual: 59,
    desc: "Established & multi-location businesses.",
    features: ["Everything in Professional", "Unlimited staff", "White-label booking page", "Multiple locations", "Webhooks & Zapier integration", "Priority support & onboarding call"],
  },
};

function LoginPage() {
  // Read ?plan= from URL — if present, skip plan picker and go straight to details
  const urlPlan   = new URLSearchParams(window.location.search).get("plan")?.toLowerCase();
  const validPlan = PLAN_META[urlPlan] ? urlPlan : null;

  // mode: "login" | "pick-plan" | "signup"
  const [mode,     setMode]   = React.useState(validPlan ? "signup" : "login");
  const [plan,     setPlan]   = React.useState(validPlan || "professional");
  const [billing,  setBilling] = React.useState("annual"); // "monthly" | "annual"
  const [email,    setEmail]  = React.useState("");
  const [password, setPass]   = React.useState("");
  const [error,    setError]  = React.useState("");
  const [info,     setInfo]   = React.useState("");
  const [busy,     setBusy]   = React.useState(false);

  const goSignup = () => { setMode("pick-plan"); setError(""); setInfo(""); };
  const goLogin  = () => { setMode("login");     setError(""); setInfo(""); };
  const pickPlan = (p) => { setPlan(p); setMode("signup"); };

  const submit = async (e) => {
    e.preventDefault();
    setError(""); setInfo(""); setBusy(true);
    try {
      if (mode === "login") {
        const { error } = await sb.auth.signInWithPassword({ email, password });
        if (error) setError(error.message);
      } else {
        const { error } = await sb.auth.signUp({ email, password });
        if (error) {
          setError(error.message);
        } else {
          // Persist chosen plan + billing period so billing view can surface it after first login
          localStorage.setItem("nexus_pending_plan", plan);
          localStorage.setItem("nexus_pending_billing", billing);
          setInfo("Account created! Check your email to confirm, then sign in.");
        }
      }
    } finally {
      setBusy(false);
    }
  };

  const logo = (
    <img src="logo/nexus-bookings-logo-dark.png" alt="Nexus Booking"
      style={{height:76, width:"auto", display:"block", margin:"0 auto 20px"}}/>
  );

  // ── Plan picker step ──────────────────────────────────────────
  if (mode === "pick-plan") {
    const isAnnual = billing === "annual";
    return (
      <div className="login-shell">
        <div className="login-card" style={{maxWidth:680, width:"100%"}}>
          {logo}
          <p className="login-sub" style={{marginBottom:16}}>Choose the plan that's right for you</p>

          {/* Billing toggle */}
          <div style={{display:"flex", alignItems:"center", justifyContent:"center", gap:10, marginBottom:20}}>
            <span style={{fontSize:13, color: !isAnnual ? "var(--text)" : "var(--text-muted)", fontWeight: !isAnnual ? 600 : 400}}>Monthly</span>
            <button onClick={() => setBilling(b => b === "annual" ? "monthly" : "annual")} style={{
              all:"unset", cursor:"pointer", width:44, height:24, borderRadius:12, position:"relative",
              background: isAnnual ? "var(--accent,#4f46e5)" : "var(--border,#cbd5e1)",
              transition:"background .2s",
            }}>
              <span style={{
                position:"absolute", top:3, left: isAnnual ? 23 : 3,
                width:18, height:18, borderRadius:"50%", background:"#fff",
                transition:"left .2s", boxShadow:"0 1px 3px rgba(0,0,0,.2)",
              }}/>
            </button>
            <span style={{fontSize:13, color: isAnnual ? "var(--text)" : "var(--text-muted)", fontWeight: isAnnual ? 600 : 400}}>
              Annual
              <span style={{
                marginLeft:6, fontSize:11, fontWeight:700, padding:"1px 6px", borderRadius:8,
                background:"#dcfce7", color:"#16a34a",
              }}>Save ~25%</span>
            </span>
          </div>

          <div style={{display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:12, marginBottom:20}}>
            {Object.entries(PLAN_META).map(([key, m]) => {
              const price    = isAnnual ? m.annual  : m.monthly;
              const subPrice = isAnnual ? m.monthly : null;
              return (
                <button key={key} onClick={() => pickPlan(key)} style={{
                  all:"unset", cursor:"pointer", display:"flex", flexDirection:"column",
                  padding:"16px 14px", borderRadius:10, textAlign:"left",
                  border: `2px solid ${plan === key ? "var(--accent,#4f46e5)" : "var(--border,#e2e8f0)"}`,
                  background: m.popular ? "var(--accent-soft,#eef2ff)" : "var(--surface,#fff)",
                  position:"relative", transition:"border-color .15s",
                }}>
                  {m.popular && (
                    <span style={{
                      position:"absolute", top:-10, left:"50%", transform:"translateX(-50%)",
                      background:"var(--accent,#4f46e5)", color:"#fff",
                      fontSize:10, fontWeight:700, padding:"2px 8px", borderRadius:10, whiteSpace:"nowrap",
                    }}>MOST POPULAR</span>
                  )}
                  <div style={{fontWeight:700, fontSize:15, color:"var(--text)", marginBottom:4}}>{m.label}</div>
                  <div style={{fontWeight:700, fontSize:20, color:"var(--accent,#4f46e5)", lineHeight:1}}>
                    £{price}<span style={{fontSize:13, fontWeight:400}}>/mo</span>
                  </div>
                  {isAnnual ? (
                    <div style={{fontSize:11, color:"var(--text-muted)", marginTop:2, marginBottom:10}}>
                      billed annually · <span style={{textDecoration:"line-through"}}>£{subPrice}/mo</span>
                    </div>
                  ) : (
                    <div style={{fontSize:11, color:"#16a34a", marginTop:2, marginBottom:10}}>
                      or £{m.annual}/mo billed annually
                    </div>
                  )}
                  <div style={{fontSize:12, color:"var(--text-muted)", marginBottom:10, lineHeight:1.4}}>{m.desc}</div>
                  <ul style={{margin:0, padding:0, listStyle:"none", display:"flex", flexDirection:"column", gap:5}}>
                    {m.features.map((f, i) => (
                      <li key={i} style={{display:"flex", gap:6, alignItems:"flex-start", fontSize:12, color:"var(--text)"}}>
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--accent,#4f46e5)" strokeWidth="3" style={{flexShrink:0, marginTop:1}}>
                          <path d="M20 6 9 17l-5-5"/>
                        </svg>
                        {f}
                      </li>
                    ))}
                  </ul>
                </button>
              );
            })}
          </div>

          <button className="login-toggle" onClick={goLogin}>Already have an account? Sign in</button>
        </div>
      </div>
    );
  }

  // ── Signup details step ───────────────────────────────────────
  if (mode === "signup") {
    const m     = PLAN_META[plan];
    const price = billing === "annual" ? m.annual : m.monthly;
    const billingLabel = billing === "annual" ? "billed annually" : "billed monthly";
    return (
      <div className="login-shell">
        <div className="login-card">
          {logo}

          {/* Selected plan + billing badge */}
          <div style={{
            display:"flex", alignItems:"center", justifyContent:"space-between",
            padding:"8px 12px", borderRadius:8, marginBottom:16,
            background:"var(--accent-soft,#eef2ff)",
            border:"1px solid var(--accent-border,#c7d2fe)",
          }}>
            <div style={{display:"flex", alignItems:"center", gap:7}}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent,#4f46e5)" strokeWidth="2.5">
                <path d="M20 12V22H4V12"/><path d="M22 7H2v5h20V7z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/>
              </svg>
              <div>
                <div style={{fontSize:13, fontWeight:600, color:"var(--accent,#4f46e5)"}}>
                  {m.label} · £{price}/mo
                </div>
                <div style={{fontSize:11, color:"var(--text-muted)"}}>{billingLabel}</div>
              </div>
            </div>
            {!validPlan && (
              <button onClick={() => setMode("pick-plan")} style={{
                all:"unset", cursor:"pointer", fontSize:12,
                color:"var(--accent,#4f46e5)", textDecoration:"underline",
              }}>Change</button>
            )}
          </div>

          <p className="login-sub">Create your account</p>

          <form className="login-form" onSubmit={submit}>
            <div className="bk-field">
              <label>Email</label>
              <input className="bk-input" type="email" value={email}
                onChange={e => setEmail(e.target.value)} required placeholder="you@example.com"/>
            </div>
            <div className="bk-field">
              <label>Password</label>
              <input className="bk-input" type="password" value={password}
                onChange={e => setPass(e.target.value)} required placeholder="••••••••" minLength={6}/>
            </div>

            {error && <div className="login-msg is-error">{error}</div>}
            {info  && <div className="login-msg is-info">{info}</div>}

            <button className="btn primary" style={{width:"100%", marginTop:4}} type="submit" disabled={busy}>
              {busy ? "Please wait…" : "Create account"}
            </button>
          </form>

          <button className="login-toggle" onClick={goLogin}>Already have an account? Sign in</button>
        </div>
      </div>
    );
  }

  // ── Login step ────────────────────────────────────────────────
  return (
    <div className="login-shell">
      <div className="login-card">
        {logo}
        <p className="login-sub">Sign in to your dashboard</p>

        <form className="login-form" onSubmit={submit}>
          <div className="bk-field">
            <label>Email</label>
            <input className="bk-input" type="email" value={email}
              onChange={e => setEmail(e.target.value)} required placeholder="you@example.com"/>
          </div>
          <div className="bk-field">
            <label>Password</label>
            <input className="bk-input" type="password" value={password}
              onChange={e => setPass(e.target.value)} required placeholder="••••••••" minLength={6}/>
          </div>

          {error && <div className="login-msg is-error">{error}</div>}
          {info  && <div className="login-msg is-info">{info}</div>}

          <button className="btn primary" style={{width:"100%", marginTop:4}} type="submit" disabled={busy}>
            {busy ? "Please wait…" : "Sign in"}
          </button>
        </form>

        <button className="login-toggle" onClick={goSignup}>No account yet? Sign up</button>
      </div>
    </div>
  );
}
