const LoginScreen = ({ onLogin, initialError, onErrorClear }) => {
  const [mode, setMode] = React.useState("password");
  const [email, setEmail] = React.useState(""); const [password, setPassword] = React.useState("");
  const [showPwd, setShowPwd] = React.useState(false); const [step, setStep] = React.useState("form");
  const [errMsg, setErrMsg] = React.useState(""); const [loading, setLoading] = React.useState(false);
  const [globalErr, setGlobalErr] = React.useState(initialError || "");
  React.useEffect(() => setGlobalErr(initialError || ""), [initialError]);

  const submitPassword = async e => {
    e.preventDefault();
    if (!email || !password) return;
    setLoading(true); setErrMsg("");
    try { await window.TRN_AUTH.signInWithPassword(email, password); }
    catch (err) {
      const m = err.message || "";
      setErrMsg(m.includes("Invalid login") || m.includes("invalid_credentials") ? "อีเมลหรือรหัสผ่านไม่ถูกต้อง" : m || "เกิดข้อผิดพลาด");
      setStep("error");
    } finally { setLoading(false); }
  };

  const submitMagic = async e => {
    e.preventDefault();
    if (!email) return;
    setLoading(true); setErrMsg("");
    try { await window.TRN_AUTH.sendPasswordReset(email); setStep("sent"); }
    catch (err) { setErrMsg(err.message || "เกิดข้อผิดพลาด"); setStep("error"); }
    finally { setLoading(false); }
  };

  return (
    <div className="page-enter" style={{ minHeight:"100vh", display:"grid", gridTemplateColumns:"1fr 1fr" }}>
      {/* LEFT */}
      <div style={{ position:"relative", padding:"60px 70px", display:"flex", flexDirection:"column", justifyContent:"space-between", overflow:"hidden", borderRight:"1px solid var(--border)" }}>
        <GlowBlob color="rgba(0,212,168,0.5)" x={-100} y={-100} size={500} opacity={0.35} />
        <GlowBlob color="rgba(124,92,255,0.4)" x={100} y="55vh" size={380} opacity={0.25} />

        <div style={{ position:"relative", zIndex:2, display:"flex", alignItems:"center", gap:12 }}>
          <div style={{ width:42, height:42, borderRadius:12, background:"linear-gradient(135deg,#00d4a8,#7c5cff)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:16, color:"#fff", fontWeight:700, boxShadow:"0 10px 30px -8px rgba(0,212,168,0.5)" }}>TF</div>
          <div><div style={{ fontSize:16, fontWeight:600 }}>Training Follow-Up</div><div className="faint" style={{ fontSize:11 }}>ระบบติดตามผลการฝึกอบรม</div></div>
        </div>

        <div style={{ position:"relative", zIndex:2, maxWidth:460 }}>
          <div className="chip chip-teal" style={{ marginBottom:20 }}><span className="live-dot" /> ระบบพร้อมใช้งาน</div>
          <h1 style={{ fontSize:38, fontWeight:700, lineHeight:1.2, letterSpacing:-0.8, margin:"0 0 18px" }}>
            ติดตามผลการฝึกอบรม<br/>
            <span style={{ background:"linear-gradient(135deg,#00d4a8,#7c5cff)", WebkitBackgroundClip:"text", WebkitTextFillColor:"transparent", backgroundClip:"text" }}>อย่างเป็นระบบ</span>
          </h1>
          <p className="muted" style={{ fontSize:14, lineHeight:1.75, margin:0 }}>
            บันทึกผลการประเมินตนเองและผู้บังคับบัญชา วัดผลพฤติกรรม 10 ด้าน พร้อม Dashboard สรุปภาพรวมรายหลักสูตรและรายแผนก
          </p>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:12, marginTop:28 }}>
            {[
              { v:"10", label:"ด้านพฤติกรรม", c:"var(--teal)" },
              { v:"2",  label:"ผู้ประเมิน/คน", c:"var(--purple)" },
              { v:"✓",  label:"Dashboard", c:"var(--yellow)" },
            ].map((s,i) => (
              <div key={i} className="glass" style={{ padding:"14px 16px" }}>
                <div style={{ fontSize:26, fontWeight:700, color:s.c, lineHeight:1 }}>{s.v}</div>
                <div className="faint" style={{ fontSize:11.5, marginTop:6 }}>{s.label}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="faint" style={{ fontSize:12, position:"relative", zIndex:2 }}>© 2569 Training Follow-Up · Sahamit Product Co., Ltd.</div>
      </div>

      {/* RIGHT — form */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"center", padding:"40px" }}>
        {mode === "magic" && step === "sent" ? (
          <div style={{ width:"100%", maxWidth:360, textAlign:"center" }} className="page-enter">
            <div style={{ fontSize:40, marginBottom:16 }}>📧</div>
            <h2 style={{ fontSize:22, fontWeight:600, margin:"0 0 8px" }}>ตรวจสอบอีเมลของคุณ</h2>
            <p className="muted" style={{ fontSize:13.5, marginBottom:20 }}>ส่ง Magic Link ไปที่ <strong>{email}</strong> แล้ว</p>
            <button className="btn btn-ghost btn-sm" onClick={() => { setMode("password"); setStep("form"); }}>← กลับหน้าล็อกอิน</button>
          </div>
        ) : mode === "password" ? (
          <form onSubmit={submitPassword} style={{ width:"100%", maxWidth:360 }} className="page-enter">
            <h2 style={{ fontSize:26, fontWeight:600, margin:"0 0 4px" }}>เข้าสู่ระบบ</h2>
            <p className="muted" style={{ fontSize:13, margin:"0 0 26px" }}>Training Follow-Up System</p>

            {globalErr && (
              <div style={{ padding:"10px 14px", borderRadius:10, marginBottom:16, background:"rgba(255,201,77,0.1)", border:"1px solid rgba(255,201,77,0.35)", fontSize:12.5 }}>
                ⚠️ {globalErr}
                <button type="button" onClick={() => { setGlobalErr(""); onErrorClear?.(); }} style={{ float:"right", background:"none", border:"none", cursor:"pointer", color:"var(--text-faint)" }}>✕</button>
              </div>
            )}

            <label className="field-label">อีเมล</label>
            <div style={{ position:"relative", marginBottom:14 }}>
              <Icon name="mail" size={15} color="var(--text-faint)" style={{ position:"absolute", left:13, top:"50%", transform:"translateY(-50%)" }} />
              <input className="input" type="email" value={email} onChange={e => { setEmail(e.target.value); setStep("form"); }} style={{ paddingLeft:38 }} placeholder="your@company.co.th" autoFocus />
            </div>

            <label className="field-label">รหัสผ่าน</label>
            <div style={{ position:"relative", marginBottom:8 }}>
              <Icon name="lock" size={15} color="var(--text-faint)" style={{ position:"absolute", left:13, top:"50%", transform:"translateY(-50%)" }} />
              <input className="input" type={showPwd?"text":"password"} value={password} onChange={e => { setPassword(e.target.value); setStep("form"); }} style={{ paddingLeft:38, paddingRight:40 }} placeholder="••••••••" />
              <button type="button" onClick={() => setShowPwd(p => !p)} style={{ position:"absolute", right:11, top:"50%", transform:"translateY(-50%)", background:"none", border:"none", cursor:"pointer", color:"var(--text-faint)" }}>
                <Icon name={showPwd?"eye-off":"eye"} size={15} />
              </button>
            </div>

            {step === "error" && <div style={{ padding:"10px 14px", borderRadius:8, marginBottom:10, background:"rgba(255,93,143,0.1)", border:"1px solid rgba(255,93,143,0.3)", fontSize:13, color:"var(--pink)" }}>{errMsg}</div>}

            <button type="submit" className="btn btn-primary shine" disabled={loading || !email || !password} style={{ height:44, width:"100%", justifyContent:"center", fontSize:14.5, marginTop:14 }}>
              {loading ? <><span className="live-dot" /> กำลังเข้าสู่ระบบ…</> : "เข้าสู่ระบบ"}
            </button>

            <div style={{ textAlign:"center", marginTop:16 }}>
              <button type="button" className="btn btn-ghost btn-sm" onClick={() => { setMode("magic"); setStep("form"); }} style={{ fontSize:12.5 }}>ลืมรหัสผ่าน? รับ Magic Link</button>
            </div>
          </form>
        ) : (
          <form onSubmit={submitMagic} style={{ width:"100%", maxWidth:360 }} className="page-enter">
            <h2 style={{ fontSize:24, fontWeight:600, margin:"0 0 4px" }}>รับ Magic Link</h2>
            <p className="muted" style={{ fontSize:13, margin:"0 0 22px" }}>ระบบจะส่งลิงก์เข้าสู่ระบบไปยังอีเมล</p>
            <label className="field-label">อีเมล</label>
            <div style={{ position:"relative", marginBottom:12 }}>
              <Icon name="mail" size={15} color="var(--text-faint)" style={{ position:"absolute", left:13, top:"50%", transform:"translateY(-50%)" }} />
              <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} style={{ paddingLeft:38 }} placeholder="your@company.co.th" autoFocus />
            </div>
            {step === "error" && <div style={{ padding:"10px 14px", borderRadius:8, marginBottom:10, background:"rgba(255,93,143,0.1)", border:"1px solid rgba(255,93,143,0.3)", fontSize:13, color:"var(--pink)" }}>{errMsg}</div>}
            <button type="submit" className="btn btn-primary shine" disabled={loading || !email} style={{ height:44, width:"100%", justifyContent:"center", marginTop:6 }}>
              {loading ? "กำลังส่ง…" : "ส่ง Magic Link"}
            </button>
            <div style={{ textAlign:"center", marginTop:14 }}>
              <button type="button" className="btn btn-ghost btn-sm" onClick={() => { setMode("password"); setStep("form"); }} style={{ fontSize:12.5 }}>← กลับ</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};
window.LoginScreen = LoginScreen;
