/* Login + code redemption */
const { useState } = React;
const { Brand, Icon, Eyebrow } = window;

function Login({ go, onLogin }) {
  const [mode, setMode] = useState("login"); // 'login' | 'redeem'
  const [email, setEmail] = useState("juan@example.com");
  const [password, setPassword] = useState("••••••••");
  const [code, setCode] = useState("");
  const [err, setErr] = useState("");
  const [showHelp, setShowHelp] = useState(false);

  function submitLogin() {
    setErr("");
    if (!email || !password) { setErr("Enter your email and password"); return; }
    onLogin({ email, name: "Juan Santos", nickname: "Juan", isFirstTime: false });
  }
  function submitRedeem() {
    setErr("");
    const codes = window.MOCK.ACCESS_CODES;
    const found = codes[code.trim().toUpperCase()];
    if (!found) { setErr("That code doesn't look right. Try FIT-30, FIT-90 or FIT-365."); return; }
    onLogin({ email: "newmember@example.com", name: "New Member", nickname: "Member", isFirstTime: true, code: code.trim().toUpperCase(), days: found.days });
  }

  return (
    <div className="fade-in auth-split">
      {/* Left — brand side */}
      <div style={{
        background: "var(--fg)",
        color: "var(--bg)",
        padding: 48,
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        position: "relative", overflow: "hidden",
      }}>
        <div className="between">
          <Brand size="md" />
          <button className="btn btn-ghost btn-sm"
                  style={{ color: "var(--bg)", borderColor: "var(--fg-dim)" }}
                  onClick={() => go("landing")}>
            <Icon name="arrow" size={14} style={{ transform: "rotate(180deg)" }}/> Back
          </button>
        </div>

        <div>
          <div className="eyebrow" style={{ color: "var(--bg-soft)", opacity: 0.7 }}>Members only</div>
          <h1 className="h-hero" style={{ marginTop: 16, color: "var(--bg)", maxWidth: 520 }}>
            Welcome back.<br />
            Let's <span style={{ color: "var(--accent)" }}>get to work.</span>
          </h1>
          <p className="muted" style={{ color: "var(--bg-soft)", opacity: 0.7, maxWidth: 460, marginTop: 24 }}>
            Get Fit is invite-only — your coach hands out access codes worth 7, 30, 60,
            90, or 365 days. Top up any time from the Membership tab.
          </p>
        </div>

        <div className="row" style={{ gap: 12, flexWrap: "wrap" }}>
          {Object.entries(window.MOCK.ACCESS_CODES).map(([k, v]) => (
            <div key={k} style={{
              padding: "12px 16px",
              border: "1px solid var(--fg-dim)",
              borderRadius: 12,
            }}>
              <div className="mono" style={{ fontSize: 11, opacity: 0.6 }}>{v.label}</div>
              <div className="mono" style={{ marginTop: 4, fontWeight: 700, letterSpacing: "0.05em" }}>{k}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Right — form */}
      <div style={{ padding: 48, display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <div className="seg" style={{ alignSelf: "flex-start", marginBottom: 32 }}>
          <button className={mode === "login"  ? "on" : ""} onClick={() => { setMode("login"); setErr(""); }}>Log in</button>
          <button className={mode === "redeem" ? "on" : ""} onClick={() => { setMode("redeem"); setErr(""); }}>Redeem code</button>
        </div>

        {mode === "login" && (
          <div className="col" style={{ gap: 18, maxWidth: 380 }}>
            <Eyebrow>Existing member</Eyebrow>
            <h2 className="h-section" style={{ margin: 0 }}>Log in</h2>
            <div className="field">
              <label className="field-label">Email</label>
              <input className="field-input" value={email} onChange={e => setEmail(e.target.value)} />
            </div>
            <div className="field">
              <label className="field-label">Password</label>
              <input className="field-input" type="password" value={password} onChange={e => setPassword(e.target.value)} />
            </div>
            {err && <div className="mono" style={{ fontSize: 12, color: "var(--m-protein)" }}>{err}</div>}
            <button className="btn btn-primary btn-block" style={{ marginTop: 8 }} onClick={submitLogin}>
              Log in <Icon name="arrow" size={14} />
            </button>
            <button className="muted" style={{ fontSize: 13, marginTop: 4, textAlign: "left" }}
                    onClick={() => setShowHelp(s => !s)}>
              Forgot password? <span style={{ textDecoration: "underline" }}>{showHelp ? "hide" : "help"}</span>
            </button>
            {showHelp && (
              <div className="card sunken" style={{ fontSize: 13 }}>
                Drop a DM to <span className="mono">@1500calories</span> or email
                <span className="mono"> reset@getfit.app</span> — admin will reset within 24h.
              </div>
            )}
          </div>
        )}

        {mode === "redeem" && (
          <div className="col" style={{ gap: 18, maxWidth: 380 }}>
            <Eyebrow>New member</Eyebrow>
            <h2 className="h-section" style={{ margin: 0 }}>Redeem your code</h2>
            <p className="muted" style={{ fontSize: 14, margin: 0 }}>
              Got an access code from your coach? Enter it below to create your account and
              unlock the program.
            </p>
            <div className="field">
              <label className="field-label">Access code</label>
              <input className="field-input mono" placeholder="FIT-30"
                     value={code} onChange={e => setCode(e.target.value)}
                     style={{ letterSpacing: "0.08em", fontSize: 17, textTransform: "uppercase" }} />
            </div>
            {err && <div className="mono" style={{ fontSize: 12, color: "var(--m-protein)" }}>{err}</div>}
            <button className="btn btn-primary btn-block" onClick={submitRedeem}>
              Redeem & continue <Icon name="arrow" size={14} />
            </button>
            <div className="card sunken" style={{ fontSize: 12, padding: 14 }}>
              <span className="eyebrow">Try these demo codes</span>
              <div className="row" style={{ marginTop: 8, gap: 6, flexWrap: "wrap" }}>
                {Object.keys(window.MOCK.ACCESS_CODES).map(c => (
                  <button key={c} className="chip" onClick={() => setCode(c)}>{c}</button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Login });
