/* app.jsx — โครงแอป: ล็อกอิน, เปลี่ยนรหัสผ่าน, เมนู, เลือกหน้าตามประเภทผู้ใช้
 * เส้นทางใช้ hash: #home (ภาพรวม) · #dept/<รหัสฝ่าย> · #flags · #settings
 * ผู้ใช้ประเภทฝ่ายเห็นหน้าเดียวคือแบบฟอร์มของฝ่ายตัวเอง */

function LoginPage({ onDone }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!username.trim() || !password) { setErr('กรอกชื่อผู้ใช้และรหัสผ่าน'); return; }
    setBusy(true); setErr('');
    try { await API.login(username, password); onDone(); }
    catch (ex) { setErr(ex.message); } finally { setBusy(false); }
  };
  return (
    <div className="login">
      <form className="card" onSubmit={submit}>
        <div className="login-head">
          <img className="logo" src="waterpog-logo.png" alt="Water POG" />
          <div className="title">ขออนุมัติงบประมาณ</div>
          <div className="mute small">เข้าสู่ระบบด้วยบัญชีที่ฝ่ายการเงินส่งให้</div>
        </div>
        <label className="field">ชื่อผู้ใช้
          <input type="text" value={username} autoFocus autoComplete="username" onChange={(e) => { setUsername(e.target.value); setErr(''); }} />
        </label>
        <label className="field">รหัสผ่าน
          <PasswordInput value={password} autoComplete="current-password" onChange={(e) => { setPassword(e.target.value); setErr(''); }} />
        </label>
        {err && <div className="err" role="alert">{err}</div>}
        <button className="btn primary" disabled={busy} type="submit">{busy ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ'}</button>
      </form>
    </div>
  );
}

function ChangePassword({ forced, onDone, onCancel }) {
  const [oldPassword, setOld] = useState('');
  const [newPassword, setNew] = useState('');
  const [again, setAgain] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (newPassword.length < 8) { setErr('รหัสผ่านใหม่ต้องยาวอย่างน้อย 8 ตัวอักษร'); return; }
    if (!/\p{L}/u.test(newPassword) || !/\d/.test(newPassword)) { setErr('รหัสผ่านใหม่ต้องมีทั้งตัวอักษรและตัวเลข'); return; }
    if (newPassword !== again) { setErr('รหัสผ่านใหม่ 2 ช่องไม่ตรงกัน'); return; }
    setBusy(true); setErr('');
    try { await API.changePassword(oldPassword, newPassword); toast('เปลี่ยนรหัสผ่านแล้ว'); onDone(); }
    catch (ex) { setErr(ex.message); } finally { setBusy(false); }
  };
  const body = (
    <form onSubmit={submit} style={{ display: 'grid', gap: 12 }}>
      {forced && <p className="mute small">เข้าใช้ครั้งแรก ตั้งรหัสผ่านของตัวเองก่อนเริ่มกรอกงบ</p>}
      <label className="field">{forced ? 'รหัสผ่านชั่วคราวที่ได้รับ' : 'รหัสผ่านเดิม'}
        <PasswordInput value={oldPassword} autoFocus autoComplete="current-password" onChange={(e) => { setOld(e.target.value); setErr(''); }} />
      </label>
      <label className="field">รหัสผ่านใหม่ (อย่างน้อย 8 ตัว มีทั้งตัวอักษรและตัวเลข)
        <PasswordInput value={newPassword} autoComplete="new-password" onChange={(e) => { setNew(e.target.value); setErr(''); }} />
      </label>
      <label className="field">รหัสผ่านใหม่อีกครั้ง
        <PasswordInput value={again} autoComplete="new-password" onChange={(e) => { setAgain(e.target.value); setErr(''); }} />
      </label>
      {err && <div className="err" role="alert">{err}</div>}
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        {onCancel && <button type="button" className="btn" onClick={onCancel}>ยกเลิก</button>}
        <button type="submit" className="btn primary" disabled={busy}>ตั้งรหัสผ่านใหม่</button>
      </div>
    </form>
  );
  if (forced) {
    return (
      <div className="login">
        <div className="card">
          <div className="login-head">
            <img className="logo" src="waterpog-logo.png" alt="Water POG" />
            <div className="title">ตั้งรหัสผ่านใหม่</div>
          </div>
          {body}
        </div>
      </div>
    );
  }
  return <Modal title="เปลี่ยนรหัสผ่าน" onClose={onCancel}>{body}</Modal>;
}

const parseHash = () => decodeURIComponent((window.location.hash || '').replace(/^#\/?/, ''));

function App() {
  const [phase, setPhase] = useState(API.hasSession() ? 'loading' : 'login');
  const [ctx, setCtx] = useState(null);          // { user, dept, round }
  const [route, setRoute] = useState(parseHash());
  const [pwOpen, setPwOpen] = useState(false);
  const [bootErr, setBootErr] = useState('');

  const loadMe = useCallback(async () => {
    setBootErr('');
    try { setCtx(await API.me()); setPhase('ready'); }
    catch (e) { if (e.status === 401) setPhase('login'); else setBootErr(e.message); }
  }, []);

  useEffect(() => { if (API.hasSession()) loadMe(); }, [loadMe]);
  useEffect(() => {
    const onHash = () => setRoute(parseHash());
    const onExpired = () => { setCtx(null); setPhase('login'); toast('หมดเวลาใช้งาน เข้าสู่ระบบอีกครั้ง', 'error'); };
    window.addEventListener('hashchange', onHash);
    window.addEventListener('wpb-auth-expired', onExpired);
    return () => { window.removeEventListener('hashchange', onHash); window.removeEventListener('wpb-auth-expired', onExpired); };
  }, []);

  const go = (r) => { window.location.hash = '#' + r; };
  const logout = () => { API.logout(); setCtx(null); setPhase('login'); window.location.hash = ''; };

  if (phase === 'login') return <><LoginPage onDone={() => { setPhase('loading'); loadMe(); }} /><ToastHost /></>;
  if (bootErr) return <div className="boot"><p className="err">{bootErr}</p><p><button className="btn sm" onClick={loadMe}>ลองใหม่</button></p></div>;
  if (phase === 'loading' || !ctx) return <div className="boot">กำลังโหลด…</div>;

  const me = ctx.user;
  if (me.mustChangePassword) return <><ChangePassword forced onDone={loadMe} /><ToastHost /></>;

  const isDept = me.role === 'dept';
  const tab = isDept ? 'form' : route.startsWith('dept/') ? 'home' : route === 'flags' ? 'flags' : route === 'settings' && me.role === 'admin' ? 'settings' : 'home';

  let page;
  if (!ctx.round) {
    // ยังไม่มีรอบ: ผู้ดูแลเปิดรอบได้จากหน้านี้เลย · คนอื่นเห็นข้อความรอ
    page = me.role === 'admin' ? (
      <ReferenceCard round={null} onChanged={loadMe} />
    ) : (
      <div className="card pad">
        <h2>ยังไม่ได้เปิดรอบขออนุมัติงบ</h2>
        <p className="mute">ยังไม่มียอดอ้างอิงในระบบ ติดต่อฝ่ายการเงิน</p>
      </div>
    );
  } else if (isDept) {
    page = ctx.dept
      ? <BudgetForm key={ctx.dept.code} deptCode={ctx.dept.code} me={me} />
      : <div className="card pad"><p className="err">บัญชีนี้ยังไม่ได้ผูกกับฝ่าย ติดต่อฝ่ายการเงิน</p></div>;
  } else if (route.startsWith('dept/')) {
    const code = route.slice(5);
    page = <BudgetForm key={code} deptCode={code} me={me} onBack={() => go('home')} />;
  } else if (tab === 'flags') {
    page = <AdminFlags go={go} />;
  } else if (tab === 'settings') {
    page = <AdminSettings me={me} round={ctx.round} onRound={(round) => setCtx({ ...ctx, round })} />;
  } else {
    page = <AdminHome go={go} />;
  }

  return (
    <>
      <div className="topbar">
        <div className="topbar-in">
          <div className="brand">Water POG · <span>งบประมาณ{ctx.round ? ' ' + ctx.round.year : ''}</span></div>
          <div className="nav">
            {!isDept && <button className={tab === 'home' ? 'on' : ''} onClick={() => go('home')}>ภาพรวม</button>}
            {!isDept && <button className={tab === 'flags' ? 'on' : ''} onClick={() => go('flags')}>รายการเกินเกณฑ์</button>}
            {me.role === 'admin' && <button className={tab === 'settings' ? 'on' : ''} onClick={() => go('settings')}>ตั้งค่า</button>}
          </div>
          <div className="who">
            <span className="name">{me.displayName || me.username} · {isDept ? me.dept : ROLE_LABEL[me.role]}</span>
            <button className="btn ghost sm" onClick={() => setPwOpen(true)} title="เปลี่ยนรหัสผ่าน" aria-label="เปลี่ยนรหัสผ่าน"><Icon name="key" /></button>
            <button className="btn ghost sm" onClick={logout}><Icon name="logout" />ออก</button>
          </div>
        </div>
      </div>
      <div className="page">{page}</div>
      {pwOpen && <ChangePassword onDone={() => setPwOpen(false)} onCancel={() => setPwOpen(false)} />}
      <ToastHost />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
