// Employees.jsx — Master Data › Employees. Operators & Riggers master records.
// Admin: full CRUD + certification editing. Other roles: view-only.

// Modal to record/renew an operator's certifications and their expiry dates.
function CertEditModal({ operator, onClose, onSave }) {
  const [rows, setRows] = React.useState(() => {
    const byCode = Object.fromEntries((operator.certs || []).map(c => [c.code, c.exp]));
    return CERT_LEGEND.map(l => ({ code: l.code, label: l.label, color: l.color, held: l.code in byCode, exp: byCode[l.code] || '' }));
  });

  const update = (code, patch) => setRows(rs => rs.map(r => r.code === code ? { ...r, ...patch } : r));
  const incomplete = rows.some(r => r.held && !r.exp);

  const save = () => {
    const certs = rows.filter(r => r.held && r.exp).map(r => ({ code: r.code, exp: r.exp }));
    onSave(certs);
  };

  return (
    <div className="install-modal" onClick={onClose}>
      <div className="install-modal__card" onClick={e => e.stopPropagation()} style={{maxWidth: 560, width: '94vw'}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14}}>
          <div style={{width: 44, height: 44, borderRadius: 10, background: 'var(--color-navy)', display: 'grid', placeItems: 'center', color: 'var(--color-yellow)', flexShrink: 0}}>
            <Shield size={20}/>
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontWeight: 700, fontSize: 17, color: 'var(--color-navy)'}}>Certifications — {operator.name}</div>
            <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 2}}>Tick each cert held and set its expiry date. Expired certs are hidden from booking; renewal reminders fire {CERT_RENEW_WINDOW_DAYS} days before.</div>
          </div>
          <button type="button" className="install-banner__close" onClick={onClose}><X size={18}/></button>
        </div>

        <div style={{display: 'flex', flexDirection: 'column', gap: 6, maxHeight: '52vh', overflowY: 'auto'}}>
          {rows.map(r => {
            const st = r.held && r.exp ? certState(r.exp) : null;
            const badge = st === 'expired' ? {t: 'Expired', c: 'var(--color-danger)', bg: 'rgba(239,68,68,0.1)'}
              : st === 'expiring' ? {t: 'Renew soon', c: '#b45309', bg: 'rgba(217,119,6,0.12)'}
              : st === 'valid' ? {t: 'Valid', c: '#15803d', bg: 'rgba(34,197,94,0.1)'} : null;
            return (
              <div key={r.code} style={{display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 8, border: '1px solid var(--color-grey-200)', background: r.held ? 'white' : 'var(--color-grey-50)'}}>
                <label style={{display: 'flex', alignItems: 'center', gap: 9, cursor: 'pointer', flex: 1, minWidth: 0}}>
                  <input type="checkbox" checked={r.held} onChange={e => update(r.code, { held: e.target.checked })} style={{width: 16, height: 16, accentColor: 'var(--color-navy)'}}/>
                  <span style={{width: 9, height: 9, borderRadius: '50%', background: r.color, flexShrink: 0}}/>
                  <span style={{fontWeight: 700, fontSize: 13, color: 'var(--color-navy)', minWidth: 42}}>{r.code}</span>
                  <span style={{fontSize: 12, color: 'var(--color-grey-500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>{r.label}</span>
                </label>
                {badge ? <span style={{fontSize: 10.5, fontWeight: 700, color: badge.c, background: badge.bg, padding: '2px 8px', borderRadius: 999, whiteSpace: 'nowrap'}}>{badge.t}</span> : null}
                <input type="date" value={r.exp} disabled={!r.held}
                  onChange={e => update(r.code, { exp: e.target.value })}
                  className="input" style={{width: 150, padding: '6px 8px', fontSize: 12, opacity: r.held ? 1 : 0.45}}/>
              </div>
            );
          })}
        </div>

        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginTop: 16}}>
          <span style={{fontSize: 12, color: incomplete ? 'var(--color-danger)' : 'var(--color-grey-500)'}}>
            {incomplete ? 'Set an expiry date for every ticked cert.' : 'Changes apply to booking immediately.'}
          </span>
          <div style={{display: 'flex', gap: 8}}>
            <button className="btn btn--ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn--primary" disabled={incomplete} onClick={save} style={{opacity: incomplete ? 0.5 : 1}}>Save certifications</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function EmployeesPage({ role }) {
  const [tab, setTab] = React.useState('operators');
  const [ops, setOps] = React.useState(OPERATORS);
  const [editOp, setEditOp] = React.useState(null);
  const isAdmin = role === 'Admin';

  return (
    <div className="page">
      <div className="note-banner">
        <HardHat size={16} style={{color: 'var(--color-navy)'}}/>
        <div>
          <strong>Employees</strong> — field crew master records: crane operators and riggers, with licences and live certifications. {isAdmin ? 'You can add, edit and renew certs.' : 'View-only — only Admin can edit employee records.'}
        </div>
      </div>

      <div className="tab-bar">
        <button className={"tab-btn " + (tab === 'operators' ? 'tab-btn--active' : '')} onClick={() => setTab('operators')}>
          <HardHat size={14}/> Operators ({OPERATORS.length})
        </button>
        <button className={"tab-btn " + (tab === 'riggers' ? 'tab-btn--active' : '')} onClick={() => setTab('riggers')}>
          <Hook size={14}/> Riggers ({RIGGERS.length})
        </button>
      </div>

      {tab === 'operators' ? (
        <div className="card">
          <div className="card__header">
            <div>
              <h3 className="card__title">Operators</h3>
              <div className="card__sub">Crane drivers · NIOSH/OPL licensed</div>
            </div>
            {isAdmin ? <button className="btn btn--primary"><Plus size={14}/> Add Operator</button> : <span className="restricted-tag"><Lock size={11}/> Admin only</span>}
          </div>
          <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
            <table className="table">
              <thead><tr><th>ID</th><th>Name</th><th>Phone</th><th>License</th><th>Certifications</th><th>Status</th><th></th></tr></thead>
              <tbody>
                {ops.map(o => {
                  const active = activeCerts(o.certs);
                  const expired = (o.certs || []).filter(c => certState(c.exp) === 'expired');
                  const soon = active.filter(c => certState(c.exp) === 'expiring').length;
                  return (
                  <tr key={o.id}>
                    <td style={{fontFamily: 'monospace', fontSize: 12}}>{o.id}</td>
                    <td style={{fontWeight: 600}}>{o.name}</td>
                    <td>{o.phone}</td>
                    <td style={{fontFamily: 'monospace', fontSize: 12}}>{o.license}</td>
                    <td style={{maxWidth: 320}}>
                      <div style={{display: 'flex', flexWrap: 'wrap', gap: 5, alignItems: 'center'}}>
                        {active.length === 0 ? <span style={{fontSize: 11, color: 'var(--color-grey-400)', fontStyle: 'italic'}}>None valid</span> : null}
                        {active.map(c => {
                          const exp = certState(c.exp) === 'expiring';
                          return (
                            <span key={c.code} title={(CERT_LABEL[c.code] || c.code) + ' · valid to ' + fmtCertDate(c.exp)}
                              style={{display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 999,
                                background: exp ? 'rgba(217,119,6,0.12)' : 'var(--color-grey-100)',
                                border: exp ? '1px solid rgba(217,119,6,0.5)' : '1px solid transparent',
                                fontSize: 10.5, fontWeight: 700, color: exp ? '#b45309' : 'var(--color-grey-700)', whiteSpace: 'nowrap'}}>
                              <span style={{width: 7, height: 7, borderRadius: '50%', background: CERT_COLOR[c.code] || '#999'}}/>
                              {c.code}
                            </span>
                          );
                        })}
                        {soon > 0 ? <span style={{fontSize: 10.5, color: '#b45309', fontWeight: 600}}>· {soon} renew soon</span> : null}
                        {expired.length > 0 ? <span title={expired.map(c => c.code + ' expired ' + fmtCertDate(c.exp)).join(', ')} style={{fontSize: 10.5, color: 'var(--color-danger)', fontWeight: 600}}>· {expired.length} expired</span> : null}
                      </div>
                    </td>
                    <td><span className={"status status--" + (o.status === 'On Job' ? 'orange' : 'green')}>{o.status}</span></td>
                    <td>{isAdmin ? <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12}} onClick={() => window.askAdminPassword('Edit operator certifications', () => setEditOp(o))}><Edit size={12}/></button> : null}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}

      {editOp ? (
        <CertEditModal
          operator={editOp}
          onClose={() => setEditOp(null)}
          onSave={(certs) => { setOps(prev => prev.map(o => o.id === editOp.id ? { ...o, certs } : o)); setEditOp(null); }}
        />
      ) : null}

      {tab === 'riggers' ? (
        <div className="card">
          <div className="card__header">
            <div>
              <h3 className="card__title">Riggers</h3>
              <div className="card__sub">Lift assistants · Slung-load certified</div>
            </div>
            {isAdmin ? <button className="btn btn--primary"><Plus size={14}/> Add Rigger</button> : <span className="restricted-tag"><Lock size={11}/> Admin only</span>}
          </div>
          <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
            <table className="table">
              <thead><tr><th>ID</th><th>Name</th><th>Phone</th><th>Cert</th><th>Status</th><th></th></tr></thead>
              <tbody>
                {RIGGERS.map(r => (
                  <tr key={r.id}>
                    <td style={{fontFamily: 'monospace', fontSize: 12}}>{r.id}</td>
                    <td style={{fontWeight: 600}}>{r.name}</td>
                    <td>{r.phone}</td>
                    <td style={{fontFamily: 'monospace', fontSize: 12}}>{r.cert}</td>
                    <td><span className={"status status--" + (r.status === 'On Job' ? 'orange' : 'green')}>{r.status}</span></td>
                    <td>{isAdmin ? <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12}} onClick={() => window.askAdminPassword('Edit master data record', () => {})}><Edit size={12}/></button> : null}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { EmployeesPage });
