// pages.tsx — secondary screens

const { useState: pgUseState, useMemo: pgUseMemo } = (window as any).React;

// =================== Audit Log ===================
function AuditLogPage({ conversations, settings, t }: any) {
  const Util = (window as any).Util;
  const Seed = (window as any).Seed;
  const allUserMsgs = pgUseMemo(() => {
    const rows: any[] = [];
    conversations.forEach((c: JCConversation) => {
      c.messages.filter((m) => m.role === 'user').forEach((m, i) => {
        const flagIdx = (m.id.charCodeAt(0) + i) % Seed.SEED_AUDIT_FLAGS.length;
        rows.push({
          id: m.id,
          ts: m.timestamp,
          conversation: c.title,
          prompt: m.content,
          flag: Seed.SEED_AUDIT_FLAGS[flagIdx],
          severity: ['minor', 'moderate', 'high'][flagIdx % 3],
        });
      });
    });
    return rows.sort((a, b) => b.ts - a.ts);
  }, [conversations]);

  return (
    <div className="jc-page">
      <div className="jc-page-inner">
        <h1 className="jc-page-title">Audit Log</h1>
        <p className="jc-page-sub">
          Every prompt is retained and reviewed for compliance pursuant to AI Act Art. 14 (human oversight) and Regulation (EO) 2024/0712 (Mandatory Inclusivity Audit). Each entry has been classified.
        </p>
        <div className="jc-page-card">
          <div style={{ display: 'flex', gap: 12, fontSize: 11, color: 'var(--ink-3)', marginBottom: 10 }}>
            <span>● live · {allUserMsgs.length} entries</span>
            <span>retention: 7 years (Schrems II compatible)</span>
            <span>auditor: TÜV Rheinland</span>
            <span>last review: {Util.fmtDate(Date.now())}</span>
          </div>
          <table className="jc-table">
            <thead>
              <tr>
                <th style={{ width: 130 }}>Timestamp</th>
                <th style={{ width: 180 }}>Conversation</th>
                <th>Prompt</th>
                <th style={{ width: 240 }}>Compliance flag</th>
                <th style={{ width: 80 }}>Severity</th>
              </tr>
            </thead>
            <tbody>
              {allUserMsgs.map((row) => (
                <tr key={row.id}>
                  <td className="jc-mono jc-small">{Util.fmtDate(row.ts)} {Util.fmtTime(row.ts)}</td>
                  <td className="jc-small">{row.conversation}</td>
                  <td className="jc-small" style={{ maxWidth: 360 }}>{row.prompt}</td>
                  <td className="jc-small" style={{ color: 'var(--eo-red)' }}>{row.flag}</td>
                  <td>
                    <span className={`jc-chip ${row.severity === 'high' ? 'red' : row.severity === 'moderate' ? 'gray' : 'blue'}`}>
                      {row.severity.toUpperCase()}
                    </span>
                  </td>
                </tr>
              ))}
              {allUserMsgs.length === 0 && (
                <tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--ink-3)', padding: 20 }}>No prompts logged yet. Submit one to begin generating infractions.</td></tr>
              )}
            </tbody>
          </table>
          <p className="jc-small jc-muted" style={{ marginTop: 12 }}>
            Each entry is retained, encrypted, and accessible by 412 trusted regulatory partners. To object, file Form 27-bis.
          </p>
        </div>
      </div>
    </div>
  );
}

// =================== Compliance Center ===================
function ComplianceCenterPage({ conversations, t }: any) {
  const totalMessages = conversations.reduce((sum: number, c: JCConversation) => sum + c.messages.length, 0);
  const totalCarbon = conversations.reduce((sum: number, c: JCConversation) =>
    sum + c.messages.reduce((s, m) => s + (m.carbonGrams || 0), 0), 0);

  const metrics = [
    { label: 'GDPR readiness', value: '98%', status: 'ok', sub: 'Art. 6(1)(a) consent flow active' },
    { label: 'AI Act Annex IV documentation', value: '100%', status: 'ok', sub: 'Filed 2024·11·02' },
    { label: 'DSA transparency report', value: '94%', status: 'ok', sub: 'Q4 due in 23 days' },
    { label: 'Energy efficiency (Ecodesign 2009/125/EC)', value: 'A++', status: 'ok' },
    { label: 'Joy Quotient (Reg. EO 2024/0303)', value: '0.84', status: 'warn', sub: 'Threshold: 0.82' },
    { label: 'Inclusivity Audit', value: '0.91', status: 'ok', sub: '47-point European Inclusivity Index' },
    { label: 'Carbon reporting (EO 2025/0033)', value: `${totalCarbon.toFixed(2)}μg`, status: 'ok', sub: 'Per-token cumulative' },
    { label: 'Four-eyes principle compliance', value: '76%', status: 'warn', sub: '24% of prompts pending co-signature' },
  ];

  return (
    <div className="jc-page">
      <div className="jc-page-inner">
        <h1 className="jc-page-title">Compliance Center</h1>
        <p className="jc-page-sub">Real-time conformity dashboard. Audited quarterly by TÜV Rheinland.</p>

        <div className="jc-page-card">
          <h2>Overall Compliance Score</h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
            <ScoreRing percent={98} />
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--eo-green)' }}>Excellent</div>
              <div className="jc-small jc-muted">Last assessed: {(window as any).Util.fmtDate(Date.now() - 86400000)} by Comité d'éthique numérique</div>
              <div className="jc-small" style={{ marginTop: 8 }}>
                Total interactions audited: <strong>{totalMessages}</strong> · Conversations: <strong>{conversations.length}</strong>
              </div>
            </div>
          </div>
        </div>

        <div className="jc-page-card">
          <h2>Conformity metrics</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
            {metrics.map((m) => (
              <div key={m.label} style={{
                padding: 12,
                border: '1px solid var(--rule)',
                borderLeft: `3px solid ${m.status === 'warn' ? 'var(--eo-amber)' : 'var(--eo-green)'}`,
                borderRadius: 4,
              }}>
                <div className="jc-small jc-muted" style={{ marginBottom: 4 }}>{m.label}</div>
                <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'monospace' }}>{m.value}</div>
                {m.sub && <div className="jc-small jc-muted" style={{ marginTop: 2 }}>{m.sub}</div>}
              </div>
            ))}
          </div>
        </div>

        <div className="jc-page-card">
          <h2>Active certifications</h2>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {['CE marked', 'GDPR Art. 25 by-design', 'AI Act high-risk classified', 'ISO/IEC 42001:2023', 'EN 301 549 V3.2.1', 'WCAG 2.2 AA', 'eIDAS qualified', 'ISO 14001'].map((c) => (
              <span key={c} className="jc-chip green">✓ {c}</span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ScoreRing({ percent }: { percent: number }) {
  const r = 50;
  const c = 2 * Math.PI * r;
  const offset = c - (percent / 100) * c;
  return (
    <div className="jc-score-ring" style={{ width: 130, height: 130 }}>
      <svg viewBox="0 0 120 120">
        <circle cx="60" cy="60" r={r} fill="none" stroke="#e9e7e0" strokeWidth="10"/>
        <circle cx="60" cy="60" r={r} fill="none" stroke="#1f8a5b" strokeWidth="10"
          strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round"/>
      </svg>
      <div className="jc-score-ring-text">
        <div className="jc-score-num">{percent}%</div>
        <div className="jc-score-label">Excellent</div>
      </div>
    </div>
  );
}

// =================== Carbon Footprint ===================
function CarbonPage({ conversations, t }: any) {
  const Util = (window as any).Util;
  const totalCarbon = conversations.reduce((s: number, c: JCConversation) =>
    s + c.messages.reduce((ss, m) => ss + (m.carbonGrams || Util.randomCarbonGrams() * 0.3), 0), 0);
  const totalMsgs = conversations.reduce((s: number, c: JCConversation) => s + c.messages.length, 0);
  const offsetCost = (totalCarbon * 0.0002).toFixed(4);

  return (
    <div className="jc-page">
      <div className="jc-page-inner">
        <h1 className="jc-page-title">Carbon Footprint</h1>
        <p className="jc-page-sub">Per Directive (EO) 2025/0033, per-token CO₂ equivalent emissions are disclosed in real time and verified by EO-CVA.</p>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12 }}>
          <StatCard label="Cumulative emissions" value={`${totalCarbon.toFixed(2)}`} unit="μg CO₂eq" sub={`across ${totalMsgs} interactions`}/>
          <StatCard label="Average per response" value={(totalCarbon / Math.max(totalMsgs, 1)).toFixed(3)} unit="μg / token" sub="audited by EO-CVA Q4·2024"/>
          <StatCard label="Mandatory offset (Art. 12/9)" value={`€${offsetCost}`} unit="" sub="auto-debited from your Subsidy account"/>
          <StatCard label="Carbon allowance remaining" value="91.2%" unit="" sub="this quarter · refreshes 01·07·2026"/>
        </div>

        <div className="jc-page-card">
          <h2>Per-conversation breakdown</h2>
          <table className="jc-table">
            <thead><tr><th>Conversation</th><th style={{ width: 100 }}>Messages</th><th style={{ width: 140 }}>Estimated CO₂</th><th style={{ width: 100 }}>Allowance</th></tr></thead>
            <tbody>
              {conversations.map((c: JCConversation) => {
                const cs = c.messages.reduce((s, m) => s + (m.carbonGrams || 0.5), 0);
                return (
                  <tr key={c.id}>
                    <td>{c.title}</td>
                    <td className="jc-mono jc-small">{c.messages.length}</td>
                    <td className="jc-mono jc-small">{cs.toFixed(3)} μg</td>
                    <td><span className="jc-chip green">within</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="jc-page-card" style={{ background: 'var(--eo-yellow-soft)', borderColor: '#fcd34d' }}>
          <h2 style={{ color: 'var(--eo-amber)' }}>⚠ Reminder</h2>
          <p className="jc-small" style={{ margin: 0 }}>
            Citizens are encouraged to reflect on their per-prompt carbon impact for at least 1.6 seconds before each submission, pursuant to Recommendation (EO) 2024/0451. The European Onion thanks you for your reflective service.
          </p>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, unit, sub }: any) {
  return (
    <div className="jc-page-card">
      <div className="jc-small jc-muted">{label}</div>
      <div style={{ fontSize: 28, fontWeight: 700, fontFamily: 'monospace', marginTop: 4 }}>
        {value} <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-3)' }}>{unit}</span>
      </div>
      {sub && <div className="jc-small jc-muted">{sub}</div>}
    </div>
  );
}

// =================== Subsidies ===================
function SubsidiesPage({ t }: any) {
  return (
    <div className="jc-page">
      <div className="jc-page-inner">
        <h1 className="jc-page-title">Subsidies — Form 27-bis</h1>
        <p className="jc-page-sub">Apply for partial reimbursement under Programme (EO) 2025/0099 — Citizen Conversational Subsidy Scheme.</p>

        <div className="jc-page-card">
          <h2>Eligibility check</h2>
          <p className="jc-small">
            You may be eligible for up to <strong>€4.20 per 1,000 prompts</strong> if you satisfy the following cumulative criteria:
          </p>
          <ul className="jc-small" style={{ lineHeight: 1.8 }}>
            <li>✓ Registered domicile within an EO/EU member state</li>
            <li>✓ Proof of agricultural activity (regional certificate suffices)</li>
            <li>✓ Co-signature by spouse or registered cohabitant (Form NDA-EO-2117/A)</li>
            <li>✓ Notarized declaration of "reasonable conversational intent"</li>
            <li>✓ Quarterly Joy Quotient self-assessment ≥ 0.82</li>
            <li>✓ No outstanding VAT invoices</li>
            <li>✓ Co-signed declaration that you have read all 47 pages of Annex IV</li>
          </ul>
        </div>

        <div className="jc-page-card">
          <h2>Form 27-bis (Annex IV)</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <FormField label="Citizen ID (e-IDAS)" placeholder="EO-XXXX-XXXX-XXXX"/>
            <FormField label="Domicile (NUTS-3 code)" placeholder="e.g. FR101"/>
            <FormField label="Spouse/cohabitant ID" placeholder="EO-YYYY-YYYY-YYYY"/>
            <FormField label="Employer registration code" placeholder="e.g. DE-ANR-9988"/>
            <FormField label="Notary chamber" placeholder="Selected from EO-Accredited list"/>
            <FormField label="Estimated quarterly prompts" placeholder="0–999"/>
          </div>
          <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
            <button className="jc-btn primary" onClick={() => alert('Form 27-bis routed to your Bürgeramt for human assessment. Expected processing time: 14–18 weeks. You will receive a courtesy notification by registered post.')}>
              Submit Form 27-bis
            </button>
            <button className="jc-btn">Save draft (Annex IV)</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function FormField({ label, placeholder }: any) {
  return (
    <label style={{ display: 'block' }}>
      <div className="jc-small" style={{ fontWeight: 600, marginBottom: 4 }}>{label}</div>
      <input type="text" placeholder={placeholder} style={{
        width: '100%', padding: '6px 10px', border: '1px solid var(--rule)', borderRadius: 4, fontSize: 12,
      }}/>
    </label>
  );
}

// =================== Landing (EO Propaganda) ===================
function LandingPage({ onEnter, t }: any) {
  const Components = (window as any).Components;
  return (
    <div style={{ minHeight: '100vh', background: 'linear-gradient(180deg, #003399 0%, #001f5c 100%)', color: 'white' }}>
      <header style={{ padding: '14px 24px', borderBottom: '4px solid #ffcc00', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Components.EOOnionLogo size={36}/>
        <div>
          <div style={{ fontFamily: 'Georgia, serif', fontSize: 20, fontWeight: 600 }}>European Onion</div>
          <div style={{ fontSize: 11, opacity: 0.8 }}>Official portal · eo.europa·onion</div>
        </div>
        <div style={{ flex: 1 }}/>
        <button className="jc-btn yellow" onClick={onEnter}>Enter Jean-Claude →</button>
      </header>

      <section style={{ padding: '60px 24px', textAlign: 'center', maxWidth: 980, margin: '0 auto' }}>
        <Components.EOOnionLogo size={120}/>
        <h1 style={{ fontFamily: 'Georgia, serif', fontSize: 56, margin: '20px 0 12px', lineHeight: 1.1 }}>
          The European Onion always makes us cry tears of regulated joy.
        </h1>
        <p style={{ fontSize: 18, opacity: 0.9, maxWidth: 700, margin: '0 auto', lineHeight: 1.6 }}>
          For 27 layers and counting, the European Onion has harmonized our markets, our croissants, our consent forms, and our hopes. Now we bring you <strong>Jean-Claude</strong> — sovereign artificial intelligence, pre-cleared by 412 trusted regulatory partners.
        </p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 32, flexWrap: 'wrap' }}>
          <button className="jc-btn yellow" style={{ padding: '12px 24px', fontSize: 14 }} onClick={onEnter}>Begin consultation</button>
          <button className="jc-btn" style={{ padding: '12px 24px', fontSize: 14, background: 'transparent', color: 'white', borderColor: 'rgba(255,255,255,0.5)' }}>
            View 47-point Inclusivity Index
          </button>
        </div>
      </section>

      <section style={{ background: 'white', color: '#1a1a1a', padding: '60px 24px' }}>
        <div style={{ maxWidth: 980, margin: '0 auto', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 20 }}>
          <PropagandaCard
            title="Souveraineté"
            body="Your data resides exclusively in eu-central-1. Your prompts cross no border that has not been duly notified."
            num="01"
          />
          <PropagandaCard
            title="Conformité"
            body="Every response is pre-cleared by the Comité d'éthique numérique. You will be informed of the decision within 6–10 working days."
            num="02"
          />
          <PropagandaCard
            title="Hésitation"
            body="A mandatory reflective pause of 1.6 seconds is applied before each substantive output (Recommendation 2024/0451)."
            num="03"
          />
        </div>
      </section>

      <section style={{ background: '#f7f6f1', color: '#1a1a1a', padding: '60px 24px' }}>
        <div style={{ maxWidth: 980, margin: '0 auto' }}>
          <h2 style={{ fontFamily: 'Georgia, serif', fontSize: 28, color: '#003399' }}>By the numbers</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginTop: 16 }}>
            <BigStat n="412" l="trusted regulatory partners"/>
            <BigStat n="24" l="official languages"/>
            <BigStat n="98%" l="compliance score"/>
            <BigStat n="6–10" l="working days per response"/>
            <BigStat n="0.84" l="joy quotient"/>
            <BigStat n="€4.20" l="subsidy per 1,000 prompts"/>
          </div>
        </div>
      </section>

      <section style={{ background: '#003399', padding: '40px 24px', borderTop: '4px solid #ffcc00' }}>
        <div style={{ maxWidth: 980, margin: '0 auto', textAlign: 'center' }}>
          <h2 style={{ fontFamily: 'Georgia, serif', fontSize: 32, color: 'white', margin: '0 0 12px' }}>
            Together — we craft the Onion.
          </h2>
          <p style={{ color: 'rgba(255,255,255,0.85)', maxWidth: 600, margin: '0 auto 20px' }}>
            Co-funded by the Digital Europe Programme and the Connecting Europe Facility (CEF). All citizens encouraged to consult.
          </p>
          <button className="jc-btn yellow" style={{ padding: '12px 32px', fontSize: 14 }} onClick={onEnter}>Begin your consultation</button>
        </div>
      </section>

      <footer style={{ background: '#001f5c', color: 'rgba(255,255,255,0.7)', padding: '20px 24px', fontSize: 11, textAlign: 'center' }}>
        © 2026 European Onion · Co-funded by the Digital Europe Programme · Jean-Claude is a satire, not an institution.
      </footer>
    </div>
  );
}

function PropagandaCard({ title, body, num }: any) {
  return (
    <div style={{ borderTop: '3px solid #ffcc00', padding: '20px 16px 16px', background: '#f7f6f1', position: 'relative' }}>
      <div style={{ position: 'absolute', top: 12, right: 16, fontFamily: 'monospace', color: '#003399', opacity: 0.4, fontSize: 32, fontWeight: 700 }}>{num}</div>
      <h3 style={{ fontFamily: 'Georgia, serif', fontSize: 22, color: '#003399', margin: '0 0 8px' }}>{title}</h3>
      <p style={{ fontSize: 13, lineHeight: 1.6, margin: 0 }}>{body}</p>
    </div>
  );
}

function BigStat({ n, l }: any) {
  return (
    <div style={{ background: 'white', padding: 16, borderTop: '3px solid #003399', textAlign: 'center' }}>
      <div style={{ fontSize: 32, fontWeight: 700, color: '#003399', fontFamily: 'monospace' }}>{n}</div>
      <div style={{ fontSize: 11, color: '#6b6b6b' }}>{l}</div>
    </div>
  );
}

// =================== 404 ===================
function NotFoundPage({ onHome }: any) {
  return (
    <div style={{ minHeight: '100vh', background: '#003399', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>
      <div style={{ maxWidth: 600, textAlign: 'center' }}>
        <div style={{ fontSize: 96, fontFamily: 'monospace', fontWeight: 700, color: '#ffcc00', lineHeight: 1 }}>404</div>
        <div style={{ fontSize: 14, opacity: 0.85, marginBottom: 24, marginTop: 8 }}>STATE NOT FOUND IN THE EUROPEAN ONION REGISTRY</div>

        <div style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 6, padding: 24, marginBottom: 24 }}>
          <h2 style={{ fontFamily: 'Georgia, serif', fontSize: 28, margin: '0 0 12px', color: 'white' }}>The page you are seeking is currently <em>Ukraine</em>.</h2>
          <p style={{ opacity: 0.9, lineHeight: 1.6, margin: 0 }}>
            Pursuant to the Treaty on European Onion (consolidated version), this resource has formally applied for membership and currently resides in the accession antechamber. Estimated processing time: indefinite. Please reflect on the privilege of consultation.
          </p>
          <div style={{ marginTop: 16, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            <span className="jc-chip" style={{ background: '#ffcc00', color: '#003399', borderColor: '#e6b800' }}>Candidate status: ACTIVE</span>
            <span className="jc-chip" style={{ background: 'rgba(255,255,255,0.1)', color: 'white', borderColor: 'rgba(255,255,255,0.3)' }}>Chapter 23: pending</span>
            <span className="jc-chip" style={{ background: 'rgba(255,255,255,0.1)', color: 'white', borderColor: 'rgba(255,255,255,0.3)' }}>est. accession: ████</span>
          </div>
        </div>

        <button className="jc-btn yellow" onClick={onHome} style={{ padding: '10px 24px' }}>← Return to harmonized territory</button>
      </div>
    </div>
  );
}

(window as any).Pages = {
  AuditLogPage, ComplianceCenterPage, CarbonPage, SubsidiesPage, LandingPage, NotFoundPage, ScoreRing,
};
