// ---------- Employees ----------
function EmpFace({ emp, size }) {
  const [bad, setBad] = React.useState(false);
  const s = size || 36;
  if (!emp.avatar_url || bad) {
    return (
      <div style={{ width: s, height: s, borderRadius: '50%', background: 'var(--accent-dim)', border: '1px solid var(--accent-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--accent)', fontWeight: 600, fontSize: s > 34 ? 12 : 11, flexShrink: 0 }}>
        {emp.initials}
      </div>
    );
  }
  return <img alt="" loading="lazy" src={emp.avatar_url} width={s} height={s} style={{ borderRadius: '50%', objectFit: 'cover', border: '1px solid var(--accent-border)', flexShrink: 0 }} onError={() => setBad(true)} />;
}

function Employees({ role }) {
  const [search, setSearch] = React.useState('');
  const [deptFilter, setDept] = React.useState('all');
  const [showAdd, setShowAdd] = React.useState(false);
  const [profile, setProfile] = React.useState(null);
  const [, bump] = React.useState(0);
  React.useEffect(() => {
    const h = () => bump((x) => x + 1);
    window.addEventListener('gh-admin-data', h);
    return () => window.removeEventListener('gh-admin-data', h);
  }, []);

  const isBoss = role === 'boss';

  const list = window.EMPLOYEES || EMPLOYEES;

  const filtered = list.filter((e) => {
    if (deptFilter !== 'all' && e.department !== deptFilter) return false;
    if (search && !e.full_name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const roleColors = { boss:'badge-terra', production_manager:'badge-gold', accountant:'badge-blue', employee:'badge-muted' };

  return (
    <div style={{display:'flex',flexDirection:'column',gap:20}}>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:14}}>
        <MiniKpi label="Total" value={list.length} delta={`${list.filter(e=>e.status==='active').length} active`} color="var(--accent)"/>
        <MiniKpi label="Production" value={list.filter(e=>e.department==='Production').length} delta="on roster" color="var(--gold)"/>
        <MiniKpi label="Retail · Hybah" value={list.filter(e=>typeof e.department === 'string' && e.department.indexOf('Hybah')!==-1).length} delta="boutiques" color="var(--green)"/>
        <MiniKpi label="On leave" value="2" delta="this week" color="var(--blue)"/>
      </div>

      <div style={{display:'flex',justifyContent:'space-between',gap:12,flexWrap:'wrap'}}>
        <div style={{display:'flex',gap:10,flex:1,maxWidth:520}}>
          <div style={{flex:1,display:'flex',alignItems:'center',gap:10,padding:'8px 14px',background:'var(--card)',border:'1px solid var(--border)',borderRadius:999}}>
            <Icon.Search size={15} style={{color:'var(--text-dim)'}}/>
            <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by name..." style={{width:'100%'}}/>
          </div>
          <select value={deptFilter} onChange={e=>setDept(e.target.value)} style={{padding:'8px 14px',background:'var(--card)',border:'1px solid var(--border)',borderRadius:999,fontSize:13}}>
            <option value="all">All departments</option>
            {DEPARTMENTS.map(d => <option key={d}>{d}</option>)}
          </select>
        </div>
        {isBoss && <button className="btn btn-primary btn-sm" onClick={()=>setShowAdd(true)}><Icon.Plus size={13}/> Add employee</button>}
      </div>

      <TablePanel>
        <div className="gh-emp-scroll" style={{ overflowX: 'auto' }}>
          <table style={{width:'100%',borderCollapse:'collapse',minWidth:640}}>
            <thead><tr>
              <Th>Name</Th><Th>Role</Th><Th>Department</Th><Th>Status</Th><Th align="end">Salary</Th><Th>Start · tenure</Th><Th align="end"></Th>
            </tr></thead>
            <tbody>
              {filtered.map(e => (
              <tr key={e.id} style={{cursor:'pointer'}} onClick={()=>setProfile(e)}>
                <Td>
                  <div style={{display:'flex',alignItems:'center',gap:12}}>
                    <EmpFace emp={e} size={36} />
                    <div>
                      <div style={{fontWeight:500}}>{e.full_name}</div>
                      <div style={{fontSize:11,color:'var(--text-dim)'}}>{e.email}</div>
                    </div>
                  </div>
                </Td>
                <Td><span className={'badge '+roleColors[e.role]} style={{textTransform:'capitalize'}}>{e.role.replace('_',' ')}</span></Td>
                <Td><span style={{color:'var(--text-dim)'}}>{e.department}</span></Td>
                <Td><StatusBadge status={e.status}/></Td>
                <Td align="end"><span className="mono">{fmtNumber(e.salary)}</span> <span style={{color:'var(--text-dim)',fontSize:11}}>FCFA</span></Td>
                <Td>
                  <div className="mono" style={{color:'var(--text-dim)',fontSize:11}}>{fmtDate(e.join_date)}</div>
                  <div style={{fontSize:11,color:'var(--accent)',marginTop:2}}>{formatTenureSince(e.join_date, e.tenure_display_mode || 'months')}</div>
                </Td>
                <Td align="end"><button type="button" style={{color:'var(--text-dim)'}} onClick={(ev)=>{ev.stopPropagation();setProfile(e);}}><Icon.MoreH size={16}/></button></Td>
              </tr>
              ))}
            </tbody>
          </table>
        </div>
      </TablePanel>

      <style>{`
        @media (max-width: 700px) {
          .gh-emp-scroll { -webkit-overflow-scrolling: touch; }
        }
      `}</style>

      {profile && <EmployeeProfileModal employee={profile} onClose={()=>setProfile(null)} isBoss={isBoss}/>}
      {showAdd && (
        <div className="modal-backdrop" onClick={()=>setShowAdd(false)}>
          <div className="modal" onClick={e=>e.stopPropagation()}>
            <h3 style={{fontSize:24,marginBottom:20}}>Add employee</h3>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Full name</label><input placeholder="e.g. Amira Hissein"/></div>
              <div className="field"><label>Email</label><input type="email"/></div>
              <div className="field"><label>Phone</label><input/></div>
              <div className="field"><label>Role</label><select><option>employee</option><option>production_manager</option><option>accountant</option></select></div>
              <div className="field"><label>Department</label><select>{DEPARTMENTS.map(d=><option key={d}>{d}</option>)}</select></div>
              <div className="field"><label>Salary (FCFA)</label><input type="number" defaultValue="180000"/></div>
              <div className="field"><label>Start date</label><input type="date" defaultValue={new Date().toISOString().slice(0, 10)} /></div>
            </div>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:24}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setShowAdd(false)}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={()=>setShowAdd(false)}>Create (connect backend)</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function EmployeeProfileModal({ employee, onClose, isBoss }) {
  const [tab, setTab] = React.useState('personal');
  const [editTenure, setEditTenure] = React.useState(false);
  const [joinEdit, setJoinEdit] = React.useState('');
  const [modeEdit, setModeEdit] = React.useState('months');

  const [, refresh] = React.useState(0);
  React.useEffect(() => {
    const h = () => refresh((x) => x + 1);
    window.addEventListener('gh-admin-data', h);
    return () => window.removeEventListener('gh-admin-data', h);
  }, []);

  const live = React.useMemo(() => (window.EMPLOYEES || []).find(e => e.id === employee.id) || employee, [employee, refresh]);

  React.useEffect(() => {
    setJoinEdit(live.join_date || '');
    setModeEdit(live.tenure_display_mode || 'months');
  }, [live]);

  const warns = WARNINGS.filter(w => w.employee_id === employee.id);
  const leaves = LEAVES.filter(l => l.employee_id === employee.id);

  const saveTenure = () => {
    if (!window.__saveEmployeePatch || !joinEdit.trim()) return;
    window.__saveEmployeePatch(live.id, { join_date: joinEdit.trim(), tenure_display_mode: modeEdit });
    setEditTenure(false);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:640}}>
        <div style={{display:'flex',alignItems:'center',gap:16,marginBottom:24}}>
          <EmpFace emp={live} size={64} />
          <div style={{flex:1}}>
            <h3 style={{fontSize:26}}>{live.full_name}</h3>
            <div style={{fontSize:13,color:'var(--text-dim)',textTransform:'capitalize'}}>{live.role.replace('_',' ')} · {live.department}</div>
          </div>
          <StatusBadge status={live.status}/>
        </div>
        <div style={{display:'flex',gap:4,flexWrap:'wrap',borderBottom:'1px solid var(--border)',marginBottom:20}}>
          {['personal','hr','permissions'].map(t => (
            <button key={t} type="button" onClick={()=>setTab(t)} style={{padding:'10px 14px',fontSize:12,letterSpacing:'0.05em',textTransform:'uppercase',borderBottom:'2px solid '+(tab===t?'var(--accent)':'transparent'),color: tab===t?'var(--accent)':'var(--text-dim)',fontWeight:500}}>{t}</button>
          ))}
        </div>
        {tab==='personal' && (
          <>
            <div style={{marginBottom:14,padding:'12px 14px',background:'var(--accent-dim)',borderRadius:10,border:'1px solid var(--accent-border)'}}>
              <div style={{fontSize:11,color:'var(--text-dim)',marginBottom:4,textTransform:'uppercase',letterSpacing:'0.08em'}}>Time with Gelato House</div>
              <div style={{fontSize:22,fontFamily:"'Cormorant Garamond',serif"}}>{formatTenureSince(live.join_date, live.tenure_display_mode || 'months')}</div>
              <div style={{fontSize:11,color:'var(--text-dimmer)',marginTop:4}}>Since {fmtDate(live.join_date)} · view as {live.tenure_display_mode || 'months'}</div>
              {isBoss && (
                <button type="button" className="btn btn-ghost btn-sm" style={{ marginTop: 10 }} onClick={() => setEditTenure(true)}>
                  <Icon.Edit size={12} /> Edit start date · display
                </button>
              )}
            </div>
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:14}}>
              <InfoRow label="Email" value={live.email}/>
              <InfoRow label="Phone" value={live.phone}/>
              <InfoRow label="Salary" value={fmtNumber(live.salary)+' FCFA'}/>
              <InfoRow label="Start date (HR)" value={fmtDate(live.join_date)}/>
              <InfoRow label="Emergency" value={live.emergency_contact}/>
            </div>

            {editTenure && isBoss && (
              <div style={{ marginTop: 18, padding: 16, background: 'var(--card2)', borderRadius: 12, border: '1px solid var(--border)' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div className="field">
                    <label>Start date (first day)</label>
                    <input type="date" value={joinEdit} onChange={(e)=>setJoinEdit(e.target.value)} />
                  </div>
                  <div className="field">
                    <label>Show tenure as</label>
                    <select value={modeEdit} onChange={(e)=>setModeEdit(e.target.value)}>
                      <option value="months">Months · anniversaires</option>
                      <option value="weeks">Weeks</option>
                      <option value="days">Days</option>
                    </select>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button type="button" className="btn btn-primary btn-sm" onClick={saveTenure}>Save</button>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => setEditTenure(false)}>Cancel</button>
                </div>
              </div>
            )}
          </>
        )}
        {tab==='hr' && (
          <div style={{display:'flex',flexDirection:'column',gap:20}}>
            <div>
              <div style={{fontSize:11,letterSpacing:'0.15em',textTransform:'uppercase',color:'var(--text-dim)',marginBottom:10}}>Warnings ({warns.length})</div>
              {warns.length === 0 ? <div style={{fontSize:13,color:'var(--text-dim)'}}>No warnings on file.</div> :
                warns.map(w => (
                  <div key={w.id} style={{padding:12,background:'var(--card2)',borderRadius:8,marginBottom:6,display:'flex',gap:12,alignItems:'center'}}>
                    <StatusBadge status={w.severity}/>
                    <div style={{flex:1,fontSize:13}}>{w.reason}</div>
                    <div style={{fontSize:11,color:'var(--text-dim)'}}>{fmtDate(w.issued_date)}</div>
                  </div>
                ))
              }
            </div>
            <div>
              <div style={{fontSize:11,letterSpacing:'0.15em',textTransform:'uppercase',color:'var(--text-dim)',marginBottom:10}}>Leave history ({leaves.length})</div>
              {leaves.length === 0 ? <div style={{fontSize:13,color:'var(--text-dim)'}}>No leave requests.</div> :
                leaves.map(l => (
                  <div key={l.id} style={{padding:12,background:'var(--card2)',borderRadius:8,marginBottom:6,display:'flex',gap:12,alignItems:'center'}}>
                    <StatusBadge status={l.status}/>
                    <div style={{flex:1,fontSize:13}}>{fmtDate(l.start_date)} → {fmtDate(l.end_date)} · <span style={{color:'var(--text-dim)'}}>{l.reason}</span></div>
                  </div>
                ))
              }
            </div>
          </div>
        )}
        {tab==='permissions' && (
          <div style={{display:'flex',flexDirection:'column',gap:8}}>
            {FEATURE_KEYS.map(f => {
              const has = ROLE_FEATURES[live.role]?.[f.key];
              return (
                <div key={f.key} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'10px 12px',background:'var(--card2)',borderRadius:8}}>
                  <span style={{fontSize:13}}>{f.label}</span>
                  <span className={'badge ' + (has ? 'badge-green' : 'badge-muted')}>{has ? 'Included' : '—'}</span>
                </div>
              );
            })}
          </div>
        )}
        <button type="button" className="btn btn-primary" style={{ width: '100%', marginTop: 20 }} onClick={onClose}>Close</button>
      </div>
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div>
      <div style={{fontSize:10,letterSpacing:'0.15em',textTransform:'uppercase',color:'var(--text-dim)',marginBottom:4,fontFamily:'JetBrains Mono'}}>{label}</div>
      <div style={{fontSize:13}}>{value}</div>
    </div>
  );
}

Object.assign(window, { Employees });
