function daysBetween(a, b) { return Math.round((b - a) / 86400000); }
function certStatus(expiresAt) {
  const days = daysBetween(new Date(), expiresAt);
  if (days < 0) return 'expired';
  if (days <= 30) return 'expiring';
  return 'active';
}
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function CertificateDialog({ record, onClose, onIssue, onRenew }) {
  const { Badge, Button } = window.TheUpperDeckDesignSystem_4d3294;
  if (!record) return null;
  const cert = record.certificate;
  const issuedAt = cert ? new Date(cert.issued_at) : null;
  const expiresAt = cert ? new Date(cert.expires_at) : null;
  const status = cert ? certStatus(expiresAt) : null;
  const url = cert ? 'https://theupperdeck.example/certificate/' + cert.id : '';
  const statusTone = { active: 'success', expiring: 'warning', expired: 'error' };
  const statusLabel = { active: 'Active', expiring: 'Expiring soon', expired: 'Expired' };
  return (
    <window.TheUpperDeckDesignSystem_4d3294.Dialog open={!!record} title="Certificate" onClose={onClose} footer={<>
      <Button variant="ghost" onClick={onClose}>Close</Button>
      {!cert && <Button onClick={() => onIssue(record)}>Issue certificate</Button>}
      {cert && <Button variant="secondary" onClick={() => onRenew(cert.id)}>Renew (reset 1yr)</Button>}
    </>}>
      {cert ? (
        <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
          <div style={{ background: 'linear-gradient(135deg, #0E2247 0%, #173463 100%)', borderRadius: 8, padding: 6, width: 300, flexShrink: 0 }}>
            <div style={{ border: '1.5px solid var(--orange-500)', borderRadius: 6, padding: '26px 20px', textAlign: 'center', position: 'relative' }}>
              <div style={{ fontSize: 10, letterSpacing: 1, color: 'var(--orange-500)', textTransform: 'uppercase', fontWeight: 700 }}>Certificate of Completion</div>
              <div style={{ width: 44, height: 2, background: 'var(--orange-500)', margin: '12px auto' }} />
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 700, color: 'white' }}>{record.name}</div>
              <div style={{ color: 'rgba(255,255,255,0.6)', fontSize: 11, margin: '8px 0' }}>has successfully completed</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'white' }}>{record.eventTitle}</div>
              <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 11, margin: '4px 0 18px' }}>{issuedAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
              <div style={{ borderTop: '1px solid rgba(255,255,255,0.35)', paddingTop: 6, fontSize: 12, fontWeight: 600, display: 'inline-block', color: 'white' }}>{record.facilitator || 'The Upper Deck'}</div>
              <div style={{ fontSize: 10, color: 'var(--orange-500)', textTransform: 'uppercase', letterSpacing: 1 }}>Accreditor</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(255,255,255,0.5)', marginTop: 14 }}>Ref: {cert.id}</div>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1, color: 'rgba(255,255,255,0.35)', marginTop: 8 }}>THE UPPER DECK</div>
              <img src={'https://api.qrserver.com/v1/create-qr-code/?size=140x140&margin=0&color=FFFFFF&bgcolor=0E2247&data=' + encodeURIComponent(url)} alt="Certificate verification QR code" style={{ position: 'absolute', right: 12, bottom: 12, width: 40, height: 40 }} />
            </div>
          </div>
          <div style={{ flex: '1 1 220px', display: 'flex', flexDirection: 'column', gap: 10, fontSize: 'var(--text-sm)' }}>
            <div><span style={{ color: 'var(--text-muted)' }}>Attendee: </span><strong>{record.name}</strong></div>
            <div><span style={{ color: 'var(--text-muted)' }}>Email: </span>{record.email}</div>
            <div><span style={{ color: 'var(--text-muted)' }}>Event: </span>{record.eventTitle}</div>
            <div><span style={{ color: 'var(--text-muted)' }}>Issued: </span>{issuedAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
            <div><span style={{ color: 'var(--text-muted)' }}>Expires: </span>{expiresAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
            <div><Badge tone={statusTone[status]}>{statusLabel[status]}</Badge></div>
            <div style={{ borderTop: '1px solid var(--border-default)', paddingTop: 10, marginTop: 4 }}>
              <div style={{ color: 'var(--text-muted)', marginBottom: 6 }}>Public certificate link</div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <img src={'https://api.qrserver.com/v1/create-qr-code/?size=100x100&margin=0&data=' + encodeURIComponent(url)} alt="Certificate QR code" style={{ width: 64, height: 64 }} />
                <a href={url} target="_blank" rel="noreferrer" style={{ fontSize: 'var(--text-xs)', wordBreak: 'break-all', color: 'var(--brand-primary)' }}>{url}</a>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ fontSize: 'var(--text-sm)', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div><span style={{ color: 'var(--text-muted)' }}>Attendee: </span><strong>{record.name}</strong></div>
          <div><span style={{ color: 'var(--text-muted)' }}>Email: </span>{record.email}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Event: </span>{record.eventTitle}</div>
          <p style={{ color: 'var(--text-muted)' }}>No certificate issued yet for this attendee.</p>
        </div>
      )}
    </window.TheUpperDeckDesignSystem_4d3294.Dialog>
  );
}

function CertificatesScreen({ adminId }) {
  const { Badge } = window.TheUpperDeckDesignSystem_4d3294;
  const { CustomSelect, SearchInput, Btn, ColumnPicker, useColumnPrefs } = window.UdUI;
  const CERT_COLUMNS = [{ key: 'attendee', label: 'Attendee', locked: true }, { key: 'event', label: 'Event' }, { key: 'expires', label: 'Expires' }, { key: 'status', label: 'Status' }];
  const [certCols, setCertCols] = useColumnPrefs('certificates', CERT_COLUMNS.map((c) => c.key));
  const [rowsRaw, setRowsRaw] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [statusFilter, setStatusFilter] = React.useState('');
  const [eventFilter, setEventFilter] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [viewing, setViewing] = React.useState(null);
  const [page, setPage] = React.useState(1);
  const PAGE_SIZE = 20;

  function reload() {
    setLoading(true);
    window.fetchCertEligibleLive().then((data) => { setRowsRaw(data); setLoading(false); });
  }
  React.useEffect(() => { reload(); }, []);

  const allRows = rowsRaw.map((r) => ({ ...r, status: r.certificate ? certStatus(new Date(r.certificate.expires_at)) : 'none' }));
  const mainEvents = Array.from(new Map(allRows.map((r) => [r.mainId, r.mainTitle])).entries()).map(([value, label]) => ({ value, label }));

  const rows = allRows.filter((r) => {
    if (statusFilter && r.status !== statusFilter) return false;
    if (eventFilter && r.mainId !== eventFilter) return false;
    if (search && (r.name + ' ' + r.eventTitle).toLowerCase().indexOf(search.toLowerCase()) === -1) return false;
    return true;
  });
  const totalPages = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
  const pageSafe = Math.min(page, totalPages);
  const pageRows = rows.slice((pageSafe - 1) * PAGE_SIZE, pageSafe * PAGE_SIZE);

  async function issue(record) {
    await window.issueCertificateLive(record.ticketId, record.subEventId, adminId);
    reload();
    setViewing(null);
  }
  async function renew(certId) {
    await window.renewCertificateLive(certId);
    reload();
    setViewing(null);
  }

  const statusTone = { active: 'success', expiring: 'warning', expired: 'error', none: 'neutral' };
  const statusLabel = { active: 'Active', expiring: 'Expiring soon', expired: 'Expired', none: 'Not issued' };

  return (
    <div>
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, alignItems: 'center', flexWrap: 'wrap' }}>
        <SearchInput value={search} onChange={setSearch} placeholder={'Search attendee, event…'} width={220} />
        <CustomSelect value={eventFilter} onChange={setEventFilter} placeholder="All events" width={200} options={mainEvents} />
        <CustomSelect value={statusFilter} onChange={setStatusFilter} placeholder="All statuses" width={170} options={[{ value: 'none', label: 'Not issued' }, { value: 'active', label: 'Active' }, { value: 'expiring', label: 'Expiring soon' }, { value: 'expired', label: 'Expired' }]} />
        <ColumnPicker columns={CERT_COLUMNS} visible={certCols} onChange={setCertCols} />
      </div>
      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto' }}>
        {loading && <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>Loading…</div>}
        {!loading && <table style={{ width: '100%', minWidth: 780, borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
          <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
            {certCols.includes('attendee') && <th style={{ padding: '12px 16px' }}>Attendee</th>}
            {certCols.includes('event') && <th style={{ padding: '12px 16px' }}>Event</th>}
            {certCols.includes('expires') && <th style={{ padding: '12px 16px' }}>Expires</th>}
            {certCols.includes('status') && <th style={{ padding: '12px 16px' }}>Status</th>}
            <th style={{ padding: '12px 16px' }}></th>
          </tr></thead>
          <tbody>
            {pageRows.map((r) => (
              <tr key={r.ticketId} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                {certCols.includes('attendee') && <td style={{ padding: '14px 16px', fontWeight: 600 }}>{r.name}</td>}
                {certCols.includes('event') && <td style={{ padding: '14px 16px', color: 'var(--text-secondary)' }}>{r.eventTitle}</td>}
                {certCols.includes('expires') && <td style={{ padding: '14px 16px', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', whiteSpace: 'nowrap' }}>{r.certificate ? new Date(r.certificate.expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '\u2014'}</td>}
                {certCols.includes('status') && <td style={{ padding: '14px 16px' }}><Badge tone={statusTone[r.status]}>{statusLabel[r.status]}</Badge></td>}
                <td style={{ padding: '14px 16px', textAlign: 'right', whiteSpace: 'nowrap' }}><Btn size="sm" variant="secondary" onClick={() => setViewing(r)}>View</Btn></td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan={5} style={{ padding: 16, color: 'var(--text-muted)' }}>No checked-in, paid attendees match this filter.</td></tr>}
          </tbody>
        </table>}
      </div>
      {rows.length > 0 && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>
          <span>{rows.length} attendee{rows.length === 1 ? '' : 's'} eligible {'·'} checked-in &amp; paid</span>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <window.UdUI.Btn size="sm" variant="secondary" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={pageSafe === 1}>Prev</window.UdUI.Btn>
            <span>Page {pageSafe} of {totalPages}</span>
            <window.UdUI.Btn size="sm" variant="secondary" onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={pageSafe === totalPages}>Next</window.UdUI.Btn>
          </div>
        </div>
      )}
      <CertificateDialog record={viewing} onClose={() => setViewing(null)} onIssue={issue} onRenew={renew} />
    </div>
  );
}
window.CertificatesScreen = CertificatesScreen;
