// หน้าเข้าสู่ระบบ — พนักงานล็อกอินด้วย user + รหัสของตัวเอง
// รหัสเริ่มต้นเจ้าของร้าน: user "owner" / รหัส "S12345678"
const AUTH_KEY = "ssphone-auth"; // เก็บ userId ที่ล็อกอินอยู่

function LoginGate({ children }) {
  const { st, dispatch } = useStore();
  const s = st ? st.settings : null;
  const [authed, setAuthed] = React.useState(null);
  const [uname, setUname] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [err, setErr] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const [forgot, setForgot] = React.useState(false);

  // Check auth after st is ready and has users
  React.useEffect(() => {
    if (st && st.users && st.users.length > 0) {
      try {
        const uid = localStorage.getItem(AUTH_KEY);
        if (uid && st.users.some((u) => u.id === uid)) {
          setAuthed(uid);
        }
      } catch (e) {}
    }
  }, [st, st?.users]);

  React.useEffect(() => {
    window.__ssLogout = () => { try { localStorage.removeItem(AUTH_KEY); } catch (e) {} setAuthed(null); setPw(""); setUname(""); };
  }, []);

  // Don't render login form until st is initialized
  if (!st || !st.users) {
    return <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100vh", fontSize: 18 }}>Loading...</div>;
  }

  if (authed) return children;

  const handleLogin = () => {
    if (!st || !st.users || !st.users.length) {
      setErr("ระบบยังไม่พร้อม");
      return;
    }
    const u = st.users.find((x) => (x.username || "").toLowerCase() === uname.trim().toLowerCase());
    if (u && u.password === pw) {
      try {
        localStorage.setItem(AUTH_KEY, u.id);
        const ui = { userId: u.id, page: "dashboard", branch: st.roles[u.role].allBranch ? "ALL" : u.branch };
        localStorage.setItem("ssphone-ui", JSON.stringify(ui));
      } catch (e) {}
      setAuthed(u.id); setErr("");
    } else {
      setErr("ชื่อผู้ใช้หรือรหัสไม่ถูกต้อง");
      setShake(true); setTimeout(() => setShake(false), 500);
    }
  };

  return (
    <div style={{ position: "fixed", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: T.bodyFont, background: "radial-gradient(1200px 600px at 70% -10%, #1B3FA0 0%, transparent 60%), linear-gradient(160deg, #0E1B3D, #13265C 60%, #0E1B3D)", overflow: "hidden" }}>
      <div style={{ position: "absolute", width: 460, height: 460, borderRadius: "50%", background: "radial-gradient(circle, rgba(46,99,231,.45), transparent 70%)", top: "55%", left: "12%", filter: "blur(20px)" }}></div>
      <div style={{ position: "absolute", width: 360, height: 360, borderRadius: "50%", background: "radial-gradient(circle, rgba(229,48,47,.30), transparent 70%)", top: "-8%", right: "8%", filter: "blur(20px)" }}></div>

      <div className={shake ? "ss-shake" : ""} style={{ position: "relative", width: 390, maxWidth: "92vw", background: "#fff", borderRadius: 22, padding: "32px 34px 26px", boxShadow: "0 30px 80px rgba(0,0,0,.5)", animation: "ss-pop .35s cubic-bezier(.2,.9,.3,1.2)" }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 9, marginBottom: 20 }}>
          <div style={{ width: 72, height: 72, borderRadius: 19, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 24px rgba(46,99,231,.25)", border: `1px solid ${T.border}` }}>
            <img src={logoSrc(st)} alt="logo" style={{ width: 58, height: 58, objectFit: "contain" }} />
          </div>
          <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 23, letterSpacing: 0.5, color: T.text }}>{s.name || "SSPHONE"}</div>
          <div style={{ fontSize: 12.5, color: T.sub }}>{s.tagline || "ระบบบริหารร้านมือถือ"}</div>
        </div>

        {!forgot ? (
          <React.Fragment>
            <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
              <Field label="ชื่อผู้ใช้ (User)">
                <input className="ss-input" autoFocus value={uname}
                  onChange={(e) => { setUname(e.target.value); setErr(""); }}
                  onKeyDown={(e) => { if (e.key === "Enter") handleLogin(); }}
                  placeholder="เช่น owner"
                  style={{ ...ssInputStyle(), fontSize: 15, padding: "11px 13px" }} />
              </Field>
              <Field label="รหัสผ่าน">
                <input className="ss-input" type="password" value={pw}
                  onChange={(e) => { setPw(e.target.value); setErr(""); }}
                  onKeyDown={(e) => { if (e.key === "Enter") handleLogin(); }}
                  placeholder="รหัสผ่านของคุณ"
                  style={{ ...ssInputStyle(), fontSize: 15, letterSpacing: 1, padding: "11px 13px" }} />
              </Field>
            </div>
            <div style={{ height: 17, fontSize: 12, color: T.accent, fontWeight: 600, textAlign: "center", marginTop: 5 }}>{err}</div>
            <Btn onClick={handleLogin} style={{ width: "100%", justifyContent: "center", fontSize: 15, padding: "12px 0", marginTop: 2 }}>เข้าสู่ระบบ →</Btn>
            <div style={{ textAlign: "center", marginTop: 13 }}>
              <a className="ss-link" onClick={() => setForgot(true)} style={{ color: T.sub }}>ลืมรหัส? (เจ้าของร้าน)</a>
            </div>
            <div style={{ textAlign: "center", marginTop: 14, fontSize: 11, color: "#9AA6BE", lineHeight: 1.7 }}>
              เจ้าของร้านสร้าง/แก้รหัสพนักงานได้ที่ “ตั้งค่าระบบ”<br />ตัวอย่าง: <b style={{ fontFamily: "monospace", color: T.sub }}>owner / S12345678</b>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ fontSize: 13, color: T.sub, lineHeight: 1.6, marginBottom: 14 }}>
              ระบบจะส่งลิงก์เปลี่ยนรหัสไปยังอีเมลเจ้าของร้านที่ลงทะเบียนไว้
            </div>
            <Field label="อีเมลเจ้าของร้าน">
              <TextInput value={s.ownerEmail} onChange={(e) => dispatch({ type: "SETTINGS_SET", patch: { ownerEmail: e.target.value } })} />
            </Field>
            <Btn kind="soft" onClick={() => { window.__ssToast && window.__ssToast(`ส่งลิงก์ไปที่ ${s.ownerEmail}`, "info"); setForgot(false); }} style={{ width: "100%", justifyContent: "center", marginTop: 14 }}>✉ ส่งลิงก์เปลี่ยนรหัส</Btn>
            <div style={{ textAlign: "center", marginTop: 14 }}>
              <a className="ss-link" onClick={() => setForgot(false)} style={{ color: T.sub }}>← กลับไปหน้าเข้าสู่ระบบ</a>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}
window.LoginGate = LoginGate;
