/* ============================================================
   HR / Admin Dashboard — Evans Web Store
   ============================================================ */

function AdminScreen() {
  const { navigate, user } = useContext(AppCtx);
  const [tab, setTab] = useState('overview');
  const [addOpen, setAddOpen] = useState(false);

  const nav = [
    ['overview', 'grid', 'Overview'],
    ['employees', 'users', 'Employees'],
    ['orders', 'receipt', 'Orders'],
    ['overages', 'alert', 'Overages'],
    ['products', 'box', 'Products'],
    ['settings', 'settings', 'Settings'],
  ];
  const overageCount = ADMIN_EMPLOYEES.filter(e => e.used > e.total).length;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '252px 1fr', minHeight: '100vh', background: 'var(--bg)' }}>
      {/* Sidebar */}
      <aside style={{ background: 'var(--ink)', color: 'rgba(255,255,255,.7)', display: 'flex', flexDirection: 'column', position: 'sticky', top: 0, height: '100vh' }}>
        <div style={{ padding: '22px 20px' }}><Logo size={30} light /></div>
        <div style={{ padding: '0 16px', marginTop: 8 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-display)', fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,.4)', padding: '8px 12px' }}>HR Console</div>
          {nav.map(([id, icon, label]) => (
            <button key={id} onClick={() => setTab(id)} className="row" style={{ width: '100%', gap: 12, padding: '11px 12px', borderRadius: 10, border: 'none', marginBottom: 2, textAlign: 'left', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, cursor: 'pointer', background: tab === id ? 'rgba(255,255,255,.10)' : 'transparent', color: tab === id ? '#fff' : 'rgba(255,255,255,.66)' }}>
              <Icon name={icon} size={18} /> <span className="grow">{label}</span>
              {id === 'overages' && overageCount > 0 && <span style={{ background: 'var(--amber)', color: '#fff', fontSize: 11, fontWeight: 700, borderRadius: 99, padding: '1px 7px' }}>{overageCount}</span>}
            </button>
          ))}
        </div>
        <div className="grow" />
        <div style={{ padding: 16 }}>
          <div className="row" style={{ gap: 10, padding: 12, borderRadius: 12, background: 'rgba(255,255,255,.06)' }}>
            <span style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--teal-600)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13 }}>OT</span>
            <div className="grow" style={{ lineHeight: 1.2 }}>
              <div style={{ color: '#fff', fontWeight: 600, fontSize: 13.5, fontFamily: 'var(--font-display)' }}>Olivia Trahan</div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.5)' }}>HR Admin</div>
            </div>
          </div>
          <button className="row" onClick={() => navigate('home')} style={{ width: '100%', gap: 10, marginTop: 10, padding: '10px 12px', borderRadius: 10, border: 'none', background: 'transparent', color: 'rgba(255,255,255,.6)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer' }}><Icon name="logout" size={16} /> Back to store</button>
        </div>
      </aside>

      {/* Main */}
      <main className="scroll" style={{ padding: '28px 34px', overflow: 'auto' }}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <h1 style={{ fontSize: 26 }}>{nav.find(n => n[0] === tab)[2]}</h1>
            <p className="muted" style={{ marginTop: 4, fontSize: 13.5 }}>Evans Equipment &amp; Environmental · Employee web store</p>
          </div>
          <div className="row" style={{ gap: 10 }}>
            <button className="btn btn-ghost btn-icon"><Icon name="bell" size={18} /></button>
            {tab === 'employees' && <button className="btn btn-primary" onClick={() => setAddOpen(true)}><Icon name="plus" size={16} /> Add employee</button>}
          </div>
        </div>
        {tab === 'overview' && <AdminOverview setTab={setTab} />}
        {tab === 'employees' && <AdminEmployees />}
        {tab === 'orders' && <AdminOrders />}
        {tab === 'overages' && <AdminOverages />}
        {(tab === 'products' || tab === 'settings') && <AdminPlaceholder tab={tab} />}
      </main>
      {addOpen && <AddEmployeeModal onClose={() => setAddOpen(false)} />}
    </div>
  );
}

/* ---------- Overview ---------- */
function AdminOverview({ setTab }) {
  const totalEmp = ADMIN_EMPLOYEES.filter(e => e.status === 'Active').length;
  const issued = ADMIN_EMPLOYEES.reduce((n, e) => n + e.total, 0);
  const spent = ADMIN_EMPLOYEES.reduce((n, e) => n + Math.min(e.used, e.total), 0);
  const overages = ADMIN_EMPLOYEES.filter(e => e.used > e.total);
  const overTotal = overages.reduce((n, e) => n + (e.used - e.total), 0);
  return (
    <div className="fade-up">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        <StatCard icon="users" label="Active employees" value={totalEmp} tone="teal" />
        <StatCard icon="coins" label="Points issued" value={issued.toLocaleString()} sub="this cycle" />
        <StatCard icon="receipt" label="Points spent" value={spent.toLocaleString()} sub={`${Math.round(spent / issued * 100)}% of allowance`} />
        <StatCard icon="alert" label="Open overages" value={`$${overTotal}`} sub={`${overages.length} employees`} tone="amber" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20, marginTop: 20 }}>
        {/* Recent orders */}
        <div className="card">
          <div className="row card-pad" style={{ justifyContent: 'space-between', paddingBottom: 12 }}>
            <h3 style={{ fontSize: 16 }}>Recent orders</h3>
            <span className="link" style={{ fontSize: 13 }} onClick={() => setTab('orders')}>View all</span>
          </div>
          <table className="tbl">
            <thead><tr><th>Order</th><th>Employee</th><th>Date</th><th>Points</th><th></th></tr></thead>
            <tbody>
              {ADMIN_ORDERS.slice(0, 5).map(o => (
                <tr key={o.id}>
                  <td className="mono-num" style={{ fontWeight: 600 }}>{o.id}</td>
                  <td>{o.emp}</td>
                  <td className="muted">{o.date}</td>
                  <td className="mono-num" style={{ fontWeight: 600 }}>{o.points}</td>
                  <td>{o.over ? <span className="badge badge-amber">Over</span> : <span className="badge badge-ok">OK</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {/* Overage alerts */}
        <div className="card card-pad">
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 14 }}>
            <h3 style={{ fontSize: 16 }}>Needs attention</h3>
            <span className="badge badge-amber">{overages.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {overages.map(e => (
              <div key={e.email} className="row" style={{ gap: 12, padding: 12, borderRadius: 11, background: 'var(--amber-bg)' }}>
                <Icon name="alert" size={18} style={{ color: 'var(--amber)', flexShrink: 0 }} />
                <div className="grow">
                  <div style={{ fontWeight: 600, fontSize: 13.5, fontFamily: 'var(--font-display)' }}>{e.name}</div>
                  <div style={{ fontSize: 12, color: '#7a5210' }}>Owes ${e.used - e.total} · {e.dept}</div>
                </div>
                <button className="btn btn-sm btn-ghost" style={{ background: '#fff' }}>Resolve</button>
              </div>
            ))}
            <button className="btn btn-ghost btn-block" style={{ marginTop: 4 }} onClick={() => setTab('overages')}>Review all overages</button>
          </div>
        </div>
      </div>
    </div>
  );
}
function StatCard({ icon, label, value, sub, tone }) {
  const bg = tone === 'teal' ? 'var(--teal-600)' : tone === 'amber' ? 'var(--amber)' : 'var(--surface-2)';
  const fg = tone ? '#fff' : 'var(--muted)';
  return (
    <div className="card card-pad">
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <span style={{ width: 38, height: 38, borderRadius: 10, background: bg, color: fg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={19} /></span>
      </div>
      <div className="mono-num" style={{ fontSize: 28, fontWeight: 800, marginTop: 14 }}>{value}</div>
      <div className="muted" style={{ fontSize: 13 }}>{label}{sub && <span style={{ color: 'var(--faint)' }}> · {sub}</span>}</div>
    </div>
  );
}

/* ---------- Employees ---------- */
function AdminEmployees() {
  const [q, setQ] = useState('');
  const list = ADMIN_EMPLOYEES.filter(e => e.name.toLowerCase().includes(q.toLowerCase()) || e.email.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="card fade-up" style={{ overflow: 'hidden' }}>
      <div className="row card-pad" style={{ justifyContent: 'space-between', paddingBottom: 14, gap: 14 }}>
        <div className="row" style={{ gap: 10, border: '1px solid var(--line)', borderRadius: 10, padding: '8px 12px', width: 280, background: 'var(--surface-2)' }}>
          <Icon name="search" size={17} style={{ color: 'var(--muted)' }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search employees…" style={{ border: 'none', background: 'transparent', outline: 'none', width: '100%', fontSize: 14, fontFamily: 'inherit' }} />
        </div>
        <span className="muted" style={{ fontSize: 13 }}>{list.length} of {ADMIN_EMPLOYEES.length}</span>
      </div>
      <table className="tbl">
        <thead><tr><th>Employee</th><th>Role</th><th>Department</th><th>Points used</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {list.map(e => {
            const over = e.used > e.total;
            const pct = Math.min(100, e.used / e.total * 100);
            return (
              <tr key={e.email}>
                <td>
                  <div className="row" style={{ gap: 11 }}>
                    <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--teal-50)', color: 'var(--teal-700)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12 }}>{e.name.split(' ').map(n => n[0]).join('')}</span>
                    <div><div style={{ fontWeight: 600, fontSize: 14, fontFamily: 'var(--font-display)' }}>{e.name}</div><div className="muted" style={{ fontSize: 12 }}>{e.email}</div></div>
                  </div>
                </td>
                <td>{e.role === 'HR Admin' ? <span className="badge badge-teal">HR Admin</span> : <span className="muted">Employee</span>}</td>
                <td className="muted">{e.dept}</td>
                <td style={{ minWidth: 160 }}>
                  <div className="row" style={{ gap: 10 }}>
                    <div style={{ width: 70, height: 6, borderRadius: 99, background: 'var(--line-2)', overflow: 'hidden' }}><i style={{ display: 'block', height: '100%', width: pct + '%', background: over ? 'var(--amber)' : 'var(--teal-600)' }} /></div>
                    <span className="mono-num" style={{ fontSize: 13, fontWeight: 600, color: over ? 'var(--amber)' : 'var(--ink-2)' }}>{e.used}/{e.total}</span>
                  </div>
                </td>
                <td>{e.status === 'Active' ? <span className="badge badge-ok">Active</span> : <span className="badge badge-gray">Invited</span>}</td>
                <td>
                  <div className="row" style={{ gap: 4 }}>
                    <button className="btn btn-icon btn-ghost btn-sm" title="Edit"><Icon name="edit" size={15} /></button>
                    <button className="btn btn-icon btn-ghost btn-sm" title="Remove"><Icon name="trash" size={15} /></button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Orders ---------- */
function AdminOrders() {
  return (
    <div className="card fade-up" style={{ overflow: 'hidden' }}>
      <table className="tbl">
        <thead><tr><th>Order</th><th>Employee</th><th>Date</th><th>Items</th><th>Points</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {ADMIN_ORDERS.map(o => (
            <tr key={o.id}>
              <td className="mono-num" style={{ fontWeight: 600 }}>{o.id}</td>
              <td>{o.emp}</td>
              <td className="muted">{o.date}</td>
              <td>{o.items}</td>
              <td className="mono-num" style={{ fontWeight: 600 }}>{o.points} pts</td>
              <td>{o.over ? <span className="badge badge-amber">Overage</span> : <span className="badge badge-ok">Within allowance</span>}</td>
              <td><button className="btn btn-sm btn-ghost">View</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Overages ---------- */
function AdminOverages() {
  const overages = ADMIN_EMPLOYEES.filter(e => e.used > e.total);
  return (
    <div className="fade-up">
      <div className="card card-pad" style={{ background: 'var(--amber-bg)', borderColor: 'var(--amber-line)', marginBottom: 18, display: 'flex', gap: 13, alignItems: 'center' }}>
        <Icon name="alert" size={22} style={{ color: 'var(--amber)' }} />
        <span style={{ fontSize: 14, color: '#7a5210' }}>{overages.length} employees have exceeded their allowance. Total outstanding: <b>${overages.reduce((n, e) => n + (e.used - e.total), 0)}</b>. These should be billed to the company or the employee.</span>
      </div>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Employee</th><th>Department</th><th>Allowance</th><th>Used</th><th>Owes</th><th></th></tr></thead>
          <tbody>
            {overages.map(e => (
              <tr key={e.email}>
                <td><div style={{ fontWeight: 600, fontSize: 14, fontFamily: 'var(--font-display)' }}>{e.name}</div><div className="muted" style={{ fontSize: 12 }}>{e.email}</div></td>
                <td className="muted">{e.dept}</td>
                <td className="mono-num">{e.total} pts</td>
                <td className="mono-num" style={{ color: 'var(--amber)', fontWeight: 600 }}>{e.used} pts</td>
                <td className="mono-num" style={{ fontWeight: 700, color: 'var(--danger)' }}>${e.used - e.total}</td>
                <td><div className="row" style={{ gap: 8 }}><button className="btn btn-sm btn-soft">Mark billed</button><button className="btn btn-sm btn-ghost">Adjust</button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------- Placeholder tabs ---------- */
function AdminPlaceholder({ tab }) {
  const copy = tab === 'products'
    ? { icon: 'box', title: 'Product management', desc: 'Add, edit, and remove catalog items, manage colors and sizes, and assign products to Men\u2019s, Women\u2019s, or Technician categories. Imported from the existing store during setup.' }
    : { icon: 'settings', title: 'Store settings', desc: 'Configure the annual point allowance, reset schedule, delivery locations, overage rules, and HR notification recipients. Super Admin access required.' };
  return (
    <div className="card card-pad fade-up center" style={{ padding: '64px 40px' }}>
      <div style={{ width: 64, height: 64, borderRadius: 16, background: 'var(--teal-50)', color: 'var(--teal-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}><Icon name={copy.icon} size={28} /></div>
      <h2 style={{ fontSize: 20 }}>{copy.title}</h2>
      <p className="muted" style={{ marginTop: 10, maxWidth: 440, marginInline: 'auto', lineHeight: 1.6 }}>{copy.desc}</p>
      <span className="badge badge-gray" style={{ marginTop: 18 }}>Wired up during backend handoff</span>
    </div>
  );
}

/* ---------- Add employee modal ---------- */
function AddEmployeeModal({ onClose }) {
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(16,32,30,.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }} onClick={onClose}>
      <div className="card fade-up" style={{ width: 480, boxShadow: 'var(--shadow-lg)', padding: 26 }} onClick={e => e.stopPropagation()}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
          <h2 style={{ fontSize: 21 }}>Add employee</h2>
        </div>
        <p className="muted" style={{ fontSize: 13.5, marginBottom: 20 }}>They'll receive an email invite to set their password. The annual allowance is applied automatically.</p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div className="field"><label>Full name</label><input className="input" placeholder="Jane Doe" /></div>
          <div className="field"><label>Employee ID</label><input className="input" placeholder="EV-1043" /></div>
          <div className="field" style={{ gridColumn: '1 / -1' }}><label>Work email</label><input className="input" placeholder="j.doe@evansequip.com" /></div>
          <div className="field"><label>Department / role</label><select className="select"><option>Field Technician</option><option>Welding</option><option>Office</option><option>Management</option></select></div>
          <div className="field"><label>Access categories</label><select className="select"><option>Men's + Technicians</option><option>Women's + Technicians</option><option>Men's only</option><option>Women's only</option><option>All</option></select></div>
          <div className="field"><label>Annual points</label><input className="input mono-num" defaultValue="300" /></div>
          <div className="field"><label>Permission level</label><select className="select"><option>Employee</option><option>HR Admin</option><option>Super Admin</option></select></div>
        </div>
        <div className="row" style={{ gap: 12, marginTop: 24, justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={onClose}><Icon name="plus" size={16} /> Add &amp; send invite</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen, AdminOverview, StatCard, AdminEmployees, AdminOrders, AdminOverages, AdminPlaceholder, AddEmployeeModal });
