/* INDIEKOS — Layar login: Operator + Superadmin (email/Google + daftar),
   dan Penghuni (No HP + OTP WhatsApp). */
function LoginScreen({ scope, title, sub, denied, onSignedIn }) {
  const [mode, setMode]         = useState("login"); // 'login' | 'signup'
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [kosName, setKosName]   = useState("");
  const [ownerName, setOwnerName] = useState("");
  const [propName, setPropName] = useState("");
  const [loading, setLoading]   = useState(false);
  const [err, setErr]           = useState(denied || "");
  const [ok, setOk]             = useState("");

  // Penghuni OTP state
  const [otpStep, setOtpStep]   = useState("phone"); // 'phone' | 'code'
  const [otpPhone, setOtpPhone] = useState("");
  const [otpCode, setOtpCode]   = useState("");
  const [masked, setMasked]     = useState("");

  useEffect(() => { setErr(denied || ""); }, [denied]);
  const allowSignup = scope !== "superadmin";
  const isPenghuni = scope === "penghuni";

  const googleSignIn = async () => {
    setErr(""); setLoading(true);
    try {
      const { error } = await window._supabase.auth.signInWithOAuth({
        provider: "google",
        options: { redirectTo: window.location.origin + window.location.pathname },
      });
      if (error) { setErr(error.message || "Google sign-in gagal"); setLoading(false); }
    } catch (ex) { setErr(ex.message || "Google sign-in gagal"); setLoading(false); }
  };

  const submit = async (e) => {
    e.preventDefault(); setErr(""); setLoading(true);
    try {
      const { data, error } = await window._supabase.auth.signInWithPassword({ email: email.trim(), password });
      if (error) { setErr(error.message || "Email/password tidak cocok"); return; }
      onSignedIn && onSignedIn(data.session);
    } catch (ex) { setErr(ex.message || "Gagal masuk"); } finally { setLoading(false); }
  };

  const submitSignup = async (e) => {
    e.preventDefault(); setErr(""); setOk(""); setLoading(true);
    try {
      const r = await fetch(window.INDIEKOS_API + "/public-signup", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ account_name: kosName.trim(), owner_name: ownerName.trim(), owner_email: email.trim(), password, property_name: propName.trim() }),
      });
      const j = await r.json();
      if (!r.ok) { setErr(j.error || "Pendaftaran gagal"); return; }
      setOk("Akun berhasil dibuat! Sedang masuk…");
      const { data, error } = await window._supabase.auth.signInWithPassword({ email: email.trim(), password });
      if (error) { setErr("Akun dibuat, tapi gagal masuk otomatis. Coba login manual."); setMode("login"); return; }
      onSignedIn && onSignedIn(data.session);
    } catch (ex) { setErr(ex.message || "Pendaftaran gagal"); } finally { setLoading(false); }
  };

  // ---- Penghuni: kirim OTP ----
  const sendOtp = async (e) => {
    if (e) e.preventDefault();
    setErr(""); setOk(""); setLoading(true);
    try {
      const r = await fetch(window.INDIEKOS_API + "/tenant/request-otp", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone: otpPhone.trim() }),
      });
      const j = await r.json();
      if (!r.ok) { setErr(j.error || "Gagal mengirim kode"); return; }
      setMasked(j.phone_masked || "");
      setOtpStep("code");
      setOk("Kode OTP dikirim ke WhatsApp kamu. Cek pesan dari pengelola kos ya.");
    } catch (ex) { setErr(ex.message || "Gagal mengirim kode"); } finally { setLoading(false); }
  };

  // ---- Penghuni: verifikasi OTP + mint sesi ----
  const verifyOtp = async (e) => {
    if (e) e.preventDefault();
    setErr(""); setLoading(true);
    try {
      const r = await fetch(window.INDIEKOS_API + "/tenant/verify-otp", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone: otpPhone.trim(), code: otpCode.trim() }),
      });
      const j = await r.json();
      if (!r.ok) { setErr(j.error || "Verifikasi gagal"); return; }
      const { data, error } = await window._supabase.auth.verifyOtp({ token_hash: j.token_hash, type: "magiclink" });
      if (error) { setErr(error.message || "Gagal membuat sesi login"); return; }
      onSignedIn && onSignedIn(data.session);
    } catch (ex) { setErr(ex.message || "Verifikasi gagal"); } finally { setLoading(false); }
  };

  const Shell = (children, head, subt) => (
    <div style={{ minHeight:"100vh", display:"grid", placeItems:"center", background:"var(--surface-2, var(--cream, #f7f4ee))", padding:"24px" }}>
      <div className="card" style={{ width:"min(420px, 100%)", padding:"28px 26px" }}>
        <div className="col gap-2" style={{ alignItems:"center", marginBottom:18 }}>
          <img src="assets/indiekost.png" alt="INDIEKOS" style={{ width:48, height:48, borderRadius:12 }} onError={(e)=>{ e.currentTarget.style.display="none"; }} />
          <h2 style={{ margin:"6px 0 0", fontSize:"var(--fs-xl)" }}>{head}</h2>
          {subt && <div className="mut" style={{ fontSize:"var(--fs-xs)", textAlign:"center" }}>{subt}</div>}
        </div>
        {children}
        <div className="mut" style={{ fontSize:"var(--fs-2xs)", textAlign:"center", marginTop:14 }}>
          {scope === "superadmin" ? "Console platform INDIEKOS" : isPenghuni ? "Portal penghuni INDIE KOS" : "Manajemen kost"}
        </div>
      </div>
    </div>
  );

  // ============ PENGHUNI (No HP + OTP) ============
  if (isPenghuni) {
    if (otpStep === "phone") {
      return Shell(
        <form onSubmit={sendOtp} className="col gap-4">
          <div className="field">
            <label>Nomor WhatsApp</label>
            <input className="input" type="tel" inputMode="numeric" autoFocus required value={otpPhone}
                   onChange={(e)=>setOtpPhone(e.target.value)} placeholder="08xxxxxxxxxx" />
            <div className="mut" style={{ fontSize:"var(--fs-2xs)", marginTop:6 }}>Kode OTP dikirim ke WhatsApp kamu dari nomor pengelola kos.</div>
          </div>
          {err && <div className="banner banner-danger" role="alert"><Icon name="alert" size={16}/><span>{err}</span></div>}
          <button className="btn btn-primary" type="submit" disabled={loading || otpPhone.replace(/\D/g,"").length < 9}>
            {loading ? "Mengirim…" : "Kirim kode OTP"}
          </button>
        </form>,
        "Masuk Penghuni", "Pantau tagihan & info kos kamu"
      );
    }
    return Shell(
      <form onSubmit={verifyOtp} className="col gap-4">
        <div className="field">
          <label>Kode OTP</label>
          <input className="input" inputMode="numeric" autoFocus required maxLength={6} value={otpCode}
                 onChange={(e)=>setOtpCode(e.target.value.replace(/\D/g,""))} placeholder="6 digit" style={{ letterSpacing:"0.3em", textAlign:"center", fontSize:"var(--fs-lg)" }} />
          <div className="mut" style={{ fontSize:"var(--fs-2xs)", marginTop:6 }}>Kode dikirim ke WhatsApp {masked || "kamu"}. Berlaku 5 menit.</div>
        </div>
        {ok && <div className="banner banner-success"><Icon name="checkCircle" size={16}/><span>{ok}</span></div>}
        {err && <div className="banner banner-danger" role="alert"><Icon name="alert" size={16}/><span>{err}</span></div>}
        <button className="btn btn-primary" type="submit" disabled={loading || otpCode.length !== 6}>
          {loading ? "Memeriksa…" : "Masuk"}
        </button>
        <div className="row between" style={{ fontSize:"var(--fs-xs)" }}>
          <a href="#" onClick={(e)=>{e.preventDefault(); setErr(""); setOk(""); setOtpCode(""); setOtpStep("phone");}}>← Ganti nomor</a>
          <a href="#" onClick={(e)=>{e.preventDefault(); if(!loading) sendOtp();}} style={{ fontWeight:600 }}>Kirim ulang kode</a>
        </div>
      </form>,
      "Masukkan kode", "Verifikasi nomor WhatsApp kamu"
    );
  }

  // ============ OPERATOR / SUPERADMIN ============
  const isSignup = mode === "signup";
  return Shell(
    <>
      {isSignup ? (
        <form onSubmit={submitSignup} className="col gap-4">
          <div className="field"><label>Nama kos / usaha</label><input className="input" required autoFocus value={kosName} onChange={(e)=>setKosName(e.target.value)} placeholder="Kos Mawar Residence" /></div>
          <div className="field"><label>Nama kamu</label><input className="input" value={ownerName} onChange={(e)=>setOwnerName(e.target.value)} placeholder="Nama pemilik" /></div>
          <div className="field"><label>Email</label><input className="input" type="email" autoComplete="email" required value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="nama@domain.id" /></div>
          <div className="field"><label>Password <span className="mut" style={{fontWeight:400}}>· min 8 karakter</span></label><input className="input" type="password" autoComplete="new-password" required value={password} onChange={(e)=>setPassword(e.target.value)} placeholder="••••••••" /></div>
          <div className="field"><label>Nama properti pertama <span className="mut" style={{fontWeight:400}}>· opsional</span></label><input className="input" value={propName} onChange={(e)=>setPropName(e.target.value)} placeholder="Properti utama" /></div>
          {err && <div className="banner banner-danger" role="alert"><Icon name="alert" size={16}/><span>{err}</span></div>}
          {ok && <div className="banner banner-success"><Icon name="checkCircle" size={16}/><span>{ok}</span></div>}
          <button className="btn btn-primary" type="submit" disabled={loading || !kosName || !email || password.length < 8}>{loading ? "Memproses…" : "Buat akun"}</button>
        </form>
      ) : (
        <form onSubmit={submit} className="col gap-4">
          <div className="field"><label>Email</label><input className="input" type="email" autoComplete="email" required autoFocus value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="nama@domain.id" /></div>
          <div className="field"><label>Password</label><input className="input" type="password" autoComplete="current-password" required value={password} onChange={(e)=>setPassword(e.target.value)} placeholder="••••••••" /></div>
          {err && <div className="banner banner-danger" role="alert"><Icon name="alert" size={16}/><span>{err}</span></div>}
          <button className="btn btn-primary" type="submit" disabled={loading || !email || !password}>{loading ? "Memproses…" : "Masuk"}</button>
        </form>
      )}

      {!isSignup && (
        <>
          <div className="row gap-3" style={{ alignItems:"center", margin:"14px 0" }}>
            <span style={{ flex:1, height:1, background:"var(--ink-100, #e6e4dc)" }}/>
            <span className="mut" style={{ fontSize:"var(--fs-2xs)" }}>atau</span>
            <span style={{ flex:1, height:1, background:"var(--ink-100, #e6e4dc)" }}/>
          </div>
          <button type="button" className="btn btn-ghost" disabled={loading} onClick={googleSignIn}
                  style={{ width:"100%", display:"flex", alignItems:"center", justifyContent:"center", gap:9, border:"1.5px solid var(--ink-200, #d8d5cb)" }}>
            <svg width="17" height="17" viewBox="0 0 48 48"><path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3C33.7 32.7 29.3 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3l5.7-5.7C34.3 6.1 29.4 4 24 4 13 4 4 13 4 24s9 20 20 20 20-9 20-20c0-1.3-.1-2.6-.4-3.9z"/><path fill="#FF3D00" d="m6.3 14.7 6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.9 1.2 8 3l5.7-5.7C34.3 6.1 29.4 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/><path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.3 0-9.7-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z"/><path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4.1 5.5l6.2 5.2C41.4 34.9 44 30 44 24c0-1.3-.1-2.6-.4-3.9z"/></svg>
            Masuk dengan Google
          </button>
        </>
      )}

      {allowSignup && (
        <div className="mut" style={{ fontSize:"var(--fs-xs)", textAlign:"center", marginTop:16 }}>
          {isSignup ? (<>Sudah punya akun? <a href="#" onClick={(e)=>{e.preventDefault(); setErr(""); setOk(""); setMode("login");}} style={{fontWeight:600}}>Masuk di sini</a></>)
                    : (<>Belum punya akun? <a href="#" onClick={(e)=>{e.preventDefault(); setErr(""); setMode("signup");}} style={{fontWeight:600}}>Daftar sebagai pemilik kos</a></>)}
        </div>
      )}
    </>,
    isSignup ? "Daftar pemilik kos" : title,
    isSignup ? "Buat akun INDIEKOS gratis — coba 14 hari, tanpa kartu kredit." : sub
  );
}
window.LoginScreen = LoginScreen;
