// Staff.jsx — Staff & PINs CRUD.

const ROLES = ['Admin', 'Crew'];
const ROLE_BG = {
  Admin: '#EDE9FE',
  Crew:  '#E0F2FE',
};
const ROLE_FG = {
  Admin: '#5B21B6',
  Crew:  '#075985',
};

const Staff = () => {
  const [staff, setStaff] = usePersistent('portal_staff_v3', window.SAMPLE_STAFF);
  const [editing, setEditing] = useState(null); // staff object or 'new'
  const [revealId, setRevealId] = useState(null);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');
  const [toast, setToast] = useState('');

  const visible = staff.filter(s => {
    if (search && !s.name.toLowerCase().includes(search.toLowerCase())) return false;
    if (roleFilter !== 'all' && s.role !== roleFilter) return false;
    return true;
  });

  const save = (s) => {
    if (s.id && staff.some(x => x.id === s.id)) {
      setStaff(st => st.map(x => x.id === s.id ? s : x));
      setToast('Staff updated');
    } else {
      const id = 's-' + Date.now();
      setStaff(st => [...st, { ...s, id }]);
      setToast('Staff added');
    }
    setEditing(null);
  };

  const remove = (id) => {
    if (!confirm('Remove this staff member? Their past activity is preserved.')) return;
    setStaff(st => st.filter(x => x.id !== id));
    setToast('Staff removed');
  };

  const lastLogins = ['11 min ago','1h ago','3h ago','Yesterday','2 days ago','Today, 9:04','Today, 11:32','Today, 8:12'];

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1280 }}>
      <div className="portal-page-header">
        <div>
          <h1 className="portal-page-title">Staff & PINs</h1>
          <div className="portal-page-subtitle">{staff.length} people · 4-digit PINs unlock the iPad app at clock-in.</div>
        </div>
        <PBtn variant="primary" icon="plus" onClick={() => setEditing('new')}>Add staff</PBtn>
      </div>

      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 16 }}>
        <div style={{ position: 'relative', flex: 1, maxWidth: 280 }}>
          <PIcon name="search" size={14} color="var(--fg-3)" style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)' }} />
          <input className="portal-input" placeholder="Search by name…" value={search} onChange={e => setSearch(e.target.value)} style={{ paddingLeft: 32, height: 34 }} />
        </div>
        <div style={{ display: 'inline-flex', background: 'var(--bg-sunken)', borderRadius: 8, padding: 3 }}>
          {[{ id: 'all', label: 'All' }, ...ROLES.map(r => ({ id: r, label: r }))].map(opt => (
            <button key={opt.id} onClick={() => setRoleFilter(opt.id)} style={{
              padding: '6px 12px',
              background: roleFilter === opt.id ? '#FFFFFF' : 'transparent',
              border: 'none',
              borderRadius: 6,
              fontSize: 12.5,
              fontWeight: roleFilter === opt.id ? 600 : 500,
              color: roleFilter === opt.id ? 'var(--fg-1)' : 'var(--fg-2)',
              cursor: 'pointer',
              boxShadow: roleFilter === opt.id ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
            }}>{opt.label}</button>
          ))}
        </div>
      </div>

      <div className="portal-card">
        <table className="portal-table">
          <thead>
            <tr>
              <th>Person</th>
              <th style={{ width: 110 }}>Role</th>
              <th style={{ width: 140 }}>PIN</th>
              <th style={{ width: 160 }}>Last login</th>
              <th style={{ width: 90 }}></th>
            </tr>
          </thead>
          <tbody>
            {visible.map((s, i) => (
              <tr key={s.id}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <PAvatar staff={s} size={28} />
                    <span style={{ fontWeight: 500 }}>{s.name}</span>
                  </div>
                </td>
                <td>
                  {s.role && (
                    <span style={{
                      display: 'inline-block',
                      padding: '3px 9px',
                      background: ROLE_BG[s.role] || 'var(--bg-sunken)',
                      color: ROLE_FG[s.role] || 'var(--fg-2)',
                      borderRadius: 999,
                      fontSize: 11.5,
                      fontWeight: 600,
                    }}>{s.role}</span>
                  )}
                </td>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ fontFamily: "ui-monospace, 'SF Mono', Menlo, monospace", fontSize: 13, letterSpacing: 2, color: 'var(--fg-1)' }}>
                      {revealId === s.id ? s.pin : '••••'}
                    </span>
                    <button onClick={() => setRevealId(revealId === s.id ? null : s.id)} style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>
                      {revealId === s.id ? 'Hide' : 'Reveal'}
                    </button>
                  </div>
                </td>
                <td style={{ fontSize: 12, color: 'var(--fg-2)' }}>{lastLogins[i % lastLogins.length]}</td>
                <td>
                  <div className="row-actions">
                    <button onClick={() => setEditing(s)} title="Edit"><PIcon name="edit" size={13} /></button>
                    <button onClick={() => remove(s.id)} title="Remove"><PIcon name="trash" size={13} /></button>
                  </div>
                </td>
              </tr>
            ))}
            {visible.length === 0 && (
              <tr><td colSpan={5} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>No staff match your filter.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {editing && (
        <StaffEditor
          initial={editing === 'new' ? null : editing}
          onClose={() => setEditing(null)}
          onSave={save}
          existingPins={staff.filter(x => editing === 'new' || x.id !== editing.id).map(x => x.pin)}
        />
      )}

      <PToast message={toast} open={!!toast} onClose={() => setToast('')} />
    </div>
  );
};

const StaffEditor = ({ initial, onClose, onSave, existingPins }) => {
  const [name, setName] = useState(initial?.name || '');
  const [role, setRole] = useState(initial?.role || 'Crew');
  const [pin, setPin]   = useState(initial?.pin || '');
  const [color, setColor] = useState(initial?.color || '#2563EB');

  const colors = ['#2563EB','#DB2777','#059669','#EA580C','#7C3AED','#0891B2','#CA8A04','#BE123C','#475569'];
  const initials = name.trim().split(/\s+/).map(w => w[0]).join('').slice(0,2).toUpperCase();

  const pinValid = /^\d{4}$/.test(pin);
  const pinTaken = existingPins.includes(pin);
  const canSave = name.trim() && pinValid && !pinTaken;

  const generatePin = () => {
    let p;
    do { p = String(Math.floor(1000 + Math.random() * 9000)); }
    while (existingPins.includes(p));
    setPin(p);
  };

  const handleSave = () => {
    if (!canSave) return;
    onSave({ ...(initial || {}), id: initial?.id, name: name.trim(), role, pin, color, initials });
  };

  return (
    <PModal open onClose={onClose} title={initial ? `Edit ${initial.name}` : 'Add staff'} width={460}>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: color, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 500, fontSize: 22 }}>
            {initials || '?'}
          </div>
          <div style={{ flex: 1 }}>
            <Label>Name</Label>
            <input className="portal-input" placeholder="First name" value={name} onChange={e => setName(e.target.value)} autoFocus style={{ height: 36 }} />
          </div>
        </div>

        <div>
          <Label>Role</Label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {ROLES.map(r => (
              <button key={r} onClick={() => setRole(r)} style={{
                padding: '7px 14px',
                background: role === r ? (ROLE_BG[r] || 'var(--bg-sunken)') : 'var(--bg-sunken)',
                color: role === r ? (ROLE_FG[r] || 'var(--fg-1)') : 'var(--fg-2)',
                border: '1px solid ' + (role === r ? (ROLE_FG[r] || 'var(--fg-1)') + '40' : 'transparent'),
                borderRadius: 999,
                fontSize: 12.5,
                fontWeight: role === r ? 600 : 500,
                cursor: 'pointer',
              }}>{r}</button>
            ))}
          </div>
        </div>

        <div>
          <Label>Avatar color</Label>
          <div style={{ display: 'flex', gap: 6 }}>
            {colors.map(c => (
              <button key={c} onClick={() => setColor(c)} style={{
                width: 24, height: 24, borderRadius: 999, background: c,
                boxShadow: color === c ? '0 0 0 2px #fff, 0 0 0 4px var(--fg-1)' : 'none',
              }} />
            ))}
          </div>
        </div>

        <div>
          <Label>4-digit PIN</Label>
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              className="portal-input"
              value={pin}
              onChange={e => { const v = e.target.value.replace(/\D/g, '').slice(0,4); setPin(v); }}
              placeholder="••••"
              style={{
                fontFamily: "ui-monospace, 'SF Mono', Menlo, monospace",
                fontSize: 16, letterSpacing: 6, textAlign: 'center',
                height: 40, width: 120,
              }}
            />
            <PBtn variant="secondary" size="sm" onClick={generatePin}>Generate</PBtn>
          </div>
          {pin && !pinValid && <div style={{ fontSize: 11.5, color: '#8B2A1A', marginTop: 6 }}>PIN must be exactly 4 digits</div>}
          {pinTaken && <div style={{ fontSize: 11.5, color: '#8B2A1A', marginTop: 6 }}>That PIN is already in use</div>}
        </div>
      </div>
      <div style={{ padding: '12px 18px', borderTop: '1px solid var(--border-2)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
        <PBtn variant="primary" disabled={!canSave} onClick={handleSave}>{initial ? 'Save changes' : 'Add staff'}</PBtn>
      </div>
    </PModal>
  );
};

window.Staff = Staff;
