// Authentication screens: Login, Signup, Reset password
const { useState: useState_auth } = React;

function AuthScreen({ onAuth, store, onGuestMode }) {
  const [mode, setMode] = useState_auth("login");  // login | signup | reset

  return (
    <div className="auth-screen" data-screen-label="Auth">
      <div className="auth-card">
        <div className="auth-logo">
          <Icon name="shuttle" size={26} stroke={1.8} />
        </div>
        {mode === "login" && <LoginForm onAuth={onAuth} setMode={setMode} store={store} onGuestMode={onGuestMode} />}
        {mode === "signup" && <SignupForm onAuth={onAuth} setMode={setMode} />}
        {mode === "reset" && <ResetForm setMode={setMode} sbMode={store.sbMode} />}
      </div>
      <div style={{position:"absolute", bottom: 16, left: 0, right: 0, textAlign:"center", display:"flex", flexDirection:"column", gap:4, alignItems:"center", padding:"0 16px"}}>
        <div style={{color:"var(--text-3)", fontSize:12}}>
          BadMatch · ระบบจับคู่ผู้เล่นแบดมินตันอย่างยุติธรรม
        </div>
        <BrandCredit variant="footer" />
      </div>
    </div>
  );
}

function LoginForm({ onAuth, setMode, onGuestMode }) {
  const [identifier, setIdentifier] = useState_auth("");
  const [pw, setPw] = useState_auth("");
  const [busy, setBusy] = useState_auth(false);
  const toast = useToast();

  // Awaits onAuth (async in live mode); surfaces errors as a toast and unsticks the button.
  const tryAuth = async (creds) => {
    setBusy(true);
    try {
      await onAuth(creds);
    } catch (err) {
      toast(err?.message || "เข้าสู่ระบบไม่สำเร็จ");
      setBusy(false);
    }
  };

  const submit = (e) => {
    e.preventDefault();
    if (!identifier || !pw) return toast("กรุณากรอก Username/Email และรหัสผ่าน");
    tryAuth({ identifier: identifier.trim(), password: pw });
  };

  return (
    <>
      <h1 className="auth-title">เข้าสู่ระบบ</h1>
      <p className="auth-sub">BadMatch · ระบบจัดก๊วนแบดมินตัน</p>

      <form onSubmit={submit}>
        <div className="field">
          <label>Username หรือ Email</label>
          <input type="text" autoComplete="username" autoCapitalize="none" spellCheck="false" value={identifier}
            onChange={(e) => setIdentifier(e.target.value)} placeholder="ชื่อผู้ใช้ หรือ you@example.com" />
        </div>
        <div className="field">
          <label>รหัสผ่าน</label>
          <input type="password" autoComplete="current-password" value={pw}
            onChange={(e) => setPw(e.target.value)} placeholder="รหัสผ่าน" />
        </div>
        <div className="spread" style={{margin: "4px 0 16px"}}>
          <label className="row small" style={{cursor:"pointer"}}>
            <input type="checkbox" defaultChecked style={{width:14, height:14}} />
            จดจำฉันไว้
          </label>
          <button type="button" className="btn ghost sm" onClick={() => setMode("reset")}>ลืมรหัสผ่าน?</button>
        </div>
        <button type="submit" className="btn primary lg block" disabled={busy}>
          {busy ? "กำลังเข้าสู่ระบบ…" : "เข้าสู่ระบบ"}
        </button>
      </form>

      <div className="auth-foot-note">
        <div className="viewer-note">
          <Icon name="eye" size={14} />
          <span><b>ผู้ชม</b> ไม่ต้องเข้าสู่ระบบ — เปิดผ่านลิงก์แชร์หรือ QR Code จากเจ้าของก๊วน</span>
        </div>
        <div className="center small muted" style={{marginTop: 10}}>
          บัญชีใหม่ต้องให้ Super User สร้างให้ — ไม่มีการสมัครแบบเปิด
        </div>
      </div>

      {onGuestMode && (
        <div style={{marginTop:18, borderTop:"0.5px solid var(--sep-soft)", paddingTop:16}}>
          <button type="button" className="btn block" style={{justifyContent:"center", gap:8}}
            onClick={onGuestMode}>
            <Icon name="shuttle" size={14} stroke={2}/>
            เล่นแบบไม่ล็อคอิน (Guest Mode)
          </button>
          <div className="center small muted" style={{marginTop:6}}>
            ออฟไลน์ · เก็บข้อมูลใน localStorage · ไม่ต้องอินเตอร์เน็ต
          </div>
        </div>
      )}
    </>
  );
}

function SignupForm({ onAuth, setMode }) {
  const [name, setName] = useState_auth("");
  const [email, setEmail] = useState_auth("");
  const [pw, setPw] = useState_auth("");
  const toast = useToast();

  const submit = (e) => {
    e.preventDefault();
    if (!name || !email || !pw) return toast("กรุณากรอกข้อมูลให้ครบ");
    if (pw.length < 6) return toast("รหัสผ่านอย่างน้อย 6 ตัวอักษร");
    onAuth({ name, email });
    toast("สมัครสำเร็จ ยินดีต้อนรับ 🎉");
  };

  return (
    <>
      <h1 className="auth-title">สร้างบัญชีใหม่</h1>
      <p className="auth-sub">เริ่มจัดก๊วนได้ใน 30 วินาที</p>
      <form onSubmit={submit}>
        <div className="field"><label>ชื่อ</label>
          <input value={name} onChange={(e)=>setName(e.target.value)} placeholder="ชื่อจริง / ชื่อเล่น" />
        </div>
        <div className="field"><label>อีเมล</label>
          <input type="email" value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="you@example.com" />
        </div>
        <div className="field"><label>รหัสผ่าน</label>
          <input type="password" value={pw} onChange={(e)=>setPw(e.target.value)} placeholder="อย่างน้อย 6 ตัวอักษร" />
        </div>
        <button type="submit" className="btn primary lg block">สมัครสมาชิก</button>
      </form>
      <div className="center mt-2 small muted">
        มีบัญชีอยู่แล้ว? <button className="btn ghost sm" onClick={() => setMode("login")}>เข้าสู่ระบบ</button>
      </div>
    </>
  );
}

function ResetForm({ setMode, sbMode }) {
  const [email, setEmail] = useState_auth("");
  const [sent, setSent] = useState_auth(false);
  const [busy, setBusy] = useState_auth(false);
  const [err, setErr] = useState_auth("");
  const toast = useToast();

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim()) return setErr("กรุณากรอกอีเมล");
    setErr("");
    setBusy(true);
    try {
      if (sbMode && window.sb) {
        await window.sb.auth.resetPasswordForEmail(email.trim(), {
          redirectTo: window.location.origin,
        });
      }
      setSent(true);
    } catch (e) {
      setErr("ส่งลิงก์ไม่สำเร็จ — ลองใหม่อีกครั้ง");
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <h1 className="auth-title">รีเซ็ตรหัสผ่าน</h1>
      <p className="auth-sub">เราจะส่งลิงก์สำหรับตั้งรหัสใหม่ไปยังอีเมลของคุณ</p>
      {!sent ? (
        <form onSubmit={submit}>
          <div className="field">
            <label>อีเมลที่ลงทะเบียนไว้</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com" autoCapitalize="none" autoFocus />
          </div>
          {err && (
            <div style={{background:"rgba(255,59,48,0.1)", color:"var(--red)", borderRadius:8, padding:"10px 14px", marginBottom:12, fontSize:14}}>
              {err}
            </div>
          )}
          <button type="submit" className="btn primary lg block" disabled={busy}>
            {busy ? "กำลังส่ง…" : "ส่งลิงก์รีเซ็ต"}
          </button>
        </form>
      ) : (
        <div className="card-pad center" style={{background:"var(--green-soft)", borderRadius:14, color:"#1f9e3e"}}>
          <Icon name="check" size={28} stroke={2.4} />
          <div style={{fontWeight:600, marginTop:6}}>ส่งลิงก์แล้ว</div>
          <div className="small">เช็คอีเมล <b>{email}</b> ภายใน 5 นาที</div>
          <div className="small" style={{marginTop:6, color:"var(--text-3)"}}>ถ้าไม่พบ ลองเช็คโฟลเดอร์ Spam</div>
        </div>
      )}
      <div className="center mt-2 small muted">
        <button className="btn ghost sm" onClick={() => setMode("login")}>← กลับไปเข้าสู่ระบบ</button>
      </div>
    </>
  );
}

Object.assign(window, { AuthScreen });
