// Excavation archive — scan history, navigates to Dashboard for viewing

const ARCHIVE_API = 'https://r5vefiej3l.execute-api.eu-central-1.amazonaws.com/prod';
const ARCH_COG    = '7nffjheavp985k7b4bgug45jf4';

function archToken() {
  const last = localStorage.getItem(`CognitoIdentityServiceProvider.${ARCH_COG}.LastAuthUser`);
  if (last) { const t = localStorage.getItem(`CognitoIdentityServiceProvider.${ARCH_COG}.${last}.idToken`); if (t) return t; }
  return window.getIdToken ? window.getIdToken() : '';
}
async function archApi(method, path) {
  const res = await fetch(`${ARCHIVE_API}${path}`, { method, headers: { Authorization: `Bearer ${archToken()}` } });
  const d = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(d.error || `HTTP ${res.status}`);
  return d;
}

function getHistory() {
  try { return JSON.parse(localStorage.getItem('fossyl_job_history') || '[]'); } catch { return []; }
}
function fmtDate(iso) {
  if (!iso) return '—';
  try { return new Date(iso).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return iso.slice(0, 10); }
}
function fmtNum(n) { return n && n > 0 ? n.toLocaleString() : '—'; }

function ReportPage() {
  const { go }    = useNav();
  const { toast } = useToast();
  const [history,     setHistory]     = useState(getHistory);
  const [downloading, setDownloading] = useState(false);
  const [deleting,    setDeleting]    = useState(null); // job_id being confirmed

  const openReport = (jobId) => {
    localStorage.setItem('fossyl_active_job', jobId);
    go('report');
  };

  const handleDownload = async (jobId) => {
    setDownloading(true);
    try {
      const d = await archApi('GET', `/download/${jobId}`);
      window.location.href = d.download_url;
    } catch (e) { toast(e.message || 'Download failed', { tone: 'error' }); }
    finally { setDownloading(false); }
  };

  const handleShare = async (jobId) => {
    try {
      const d = await archApi('GET', `/download/${jobId}?view=1`);
      navigator.clipboard?.writeText(d.download_url).catch(() => {});
      toast('Link copied — valid 1 hour', { tone: 'success' });
    } catch (e) { toast(e.message || 'Failed', { tone: 'error' }); }
  };

  const handleDelete = (jobId) => {
    // Remove from localStorage history
    const updated = history.filter(j => j.job_id !== jobId);
    localStorage.setItem('fossyl_job_history', JSON.stringify(updated));
    // If this was the active job, clear it
    if (localStorage.getItem('fossyl_active_job') === jobId) {
      localStorage.removeItem('fossyl_active_job');
    }
    setHistory(updated);
    setDeleting(null);
    toast('Excavation removed from history', { tone: 'success' });
  };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '240px 1fr', background: 'var(--bg)' }}>
      <AccountSidebar current="reports" go={go}/>
      <div style={{ overflow: 'auto' }}>
        <AccountTopBar crumb={['app', 'excavations']}/>
        <div style={{ padding: '32px', maxWidth: 1180 }}>
          <SectionHeader
            number="R1"
            eyebrow="Excavation archive"
            title="Your reports."
            kicker="Click any completed scan to open the full interactive report. Download the self-contained HTML to keep it offline, forever."
          />

          {/* Delete confirmation modal */}
          {deleting && (
            <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', display: 'grid', placeItems: 'center', zIndex: 100 }}
                 onClick={() => setDeleting(null)}>
              <div onClick={e => e.stopPropagation()} style={{ width: 440, background: 'var(--bg)', border: '1px solid var(--rust-dim)', borderRadius: 3, padding: 28 }}>
                <div className="caps" style={{ color: 'var(--rust)', marginBottom: 12 }}>Remove excavation</div>
                <p style={{ fontSize: 13.5, color: 'var(--ink-dim)', lineHeight: 1.55, margin: '0 0 20px' }}>
                  This removes <span className="mono" style={{ color: 'var(--ink)' }}>{deleting.slice(0, 8)}</span> from your history.
                  The report file will expire per your plan retention. This cannot be undone.
                </p>
                <div className="row jc-e g-8">
                  <button className="btn" onClick={() => setDeleting(null)}>Cancel</button>
                  <button className="btn" style={{ borderColor: 'var(--rust-dim)', color: 'var(--rust)' }}
                    onClick={() => handleDelete(deleting)}>
                    Remove →
                  </button>
                </div>
              </div>
            </div>
          )}

          {history.length === 0 && (
            <div style={{ marginTop: 48, padding: '64px 0', textAlign: 'center', border: '1px solid var(--line)', borderRadius: 3, background: 'var(--bg-1)' }}>
              <div className="caps" style={{ marginBottom: 12 }}>No excavations yet</div>
              <h3 className="serif" style={{ fontSize: 26, fontWeight: 400, margin: '0 0 16px' }}>Run your first excavation →</h3>
              <p style={{ fontSize: 14, color: 'var(--ink-dim)', margin: '0 0 24px' }}>Upload a codebase ZIP + ZODB export to generate your first archaeological map.</p>
              <button className="btn btn-primary" onClick={() => go('upload')}>Start excavation →</button>
            </div>
          )}

          {history.length > 0 && (
            <div className="panel" style={{ marginTop: 32 }}>
              <div className="panel-h">
                <span className="caps">Excavation history</span>
                <button className="btn btn-sm" onClick={() => go('upload')}>New excavation →</button>
              </div>
              <table className="table">
                <thead>
                  <tr><th>Scan ID</th><th>Date</th><th>Status</th><th>Size</th><th>TTW scripts</th><th>Dependencies</th><th></th></tr>
                </thead>
                <tbody>
                  {history.map(j => (
                    <tr key={j.job_id} style={{ cursor: j.status === 'done' ? 'pointer' : 'default' }}
                        onClick={() => j.status === 'done' && openReport(j.job_id)}>
                      <td className="mono" style={{ color: 'var(--ink)' }}>{j.job_id.slice(0, 8)}</td>
                      <td style={{ color: 'var(--muted)' }}>{fmtDate(j.created_at)}</td>
                      <td>
                        <span className={`badge ${j.status === 'done' ? 'safe' : j.status === 'error' ? 'risk' : 'warn'}`}>
                          <span className={`dot ${j.status === 'done' ? 'safe' : j.status === 'error' ? 'risk' : 'warn'}`}/>{j.status}
                        </span>
                      </td>
                      <td className="mono">{j.report_size_kb ? `${j.report_size_kb} KB` : '—'}</td>
                      <td className="mono">{fmtNum(j.ttw_count)}</td>
                      <td className="mono">{fmtNum(j.edge_count)}</td>
                      <td>
                        {j.status === 'done' && (
                          <div className="row g-8" onClick={e => e.stopPropagation()}>
                            <button className="btn btn-sm btn-primary" onClick={() => openReport(j.job_id)}>Open report →</button>
                            <button className="btn btn-sm" disabled={downloading} onClick={() => handleDownload(j.job_id)}>HTML</button>
                            <button className="btn btn-sm" onClick={() => handleShare(j.job_id)}>Share</button>
                            <button className="btn btn-sm" style={{ color: 'var(--rust-dim)', borderColor: 'var(--rust-dim)' }}
                              onClick={() => setDeleting(j.job_id)} title="Remove from history">✕</button>
                          </div>
                        )}
                        {j.status !== 'done' && (
                          <div className="row g-8" onClick={e => e.stopPropagation()}>
                            <button className="btn btn-sm" style={{ color: 'var(--rust-dim)', borderColor: 'var(--rust-dim)' }}
                              onClick={() => setDeleting(j.job_id)} title="Remove from history">✕</button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {history.length > 0 && (
            <div className="panel" style={{ marginTop: 24 }}>
              <div className="panel-h"><span className="caps">What each report contains</span></div>
              <div className="panel-b">
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                  {[
                    ['§ 01','Overview','Summary metrics and risk indicators'],
                    ['§ 02','ZODB Divergence','Filesystem vs live database delta'],
                    ['§ 03','Dependency graph','Node-edge coupling map, entry points'],
                    ['§ 04','High coupling','Artifacts risky to modify'],
                    ['§ 05','Version groups','Duplicate script variants'],
                    ['§ 06','AI explanations','Plain-English field notes per artifact'],
                    ['§ 07','Dead code','Uncalled scripts safe to remove'],
                    ['§ 08','Source browser','Full annotated source of every artifact'],
                  ].map(([num, title, desc]) => (
                    <div key={num} style={{ padding: '12px 14px', border: '1px solid var(--line)', borderRadius: 2, background: 'var(--bg)' }}>
                      <div className="mono" style={{ fontSize: 10.5, color: 'var(--dim)', marginBottom: 4 }}>{num}</div>
                      <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>{title}</div>
                      <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', lineHeight: 1.5 }}>{desc}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReportPage });