// Login + signup + change-password flow.
// Tenant is auto-detected from email → picker shown if email belongs to >1 company.
// Visual design: Workio sign-in (warm cream + Instrument Serif headline + coral CTA).
// IMPORTANT: This file's API calls and state logic must not change without confirmation —
// only markup/styling was re-skinned from the legacy 2-column layout.

const SUPER_ADMIN_EMAIL = "superadmin@raciworks.io";

// ---------- Inline SVG icons (from Workio sign-in design) ----------
const WkEnvelopeIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="m4 7 8 6 8-6"/></svg>
);
const WkLockIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>
);
const WkEyeIcon = ({ open }) => open ? (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 12s3.5-7 9.5-7 9.5 7 9.5 7-3.5 7-9.5 7S2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/></svg>
) : (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 12s3.5-7 9.5-7c2.05 0 3.83.5 5.34 1.31"/><path d="M21.5 12s-3.5 7-9.5 7c-2.05 0-3.83-.5-5.34-1.31"/><path d="m3 3 18 18"/><path d="M9.5 9.5a3 3 0 0 0 4.95 3.04"/></svg>
);
const WkCheckIcon = () => (
  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><path d="m4 12 5 5L20 6"/></svg>
);
const WkArrowRightIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m13 6 6 6-6 6"/></svg>
);
const WkBackIcon = () => (
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5"/><path d="m11 18-6-6 6-6"/></svg>
);
const WkAlertIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
);

// Decorative background — shared across login / signup / change-password screens
const WkBackground = () => (
  <div className="wk-mesh" aria-hidden="true">
    <div className="wk-mesh-a"/><div className="wk-mesh-b"/><div className="wk-mesh-c"/><div className="wk-mesh-d"/>
    <div className="wk-bg-grain"/>
  </div>
);

const LoginScreen = ({ onLogin }) => {
  // === STATE (unchanged from legacy version) =================================
  const [mode, setMode] = useState("login"); // login | signup | change
  const [email, setEmail] = useState("");
  const [pwd, setPwd] = useState("");
  const [remember, setRemember] = useState(true);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const [showPwd, setShowPwd] = useState(false);
  const [selectedTenantId, setSelectedTenantId] = useState(null);
  const [apiMatches, setApiMatches] = useState([]);
  // Tracks whether email exists in users table at all (vs. zero memberships)
  const [apiUserExists, setApiUserExists] = useState(null); // null=unknown, true/false=resolved

  // When email changes, recompute tenant matches & reset selection if needed
  const emailLower = email.trim().toLowerCase();
  const isSuperAdminEmail = emailLower === SUPER_ADMIN_EMAIL;
  const tenantMatches = apiMatches;

  // === API LOOKUP (unchanged) ===============================================
  useEffect(() => {
    if (!emailLower || isSuperAdminEmail || typeof window === "undefined" || !window.apiClient) {
      setApiMatches([]);
      setApiUserExists(null);
      return;
    }
    let cancelled = false;
    const handle = setTimeout(async () => {
      try {
        const res = await window.apiClient.findUserByEmail(emailLower);
        if (cancelled) return;
        const userExists = !!(res && res.user_exists);
        setApiUserExists(userExists);
        const tenants = (res && res.tenants) || [];
        setApiMatches(tenants.map(r => ({
          tenant: {
            id: r.tenant_id,
            tenant_code: r.tenant_code,
            company_name: r.company_name,
            service_status: r.service_status,
            accent: "indigo",
          },
          role: r.role || "admin",
          user_id: res?.user?.user_id || null,
        })));
      } catch (e) {
        if (!cancelled) { setApiMatches([]); setApiUserExists(null); }
      }
    }, 250);
    return () => { cancelled = true; clearTimeout(handle); };
  }, [emailLower, isSuperAdminEmail]);

  useEffect(() => {
    // Auto-select if there's exactly one match; clear if 0 or selection no longer valid
    if (tenantMatches.length === 1) setSelectedTenantId(tenantMatches[0].tenant.id);
    else if (!tenantMatches.find(m => m.tenant.id === selectedTenantId)) setSelectedTenantId(null);
  }, [emailLower, tenantMatches.length]);

  // === SUBMIT HANDLER (unchanged) ===========================================
  const submitLogin = async (e) => {
    e?.preventDefault?.();
    setErr("");
    if (!email) { setErr("กรุณากรอกอีเมล"); return; }
    if (!pwd) { setErr("กรุณากรอกรหัสผ่าน"); return; }

    // Require explicit tenant selection when multiple memberships detected
    if (!isSuperAdminEmail && tenantMatches.length > 1 && !selectedTenantId) {
      setErr("คุณเป็นสมาชิกของหลายบริษัท · กรุณาเลือกบริษัทที่ต้องการเข้า");
      return;
    }

    setBusy(true);
    try {
      // Try real API login first
      if (typeof window !== "undefined" && window.apiClient) {
        // For single-tenant or already-selected → pass tenantId. Otherwise let server respond with multiple_tenants.
        const tenantId = selectedTenantId || (tenantMatches.length === 1 ? tenantMatches[0].tenant.id : null);
        const result = await window.apiClient.login(emailLower, pwd, tenantId);

        // Super Admin login path
        if (result.super_admin) {
          setBusy(false);
          onLogin({
            kind: "super_admin",
            email: result.user.email,
            user_id: result.user.user_id,
            first_name: result.user.first_name,
            last_name: result.user.last_name,
            token: result.token,
          });
          return;
        }

        // Server says user identity is valid but has no tenant memberships
        if (result.no_tenant) {
          setBusy(false);
          setErr("บัญชีของคุณยังไม่ได้ถูกผูกกับบริษัทใดในระบบ · กรุณาติดต่อผู้ดูแลระบบ");
          return;
        }

        // Server may return multiple tenants — ask user to pick
        if (result.multiple_tenants) {
          setBusy(false);
          setErr("กรุณาเลือกบริษัทก่อนเข้าสู่ระบบ");
          return;
        }

        setBusy(false);
        onLogin({
          kind: "tenant",
          tenant_id: result.tenant.id,
          role: result.user.role,
          user_id: result.user.user_id,
          email: result.user.email,
          first_name: result.user.first_name,
          last_name: result.user.last_name,
          token: result.token,
          tenant: result.tenant,
        });
        return;
      }
      setBusy(false);
      setErr("ไม่สามารถเชื่อมต่อระบบได้ กรุณาลองอีกครั้ง");
    } catch (apiErr) {
      setBusy(false);
      if (apiErr.status === 401) setErr("อีเมลหรือรหัสผ่านไม่ถูกต้อง");
      else if (apiErr.status === 403) setErr("บริษัทของท่านถูกระงับการใช้งาน");
      else if (apiErr.status === 423) setErr("บัญชีถูกล็อกชั่วคราว เนื่องจากใส่รหัสผ่านผิดหลายครั้ง กรุณารอ 15 นาที");
      else setErr(apiErr.message || "ไม่สามารถเข้าสู่ระบบได้ กรุณาลองอีกครั้ง");
    }
  };

  // === RENDER ===============================================================
  // Sub-forms (signup / change-password) render inside the same wk-screen frame
  if (mode === "signup") {
    return (
      <div className="wk-screen">
        <WkBackground/>
        <div className="wk-stage">
          <SignupForm onBack={()=>setMode("login")}/>
        </div>
      </div>
    );
  }
  if (mode === "change") {
    return (
      <div className="wk-screen">
        <WkBackground/>
        <div className="wk-stage">
          <ChangePasswordForm initialEmail={email} onBack={()=>setMode("login")}/>
        </div>
      </div>
    );
  }

  // mode === "login" — the Workio sign-in design
  return (
    <div className="wk-screen">
      <WkBackground/>
      <div className="wk-stage">
        <div className="wk-card">
          <div className="wk-card-header">
            <div className="wk-logo">W</div>
          </div>

          <div className="wk-intro">
            <h1 className="wk-title">Welcome back</h1>
            <p className="wk-tagline-thai">ระบบบริหารงานประจำวันตามหลัก RACI</p>
            <p className="wk-tagline-en">Sign in to continue to your workspace.</p>
          </div>

          <form className="wk-form" onSubmit={submitLogin} noValidate>

            {/* ----- Email field ----- */}
            <label className="wk-field">
              <span className="wk-label">อีเมล หรือชื่อผู้ใช้</span>
              <span className="wk-input-wrap">
                <span className="wk-input-icon"><WkEnvelopeIcon/></span>
                <input type="text" autoComplete="username" autoFocus
                  value={email} onChange={e=>setEmail(e.target.value)}
                  placeholder="you@company.com"/>
              </span>
              {email && !isSuperAdminEmail && apiUserExists === false && tenantMatches.length === 0 && (
                <div className="wk-info" style={{ marginTop: 6 }}>
                  <WkAlertIcon/><span>ไม่พบอีเมลนี้ในระบบ</span>
                </div>
              )}
            </label>

            {/* ----- Super-admin notice ----- */}
            {isSuperAdminEmail && (
              <div className="wk-info">
                <span>เข้าสู่ระบบในฐานะ <strong style={{ color: 'var(--wk-coral)' }}>Super Admin (SaaS Owner)</strong></span>
              </div>
            )}

            {/* ----- Tenant picker: multiple ----- */}
            {!isSuperAdminEmail && tenantMatches.length > 1 && (
              <div className="wk-field">
                <span className="wk-label">เลือกบริษัท ({tenantMatches.length})</span>
                <div className="wk-tenant-list">
                  {tenantMatches.map(m => {
                    const t = m.tenant;
                    const sel = selectedTenantId === t.id;
                    const blocked = t.service_status !== "active";
                    return (
                      <button type="button" key={t.id} onClick={()=>setSelectedTenantId(t.id)}
                        className={`wk-tenant-card${sel ? ' selected' : ''}`}
                        style={{ opacity: blocked ? 0.55 : 1 }}>
                        <span className="wk-tenant-code">{t.tenant_code}</span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--wk-ink)' }}>
                            {t.company_short || t.company_name}
                          </div>
                          <div style={{ fontSize: 11, color: 'var(--wk-muted)', marginTop: 2 }}>
                            {ROLE_META[m.role]?.label || m.role}
                            {blocked ? ` · ${t.service_status === "suspended" ? "ระงับการใช้งาน" : "สิ้นสุดบริการ"}` : ""}
                          </div>
                        </div>
                        {sel && <span style={{ color: 'var(--wk-coral)' }}><WkCheckIcon/></span>}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* ----- Tenant picker: single (auto-selected) ----- */}
            {!isSuperAdminEmail && tenantMatches.length === 1 && (
              <div className="wk-tenant-card selected" style={{ cursor: 'default' }}>
                <span className="wk-tenant-code">{tenantMatches[0].tenant.tenant_code}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--wk-ink)' }}>
                    {tenantMatches[0].tenant.company_short || tenantMatches[0].tenant.company_name}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--wk-muted)', marginTop: 2 }}>
                    {ROLE_META[tenantMatches[0].role]?.label || tenantMatches[0].role}
                  </div>
                </div>
                <span style={{ color: 'var(--wk-coral)' }}><WkCheckIcon/></span>
              </div>
            )}

            {/* ----- Zero memberships ----- */}
            {!isSuperAdminEmail && apiUserExists === true && tenantMatches.length === 0 && (
              <div className="wk-info">
                <WkAlertIcon/>
                <span>บัญชีของคุณยังไม่ได้ผูกกับบริษัทใดในระบบ · กรุณาติดต่อผู้ดูแลระบบ</span>
              </div>
            )}

            {/* ----- Password ----- */}
            <label className="wk-field">
              <span className="wk-label-row">
                <span className="wk-label">รหัสผ่าน</span>
                <button type="button" className="wk-link" onClick={()=>setMode("change")}>เปลี่ยนรหัสผ่าน</button>
              </span>
              <span className="wk-input-wrap">
                <span className="wk-input-icon"><WkLockIcon/></span>
                <input type={showPwd ? "text" : "password"} autoComplete="current-password"
                  value={pwd} onChange={e=>setPwd(e.target.value)} placeholder="••••••••"/>
                <button type="button" className="wk-eye" onClick={()=>setShowPwd(v=>!v)}
                  aria-label={showPwd ? "ซ่อนรหัสผ่าน" : "แสดงรหัสผ่าน"} tabIndex={-1}>
                  <WkEyeIcon open={showPwd}/>
                </button>
              </span>
            </label>

            {/* ----- Remember me ----- */}
            <div className="wk-remember-row">
              <label className="wk-check">
                <input type="checkbox" checked={remember} onChange={()=>setRemember(v=>!v)}/>
                <span className="wk-check-box">
                  <span className="wk-check-mark"><WkCheckIcon/></span>
                </span>
                <span>จดจำการเข้าสู่ระบบบนเครื่องนี้</span>
              </label>
            </div>

            {/* ----- Error ----- */}
            {err && (
              <div className="wk-error">
                <WkAlertIcon/><span>{err}</span>
              </div>
            )}

            {/* ----- Submit ----- */}
            <button type="submit" className="wk-submit" disabled={busy}>
              <span>{busy ? "กำลังตรวจสอบ…" : "เข้าสู่ระบบ"}</span>
              {!busy && <WkArrowRightIcon/>}
            </button>

            <p className="wk-help">
              ยังไม่มีบัญชี?{' '}
              <button type="button" className="wk-link" onClick={()=>setMode("signup")}>สร้างบัญชีใหม่</button>
            </p>
          </form>
        </div>

        <p className="wk-foot">
          <span className="wk-foot-dot"/>
          <span>Workio · v1.4.0 · Powered by ACCS</span>
        </p>
      </div>
    </div>
  );
};

// ===========================================================================
// SignupForm — wrapped in wk-card to match new design; internal logic unchanged
// ===========================================================================
const SignupForm = ({ onBack }) => {
  const [submitted, setSubmitted] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [form, setForm] = useState({
    full_name: "", email: "", phone: "", password: "", password2: "",
  });
  const set = (k,v) => setForm(p => ({...p, [k]: v}));
  const [emailStatus, setEmailStatus] = useState({ checking: false, available: null });

  // Live-check email uniqueness (debounced)
  useEffect(() => {
    if (!form.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
      setEmailStatus({ checking: false, available: null });
      return;
    }
    let cancelled = false;
    setEmailStatus(s => ({ ...s, checking: true }));
    const handle = setTimeout(async () => {
      try {
        if (!window.apiClient) return;
        const res = await window.apiClient.checkEmailAvailable(form.email);
        if (!cancelled) setEmailStatus({ checking: false, available: !!res.available });
      } catch {
        if (!cancelled) setEmailStatus({ checking: false, available: null });
      }
    }, 350);
    return () => { cancelled = true; clearTimeout(handle); };
  }, [form.email]);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!form.full_name.trim()) { setErr("กรุณากรอกชื่อ-นามสกุล"); return; }
    if (!form.email.trim()) { setErr("กรุณากรอกอีเมล"); return; }
    if (emailStatus.available === false) { setErr("อีเมลนี้มีบัญชีในระบบแล้ว · กรุณาใช้อีเมลอื่น"); return; }
    if (form.password !== form.password2) { setErr("รหัสผ่านไม่ตรงกัน"); return; }
    if (form.password.length < 6) { setErr("รหัสผ่านอย่างน้อย 6 ตัว"); return; }

    setBusy(true);
    try {
      if (typeof window !== "undefined" && window.apiClient) {
        await window.apiClient.signup({
          full_name: form.full_name,
          email: form.email,
          phone: form.phone,
          password: form.password,
        });
      }
      setSubmitted(true);
    } catch (apiErr) {
      setErr(apiErr.message || "ไม่สามารถสร้างบัญชีได้ กรุณาลองอีกครั้ง");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="wk-card">
      <button onClick={onBack} className="wk-back" type="button"><WkBackIcon/>กลับ</button>
      <div className="wk-intro" style={{ marginBottom: 18 }}>
        <h1 className="wk-title" style={{ fontSize: 32 }}>Create account</h1>
        <p className="wk-tagline-en">เพียงไม่กี่ขั้นตอน คุณก็ใช้งานระบบได้ทันที</p>
      </div>
      {!submitted ? (
        <form onSubmit={submit} className="wk-form">
          <label className="wk-field">
            <span className="wk-label">ชื่อ-นามสกุล *</span>
            <span className="wk-input-wrap">
              <input type="text" value={form.full_name} onChange={e=>set("full_name", e.target.value)} placeholder="เช่น สมหญิง ใจดี" required style={{ padding: '12px 14px' }}/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">อีเมล *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkEnvelopeIcon/></span>
              <input type="email" value={form.email} onChange={e=>set("email", e.target.value)} placeholder="you@company.co.th" required/>
            </span>
            {emailStatus.checking && (
              <div style={{ marginTop: 4, fontSize: 11, color: 'var(--wk-muted)' }}>กำลังตรวจสอบ...</div>
            )}
            {!emailStatus.checking && emailStatus.available === true && (
              <div style={{ marginTop: 4, fontSize: 11, color: '#067647', display: 'flex', alignItems: 'center', gap: 4 }}>
                <WkCheckIcon/>อีเมลนี้ยังไม่มีผู้ใช้ — ใช้ได้
              </div>
            )}
            {!emailStatus.checking && emailStatus.available === false && (
              <div style={{ marginTop: 4, fontSize: 11, color: 'var(--wk-danger)' }}>
                อีเมลนี้มีบัญชีในระบบแล้ว · กรุณาใช้อีเมลอื่น
              </div>
            )}
          </label>
          <label className="wk-field">
            <span className="wk-label">โทรศัพท์</span>
            <span className="wk-input-wrap">
              <input type="text" value={form.phone} onChange={e=>set("phone", e.target.value)} placeholder="08x-xxx-xxxx" style={{ padding: '12px 14px' }}/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">รหัสผ่าน *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkLockIcon/></span>
              <input type="password" value={form.password} onChange={e=>set("password", e.target.value)} placeholder="อย่างน้อย 6 ตัวอักษร" required/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">ยืนยันรหัสผ่าน *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkLockIcon/></span>
              <input type="password" value={form.password2} onChange={e=>set("password2", e.target.value)} placeholder="••••••••" required/>
            </span>
          </label>
          {err && (
            <div className="wk-error"><WkAlertIcon/><span>{err}</span></div>
          )}
          <button type="submit" className="wk-submit" disabled={busy || emailStatus.available === false}>
            <span>{busy ? "กำลังสร้างบัญชี..." : "สร้างบัญชี"}</span>
            {!busy && <WkArrowRightIcon/>}
          </button>
        </form>
      ) : (
        <div style={{ padding: '24px 16px', borderRadius: 12, background: 'rgba(94,232,135,.12)', border: '1px solid rgba(94,232,135,.3)', textAlign: 'center', color: '#067647', marginTop: 8 }}>
          <div style={{ fontSize: 24, marginBottom: 8 }}>✓</div>
          <div style={{ fontWeight: 700, fontSize: 14 }}>สร้างบัญชีเรียบร้อยแล้ว</div>
          <div style={{ fontSize: 12.5, marginTop: 4, color: 'var(--wk-ink-2)' }}>เข้าสู่ระบบด้วยอีเมล {form.email} ได้ทันที</div>
          <button onClick={onBack} type="button" className="wk-link" style={{ marginTop: 12, fontSize: 13 }}>← กลับไปหน้าเข้าสู่ระบบ</button>
        </div>
      )}
    </div>
  );
};

// ===========================================================================
// ChangePasswordForm — wrapped in wk-card to match new design; logic unchanged
// ===========================================================================
const ChangePasswordForm = ({ initialEmail = "", onBack }) => {
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [done, setDone] = useState(false);
  const [form, setForm] = useState({
    email: initialEmail,
    current_password: "",
    new_password: "",
    new_password2: "",
  });
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!form.email.trim()) { setErr("กรุณากรอกอีเมล"); return; }
    if (!form.current_password) { setErr("กรุณากรอกรหัสผ่านเดิม"); return; }
    if (form.new_password.length < 6) { setErr("รหัสผ่านใหม่ต้องมีอย่างน้อย 6 ตัวอักษร"); return; }
    if (form.new_password !== form.new_password2) { setErr("รหัสผ่านใหม่ทั้งสองช่องไม่ตรงกัน"); return; }
    if (form.new_password === form.current_password) { setErr("รหัสผ่านใหม่ต้องไม่ซ้ำกับรหัสผ่านเดิม"); return; }

    setBusy(true);
    try {
      if (typeof window !== "undefined" && window.apiClient) {
        await window.apiClient.changePasswordWithCredentials(
          form.email.trim(),
          form.current_password,
          form.new_password
        );
      }
      setDone(true);
    } catch (apiErr) {
      if (apiErr.status === 401) setErr("อีเมลหรือรหัสผ่านเดิมไม่ถูกต้อง");
      else if (apiErr.status === 423) setErr("บัญชีถูกล็อกชั่วคราว เนื่องจากใส่รหัสผ่านผิดหลายครั้ง");
      else setErr(apiErr.message || "ไม่สามารถเปลี่ยนรหัสผ่านได้ กรุณาลองอีกครั้ง");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="wk-card">
      <button onClick={onBack} className="wk-back" type="button"><WkBackIcon/>กลับ</button>
      <div className="wk-intro" style={{ marginBottom: 18 }}>
        <h1 className="wk-title" style={{ fontSize: 32 }}>Change password</h1>
        <p className="wk-tagline-en">ต้องยืนยันรหัสผ่านเดิมก่อนตั้งรหัสใหม่</p>
      </div>
      {!done ? (
        <form onSubmit={submit} className="wk-form">
          <label className="wk-field">
            <span className="wk-label">อีเมล *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkEnvelopeIcon/></span>
              <input type="email" value={form.email} onChange={e=>set("email", e.target.value)} placeholder="you@company.co.th" required autoFocus={!initialEmail}/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">รหัสผ่านเดิม *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkLockIcon/></span>
              <input type="password" value={form.current_password} onChange={e=>set("current_password", e.target.value)} placeholder="••••••••" required autoFocus={!!initialEmail}/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">รหัสผ่านใหม่ *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkLockIcon/></span>
              <input type="password" value={form.new_password} onChange={e=>set("new_password", e.target.value)} placeholder="อย่างน้อย 6 ตัวอักษร" required/>
            </span>
          </label>
          <label className="wk-field">
            <span className="wk-label">ยืนยันรหัสผ่านใหม่ *</span>
            <span className="wk-input-wrap">
              <span className="wk-input-icon"><WkLockIcon/></span>
              <input type="password" value={form.new_password2} onChange={e=>set("new_password2", e.target.value)} placeholder="••••••••" required/>
            </span>
          </label>
          {err && (
            <div className="wk-error"><WkAlertIcon/><span>{err}</span></div>
          )}
          <button type="submit" className="wk-submit" disabled={busy}>
            <span>{busy ? "กำลังเปลี่ยนรหัสผ่าน..." : "เปลี่ยนรหัสผ่าน"}</span>
            {!busy && <WkArrowRightIcon/>}
          </button>
        </form>
      ) : (
        <div style={{ padding: '24px 16px', borderRadius: 12, background: 'rgba(94,232,135,.12)', border: '1px solid rgba(94,232,135,.3)', textAlign: 'center', color: '#067647', marginTop: 8 }}>
          <div style={{ fontSize: 24, marginBottom: 8 }}>✓</div>
          <div style={{ fontWeight: 700, fontSize: 14 }}>เปลี่ยนรหัสผ่านเรียบร้อย</div>
          <div style={{ fontSize: 12.5, marginTop: 4, color: 'var(--wk-ink-2)' }}>ใช้รหัสผ่านใหม่เข้าสู่ระบบได้ทันที</div>
          <button onClick={onBack} type="button" className="wk-link" style={{ marginTop: 12, fontSize: 13 }}>← กลับไปหน้าเข้าสู่ระบบ</button>
        </div>
      )}
    </div>
  );
};

window.LoginScreen = LoginScreen;
