// Login screen — Klant + Admin tabs, met register-modus
function Login({ onLogin, onNav, brand }) {
  const [role, setRole] = React.useState("klant");
  const [mode, setMode] = React.useState("login"); // login | register
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const isRegister = mode === "register" && role === "klant";

  const submit = async (e) => {
    e?.preventDefault?.();
    setError("");
    if (!email || !pw) { setError("Vul e-mail en wachtwoord in."); return; }
    if (isRegister && !name) { setError("Vul uw naam in."); return; }
    if (isRegister && pw.length < 8) { setError("Wachtwoord moet minimaal 8 tekens zijn."); return; }

    setLoading(true);
    try {
      let data;
      if (isRegister) {
        data = await window.api.auth.register({ email, password: pw, name, phone });
      } else {
        data = await window.api.auth.login({ email, password: pw });
      }
      const u = data.user;
      if (role === "admin" && u.role !== "admin") {
        setError("Dit account heeft geen werkplaats-toegang.");
        await window.api.auth.logout().catch(() => {});
        return;
      }
      onLogin({ role: u.role, name: u.name, email: u.email, id: u.id });
    } catch (err) {
      setError(err.message || (isRegister ? "Registratie mislukt" : "Inloggen mislukt"));
    } finally {
      setLoading(false);
    }
  };

  const quickFill = () => {
    if (role === "admin") { setEmail("info@garage-dede.nl"); setPw("wijzigDirect2026!"); }
    else { setEmail(""); setPw(""); }
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: "1fr 1fr", background: "var(--bg)" }}>
      {/* Left: brand panel */}
      <div style={{
        position: "relative", overflow: "hidden",
        background: "linear-gradient(135deg, var(--surface) 0%, color-mix(in oklab, var(--accent) 14%, var(--surface)) 100%)",
        padding: "64px 56px",
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        borderRight: "1px solid var(--border)",
      }}>
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          backgroundImage:
            "linear-gradient(to right, color-mix(in oklab, var(--text) 4%, transparent) 1px, transparent 1px)," +
            "linear-gradient(to bottom, color-mix(in oklab, var(--text) 4%, transparent) 1px, transparent 1px)",
          backgroundSize: "48px 48px",
          maskImage: "radial-gradient(70% 70% at 30% 40%, black, transparent)",
        }}/>
        <button onClick={() => onNav("home")} style={{ background: "none", border: 0, padding: 0, cursor: "pointer", color: "var(--text)", display: "flex", alignItems: "center", gap: 12, position: "relative", zIndex: 2 }}>
          <Logo size={40}/>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22, letterSpacing: "-0.02em" }}>{brand}</span>
        </button>

        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>Inloggen</div>
          <h1 className="display" style={{ fontSize: 64, marginBottom: 24 }}>
            Welkom <span style={{ color: "var(--accent)", fontStyle: "italic", fontWeight: 700 }}>terug.</span>
          </h1>
          <p className="subhead" style={{ maxWidth: 440, fontSize: 18 }}>
            {role === "klant"
              ? "Bekijk uw afspraken, voertuigen en facturen op één plek. APK-reminders krijgt u automatisch."
              : "Plan in, beheer de werkplaats-agenda, en houd statussen up-to-date voor uw klanten."}
          </p>
        </div>

        <div style={{ position: "relative", zIndex: 2, display: "flex", flexDirection: "column", gap: 10 }}>
          <div className="text-muted" style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>
            {role === "klant" ? "Wat u kunt:" : "Snelkoppelingen:"}
          </div>
          {(role === "klant"
            ? ["Mijn voertuigen + servicehistorie", "APK-reminder 4 weken vooraf", "Afspraken inzien en verzetten", "Facturen downloaden"]
            : ["Werkplaats-agenda (drag & drop)", "Klant- en voertuigbeheer", "Werkbonnen en statussen", "Capaciteit en blokkades"]
          ).map((x, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14 }}>
              <I.Check size={14} style={{ color: "var(--accent)" }}/> {x}
            </div>
          ))}
        </div>
      </div>

      {/* Right: form */}
      <div style={{ padding: "56px", display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <div style={{ maxWidth: 440, width: "100%", margin: "0 auto" }}>
          <button onClick={() => onNav("home")} className="btn btn-ghost btn-sm" style={{ marginBottom: 28 }}>
            <I.ArrowLeft size={14}/> Terug naar home
          </button>

          {/* Role tabs */}
          <div style={{ display: "flex", padding: 4, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, marginBottom: 32 }}>
            {[
              { id: "klant", label: "Klant", icon: I.Car, sub: "Afspraken & voertuigen" },
              { id: "admin", label: "Werkplaats", icon: I.Wrench, sub: "Admin dashboard" },
            ].map(opt => (
              <button key={opt.id} onClick={() => { setRole(opt.id); setEmail(""); setPw(""); setError(""); }}
                style={{
                  flex: 1, padding: "14px 12px", borderRadius: 9, border: 0, cursor: "pointer",
                  background: role === opt.id ? "var(--bg)" : "transparent",
                  color: role === opt.id ? "var(--text)" : "var(--text-muted)",
                  fontWeight: 600, transition: "all .2s ease",
                  display: "flex", alignItems: "center", gap: 10, justifyContent: "center",
                  boxShadow: role === opt.id ? "0 1px 0 rgba(255,255,255,.04) inset, 0 4px 12px rgba(0,0,0,.25)" : "none",
                }}>
                <opt.icon size={16}/>
                <div style={{ textAlign: "left" }}>
                  <div style={{ fontSize: 14 }}>{opt.label}</div>
                  <div style={{ fontSize: 11, color: "var(--text-muted)", fontWeight: 500 }}>{opt.sub}</div>
                </div>
              </button>
            ))}
          </div>

          <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>
            {isRegister ? "Account aanmaken" : `Inloggen als ${role === "klant" ? "klant" : "admin"}`}
          </h2>
          <p className="text-muted" style={{ marginBottom: 28, marginTop: 0, fontSize: 14 }}>
            {role === "admin" ? "Alleen voor medewerkers van Garage DéDé." : (
              <>
                {isRegister ? "Heb je al een account? " : "Of "}
                <a
                  onClick={() => { setMode(isRegister ? "login" : "register"); setError(""); }}
                  style={{ color: "var(--accent)", cursor: "pointer", textDecoration: "underline" }}
                >
                  {isRegister ? "log in" : "maak een account"}
                </a>
                {isRegister ? "." : " als u nieuw bent."}
              </>
            )}
          </p>

          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {isRegister && (
              <div className="field">
                <label>Naam</label>
                <input className="input" type="text" placeholder="Jan de Vries"
                       value={name} onChange={(e) => setName(e.target.value)}/>
              </div>
            )}
            <div className="field">
              <label>E-mailadres</label>
              <input className="input" type="email" placeholder={role === "admin" ? "naam@garage-dede.nl" : "naam@voorbeeld.nl"}
                     value={email} onChange={(e) => setEmail(e.target.value)}/>
            </div>
            {isRegister && (
              <div className="field">
                <label>Telefoon (optioneel)</label>
                <input className="input" type="tel" placeholder="06 12 34 56 78"
                       value={phone} onChange={(e) => setPhone(e.target.value)}/>
              </div>
            )}
            <div className="field">
              <label>Wachtwoord {isRegister && <span className="text-muted" style={{ fontSize: 11, marginLeft: 6 }}>min. 8 tekens</span>}</label>
              <input className="input" type="password" placeholder="••••••••"
                     value={pw} onChange={(e) => setPw(e.target.value)}/>
            </div>

            {error && <div className="pill danger" style={{ alignSelf: "flex-start" }}><span className="dot"/> {error}</div>}

            <button type="submit" className="btn btn-primary btn-lg" disabled={loading}
                    style={{ marginTop: 8, opacity: loading ? 0.6 : 1 }}>
              {loading ? "Bezig…" : <>{isRegister ? "Account aanmaken" : "Inloggen"} <I.ArrowRight size={16}/></>}
            </button>

            {role === "admin" && (
              <button type="button" onClick={quickFill} className="btn btn-ghost btn-sm" style={{ marginTop: 4 }}>
                <I.Sparkle size={14}/> Demo admin-gegevens invullen
              </button>
            )}
          </form>

          <hr className="div" style={{ margin: "32px 0" }}/>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
            <a className="text-muted" style={{ textDecoration: "none" }}>Wachtwoord vergeten?</a>
            <a className="text-muted" style={{ textDecoration: "none" }}>Magic-link via e-mail</a>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Login = Login;
