/* global React, I, UI, SSSData */
// =============== ระบบเข้าสู่ระบบ · Session ===============
const { useState: useStateLG } = React;

const LG_KEY = "sss-session";
const LG_LASTUSER_KEY = "sss-last-user";
function lgUsers() {
  try { return JSON.parse(localStorage.getItem("sss-users") || "null") || window.SSSData.Users; } catch { return window.SSSData.Users; }
}
function lgFindEmp(u) {
  const E = window.SSSData.Employees || [];
  return E.find(e => e.id === u.empId) || E.find(e => e.name === u.name) || null;
}
// อ่าน session จาก localStorage (คงไว้ถาวร) ก่อน แล้วค่อย sessionStorage (เฉพาะรอบเบราว์เซอร์นี้)
function lgReadRaw() {
  try {
    return localStorage.getItem(LG_KEY) || sessionStorage.getItem(LG_KEY) || null;
  } catch { return null; }
}

window.Session = {
  get() {
    let s;
    try { s = JSON.parse(lgReadRaw() || "null"); } catch { return null; }
    if (!s) return null;
    // 🔄 รีเฟรชการผูกพนักงาน (empId) จากข้อมูลผู้ใช้ล่าสุดเสมอ
    // กันอาการ "การผูกหลุด" เมื่อ login ค้างไว้นาน แล้ว Admin มาผูก/แก้ภายหลัง —
    // session เดิมจะยังเก็บ empId เก่า/ว่าง ทำให้หน้า "งานของฉัน" ขึ้นว่ายังไม่ผูก
    try {
      const u = lgUsers().find(x => x.username === s.username);
      if (u) {
        const emp = lgFindEmp(u);
        s.role = u.role;
        s.empId = emp ? emp.id : (u.empId || null);
        s.empName = emp ? emp.name : null;
        s.isAdmin = u.role === "Admin" || /ผู้จัดการ|Manager|Account|เจ้าของ/.test(u.role);
      }
    } catch (e) {}
    return s;
  },
  // keep = true → คงการเข้าสู่ระบบถาวร (localStorage) · false → เฉพาะรอบเบราว์เซอร์นี้ (sessionStorage)
  login(username, password, keep = true) {
    const u = lgUsers().find(x => x.username === username);
    if (!u) return null;
    if (u.status === "ระงับการใช้งาน") return "suspended";
    if (password !== undefined) {
      const expect = u.password || "1234";
      if (password !== expect) return "badpass";
    }
    const emp = lgFindEmp(u);
    const sess = {
      username: u.username, name: u.name, role: u.role,
      empId: emp ? emp.id : (u.empId || null), empName: emp ? emp.name : null,
      isAdmin: u.role === "Admin" || /ผู้จัดการ|Manager|Account|เจ้าของ/.test(u.role)
    };
    try {
      const store = keep ? localStorage : sessionStorage;
      const other = keep ? sessionStorage : localStorage;
      store.setItem(LG_KEY, JSON.stringify(sess));
      other.removeItem(LG_KEY);
      localStorage.setItem(LG_LASTUSER_KEY, JSON.stringify({ username: u.username, keep }));
    } catch (e) {}
    window.SSSData.Company.currentUser = { name: u.name, role: u.role, initials: u.name.slice(0, 2) };
    window.dispatchEvent(new Event("sss-session-changed"));
    window.dispatchEvent(new Event("sss-company-changed"));
    window.logActivity && window.logActivity("เข้าสู่ระบบ", u.username, "users");
    return sess;
  },
  logout() {
    try { localStorage.removeItem(LG_KEY); sessionStorage.removeItem(LG_KEY); } catch {}
    window.dispatchEvent(new Event("sss-session-changed"));
  },
  employee() {
    const s = this.get();
    if (!s) return null;
    const E = window.SSSData.Employees || [];
    return E.find(e => e.id === s.empId) || E.find(e => e.name === s.name) || null;
  }
};
// คืนค่า currentUser จาก session ที่ค้างอยู่
(function () {
  const s = window.Session.get();
  if (s) window.SSSData.Company.currentUser = { name: s.name, role: s.role, initials: s.name.slice(0, 2) };
})();

// =============== หน้า Login ===============
function lgLastUser() { try { return JSON.parse(localStorage.getItem(LG_LASTUSER_KEY) || "null"); } catch { return null; } }

function LoginScreen() {
  const last = lgLastUser();
  const [username, setUsername] = useStateLG(last ? last.username : "");
  const [password, setPassword] = useStateLG("");
  const [keep, setKeep] = useStateLG(last ? last.keep !== false : true);
  const [showPw, setShowPw] = useStateLG(false);
  const [err, setErr] = useStateLG("");
  const [loading, setLoading] = useStateLG(false);
  const C = window.SSSData.Company || {};

  const doLogin = async () => {
    const name = username.trim();
    if (!name) { setErr("กรุณากรอกชื่อผู้ใช้"); return; }
    if (!password) { setErr("กรุณากรอกรหัสผ่าน"); return; }
    let res = window.Session.login(name, password, keep);
    if (!res && window.SSSSync) {
      setLoading(true);
      try { await window.SSSSync.load(); } catch {}
      setLoading(false);
      res = window.Session.login(name, password, keep);
    }
    if (!res) { setErr(`ไม่พบผู้ใช้ "${name}" — ตรวจสอบชื่อผู้ใช้กับผู้ดูแลระบบ`); return; }
    if (res === "suspended") { setErr("บัญชีนี้ถูกระงับการใช้งาน — ติดต่อ Admin"); return; }
    if (res === "badpass") { setErr("รหัสผ่านไม่ถูกต้อง — ลองใหม่อีกครั้ง"); return; }
    window.toast && window.toast(`ยินดีต้อนรับ ${res.name} 👋`);
  };

  const features = [
    { icon: I.money, title: "บัญชี · การเงิน · ภาษี", desc: "สมุดรายวัน ผังบัญชี กระแสเงินสด ครบในที่เดียว" },
    { icon: I.qr, title: "ลงเวลา QR · เงินเดือน · KPI", desc: "พนักงานสแกนเข้างาน คำนวณเงินเดือนอัตโนมัติ" },
    { icon: I.box, title: "สต็อก · ขาย · จัดซื้อ", desc: "ติดตามคงคลังและเอกสารการค้าแบบเรียลไทม์" }
  ];

  return (
    <div className="lg-wrap">
      <style>{`
        .lg-wrap { min-height: 100vh; display: grid; grid-template-columns: 1.08fr 0.92fr; background: var(--surface-2); font-family: var(--font); }
        .lg-hero { position: relative; overflow: hidden; color: #fff;
          background: linear-gradient(155deg, var(--brand-strong) 0%, var(--brand) 52%, var(--brand-soft) 100%);
          padding: clamp(40px, 5vw, 72px); display: flex; flex-direction: column; }
        .lg-hero::before, .lg-hero::after { content: ""; position: absolute; border-radius: 50%; background: rgba(255,255,255,0.10); filter: blur(2px); }
        .lg-hero::before { width: 420px; height: 420px; right: -140px; top: -120px; }
        .lg-hero::after { width: 300px; height: 300px; left: -110px; bottom: -120px; background: rgba(255,255,255,0.07); }
        .lg-hero-inner { position: relative; z-index: 1; display: flex; flex-direction: column; height: 100%; }
        .lg-logo { width: 56px; height: 56px; border-radius: 16px; background: rgba(255,255,255,0.18); border: 1px solid rgba(255,255,255,0.35); display: grid; place-items: center; font-family: var(--font-display); font-weight: 800; font-size: 28px; color: #fff; }
        .lg-brand { font-family: var(--font-display); font-size: clamp(26px, 2.6vw, 34px); font-weight: 800; letter-spacing: -0.01em; margin-top: 26px; line-height: 1.18; }
        .lg-tag { font-size: 15px; color: rgba(255,255,255,0.88); margin-top: 16px; max-width: 34ch; line-height: 1.6; }
        .lg-feats { margin-top: auto; display: flex; flex-direction: column; gap: 18px; padding-top: 40px; }
        .lg-feat { display: flex; gap: 14px; align-items: flex-start; }
        .lg-feat-ic { width: 40px; height: 40px; border-radius: 11px; background: rgba(255,255,255,0.16); border: 1px solid rgba(255,255,255,0.28); display: grid; place-items: center; flex-shrink: 0; }
        .lg-feat-t { font-weight: 700; font-size: 14.5px; }
        .lg-feat-d { font-size: 12.5px; color: rgba(255,255,255,0.8); line-height: 1.5; margin-top: 2px; }
        .lg-foot { margin-top: 36px; font-size: 12px; color: rgba(255,255,255,0.7); }

        .lg-formside { display: flex; align-items: center; justify-content: center; padding: 32px 24px; }
        .lg-card { width: 100%; max-width: 408px; }
        .lg-mlogo { display: none; }
        .lg-h1 { font-family: var(--font-display); font-size: 26px; font-weight: 700; color: var(--ink-1); letter-spacing: -0.01em; }
        .lg-sub { font-size: 13.5px; color: var(--ink-3); margin-top: 6px; }
        .lg-form { display: flex; flex-direction: column; gap: 16px; margin-top: 28px; }
        .lg-pw-wrap { position: relative; }
        .lg-pw-toggle { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: transparent; border: none; color: var(--ink-3); cursor: pointer; font-size: 12px; font-family: var(--font); padding: 4px 6px; border-radius: 6px; }
        .lg-pw-toggle:hover { color: var(--brand-strong); background: var(--surface-2); }
        .lg-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
        .lg-keep { display: flex; align-items: center; gap: 9px; font-size: 13px; cursor: pointer; color: var(--ink-2); user-select: none; }
        .lg-keep input { width: 17px; height: 17px; accent-color: var(--brand); cursor: pointer; }
        .lg-err { font-size: 12.5px; color: var(--danger); font-weight: 600; background: var(--danger-bg); border-radius: 8px; padding: 9px 12px; }
        .lg-submit { height: 48px; border-radius: 11px; border: none; background: var(--brand); color: var(--brand-ink); font-size: 15px; font-weight: 700; cursor: pointer; font-family: var(--font); box-shadow: 0 2px 8px var(--ring); transition: background 0.15s; }
        .lg-submit:hover { background: var(--brand-strong); }
        .lg-hint { font-size: 11.5px; color: var(--ink-3); text-align: center; line-height: 1.8; margin-top: 18px; }
        .lg-input-lg { height: 46px !important; font-size: 14.5px !important; border-radius: 10px !important; }

        @media (max-width: 920px) {
          .lg-wrap { grid-template-columns: 1fr; }
          .lg-hero { display: none; }
          .lg-mlogo { display: flex; flex-direction: column; align-items: center; text-align: center; margin-bottom: 24px; }
        }
      `}</style>

      {/* ───── Hero panel ───── */}
      <div className="lg-hero">
        <div className="lg-hero-inner">
          <div className="lg-logo">S</div>
          <div className="lg-brand">{C.name || "TRIPLES CREATIVE"}</div>
          <div className="lg-tag">โปรแกรมบริหารจัดการธุรกิจครบวงจร — บัญชี การเงิน คลังสินค้า งานบุคคล และเอกสารการค้า</div>
          <div className="lg-feats">
            {features.map((f, i) => (
              <div key={i} className="lg-feat">
                <div className="lg-feat-ic">{React.createElement(f.icon, { size: 20, stroke: "#fff" })}</div>
                <div>
                  <div className="lg-feat-t">{f.title}</div>
                  <div className="lg-feat-d">{f.desc}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="lg-foot">© {new Date().getFullYear() + 543} {C.name || "TRIPLES CREATIVE"} · ระบบภายในองค์กร</div>
        </div>
      </div>

      {/* ───── Form panel ───── */}
      <div className="lg-formside">
        <div className="lg-card">
          <div className="lg-mlogo">
            <div className="brand-logo" style={{ width: 52, height: 52, fontSize: 24, borderRadius: 14, marginBottom: 10 }}>S</div>
            <div style={{ fontSize: 18, fontWeight: 800, fontFamily: "var(--font-display)" }}>{C.name || "TRIPLES CREATIVE"}</div>
          </div>

          <div className="lg-h1">เข้าสู่ระบบ</div>
          <div className="lg-sub">ลงชื่อเข้าใช้เพื่อจัดการงานของคุณ</div>

          <div className="lg-form">
            <div className="field"><label>ชื่อผู้ใช้</label>
              <input className="input mono lg-input-lg" value={username} autoFocus
                onChange={e => { setUsername(e.target.value); setErr(""); }}
                onKeyDown={e => e.key === "Enter" && !loading && doLogin()}
                placeholder="เช่น piya"></input>
            </div>

            <div className="field"><label>รหัสผ่าน</label>
              <div className="lg-pw-wrap">
                <input className="input lg-input-lg" type={showPw ? "text" : "password"} value={password}
                  style={{ paddingRight: 56 }}
                  onChange={e => { setPassword(e.target.value); setErr(""); }}
                  onKeyDown={e => e.key === "Enter" && !loading && doLogin()}
                  placeholder="••••••••"></input>
                <button type="button" className="lg-pw-toggle" onClick={() => setShowPw(v => !v)} tabIndex={-1}>
                  {showPw ? "ซ่อน" : "แสดง"}
                </button>
              </div>
            </div>

            {err && <div className="lg-err">{err}</div>}

            <div className="lg-row">
              <label className="lg-keep">
                <input type="checkbox" checked={keep} onChange={e => setKeep(e.target.checked)}></input>
                คงการเข้าสู่ระบบ
              </label>
              <span style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{keep ? "อยู่ในระบบจนกว่าจะออก" : "ออกเมื่อปิดเบราว์เซอร์"}</span>
            </div>

            <button className="lg-submit" onClick={() => !loading && doLogin()} disabled={loading}>
              {loading ? "กำลังตรวจสอบข้อมูล…" : "เข้าสู่ระบบ"}
            </button>
          </div>

          <div className="lg-hint">ผู้ใช้ที่ยังไม่ได้ตั้งรหัสผ่าน ใช้รหัสเริ่มต้น <b>1234</b> (เปลี่ยนได้ที่ ผู้ใช้และสิทธิ์)<br />พนักงานใช้มือถือเข้าระบบเพื่อ ลงเวลา QR · ดูงานของฉัน ได้เลย</div>
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
