/* global React, API, useApp */
const { useState, useEffect, useCallback } = React;

const BASIS_LABELS = {
  legitimate_interest: 'Art. 6(1)(f) — Legitimate interest',
  contract:            'Art. 6(1)(b) — Performance of contract',
  legal_obligation:    'Art. 6(1)(c) — Legal obligation',
  vital_interests:     'Art. 6(1)(d) — Vital interests',
  public_task:         'Art. 6(1)(e) — Public task',
  consent:             'Art. 6(1)(a) — Consent',
};

const DEFAULTS = [
  {
    name: 'Contact form',
    purpose: 'Responding to incoming enquiries and evaluating potential engagements',
    lawful_basis: 'legitimate_interest',
    data_categories: 'Name, business email address, company name, enquiry text, topic',
    data_subjects: 'Prospective clients',
    retention: '2 years from last contact; deleted on request',
    processors: 'Cloudflare (form spam protection / email routing), Resend (email delivery)',
    transfers_outside_eea: 1,
    transfer_safeguard: 'EU SCCs + Cloudflare DPA + Resend DPA',
    notes: '',
  },
  {
    name: 'Client portal accounts',
    purpose: 'Providing secure access to the client portal (invoices, documents, account management)',
    lawful_basis: 'contract',
    data_categories: 'Name, business email address, phone number, company name and address, passkey credential IDs',
    data_subjects: 'Contacts of client companies',
    retention: 'Duration of business relationship + 7 years (AWR art. 52)',
    processors: 'Cloudflare (D1 database, R2 storage, Pages hosting)',
    transfers_outside_eea: 1,
    transfer_safeguard: 'EU SCCs + Cloudflare DPA (EU-West Amsterdam as primary region)',
    notes: '',
  },
  {
    name: 'Invoice administration',
    purpose: 'Issuing invoices, bookkeeping, and fiscal compliance',
    lawful_basis: 'legal_obligation',
    data_categories: 'Company name, address, VAT number, invoice contact name and email, invoice and line-item data',
    data_subjects: 'Billing contacts of client companies',
    retention: '7 years from the end of the fiscal year (AWR art. 52)',
    processors: 'Cloudflare (D1 database, R2 storage for PDF invoices)',
    transfers_outside_eea: 1,
    transfer_safeguard: 'EU SCCs + Cloudflare DPA',
    notes: 'Statutory retention obligation — deletion before 7 years is not permitted.',
  },
  {
    name: 'Transactional email delivery',
    purpose: 'Sending invoices, magic-link logins, approval requests, and confirmations',
    lawful_basis: 'contract',
    data_categories: 'Email address; invoice data (as attachment)',
    data_subjects: 'Client contacts, prospective clients',
    retention: 'Resend delivery logs: 30 days; content governed by the related activity',
    processors: 'Resend (WorkOS, Inc., US) — EU SCCs',
    transfers_outside_eea: 1,
    transfer_safeguard: 'EU SCCs + Resend DPA (resend.com/legal/dpa)',
    notes: '',
  },
];

const EMPTY_FORM = {
  name: '', purpose: '', lawful_basis: 'contract', data_categories: '',
  data_subjects: '', retention: '', processors: '',
  transfers_outside_eea: false, transfer_safeguard: '', notes: '',
};

function printRegister(activities) {
  const w = window.open('', '_blank');
  const date = new Date().toLocaleDateString('nl-NL', { day: '2-digit', month: 'long', year: 'numeric' });
  const rows = activities.map((a, i) => `
    <tr>
      <td style="text-align:center;color:#666;font-family:monospace;font-size:7.5pt;background:#f4f5fc">${i + 1}</td>
      <td><strong style="color:#0B1117">${a.name}</strong>${a.notes ? `<div style="font-size:7pt;color:#888;margin-top:2px">${a.notes}</div>` : ''}</td>
      <td>${a.purpose || '—'}</td>
      <td>${BASIS_LABELS[a.lawful_basis] || a.lawful_basis || '—'}</td>
      <td>${a.data_categories || '—'}</td>
      <td>${a.data_subjects || '—'}</td>
      <td>${a.retention || '—'}</td>
      <td>${a.processors || '—'}</td>
      <td>${a.transfers_outside_eea ? `Yes${a.transfer_safeguard ? `<br><em style="font-size:7pt;color:#555">${a.transfer_safeguard}</em>` : ''}` : 'No'}</td>
    </tr>`).join('');

  w.document.write(`<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Processing Register Art. 30 GDPR — Lake-Project</title>
<style>
@page { size: A4 landscape; margin: 12mm 15mm; }
*, *::before, *::after { box-sizing: border-box; }
body { font-family: system-ui,-apple-system,sans-serif; font-size: 8.5pt; color: #1a1a1a; margin: 0; padding: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
.doc-header { display: flex; justify-content: space-between; align-items: flex-end; border-bottom: 2pt solid #0B1117; padding-bottom: 10px; margin-bottom: 14px; }
.doc-header h1 { font-size: 14pt; margin: 0 0 3px; color: #0B1117; }
.doc-header .sub { font-size: 7.5pt; color: #555; font-family: monospace; }
.doc-header .meta { text-align: right; font-size: 7.5pt; color: #777; font-family: monospace; line-height: 1.7; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; }
col.c0 { width: 26px; }
col.c1 { width: 13%; }
col.c2 { width: 13%; }
col.c3 { width: 15%; }
col.c4 { width: 14%; }
col.c5 { width: 10%; }
col.c6 { width: 10%; }
col.c7 { width: 14%; }
col.c8 { width: 9%; }
th { background: #0B1117; color: #6FE3D1; padding: 5px 8px; text-align: left; font-size: 7pt; letter-spacing: 0.06em; text-transform: uppercase; border-right: 1px solid #1a2535; }
th:last-child { border-right: none; }
td { padding: 7px 8px; border-bottom: 1px solid #e8eaf0; border-right: 1px solid #f0f0f4; vertical-align: top; line-height: 1.45; font-size: 8pt; }
td:last-child { border-right: none; }
tr:nth-child(even) td { background: #f8f9fc; }
.footer { margin-top: 12px; padding-top: 8px; border-top: 1px solid #dde; font-size: 7pt; color: #888; font-family: monospace; display: flex; justify-content: space-between; }
.print-btn { display: block; margin-bottom: 14px; padding: 8px 18px; background: #0B1117; color: #6FE3D1; border: 1px solid #6FE3D1; border-radius: 3px; cursor: pointer; font-size: 10pt; }
@media print { .print-btn { display: none; } }
</style>
</head>
<body>
<button class="print-btn" onclick="window.print()">Print / Save as PDF (A4 landscape)</button>
<div class="doc-header">
  <div>
    <div class="sub">Lake Project · KvK 29816688 · Rotterdam, Netherlands · hello@lake-project.com</div>
    <h1>Processing Register — Art. 30 GDPR / AVG</h1>
    <div class="sub">Data controller: Alexander van der Plas · lake-project.com</div>
  </div>
  <div class="meta">
    <div>Version: ${date}</div>
    <div>${activities.length} processing activit${activities.length === 1 ? 'y' : 'ies'}</div>
    <div>Internal document — not for public distribution</div>
  </div>
</div>
<table>
<colgroup>
  <col class="c0"><col class="c1"><col class="c2"><col class="c3">
  <col class="c4"><col class="c5"><col class="c6"><col class="c7"><col class="c8">
</colgroup>
<thead>
<tr>
  <th>#</th>
  <th>Processing activity</th>
  <th>Purpose</th>
  <th>Lawful basis (Art. 6)</th>
  <th>Categories of personal data</th>
  <th>Data subjects</th>
  <th>Retention period</th>
  <th>Sub-processors</th>
  <th>Transfer outside EEA</th>
</tr>
</thead>
<tbody>${rows || '<tr><td colspan="9" style="text-align:center;padding:20px;color:#aaa;font-style:italic">No activities recorded</td></tr>'}</tbody>
</table>
<div class="footer">
  <span>Art. 30 GDPR processing register — Lake-Project</span>
  <span>Generated ${date} · Confidential</span>
</div>
</body></html>`);
  w.document.close();
}

function ActivityModal({ activity, onSave, onClose }) {
  const [form, setForm] = useState(activity
    ? { ...activity, transfers_outside_eea: !!activity.transfers_outside_eea }
    : { ...EMPTY_FORM });
  const [busy, setBusy] = useState(false);
  const { toast } = useApp();
  const f = k => e => setForm(p => ({ ...p, [k]: e.target.value }));
  const fBool = k => e => setForm(p => ({ ...p, [k]: e.target.checked }));

  async function save(e) {
    e.preventDefault(); setBusy(true);
    try {
      const result = activity?.id
        ? await API.put(`/art30/${activity.id}`, form)
        : await API.post('/art30', form);
      onSave(result);
    } catch (ex) {
      toast(ex?.error || 'Error saving', 'error');
    } finally { setBusy(false); }
  }

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{ maxWidth: 660, width: '90%', maxHeight: '88vh', overflowY: 'auto' }}>
        <div className="modal-head">
          <span className="modal-title">{activity?.id ? 'Edit processing activity' : 'Add processing activity'}</span>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <form onSubmit={save}>
          <div className="modal-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
            <div className="field" style={{ gridColumn: '1/-1' }}>
              <label className="field-label">Activity name *</label>
              <input className="field-input" required value={form.name} onChange={f('name')} placeholder="e.g. Contact form handling" />
            </div>
            <div className="field" style={{ gridColumn: '1/-1' }}>
              <label className="field-label">Purpose</label>
              <textarea className="field-input" rows={2} value={form.purpose} onChange={f('purpose')} placeholder="Why is this personal data processed?" style={{ resize: 'vertical' }} />
            </div>
            <div className="field">
              <label className="field-label">Lawful basis</label>
              <select className="field-select" value={form.lawful_basis} onChange={f('lawful_basis')}>
                {Object.entries(BASIS_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Data subjects</label>
              <input className="field-input" value={form.data_subjects} onChange={f('data_subjects')} placeholder="e.g. Client contacts, prospective clients" />
            </div>
            <div className="field" style={{ gridColumn: '1/-1' }}>
              <label className="field-label">Categories of personal data</label>
              <textarea className="field-input" rows={2} value={form.data_categories} onChange={f('data_categories')} placeholder="e.g. Name, email, company name, phone number" style={{ resize: 'vertical' }} />
            </div>
            <div className="field">
              <label className="field-label">Retention period</label>
              <input className="field-input" value={form.retention} onChange={f('retention')} placeholder="e.g. 7 years (AWR art. 52)" />
            </div>
            <div className="field">
              <label className="field-label">Sub-processors</label>
              <input className="field-input" value={form.processors} onChange={f('processors')} placeholder="e.g. Cloudflare, Resend" />
            </div>
            <div className="field" style={{ gridColumn: '1/-1' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--fg-muted)' }}>
                <input type="checkbox" checked={form.transfers_outside_eea} onChange={fBool('transfers_outside_eea')} />
                Personal data transferred outside the EEA
              </label>
            </div>
            {form.transfers_outside_eea && (
              <div className="field" style={{ gridColumn: '1/-1' }}>
                <label className="field-label">Transfer safeguard</label>
                <input className="field-input" value={form.transfer_safeguard} onChange={f('transfer_safeguard')} placeholder="e.g. EU SCCs + Cloudflare DPA" />
              </div>
            )}
            <div className="field" style={{ gridColumn: '1/-1' }}>
              <label className="field-label">Notes</label>
              <textarea className="field-input" rows={2} value={form.notes} onChange={f('notes')} placeholder="Any additional context or caveats" style={{ resize: 'vertical' }} />
            </div>
          </div>
          <div style={{ padding: '12px 20px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <button type="button" className="btn btn--ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn--primary" disabled={busy}>{busy ? 'Saving…' : 'Save'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function Register() {
  const [activities, setActivities] = useState([]);
  const [modal, setModal]           = useState(null);
  const [loading, setLoading]       = useState(true);
  const { toast } = useApp();

  const load = useCallback(() => {
    setLoading(true);
    API.get('/art30')
      .then(r => { setActivities(r || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  useEffect(() => { load(); }, [load]);

  function handleSave() {
    setModal(null);
    load();
    toast('Activity saved');
  }

  async function handleDelete(a) {
    if (!confirm(`Delete "${a.name}"?`)) return;
    try {
      await API.del(`/art30/${a.id}`);
      setActivities(prev => prev.filter(x => x.id !== a.id));
      toast('Deleted');
    } catch (ex) { toast(ex?.error || 'Error', 'error'); }
  }

  async function seedDefaults() {
    if (!confirm(`Add ${DEFAULTS.length} default Lake-Project activities to the register?`)) return;
    try {
      for (const d of DEFAULTS) await API.post('/art30', d);
      load();
      toast(`${DEFAULTS.length} activities added`);
    } catch (ex) { toast(ex?.error || 'Error', 'error'); }
  }

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Processing register</h1>
          <div className="page-subtitle">Art. 30 GDPR/AVG — internal document</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {activities.length === 0 && !loading && (
            <button className="btn btn--ghost" onClick={seedDefaults}>Load defaults</button>
          )}
          <button className="btn btn--ghost" onClick={() => printRegister(activities)}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 4 }}>
              <polyline points="6 9 6 2 18 2 18 9" /><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2" /><rect x="6" y="14" width="12" height="8" />
            </svg>
            Print A4
          </button>
          <button className="btn btn--primary" onClick={() => setModal('add')}>+ Add activity</button>
        </div>
      </div>

      {loading ? (
        <div style={{ color: 'var(--fg-subtle)', padding: 24, fontSize: 13 }}>Loading…</div>
      ) : activities.length === 0 ? (
        <div className="card">
          <div style={{ padding: 32, textAlign: 'center' }}>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg)', marginBottom: 8 }}>No processing activities yet</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 20, maxWidth: 460, margin: '0 auto 20px', lineHeight: 1.6 }}>
              GDPR Art. 30 requires maintaining a record of all processing activities. Load Lake-Project's default activities or add your own.
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
              <button className="btn btn--ghost" onClick={seedDefaults}>Load Lake-Project defaults</button>
              <button className="btn btn--primary" onClick={() => setModal('add')}>Add manually</button>
            </div>
          </div>
        </div>
      ) : (
        <div className="card" style={{ margin: 0 }}>
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th style={{ width: 32 }}>#</th>
                  <th>Activity</th>
                  <th>Purpose</th>
                  <th>Lawful basis</th>
                  <th>Retention</th>
                  <th style={{ width: 80 }}>EEA transfer</th>
                  <th style={{ width: 64 }}></th>
                </tr>
              </thead>
              <tbody>
                {activities.map((a, i) => (
                  <tr key={a.id} onClick={() => setModal(a)} style={{ cursor: 'pointer' }}>
                    <td className="mono" style={{ color: 'var(--fg-subtle)', fontSize: 11, textAlign: 'center' }}>{i + 1}</td>
                    <td style={{ fontWeight: 500 }}>{a.name}</td>
                    <td style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{a.purpose || '—'}</td>
                    <td style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)' }}>
                      {BASIS_LABELS[a.lawful_basis] || a.lawful_basis || '—'}
                    </td>
                    <td style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{a.retention || '—'}</td>
                    <td>
                      {a.transfers_outside_eea
                        ? <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--warn)', background: 'rgba(245,158,11,0.1)', padding: '2px 6px', borderRadius: 2 }}>EEA</span>
                        : <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-faint)' }}>—</span>
                      }
                    </td>
                    <td onClick={e => e.stopPropagation()}>
                      <button className="btn btn--danger btn--sm" onClick={() => handleDelete(a)}>Del</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div style={{ padding: '10px 20px', borderTop: '1px solid var(--border)', fontSize: 11, color: 'var(--fg-subtle)', fontFamily: 'var(--font-mono)', display: 'flex', justifyContent: 'space-between' }}>
            <span>{activities.length} activit{activities.length === 1 ? 'y' : 'ies'} · Art. 30 GDPR · Internal document</span>
            <a href="/trust/vok" target="_blank" style={{ color: 'var(--signal)', fontSize: 11, fontFamily: 'var(--font-mono)' }}>VOK template ↗</a>
          </div>
        </div>
      )}

      {(modal === 'add' || (modal && typeof modal === 'object')) && (
        <ActivityModal
          activity={modal === 'add' ? null : modal}
          onSave={handleSave}
          onClose={() => setModal(null)}
        />
      )}
    </div>
  );
}
window.Register = Register;
