// Login / register / wachtwoord vergeten.
// Belangrijke fixes:
// - geen race tussen "ingelogd → redirect" en form submit
// - duidelijke Nederlandse berichten
// - email-confirmation banner zichtbaar
// - geen lokale state-loop

const PageLogin = ({ setPage, compact }) => {
  const { useState, useContext, useEffect } = React;
  const auth = useContext(window.AuthContext);
  const langCtx = useContext(window.LangContext || React.createContext({ lang:"nl", t: (nl)=>nl }));
  const t = langCtx.t || ((nl) => nl);
  const lang = langCtx.lang || "nl";
  const authText = (text) => {
    if (lang !== "en" || !text) return text;
    const map = {
      "E-mail of wachtwoord onjuist. Heb je je e-mailadres al bevestigd?": "Email or password is incorrect. Have you confirmed your email address?",
      "Bevestig eerst je e-mailadres via de link die we je hebben gestuurd.": "Confirm your email address using the link we sent you first.",
      "Er bestaat al een account met dit e-mailadres. Probeer in te loggen of vraag een nieuw wachtwoord aan.": "An account already exists with this email address. Try signing in or request a new password.",
      "Wachtwoord moet minimaal 8 tekens zijn.": "Password must be at least 8 characters.",
      "Te veel pogingen. Probeer het over een paar minuten opnieuw.": "Too many attempts. Try again in a few minutes.",
      "Geen verbinding met de server. Controleer je internet en probeer opnieuw.": "No connection to the server. Check your internet and try again.",
      "Vul een geldig e-mailadres in.": "Enter a valid email address.",
      "Je bent niet (meer) ingelogd. Log opnieuw in.": "You are no longer signed in. Sign in again.",
      "Je sessie is verlopen. Log opnieuw in.": "Your session has expired. Sign in again.",
    };
    return map[text] || text;
  };

  const [mode, setMode] = useState("login"); // login | register | reset
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState(null);
  const [err, setErr] = useState(null);
  const [confirmEmailNotice, setConfirmEmailNotice] = useState(false);

  // If already logged in, bounce to account (admin → admin). Use ID-based dep.
  useEffect(() => {
    if (!auth || !auth.ready) return;
    if (auth.user) {
      setPage(auth.isAdmin ? "admin" : "account");
    }
    // eslint-disable-next-line
  }, [auth && auth.ready, auth && auth.user && auth.user.id]);

  const configMissing = !window.zsb || !window.zsb.isConfigured;

  const switchMode = (next) => {
    setMode(next);
    setErr(null);
    setMsg(null);
    setConfirmEmailNotice(false);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setErr(null); setMsg(null); setConfirmEmailNotice(false);
    setBusy(true);

    try {
      if (mode === "login") {
        const r = await window.zsb.signIn({ email: email.trim(), password });
        if (r.error) { setErr(r.error); return; }
        // Auth listener will update state; useEffect above does the redirect.
        setMsg(t("Ingelogd.","Signed in."));
      } else if (mode === "register") {
        if (password.length < 8) { setErr(t("Wachtwoord moet minimaal 8 tekens zijn.","Password must be at least 8 characters.")); return; }
        const r = await window.zsb.signUp({ email: email.trim(), password, fullName, phone });
        if (r.error) { setErr(r.error); return; }
        if (r.data && r.data.session) {
          setMsg(t("Account aangemaakt en ingelogd.","Account created and signed in."));
        } else {
          // Email confirmation required
          setConfirmEmailNotice(true);
          setMode("login");
          setPassword("");
        }
      } else if (mode === "reset") {
        if (!email.trim()) { setErr(t("Vul je e-mailadres in.","Enter your email address.")); return; }
        await window.zsb.resetPassword({ email: email.trim() });
        // Don't reveal whether the email exists — always show the same message.
        setMsg(t("Als dit e-mailadres bekend is, ontvang je binnen een paar minuten een herstellink per e-mail.","If this email address is known, you will receive a reset link within a few minutes."));
      }
    } catch (e2) {
      setErr((e2 && e2.message) || t("Onbekende fout.","Unknown error."));
    } finally {
      setBusy(false);
    }
  };

  const heading = (mode === "login")
    ? t("Inloggen","Sign in")
    : (mode === "register" ? t("Account aanmaken","Create account") : t("Wachtwoord vergeten","Forgot password"));

  // ──────────────────────────────────────────────────────────────
  // Compact mode (used by the LoginModal). Same form, no page chrome.
  // ──────────────────────────────────────────────────────────────
  if (compact) {
    return (
      <div style={{padding:"20px 24px 24px"}}>
        <div className="eyebrow" style={{marginBottom:6}}>Account</div>
        <h2 className="h-display" style={{fontSize:24, marginBottom:18}}>{heading}</h2>
        {configMissing && (
          <div className="card" style={{padding:14, marginBottom:14, background:"#fff8e6", border:"1px solid #f0d985"}}>
            <strong>{t("Supabase is nog niet geconfigureerd.","Supabase is not configured yet.")}</strong>
            <div style={{fontSize:12.5, color:"var(--ink-dim)", marginTop:6}}>
              {(window.zsb && window.zsb.initError) || t("Vul light/config.js in volgens SETUP.md.","Fill in light/config.js as described in SETUP.md.")}
            </div>
          </div>
        )}
        {confirmEmailNotice && (
          <div className="card" style={{padding:14, marginBottom:14, background:"#e7f4ec", border:"1px solid #bfe0cb"}}>
            <strong>{t("Controleer je e-mail om je account te bevestigen.","Check your email to confirm your account.")}</strong>
            <div style={{fontSize:12.5, color:"#2d5b3d", marginTop:6}}>
              {t("We hebben een bevestigingsmail naar","We sent a confirmation email to")} <strong>{email}</strong>.
              {" "}{t("Klik op de link en log daarna in.","Click the link and then sign in.")}
            </div>
          </div>
        )}
        {mode !== "reset" && (
          <div style={{display:"flex", gap:6, marginBottom:16, background:"var(--bg)", padding:4, borderRadius:10}}>
            {[{id:"login", label:t("Inloggen","Sign in")},{id:"register", label:t("Registreren","Register")}].map(tab => (
              <button key={tab.id} type="button" onClick={()=>switchMode(tab.id)} style={{
                flex:1, padding:"10px 14px", borderRadius:8, fontSize:13, fontWeight:600,
                background: mode === tab.id ? "#fff" : "transparent",
                color: mode === tab.id ? "var(--ink)" : "var(--ink-dim)",
                boxShadow: mode === tab.id ? "0 1px 3px rgba(0,0,0,.06)" : "none",
              }}>{tab.label}</button>
            ))}
          </div>
        )}
        <form onSubmit={onSubmit} noValidate>
          {mode === "register" && (
            <>
              <div className="field" style={{marginBottom:12}}>
                <label className="field-label">{t("Volledige naam","Full name")}</label>
                <input className="input" value={fullName} onChange={e=>setFullName(e.target.value)} placeholder={t("Jan de Vries","John Doe")} required/>
              </div>
              <div className="field" style={{marginBottom:12}}>
                <label className="field-label">{t("Telefoonnummer","Phone number")}</label>
                <input className="input" type="tel" value={phone} onChange={e=>setPhone(e.target.value)} placeholder="+31 6 ..."/>
              </div>
            </>
          )}
          <div className="field" style={{marginBottom:12}}>
            <label className="field-label">{t("E-mail","Email")}</label>
            <input className="input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder={t("jan@email.nl","you@email.com")} required autoComplete="email"/>
          </div>
          {mode !== "reset" && (
            <div className="field" style={{marginBottom:12}}>
              <label className="field-label">{t("Wachtwoord","Password")}</label>
              <input className="input" type="password" value={password} onChange={e=>setPassword(e.target.value)} placeholder="••••••••" required minLength={8} autoComplete={mode === "register" ? "new-password" : "current-password"}/>
            </div>
          )}
          {err && <div style={{color:"var(--bad)", fontSize:13, marginBottom:10, lineHeight:1.45}}>{authText(err)}</div>}
          {msg && <div style={{color:"var(--ok)", fontSize:13, marginBottom:10, lineHeight:1.45}}>{msg}</div>}
          <button type="submit" className="btn btn-accent btn-lg btn-block" disabled={busy || configMissing}>
            {busy ? t("Bezig…","Working…") : (mode === "login" ? t("Inloggen","Sign in") : mode === "register" ? t("Account aanmaken","Create account") : t("Stuur herstel-link","Send reset link"))}
          </button>
        </form>
        <div style={{marginTop:14, display:"flex", justifyContent:"space-between", flexWrap:"wrap", gap:10, fontSize:12.5}}>
          {mode === "login" && (
            <button type="button" onClick={()=>switchMode("reset")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:12.5}}>
              {t("Wachtwoord vergeten?","Forgot password?")}
            </button>
          )}
          {mode === "reset" && (
            <button type="button" onClick={()=>switchMode("login")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:12.5}}>
              {t("Terug naar inloggen","Back to sign in")}
            </button>
          )}
          <div style={{color:"var(--ink-mute)"}}>
            {mode === "login" && (<>{t("Nog geen account?","No account yet?")} <button type="button" onClick={()=>switchMode("register")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:12.5}}>{t("Registreer","Register")}</button></>)}
            {mode === "register" && (<>{t("Al een account?","Already have an account?")} <button type="button" onClick={()=>switchMode("login")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:12.5}}>{t("Log in","Sign in")}</button></>)}
            {mode === "reset" && (<>{t("Nog geen account?","No account yet?")} <button type="button" onClick={()=>switchMode("register")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:12.5}}>{t("Registreer","Register")}</button></>)}
          </div>
        </div>
      </div>
    );
  }

  // ──────────────────────────────────────────────────────────────
  // Full page mode (direct /#login route)
  // ──────────────────────────────────────────────────────────────
  return (
    <div className="page">
      <section style={{padding:"40px 0 16px", borderBottom:"1px solid var(--line)"}}>
        <div className="wrap">
          <div className="eyebrow" style={{marginBottom:10}}>Account</div>
          <h1 className="h-display" style={{fontSize:"clamp(34px,5vw,52px)"}}>{heading}</h1>
        </div>
      </section>

      <section className="section-sm">
        <div className="wrap" style={{maxWidth:520, margin:"0 auto"}}>
          {configMissing && (
            <div className="card" style={{padding:18, marginBottom:18, background:"#fff8e6", border:"1px solid #f0d985"}}>
              <strong>{t("Supabase is nog niet geconfigureerd.","Supabase is not configured yet.")}</strong>
              <div style={{fontSize:13, color:"var(--ink-dim)", marginTop:6}}>
                {(window.zsb && window.zsb.initError) || t("Vul light/config.js in volgens SETUP.md.","Fill in light/config.js as described in SETUP.md.")} {t("Inloggen, registreren en bestellingen werken pas nadat dit gedaan is.","Sign in, registration and orders work after this is configured.")}
              </div>
            </div>
          )}

          {confirmEmailNotice && (
            <div className="card" style={{padding:18, marginBottom:18, background:"#e7f4ec", border:"1px solid #bfe0cb"}}>
              <strong>{t("Controleer je e-mail om je account te bevestigen.","Check your email to confirm your account.")}</strong>
              <div style={{fontSize:13, color:"#2d5b3d", marginTop:6}}>
                {t("We hebben een bevestigingsmail naar","We sent a confirmation email to")} <strong>{email}</strong>.
                {" "}{t("Klik op de link in de mail en log daarna in.","Click the link in the email and then sign in.")}
                {" "}{t("Geen mail ontvangen? Check je spam-folder of probeer opnieuw te registreren.","No email received? Check your spam folder or try registering again.")}
              </div>
            </div>
          )}

          <div className="card" style={{padding:28}}>
            {mode !== "reset" && (
              <div style={{display:"flex", gap:6, marginBottom:22, background:"var(--bg)", padding:4, borderRadius:10}}>
                {[
                  {id:"login", label:t("Inloggen","Sign in")},
                  {id:"register", label:t("Registreren","Register")},
                ].map(tab => (
                  <button key={tab.id} type="button" onClick={()=>switchMode(tab.id)} style={{
                    flex:1, padding:"10px 14px", borderRadius:8, fontSize:13, fontWeight:600,
                    background: mode === tab.id ? "#fff" : "transparent",
                    color: mode === tab.id ? "var(--ink)" : "var(--ink-dim)",
                    boxShadow: mode === tab.id ? "0 1px 3px rgba(0,0,0,.06)" : "none",
                  }}>{tab.label}</button>
                ))}
              </div>
            )}

            <form onSubmit={onSubmit} noValidate>
              {mode === "register" && (
                <>
                  <div className="field" style={{marginBottom:14}}>
                    <label className="field-label">{t("Volledige naam","Full name")}</label>
                    <input className="input" value={fullName} onChange={e=>setFullName(e.target.value)} placeholder={t("Jan de Vries","John Doe")} required/>
                  </div>
                  <div className="field" style={{marginBottom:14}}>
                    <label className="field-label">{t("Telefoonnummer","Phone number")}</label>
                    <input className="input" type="tel" value={phone} onChange={e=>setPhone(e.target.value)} placeholder="+31 6 ..."/>
                  </div>
                </>
              )}

              <div className="field" style={{marginBottom:14}}>
                <label className="field-label">{t("E-mail","Email")}</label>
                <input className="input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder={t("jan@email.nl","you@email.com")} required autoComplete="email"/>
              </div>

              {mode !== "reset" && (
                <div className="field" style={{marginBottom:14}}>
                  <label className="field-label">{t("Wachtwoord","Password")}</label>
                  <input className="input" type="password" value={password} onChange={e=>setPassword(e.target.value)} placeholder="••••••••" required minLength={8} autoComplete={mode === "register" ? "new-password" : "current-password"}/>
                </div>
              )}

              {err && <div style={{color:"var(--bad)", fontSize:13, marginBottom:12, lineHeight:1.45}}>{authText(err)}</div>}
              {msg && <div style={{color:"var(--ok)", fontSize:13, marginBottom:12, lineHeight:1.45}}>{msg}</div>}

              <button type="submit" className="btn btn-accent btn-lg btn-block" disabled={busy || configMissing}>
                {busy ? t("Bezig…","Working…") : (mode === "login" ? t("Inloggen","Sign in") : mode === "register" ? t("Account aanmaken","Create account") : t("Stuur herstel-link","Send reset link"))}
              </button>
            </form>

            <div style={{marginTop:18, display:"flex", justifyContent:"space-between", flexWrap:"wrap", gap:10, fontSize:13}}>
              {mode === "login" && (
                <button type="button" onClick={()=>switchMode("reset")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:13}}>
                  {t("Wachtwoord vergeten?","Forgot password?")}
                </button>
              )}
              {mode === "reset" && (
                <button type="button" onClick={()=>switchMode("login")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:13}}>
                  {t("Terug naar inloggen","Back to sign in")}
                </button>
              )}
              <div style={{color:"var(--ink-mute)"}}>
                {mode === "login" && (
                  <>{t("Nog geen account?","No account yet?")} <button type="button" onClick={()=>switchMode("register")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:13}}>{t("Registreer","Register")}</button></>
                )}
                {mode === "register" && (
                  <>{t("Al een account?","Already have an account?")} <button type="button" onClick={()=>switchMode("login")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:13}}>{t("Log in","Sign in")}</button></>
                )}
                {mode === "reset" && (
                  <>{t("Nog geen account?","No account yet?")} <button type="button" onClick={()=>switchMode("register")} className="accent" style={{cursor:"pointer", background:"none", border:0, padding:0, fontSize:13}}>{t("Registreer","Register")}</button></>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

window.PageLogin = PageLogin;
