// Shell: sidebar + topbar

const NAV_ADMIN = [
{ id: 'dashboard', label: 'แดชบอร์ด', icon: 'dashboard' },
{ id: 'leaves', label: 'การลา', icon: 'plane', badge: 2 },
{ id: 'swap-ot', label: 'OT & สลับวันหยุด', icon: 'swap', badge: 3 },
{ id: 'employees', label: 'พนักงาน', icon: 'users' },
{ id: 'reports', label: 'รายงาน', icon: 'chart' }];

const NAV_ADMIN_SECONDARY = [
{ id: 'settings', label: 'ตั้งค่าระบบ', icon: 'settings' }];

const NAV_EMP = [
{ id: 'dashboard', label: 'ปฏิทินทีม', icon: 'calendar' },
{ id: 'my-leaves', label: 'การลาของฉัน', icon: 'plane' },
{ id: 'my-swap', label: 'สลับวันหยุด / OT', icon: 'swap' },
{ id: 'my-quota', label: 'โควต้าวันลา', icon: 'briefcase' }];


const Sidebar = ({ role, setRole, page, setPage, currentUser, onLogout, onChangePassword }) => {
  const nav = role === 'admin' ? NAV_ADMIN : NAV_EMP;
  const navSec = role === 'admin' ? NAV_ADMIN_SECONDARY : [];
  const canSwitchRole = typeof setRole === 'function';
  return (
    <aside className="sidebar" data-screen-label="Sidebar">
      <div className="brand">
        <div className="brand-logo">WC</div>
        <div>
          <div className="brand-name">Work Calendar</div>
          <div className="brand-sub">Thunderborn.Co,Ltd</div>
        </div>
      </div>

      {canSwitchRole && (
        <div className="role-switch" title="สลับมุมมอง Admin / Employee">
          <button className={role === 'admin' ? 'active' : ''} onClick={() => setRole('admin')}>
            Admin
          </button>
          <button className={role === 'employee' ? 'active' : ''} onClick={() => setRole('employee')}>
            พนักงาน
          </button>
        </div>
      )}

      <div className="nav-section">{role === 'admin' ? 'จัดการ' : 'เมนู'}</div>
      <nav className="nav">
        {nav.map((n) =>
        <button key={n.id} className={`nav-item ${page === n.id ? 'active' : ''}`} onClick={() => setPage(n.id)}>
            <Icon name={n.icon} />
            <span>{n.label}</span>
            {n.badge ? <span className="nav-badge">{n.badge}</span> : null}
          </button>
        )}
      </nav>

      {navSec.length > 0 &&
      <>
          <div className="nav-section">ระบบ</div>
          <nav className="nav">
            {navSec.map((n) =>
          <button key={n.id} className={`nav-item ${page === n.id ? 'active' : ''}`} onClick={() => setPage(n.id)}>
                <Icon name={n.icon} />
                <span>{n.label}</span>
              </button>
          )}
          </nav>
        </>
      }

      <div className="sidebar-footer">
        <div className="user-card">
          <div className="avatar" style={{ background: currentUser.color }}>{currentUser.avatar}</div>
          <div className="user-info">
            <div className="user-name">{currentUser.name}</div>
            <div className="user-role">{currentUser.appRole === 'admin' ? 'Admin' : currentUser.role}</div>
          </div>
          <button className="icon-btn" title="เปลี่ยนรหัสผ่าน" onClick={onChangePassword} style={{ width: 28, height: 28 }}>
            <Icon name="lock" size={14} style={{ color: 'var(--ink-400)' }} />
          </button>
          <button className="icon-btn" title="ออกจากระบบ" onClick={onLogout} style={{ width: 28, height: 28 }}>
            <Icon name="logout" size={15} style={{ color: 'var(--ink-400)' }} />
          </button>
        </div>
      </div>
    </aside>);

};

const Topbar = ({ title, subtitle, actions }) => {
  return (
    <header className="topbar">
      <div className="crumbs">
        <strong>{title}</strong>
        {subtitle && <span>· {subtitle}</span>}
      </div>
      <div className="topbar-actions">
        <div className="search">
          <Icon name="search" size={14} />
          <input placeholder="ค้นหาพนักงาน, การลา, OT..." />
          <kbd>⌘K</kbd>
        </div>
        <button className="icon-btn" title="แจ้งเตือน">
          <Icon name="bell" />
          <span className="dot"></span>
        </button>
        <button className="icon-btn" title="ช่วยเหลือ">
          <Icon name="info" />
        </button>
        {actions}
      </div>
    </header>);

};

window.Sidebar = Sidebar;
window.Topbar = Topbar;

// ───── Change Password Modal (self-service) ─────
const ChangePasswordModal = ({ onClose }) => {
  const [cur, setCur] = React.useState('');
  const [next, setNext] = React.useState('');
  const [conf, setConf] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [ok, setOk] = React.useState(false);

  const canSave = cur && next && next === conf && next.length >= 6 && !busy;

  const save = async () => {
    setErr(null); setBusy(true);
    try {
      await window.API.changePassword(cur, next);
      setOk(true);
      setTimeout(onClose, 1200);
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 420 }}>
        <div className="modal-header">
          <div>
            <div className="modal-title">เปลี่ยนรหัสผ่าน</div>
            <div className="text-xs muted mt-2">รหัสใหม่ต้องมีอย่างน้อย 6 ตัวอักษร · session อื่นจะถูก logout ทั้งหมด</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          {ok ? (
            <div style={{ background:'var(--swap-bg)', color:'var(--swap)', padding:14, borderRadius:8, textAlign:'center' }}>
              <Icon name="check" size={18}/> เปลี่ยนรหัสผ่านเรียบร้อย
            </div>
          ) : (<>
            <div className="field">
              <label>รหัสผ่านปัจจุบัน</label>
              <input type="password" value={cur} onChange={e => setCur(e.target.value)} autoFocus/>
            </div>
            <div className="field">
              <label>รหัสผ่านใหม่</label>
              <input type="password" value={next} onChange={e => setNext(e.target.value)}/>
              {next && next.length < 6 && <div className="field-help" style={{ color:'var(--sick)' }}>สั้นเกินไป — ต้อง ≥ 6 ตัวอักษร</div>}
            </div>
            <div className="field">
              <label>ยืนยันรหัสผ่านใหม่</label>
              <input type="password" value={conf} onChange={e => setConf(e.target.value)}/>
              {conf && next !== conf && <div className="field-help" style={{ color:'var(--sick)' }}>ไม่ตรงกัน</div>}
            </div>
            {err && <div style={{ background:'#fef2f2', color:'#b91c1c', padding:'8px 12px', borderRadius:8, fontSize:12 }}>{err}</div>}
          </>)}
        </div>
        {!ok && (
          <div className="modal-footer">
            <button className="btn btn-ghost" onClick={onClose} disabled={busy}>ยกเลิก</button>
            <button className="btn btn-primary" disabled={!canSave} onClick={save}>
              <Icon name="check" size={14}/> {busy ? 'กำลังบันทึก…' : 'บันทึก'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

window.ChangePasswordModal = ChangePasswordModal;