// Legal pages + Cookie Banner + Cookie Preferences Modal — NEW 2

const COOKIE_KEY = 'qdi_cookie_consent';

// ─── Toggle control ───────────────────────────────────────────────────────────
function Toggle({ value, onChange }) {
  return (
    <button
      type="button"
      onClick={() => onChange(!value)}
      aria-pressed={value}
      style={{
        width: 44, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer',
        background: value ? 'var(--accent-bright)' : 'rgba(0,0,0,0.15)',
        position: 'relative', transition: 'background 0.2s', flexShrink: 0,
      }}
    >
      <span style={{
        position: 'absolute', top: 3, left: value ? 22 : 3,
        width: 18, height: 18, borderRadius: '50%',
        background: '#fff', transition: 'left 0.2s',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }} />
    </button>
  );
}

// ─── Cookie Preferences Modal ─────────────────────────────────────────────────
function CookiePrefsModal({ onClose }) {
  const stored = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem(COOKIE_KEY) || '{}'); } catch { return {}; }
  }, []);

  const [analytics, setAnalytics] = React.useState(stored.analytics !== false);
  const [prefs, setPrefs] = React.useState(stored.preferences !== false);

  const save = () => {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({ analytics, preferences: prefs, ts: Date.now() }));
    onClose();
  };

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1002,
        background: 'rgba(10,10,10,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20, backdropFilter: 'blur(4px)',
      }}
    >
      <div style={{
        background: 'var(--bg)', border: '1px solid var(--border)',
        borderRadius: 14, padding: '40px 44px', maxWidth: 520, width: '100%',
        boxShadow: '0 24px 80px rgba(0,0,0,0.25)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
          <div>
            <Eyebrow>Preferences</Eyebrow>
            <h3 style={{ fontSize: 22, fontWeight: 600, margin: '12px 0 0', letterSpacing: '-0.015em', color: 'var(--text)' }}>
              Cookie Preferences
            </h3>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: '4px 8px',
            color: 'var(--text-muted)', fontSize: 20, lineHeight: 1, fontFamily: 'inherit',
          }}>×</button>
        </div>

        <Rule style={{ marginBottom: 28 }} />

        {/* Essential — always on */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24, paddingBottom: 24, borderBottom: '1px solid var(--rule)' }}>
          <div style={{ flex: 1, paddingRight: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>Essential Cookies</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.55 }}>Required for the site to function correctly. These cannot be disabled.</div>
          </div>
          <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--accent-bright)', letterSpacing: '0.1em', textTransform: 'uppercase', whiteSpace: 'nowrap', paddingTop: 2 }}>Always On</div>
        </div>

        {/* Analytics */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24, paddingBottom: 24, borderBottom: '1px solid var(--rule)' }}>
          <div style={{ flex: 1, paddingRight: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>Analytics Cookies</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.55 }}>Help us understand how visitors use the site — pages visited, time on site, and navigation patterns. No personal data is shared with third parties.</div>
          </div>
          <Toggle value={analytics} onChange={setAnalytics} />
        </div>

        {/* Preferences */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 32 }}>
          <div style={{ flex: 1, paddingRight: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>Preference Cookies</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.55 }}>Remember your site preferences, such as display settings and UI choices, across visits.</div>
          </div>
          <Toggle value={prefs} onChange={setPrefs} />
        </div>

        <button onClick={save} style={{
          width: '100%', height: 48, borderRadius: 8,
          background: 'var(--accent-bright)', color: '#fff', border: 'none',
          fontFamily: 'inherit', fontSize: 14, fontWeight: 500, cursor: 'pointer',
          boxShadow: '0 8px 24px rgba(190,140,42,0.28)',
        }}>Save Preferences</button>
      </div>
    </div>
  );
}

// ─── Cookie Banner ────────────────────────────────────────────────────────────
function CookieBanner({ onManage, navigate }) {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    try {
      const stored = localStorage.getItem(COOKIE_KEY);
      if (!stored) setTimeout(() => setVisible(true), 900);
    } catch { /* storage not available */ }
  }, []);

  // Inject slide-up animation once
  React.useEffect(() => {
    if (document.getElementById('qdi-banner-css')) return;
    const s = document.createElement('style');
    s.id = 'qdi-banner-css';
    s.textContent = '@keyframes qdi-banner-up{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}';
    document.head.appendChild(s);
  }, []);

  if (!visible) return null;

  const acceptAll = () => {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({ analytics: true, preferences: true, ts: Date.now() }));
    setVisible(false);
  };
  const rejectAll = () => {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({ analytics: false, preferences: false, ts: Date.now() }));
    setVisible(false);
  };
  const manage = () => { onManage(); setVisible(false); };

  return (
    <div style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 999,
      background: 'rgba(8,8,8,0.96)', backdropFilter: 'blur(16px)',
      borderTop: '1px solid rgba(190,140,42,0.22)',
      padding: '18px 40px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 20, flexWrap: 'wrap',
      animation: 'qdi-banner-up 0.4s cubic-bezier(0.16,1,0.3,1) both',
    }}>
      <p style={{ fontSize: 13, color: '#c4bdb5', margin: 0, lineHeight: 1.6, flex: 1, maxWidth: 680 }}>
        We use cookies to enhance your experience and analyse site performance. Essential cookies are always active.{' '}
        <span
          onClick={() => navigate && navigate('cookies')}
          style={{ color: '#d7a53a', cursor: 'pointer', textDecoration: 'underline', textDecorationColor: 'rgba(215,165,58,0.35)' }}
        >Cookie Policy</span>
      </p>
      <div style={{ display: 'flex', gap: 10, flexShrink: 0, flexWrap: 'wrap' }}>
        <button onClick={rejectAll} style={{
          height: 38, padding: '0 16px', borderRadius: 5,
          border: '1px solid rgba(255,255,255,0.12)',
          background: 'transparent', color: '#9ca3af', fontSize: 12,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Reject Non-Essential</button>
        <button onClick={manage} style={{
          height: 38, padding: '0 16px', borderRadius: 5,
          border: '1px solid rgba(215,165,58,0.35)',
          background: 'transparent', color: '#d7a53a', fontSize: 12,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Manage Preferences</button>
        <button onClick={acceptAll} style={{
          height: 38, padding: '0 20px', borderRadius: 5, border: 'none',
          background: '#d7a53a', color: '#fff', fontSize: 12,
          fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
        }}>Accept All</button>
      </div>
    </div>
  );
}

// ─── Shared legal page layout ─────────────────────────────────────────────────
function LegalPage({ navigate, title, updated, children }) {
  return (
    <div style={{ position: 'relative', zIndex: 2, padding: '120px 40px 120px' }}>
      <div style={{ maxWidth: 780, margin: '0 auto' }}>
        <button
          onClick={() => navigate('home')}
          style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: 0,
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontSize: 11, fontWeight: 500, color: 'var(--text-muted)',
            letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 52,
            transition: 'color 0.2s', fontFamily: 'inherit',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--accent-bright)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-muted)'; }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M19 12H5M11 6l-6 6 6 6" />
          </svg>
          Back to site
        </button>

        <h1 style={{ fontSize: 'clamp(36px, 5vw, 56px)', fontWeight: 600, margin: '0 0 8px', lineHeight: 1.05, letterSpacing: '-0.025em', color: 'var(--text)' }}>
          {title}
        </h1>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 48, letterSpacing: '0.04em' }}>Last updated: {updated}</div>

        <Rule style={{ marginBottom: 48 }} />

        <div style={{ fontSize: 15, lineHeight: 1.8, color: 'var(--text-soft)' }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function LegalH2({ children }) {
  return <h2 style={{ fontSize: 19, fontWeight: 600, color: 'var(--text)', margin: '40px 0 12px', letterSpacing: '-0.01em', lineHeight: 1.3 }}>{children}</h2>;
}
function LegalP({ children }) {
  return <p style={{ margin: '0 0 16px', lineHeight: 1.8 }}>{children}</p>;
}
function LegalUL({ items }) {
  return (
    <ul style={{ margin: '0 0 16px', paddingLeft: 24 }}>
      {items.map((item, i) => <li key={i} style={{ marginBottom: 6 }}>{item}</li>)}
    </ul>
  );
}

// ─── Privacy Policy ───────────────────────────────────────────────────────────
function PrivacyPolicyPage({ navigate }) {
  return (
    <LegalPage navigate={navigate} title="Privacy Policy" updated="June 2026">
      <LegalP>Quantum Defence Innovation Ltd (&ldquo;QDI&rdquo;, &ldquo;we&rdquo;, &ldquo;us&rdquo;, &ldquo;our&rdquo;), a company incorporated in England and Wales, is committed to protecting the privacy of individuals who visit our website and interact with our services. This Privacy Policy explains how we collect, use, and protect your personal data in accordance with the UK General Data Protection Regulation (UK GDPR) and the Data Protection Act 2018.</LegalP>

      <LegalH2>1. Data Controller</LegalH2>
      <LegalP>The data controller responsible for your personal data is Quantum Defence Innovation Ltd, London, United Kingdom. For all data protection matters, please use our <strong>contact form</strong>.</LegalP>

      <LegalH2>2. Data We Collect</LegalH2>
      <LegalP>We collect and process the following categories of personal data:</LegalP>
      <LegalUL items={[
        'Contact form data: your full name, email address, organisation name, enquiry type, and the content of your message, submitted when you use our contact form.',
        'Newsletter subscription data: your email address, submitted when you subscribe to the QDI Intelligence Briefing.',
        'Usage data: anonymised data about how you use our website, including pages visited, session duration, browser type, device type, and referring URL, collected automatically.',
        'Cookie data: data stored via cookies placed on your device. See our Cookie Policy for details.',
      ]} />

      <LegalH2>3. How We Use Your Data</LegalH2>
      <LegalP>We use your personal data for the following purposes:</LegalP>
      <LegalUL items={[
        'To respond to your enquiry and provide the information or services you have requested.',
        'To send you the QDI Intelligence Briefing where you have subscribed and consented.',
        'To improve the functionality and content of our website through analysis of usage data.',
        'To comply with our legal and regulatory obligations.',
      ]} />

      <LegalH2>4. Lawful Basis for Processing</LegalH2>
      <LegalUL items={[
        'Contact form submissions: legitimate interests (responding to business enquiries and pre-contractual steps).',
        'Newsletter subscriptions: consent — you may withdraw your consent at any time by unsubscribing.',
        'Usage analytics: legitimate interests (understanding and improving our website performance).',
      ]} />

      <LegalH2>5. Data Retention</LegalH2>
      <LegalUL items={[
        'Contact enquiry data: retained for up to 3 years from the date of receipt, to allow for follow-up and relationship management.',
        'Newsletter subscription data: retained until you unsubscribe or request erasure.',
        'Usage and analytics data: retained on a rolling 26-month basis.',
      ]} />

      <LegalH2>6. Sharing With Third Parties</LegalH2>
      <LegalP>We do not sell your personal data. We share data only with trusted processors who assist us in operating our website and services:</LegalP>
      <LegalUL items={[
        'Formspree (formspree.io): processes contact form and newsletter subscription data on our behalf. Based in the United States; subject to appropriate data transfer safeguards under UK GDPR.',
        'Analytics providers: we may use privacy-first analytics tools that process anonymised, aggregated usage data.',
      ]} />

      <LegalH2>7. Your Rights Under UK GDPR</LegalH2>
      <LegalP>You have the following rights in relation to your personal data held by QDI:</LegalP>
      <LegalUL items={[
        'Right of access: to request a copy of the personal data we hold about you.',
        'Right to rectification: to request correction of inaccurate data.',
        'Right to erasure: to request deletion of your data where there is no legitimate reason for us to continue processing it.',
        'Right to data portability: to receive your data in a structured, machine-readable format.',
        'Right to object: to object to processing based on legitimate interests.',
        'Right to restriction: to request that we restrict processing of your data in certain circumstances.',
      ]} />
      <LegalP>To exercise any of these rights, please use our <strong>contact form</strong>. We will respond within one month.</LegalP>

      <LegalH2>8. Complaints</LegalH2>
      <LegalP>If you are dissatisfied with how we handle your personal data, you have the right to lodge a complaint with the Information Commissioner&rsquo;s Office (ICO) at <strong>ico.org.uk</strong> or by calling 0303 123 1113.</LegalP>

      <LegalH2>9. Changes to This Policy</LegalH2>
      <LegalP>We may update this Privacy Policy from time to time. The date of the most recent revision is shown at the top of this page. Continued use of our website after any update constitutes acceptance of the revised policy.</LegalP>

      <LegalH2>10. Contact</LegalH2>
      <LegalP>For all data protection and privacy queries, please use our <strong>contact form</strong>.</LegalP>
    </LegalPage>
  );
}

// ─── Terms of Service ─────────────────────────────────────────────────────────
function TermsPage({ navigate }) {
  return (
    <LegalPage navigate={navigate} title="Terms of Service" updated="June 2026">
      <LegalP>These Terms of Service (&ldquo;Terms&rdquo;) govern your access to and use of the Quantum Defence Innovation Ltd website (the &ldquo;Site&rdquo;). By accessing or using the Site, you agree to be bound by these Terms in full. If you do not agree, please discontinue use of the Site immediately.</LegalP>

      <LegalH2>1. About QDI</LegalH2>
      <LegalP>Quantum Defence Innovation Ltd (&ldquo;QDI&rdquo;, &ldquo;we&rdquo;, &ldquo;us&rdquo;, &ldquo;our&rdquo;) is a company incorporated in England and Wales, providing quantum-safe cybersecurity solutions for government, defence, and critical infrastructure operators.</LegalP>

      <LegalH2>2. Permitted Use</LegalH2>
      <LegalP>The Site is provided for informational purposes only. You may access and view content on the Site for your personal and non-commercial use. You agree not to:</LegalP>
      <LegalUL items={[
        'Use the Site for any unlawful purpose or in contravention of applicable laws and regulations.',
        'Reproduce, distribute, or commercially exploit any content from the Site without prior written consent from QDI.',
        'Attempt to gain unauthorised access to any part of the Site or its related infrastructure.',
        'Transmit any material that is defamatory, offensive, or otherwise objectionable.',
        'Use automated tools to scrape, crawl, or harvest data from the Site without authorisation.',
      ]} />

      <LegalH2>3. Intellectual Property</LegalH2>
      <LegalP>All content on the Site — including but not limited to text, graphics, logos, icons, images, data, and software — is the exclusive property of Quantum Defence Innovation Ltd or its content licensors and is protected by copyright, trademark, and other applicable intellectual property laws.</LegalP>
      <LegalP>&copy; 2026 Quantum Defence Innovation Ltd. All Rights Reserved.</LegalP>
      <LegalP>Nothing in these Terms grants you any right or licence to use QDI&rsquo;s intellectual property without express prior written consent.</LegalP>

      <LegalH2>4. Disclaimer of Warranties</LegalH2>
      <LegalP>The Site and all content on it are provided on an &ldquo;as is&rdquo; and &ldquo;as available&rdquo; basis, without warranty of any kind, express or implied. QDI makes no representations or warranties regarding the accuracy, completeness, reliability, or suitability of any information on the Site. Information provided does not constitute legal, financial, security, or professional advice.</LegalP>

      <LegalH2>5. Limitation of Liability</LegalH2>
      <LegalP>To the fullest extent permitted by applicable law, QDI, its directors, officers, employees, and agents shall not be liable for any indirect, incidental, special, consequential, or punitive damages — including without limitation loss of profits, data, or goodwill — arising from or in connection with your access to or use of the Site, even if QDI has been advised of the possibility of such damages.</LegalP>

      <LegalH2>6. Third-Party Links</LegalH2>
      <LegalP>The Site may contain links to third-party websites for informational purposes. QDI has no control over and accepts no responsibility for the content, privacy policies, or practices of any third-party websites. The inclusion of a link does not imply endorsement.</LegalP>

      <LegalH2>7. Amendments</LegalH2>
      <LegalP>QDI reserves the right to modify these Terms at any time at its sole discretion. Amendments will be effective immediately upon publication on the Site. Your continued use of the Site following any change constitutes your acceptance of the updated Terms.</LegalP>

      <LegalH2>8. Governing Law &amp; Jurisdiction</LegalH2>
      <LegalP>These Terms are governed by and shall be construed in accordance with the laws of England and Wales. Any dispute arising under or in connection with these Terms shall be subject to the exclusive jurisdiction of the courts of England and Wales.</LegalP>

      <LegalH2>9. Contact</LegalH2>
      <LegalP>For legal queries regarding these Terms, please use our <strong>contact form</strong>.</LegalP>
    </LegalPage>
  );
}

// ─── Cookie Policy ────────────────────────────────────────────────────────────
function CookiePolicyPage({ navigate }) {
  const tableStyle = {
    width: '100%', borderCollapse: 'collapse', fontSize: 13,
    marginBottom: 24, color: 'var(--text-soft)',
  };
  const thStyle = {
    textAlign: 'left', padding: '10px 14px',
    borderBottom: '1px solid var(--border)',
    fontSize: 10, fontWeight: 600, color: 'var(--accent-bright)',
    letterSpacing: '0.15em', textTransform: 'uppercase',
  };
  const tdStyle = {
    padding: '10px 14px', borderBottom: '1px solid var(--rule)', verticalAlign: 'top',
  };

  return (
    <LegalPage navigate={navigate} title="Cookie Policy" updated="June 2026">
      <LegalH2>What Are Cookies?</LegalH2>
      <LegalP>Cookies are small text files placed on your device when you visit a website. They allow the website to recognise your device on subsequent visits and store information about your preferences or actions.</LegalP>

      <LegalH2>How We Use Cookies</LegalH2>
      <LegalP>We use cookies to operate our website, analyse usage, and remember your preferences. The categories below describe each type of cookie we use.</LegalP>

      <LegalH2>Essential Cookies</LegalH2>
      <LegalP>These cookies are strictly necessary for the Site to function. They cannot be disabled through the Cookie Preferences panel.</LegalP>
      <table style={tableStyle}>
        <thead>
          <tr>
            <th style={thStyle}>Cookie</th>
            <th style={thStyle}>Purpose</th>
            <th style={thStyle}>Duration</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={tdStyle}><code>qdi_cookie_consent</code></td>
            <td style={tdStyle}>Stores your cookie consent preferences</td>
            <td style={tdStyle}>1 year</td>
          </tr>
          <tr>
            <td style={tdStyle}><code>session_id</code></td>
            <td style={tdStyle}>Maintains your session state during a visit</td>
            <td style={tdStyle}>Session</td>
          </tr>
        </tbody>
      </table>

      <LegalH2>Analytics Cookies</LegalH2>
      <LegalP>These optional cookies help us understand how visitors use our Site. Data is collected in aggregate and anonymised form — no personally identifiable information is processed.</LegalP>
      <table style={tableStyle}>
        <thead>
          <tr>
            <th style={thStyle}>Cookie</th>
            <th style={thStyle}>Purpose</th>
            <th style={thStyle}>Duration</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={tdStyle}><code>_analytics</code></td>
            <td style={tdStyle}>Tracks page views, session duration, and navigation patterns</td>
            <td style={tdStyle}>Up to 2 years</td>
          </tr>
        </tbody>
      </table>

      <LegalH2>Preference Cookies</LegalH2>
      <LegalP>These optional cookies remember choices you make on the Site to provide a more personalised experience on return visits.</LegalP>
      <table style={tableStyle}>
        <thead>
          <tr>
            <th style={thStyle}>Cookie</th>
            <th style={thStyle}>Purpose</th>
            <th style={thStyle}>Duration</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={tdStyle}><code>_prefs</code></td>
            <td style={tdStyle}>Stores UI preference settings</td>
            <td style={tdStyle}>1 year</td>
          </tr>
        </tbody>
      </table>

      <LegalH2>Managing Your Cookies</LegalH2>
      <LegalP>You can manage your cookie preferences at any time in two ways:</LegalP>
      <LegalUL items={[
        'Via our Cookie Preferences panel — click "Cookie Preferences" in the website footer.',
        'Via your browser settings — most browsers allow you to view, manage, block, or delete cookies. Please refer to your browser\'s help documentation for instructions. Note that disabling essential cookies may impair the functionality of the Site.',
      ]} />

      <LegalH2>Changes to This Policy</LegalH2>
      <LegalP>We may update this Cookie Policy periodically. The date shown at the top of this page reflects the most recent revision.</LegalP>

      <LegalH2>Contact</LegalH2>
      <LegalP>For any questions about this policy, please use our <strong>contact form</strong>.</LegalP>
    </LegalPage>
  );
}

Object.assign(window, {
  CookiePrefsModal,
  CookieBanner,
  PrivacyPolicyPage,
  TermsPage,
  CookiePolicyPage,
});
