// ============ TaskQuest — Login / Sign-up page ============
const { useState: useStateL } = React;

function LoginPage({ theme, toggleTheme, onLogin }) {
  const live = window.TQ_BACKEND.CONFIGURED;

  const [mode, setMode] = useStateL("signin");      // 'signin' | 'signup'
  const [name, setName] = useStateL("");
  const [email, setEmail] = useStateL("");
  const [identifier, setIdentifier] = useStateL("");
  const [password, setPassword] = useStateL("");
  const [roleType, setRoleType] = useStateL("consultant");
  const [show, setShow] = useStateL(false);
  const [error, setError] = useStateL("");
  const [info, setInfo] = useStateL("");
  const [busy, setBusy] = useStateL(false);

  async function submit(e) {
    if (e) e.preventDefault();
    setError(""); setInfo(""); setBusy(true);
    try {
      if (mode === "signin") {
        const { error } = await window.TQ_BACKEND.signIn(identifier.trim(), password);
        if (error) { setError(error.message || "Could not sign in."); }
        else { onLogin(); }
      } else {
        if (!name.trim()) { setError("Please enter your full name."); setBusy(false); return; }
        const { error, needsConfirm } = await window.TQ_BACKEND.signUp({
          email: email.trim(), password, fullName: name.trim(), roleType,
        });
        if (error) { setError(error.message || "Could not create the account."); }
        else if (needsConfirm) { setInfo("Account created — check your email to confirm, then sign in."); setMode("signin"); }
        else { onLogin(); }
      }
    } catch (err) {
      setError(err.message || "Something went wrong.");
    }
    setBusy(false);
  }

  return (
    <div className="login-stage">
      {/* Brand panel */}
      <div className="login-brand">
        <div className="login-brand-top">
          <div className="brand-mark"><Ic.Layers size={16} sw={2.2} /></div>
          <div className="login-brand-name">TaskQuest</div>
        </div>
        <div className="login-brand-mid">
          <div className="login-tagline">Accountability and momentum for delivery teams.</div>
          <div className="login-sub">A Kanban-first workspace where progress earns points, managers approve in a click, and recognition lands on the leaderboard instantly.</div>
          <div className="login-mini-board" aria-hidden="true">
            {[["Happy Path", "#4cb782"], ["Needs attention", "#f2c94c"], ["Done", "#8b7cf6"]].map(([n, c]) => (
              <div className="lmb-col" key={n}>
                <div className="lmb-col-h"><span className="lmb-dot" style={{ background: c }} />{n}</div>
                <div className="lmb-card" />
                <div className="lmb-card sm" />
              </div>
            ))}
          </div>
        </div>
        <div className="login-brand-foot">{live ? "Connected workspace" : "Preview mode · not connected to a database"}</div>
      </div>

      {/* Form panel */}
      <div className="login-panel">
        <button className="icon-btn login-theme-btn" onClick={toggleTheme} title="Toggle theme">
          {theme === "dark" ? <Ic.Sun size={18} /> : <Ic.Moon size={18} />}
        </button>
        <div className="login-card">
          <div className="login-card-mobile-brand">
            <div className="brand-mark"><Ic.Layers size={15} sw={2.2} /></div>
            <div className="brand-name">Task<b>Quest</b></div>
          </div>

          <div className="login-h">{mode === "signin" ? "Sign in" : "Create your account"}</div>
          <div className="login-hsub">{mode === "signin" ? "Welcome back — sign in to your workspace." : "Join your team's workspace."}</div>

          <form className="login-form" onSubmit={submit}>
            {error && <div className="login-error"><Ic.Alert size={15} />{error}</div>}
            {info && <div className="login-error" style={{ background: "#16a39418", color: "#16a394", borderColor: "#16a39433" }}><Ic.CheckCircle size={15} />{info}</div>}

            {mode === "signup" && (
              <div className="field">
                <label className="field-label">Full name</label>
                <input className="input" autoFocus placeholder="e.g. Jordan Lee"
                  value={name} onChange={e => { setName(e.target.value); setError(""); }} />
              </div>
            )}
            {mode === "signin" ? (
              <div className="field">
                <label className="field-label">Email or username</label>
                <input className="input" type="text" autoComplete="username" autoCapitalize="none" spellCheck="false" placeholder="you@company.com or your username"
                  value={identifier} onChange={e => { setIdentifier(e.target.value); setError(""); }} />
              </div>
            ) : (
              <div className="field">
                <label className="field-label">Work email</label>
                <input className="input" type="email" autoComplete="email" placeholder="you@company.com"
                  value={email} onChange={e => { setEmail(e.target.value); setError(""); }} />
              </div>
            )}
            <div className="field">
              <label className="field-label">Password</label>
              <div className="login-pw-wrap">
                <input className="input" type={show ? "text" : "password"}
                  autoComplete={mode === "signin" ? "current-password" : "new-password"} placeholder="Enter your password"
                  value={password} onChange={e => { setPassword(e.target.value); setError(""); }} />
                <button type="button" className="login-pw-toggle" onClick={() => setShow(s => !s)} title={show ? "Hide" : "Show"}>
                  {show ? <Ic.EyeOff size={17} /> : <Ic.Eye size={17} />}
                </button>
              </div>
            </div>
            {mode === "signup" && (
              <div className="field">
                <label className="field-label">Your role</label>
                <select className="input" value={roleType} onChange={e => setRoleType(e.target.value)}>
                  <option value="consultant">Consultant</option>
                  <option value="pm">Project Manager</option>
                  <option value="dm">Delivery Manager</option>
                </select>
              </div>
            )}

            <button type="submit" className="btn btn-primary login-submit" disabled={busy}>
              <Ic.Lock size={15} />{busy ? "Please wait…" : (mode === "signin" ? "Sign in" : "Create account")}
            </button>
          </form>

          <div className="login-hint" style={{ textAlign: "center", marginTop: 16 }}>
            {mode === "signin" ? (
              <>New here? <button className="linklike" onClick={() => { setMode("signup"); setError(""); setInfo(""); }}>Create an account</button></>
            ) : (
              <>Already have an account? <button className="linklike" onClick={() => { setMode("signin"); setError(""); setInfo(""); }}>Sign in</button></>
            )}
          </div>

          {!live && (
            <div className="login-hint" style={{ marginTop: 14, opacity: .8 }}>
              <Ic.Alert size={12} style={{ verticalAlign: "-1px", marginRight: 4 }} />
              Preview mode (no Supabase keys). <b>Sign in</b> with any details to explore as an admin, or <b>Create an account</b> to preview a role. Nothing is saved.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
