/* Privacy Policy, Terms of Use, and the cookie-consent machinery.
 *
 * Scope, deliberately: these cover strikescf.com — this marketing site,
 * its waitlist form and its contact form. They do NOT cover the Strike
 * platform at app.strikescf.com, or any agreement between Strike and a
 * bank, anchor, or supplier. Those need financial-services counsel and
 * are explicitly out of scope.
 *
 * {{GOVERNING_LAW}} is an intentional, un-filled placeholder. With
 * offices in Vancouver, San Francisco and Cairo, the governing-law and
 * jurisdiction clause is a decision for Strike's actual counsel, not a
 * guess. Do not substitute a jurisdiction without a lawyer signing off.
 *
 * Vendor list verified against the repo (index.html and api/*.js). The
 * user-facing copy describes these by ROLE rather than brand, at the
 * client's request; the actual providers are recorded here so whoever
 * maintains this knows exactly who processes what:
 *   · Vercel        — hosting and analytics (/_vercel/insights/script.js)
 *   · Resend        — transactional email (api.resend.com)
 *   · Google Fonts  — webfonts (fonts.googleapis.com / fonts.gstatic.com)
 *   · unpkg         — React and Babel libraries (unpkg.com)
 * No other tracker, tag manager, or analytics product is present.
 */

const LEGAL_UPDATED = '5 September 2026';

/* ---------- Shared long-form legal layout ---------- */
function LegalPage({ screen, title, updated, intro, sections }) {
  return (
    <div className="page page-no-transform" data-screen-label={screen}>
      <section className="hero legal-hero" style={{ paddingBottom: 40 }}>
        <div className="container">
          <h1 className="display-lg" style={{ maxWidth: '16ch' }}>{title}</h1>
          <p className="legal-updated">Last updated: {updated}</p>
          <p className="legal-intro">{intro}</p>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="legal-body">
            {sections.map(sec => (
              <section className="legal-section" key={sec.h}>
                <h2 className="legal-h">{sec.h}</h2>
                {sec.p.map((para, i) => <p className="legal-p" key={i}>{para}</p>)}
                {sec.list && (
                  <ul className="legal-list">
                    {sec.list.map(li => <li key={li.k}><strong>{li.k}</strong> — {li.v}</li>)}
                  </ul>
                )}
              </section>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ══════════════════════════════════════════════════════════════════════
   /privacy
   ══════════════════════════════════════════════════════════════════════ */
function PrivacyPage() {
  return (
    <LegalPage
      screen="Privacy"
      title="Privacy Policy"
      updated={LEGAL_UPDATED}
      intro={"Strike SCF, Inc. (“Strike,” “we,” “us”) operates strikescf.com. This policy covers this website only — not the Strike platform at app.strikescf.com, which has its own privacy terms covering account and transaction data."}
      sections={[
        {
          h: 'What we collect',
          p: [
            'When you join the waitlist or contact us, we collect what you submit: your name, work email, company name, role, what best describes you (bank, anchor buyer, supplier, investor, press, or other), and any message you include.',
            'We also collect basic usage analytics — pages viewed, general location at country or region level, and device type — through a privacy-friendly analytics service, to understand how the site is used. This is not tied to your form submissions, and it only runs if you have accepted analytics cookies.',
          ],
        },
        {
          h: 'How we use it',
          p: [
            'We use waitlist and contact submissions to respond to you, route your enquiry to the right team, and send you updates about Strike if you have asked for them.',
            'We use analytics data in aggregate to understand and improve the site. We do not sell your personal information, and we do not use it for targeted advertising.',
          ],
        },
        {
          h: 'Who we share it with',
          p: [
            'We share data with the service providers that help us run this site. We do not share your information with any other third party except where required by law.',
          ],
          list: [
            { k: 'Hosting and analytics', v: 'the platform that serves this website and reports aggregate usage.' },
            { k: 'Transactional email', v: 'delivery of the notification and confirmation emails triggered by the waitlist and contact forms.' },
            { k: 'Web fonts', v: 'the typefaces this site uses are served by a third-party font host, which receives your IP address when a font loads.' },
            { k: 'JavaScript CDN', v: 'the open-source libraries this site runs on are served from a content delivery network, which likewise receives your IP address.' },
          ],
        },
        {
          h: 'Cookies and local storage',
          p: [
            'This site sets no advertising or cross-site tracking cookies. We store one item in your browser: your cookie preference, so we do not ask again on every visit. That item is essential and cannot be turned off, because it is the record of your own choice.',
            'Our analytics is cookieless — it does not set a cookie or build a profile of you — but it does process usage data, so we still gate it behind your consent. It does not load unless you accept analytics. You can change your mind at any time using the Cookie Preferences link in the footer.',
          ],
        },
        {
          h: 'Data retention',
          p: [
            'We keep waitlist and contact submissions for as long as they are relevant to your relationship with Strike, and delete them on request.',
          ],
        },
        {
          h: 'Your rights',
          p: [
            'You can ask us what data we hold about you, ask us to correct it, or ask us to delete it, by emailing info@strikescf.com.',
            'Depending on where you are located you may have additional rights under local law — for example GDPR in the EU and UK, PIPEDA in Canada, or the CCPA in California. We will honour applicable requests regardless of where you are writing from.',
          ],
        },
        {
          h: 'Children',
          p: ['This site is not directed at children, and we do not knowingly collect information from anyone under 16.'],
        },
        {
          h: 'Changes',
          p: ['We will update this policy as the site changes, and update the date at the top when we do.'],
        },
        {
          h: 'Governing law',
          // {{GOVERNING_LAW}} — pending counsel. Replace the sentence below
          // with the real clause once the jurisdiction is decided.
          p: ['The governing law for this policy is being finalised. If you need to know which jurisdiction applies to a request before then, email info@strikescf.com and we will tell you.'],
        },
        {
          h: 'Contact',
          p: ['Questions about this policy: info@strikescf.com'],
        },
      ]}
    />
  );
}

/* ══════════════════════════════════════════════════════════════════════
   /terms — website use only
   ══════════════════════════════════════════════════════════════════════ */
function TermsPage() {
  return (
    <LegalPage
      screen="Terms"
      title="Terms of Use"
      updated={LEGAL_UPDATED}
      intro={'These terms cover your use of strikescf.com (this website). They do not cover the Strike platform at app.strikescf.com, or any agreement between Strike and its bank, anchor, or supplier customers — those are governed by separate agreements.'}
      sections={[
        {
          h: 'Using this site',
          p: [
            'You can browse this site and use the waitlist and contact forms for their intended purpose: learning about Strike and getting in touch.',
            'You agree not to misuse the site — including submitting false information, attempting to access non-public parts of the site or its systems, or using it in a way that disrupts it for others.',
          ],
        },
        {
          h: 'Content and ownership',
          p: [
            'Everything on this site — text, design, the Strike name and logo, and the RedBook publication — belongs to Strike SCF, Inc. or its licensors. You can share links to it; you cannot republish or reuse it without asking us first.',
          ],
        },
        {
          h: 'No warranty',
          p: [
            'This site, including anything in RedBook, is provided as is. Nothing on it is financial, legal, or investment advice, and nothing here is an offer to provide financing to any specific party — actual financing terms are only ever set out in a direct agreement with Strike or a funding partner.',
          ],
        },
        {
          h: 'Links to other sites',
          p: [
            'This site links to the Strike platform and occasionally to third-party resources. We are not responsible for the content or practices of sites we do not operate.',
          ],
        },
        {
          h: 'Limitation of liability',
          p: ['To the extent the law allows, Strike is not liable for damages arising from your use of this website.'],
        },
        {
          h: 'Changes',
          p: ['We can update these terms as the site changes. Continued use of the site after a change means you accept the updated terms.'],
        },
        {
          h: 'Governing law',
          // {{GOVERNING_LAW}} — pending counsel. Replace the sentence below
          // with the real clause once the jurisdiction is decided.
          p: ['The governing law for these terms is being finalised. If you need to know which jurisdiction applies before then, email info@strikescf.com and we will tell you.'],
        },
        {
          h: 'Contact',
          p: ['Questions about these terms: info@strikescf.com'],
        },
      ]}
    />
  );
}

/* ══════════════════════════════════════════════════════════════════════
   Cookie consent — gates the analytics script for real
   ══════════════════════════════════════════════════════════════════════ */
const CONSENT_KEY = 'strike-cookie-consent';
const ANALYTICS_SRC = '/_vercel/insights/script.js';

function readConsent() {
  try {
    const raw = window.localStorage.getItem(CONSENT_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch { return null; }
}

function writeConsent(analytics) {
  try {
    window.localStorage.setItem(CONSENT_KEY, JSON.stringify({ analytics, ts: Date.now() }));
  } catch { /* private mode — the banner will simply ask again */ }
}

/* The analytics script is NOT in index.html. It only ever reaches the page
   through here, and only after the visitor has accepted — so declining
   means the request is never made, not merely that a banner was shown. */
function loadAnalytics() {
  if (document.querySelector('script[data-strike-analytics]')) return;
  const s = document.createElement('script');
  s.defer = true;
  s.src = ANALYTICS_SRC;
  s.setAttribute('data-strike-analytics', 'true');
  document.head.appendChild(s);
}

function CookieConsent() {
  const [decided, setDecided] = useState(() => readConsent() !== null);
  const [panelOpen, setPanelOpen] = useState(false);
  const [analytics, setAnalytics] = useState(() => {
    const c = readConsent();
    return c ? !!c.analytics : false; // defaults to off until explicitly accepted
  });

  useEffect(() => {
    const c = readConsent();
    if (c && c.analytics) loadAnalytics();
  }, []);

  useEffect(() => {
    const open = () => { setPanelOpen(true); setDecided(false); };
    window.addEventListener('strike:cookie-prefs', open);
    return () => window.removeEventListener('strike:cookie-prefs', open);
  }, []);

  const settle = (allowAnalytics) => {
    writeConsent(allowAnalytics);
    setAnalytics(allowAnalytics);
    if (allowAnalytics) loadAnalytics();
    setPanelOpen(false);
    setDecided(true);
  };

  if (decided && !panelOpen) return null;

  return (
    <div className="cookie-bar" role="dialog" aria-live="polite" aria-label="Cookie preferences">
      <div className="container cookie-bar-inner">
        {!panelOpen ? (
          <React.Fragment>
            <p className="cookie-copy">
              We use essential cookies to remember this choice, and optional analytics to understand
              how the site is used. Analytics stays off unless you accept.{' '}
              <a href="/privacy" onClick={(e) => navTo(e, '/privacy')}>Privacy Policy</a>
            </p>
            <div className="cookie-actions">
              <button type="button" className="btn btn-ghost" onClick={() => setPanelOpen(true)}>Manage preferences</button>
              <button type="button" className="btn btn-ghost" onClick={() => settle(false)}>Decline</button>
              <button type="button" className="btn btn-blue" onClick={() => settle(true)}>Accept</button>
            </div>
          </React.Fragment>
        ) : (
          <div className="cookie-panel">
            <div className="cookie-panel-head">Manage cookie preferences</div>

            <label className="cookie-toggle is-locked">
              <input type="checkbox" checked readOnly disabled />
              <span>
                <strong>Essential</strong>
                <em>Required for the site to work — this stores your cookie choice itself. Cannot be turned off.</em>
              </span>
            </label>

            <label className="cookie-toggle">
              <input
                type="checkbox"
                checked={analytics}
                onChange={(e) => setAnalytics(e.target.checked)}
              />
              <span>
                <strong>Analytics</strong>
                <em>Cookieless page and device counts, so we can see what the site is used for. No profile is built and no cookie is set. Off by default.</em>
              </span>
            </label>

            <div className="cookie-actions">
              <button type="button" className="btn btn-ghost" onClick={() => settle(false)}>Reject all</button>
              <button type="button" className="btn btn-blue" onClick={() => settle(analytics)}>Save preferences</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* Footer link target — any part of the site can reopen the manager. */
function openCookiePrefs(e) {
  if (e) e.preventDefault();
  window.dispatchEvent(new Event('strike:cookie-prefs'));
}

Object.assign(window, {
  PrivacyPage, TermsPage, CookieConsent, openCookiePrefs,
  LEGAL_UPDATED,
});
