// Cardholders page — extends home-redesign.html aesthetic, adds AI strip.

function GMPageCardholders({ customer, pushToast }) {
  const rows = window.GM_CARDHOLDERS[customer.id] || [];
  const [filter, setFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [onboarded, setOnboarded] = React.useState(false);

  const filtered = rows.filter(r => {
    if (filter === 'contractor' && r.type !== 'contractor') return false;
    if (filter === 'permanent'  && r.type !== 'permanent')  return false;
    if (filter === 'temporary'  && r.type !== 'temporary')  return false;
    if (query) {
      const q = query.toLowerCase();
      return r.name.toLowerCase().includes(q) || r.email.toLowerCase().includes(q) || r.id.toLowerCase().includes(q);
    }
    return true;
  });

  const handleOnboard = () => {
    setOnboarded(true);
    pushToast({
      title: 'Guardian onboarded 5 contractors',
      sub: 'Matched previous approval patterns · credentials issued',
      kind: 'ai',
    });
  };

  const pool = customer.pool;

  return (
    <>
      <div className="adm-page-header">
        <div>
          <h1 className="adm-page-title">Cardholders</h1>
          <p className="adm-page-sub">View, manage, and provision access credentials for {customer.name}.</p>
        </div>
        <div className="adm-page-actions">
          <button className="btn btn--ghost"><GMI.export/> Export</button>
          <button className="btn btn--primary"><GMI.plus/> Create cardholder</button>
        </div>
      </div>

      {!onboarded && (
        <GMAIStripSimple cta="Review and apply" onCta={handleOnboard}>
          <div style={{ fontWeight: 600, color: 'var(--ink)' }}>
            Guardian found <strong>5 contractors</strong> in your Acme HR sync that match previous approval patterns.
          </div>
          <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-3)', marginTop: 2 }}>
            Onboard them now · 30-day access · no manager approval needed per your policy.
          </div>
        </GMAIStripSimple>
      )}

      <div className="ch-stats">
        <div className="ch-stat card is-dark">
          <div className="ch-stat-eyebrow">Total cardholders</div>
          <div className="ch-stat-val">{customer.cardholders}</div>
          <span className="ch-stat-change">+4 this week</span>
        </div>
        <div className="ch-stat card">
          <div className="ch-stat-eyebrow">Active</div>
          <div className="ch-stat-val">{customer.cardholders - pool.invited}</div>
          <span className="ch-stat-change">{((customer.cardholders - pool.invited) / customer.cardholders * 100).toFixed(1)}%</span>
        </div>
        <div className="ch-stat card">
          <div className="ch-stat-eyebrow">Invited</div>
          <div className="ch-stat-val">{pool.invited}</div>
          <span className="ch-stat-change">of {pool.capacity} pool</span>
        </div>
        <div className="ch-stat card">
          <div className="ch-stat-eyebrow">Unassigned</div>
          <div className="ch-stat-val">{pool.available}</div>
          <span className="ch-stat-change">need credentials</span>
        </div>
      </div>

      <div className="ch-pool-banner card">
        <div className="ch-pool-banner-head">
          <h3>Credential pool</h3>
          <div className="ch-pool-banner-sub">{pool.capacity} total capacity</div>
        </div>
        <div className="ch-pool-banner-grid">
          {[
            ['Available', pool.available, 'is-available'],
            ['Invited',   pool.invited,   'is-invited'],
            ['Assigned',  pool.assigned,  'is-assigned'],
            ['Revoked',   pool.revoked,   'is-revoked'],
          ].map(([lbl, val, cls]) => (
            <div className="ch-pool-item" key={lbl}>
              <div className="ch-pool-label">{lbl}</div>
              <div className="ch-pool-bar">
                <div className={`ch-pool-bar-fill ${cls}`} style={{ width: `${(val / pool.capacity) * 100}%` }}/>
              </div>
              <div className="ch-pool-val">{val} <span className="ch-pool-val-of">/ {pool.capacity}</span></div>
            </div>
          ))}
        </div>
      </div>

      <div className="ch-table">
        <div className="ch-table-toolbar">
          <div className="ch-table-toolbar-left">
            <div className="ch-table-count"><strong>{filtered.length}</strong> cardholders</div>
            <div className="ch-filter-pills">
              {[['all','All'],['contractor','Contractor'],['permanent','Permanent'],['temporary','Temporary']].map(([k,l]) => (
                <button key={k} className={`ch-pill ${filter === k ? 'is-active' : ''}`} onClick={() => setFilter(k)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="ch-table-toolbar-right">
            <div className="ch-table-search">
              <GMI.search/>
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Filter cardholders…"/>
            </div>
            <button className="adm-icon-btn" title="Refresh"><GMI.refresh/></button>
            <button className="adm-icon-btn" title="Columns"><GMI.columns/></button>
          </div>
        </div>

        <table>
          <thead>
            <tr>
              <th style={{ width: 40 }}><input type="checkbox"/></th>
              <th>Cardholder</th>
              <th>Type</th>
              <th>Location</th>
              <th>Status</th>
              <th>User ID</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => (
              <tr key={r.id}>
                <td><input type="checkbox"/></td>
                <td>
                  <div className="ch-user">
                    <div className="ch-user-avatar">{r.initials}</div>
                    <div>
                      <div className="ch-user-name">{r.name}</div>
                      <div className="ch-user-email">{r.email}</div>
                    </div>
                  </div>
                </td>
                <td><span className={`type-tag is-${r.type}`}>{r.type}</span></td>
                <td style={{ color: 'var(--ink-3)', fontSize: 13 }}>{r.location}</td>
                <td><span className={`status-cell is-${r.status}`}>{r.status[0].toUpperCase() + r.status.slice(1)}</span></td>
                <td className="mono" style={{ color: 'var(--ink-3)', fontSize: 12 }}>{r.id}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

window.GMPageCardholders = GMPageCardholders;
