// ============================================================
// DEMIURGE — LEGAL DOCUMENT DATA MODEL
// Structured, versioned legal documents. Each doc renders through
// legal-doc.jsx (ToC, anchors, print, meta). Content is grounded in
// the ACTUAL stack (Vercel, Stripe, GoHighLevel, Resend, Supabase,
// Anthropic, Google Fonts). No invented entity details; unresolved
// items are flagged inline and marked [TO CONFIRM].
//
// Block types in `body`:
//   'text'  → string (paragraph)
//   ['h3', 'Heading']
//   ['list', [ ... ]]  |  ['olist', [ ... ]]
//   ['note', 'text', 'info'|'warn'|'']
// Exposes: window.LEGAL_DOCS, window.LEGAL_ORDER
// ============================================================

const _S = (typeof window !== 'undefined' && window.SITE) || {};
const COMPANY = _S.legalName || 'Demiurge Systems Ltd';
const REG = _S.companyNumber || '17109558';
const JURIS = _S.jurisdiction || 'England & Wales';
const CONTACT = _S.contactEmail || 'ops@demiurge.systems';
const EFFECTIVE = '25 July 2026';
const UPDATED = '25 July 2026';
const VERSION = '1.0';

const SUBPROCESSORS = _S.subprocessors || [];

const LEGAL_DOCS = {
  privacy: {
    key: 'privacy', route: '/legal/privacy',
    title: 'Privacy Policy',
    description: 'How Demiurge Systems collects, uses, and protects personal data.',
    version: VERSION, effectiveDate: EFFECTIVE, lastUpdated: UPDATED,
    intro: `This policy explains how ${COMPANY} ("Demiurge Systems", "we", "us") handles personal data collected through demiurge.systems and the services we deliver. It reflects how the site and our intake systems actually work today.`,
    sections: [
      { id: 'who-we-are', heading: 'Who we are', body: [
        `${COMPANY} is a company registered in England (company number ${REG}). We are the data controller for personal data processed through this website.`,
        ['note', `Our registered office address and, where applicable, data-protection fee registration are being finalised and will be published here before they are relied upon. [TO CONFIRM]`, 'warn'],
        `For any privacy question or to exercise your rights, contact us at ${CONTACT} or via the contact form at /contact.`
      ]},
      { id: 'data-we-collect', heading: 'Data we collect', body: [
        'We only collect what we need to respond to you and deliver our services:',
        ['list', [
          'Enquiry & contact data — name, work email, company, role, phone (optional), industry, selected package, your message, preferred contact method and availability, submitted through our contact and package forms.',
          'Account & order data — where you purchase a package: email, billing details, and subscription records. Card details are entered directly with our payment processor and are never seen or stored by us.',
          'Technical data — standard server and delivery logs (e.g. IP address, timestamp, user agent) generated by our hosting and used for security, abuse-prevention, and reliability.'
        ]],
        'We do not run third-party advertising or behavioural-tracking analytics on this site, and we do not set non-essential cookies (see “Cookies”).'
      ]},
      { id: 'how-we-use', heading: 'How we use data, and our lawful basis', body: [
        ['list', [
          'To respond to enquiries and provide the strategy call you request — lawful basis: your consent and our legitimate interest in responding to prospective customers.',
          'To provide, bill for, and support purchased services — lawful basis: performance of a contract.',
          'To secure the site, prevent abuse/spam, and keep records — lawful basis: legitimate interests.',
          'To meet legal, accounting, and tax obligations — lawful basis: legal obligation.'
        ]],
        'We do not sell personal data, and we do not use your enquiry content to train third-party AI models.'
      ]},
      { id: 'sharing', heading: 'Who we share data with (processors)', body: [
        'We share personal data only with service providers who process it on our behalf, under contract, to run the services described above:',
        ['list', SUBPROCESSORS.map(s => `${s.name} — ${s.purpose} (${s.region}).`)],
        'Each provider is permitted to use the data only to provide their service to us. We may also disclose data where required by law.'
      ]},
      { id: 'transfers', heading: 'International transfers', body: [
        'Some of our providers are located in, or transfer data to, the United States and other countries outside the UK/EEA. Where that happens, transfers are covered by appropriate safeguards such as the providers’ Standard Contractual Clauses and equivalent mechanisms offered in their data-processing terms.'
      ]},
      { id: 'retention', heading: 'Retention', body: [
        'We keep enquiry and CRM records for as long as needed to deal with your request and for a reasonable follow-up period, then review and delete or anonymise them. Order and billing records are kept for the period required by law (typically six years for UK tax purposes). You can ask us to delete your data sooner (see “Your rights”).'
      ]},
      { id: 'security', heading: 'Security', body: [
        'The site is served exclusively over HTTPS with HSTS. Payment card data is handled entirely by our PCI-DSS-compliant payment processor. Secrets and API keys are held in managed environment configuration, never in client code, and are redacted from any diagnostic output. See our Security page for the full list of implemented controls.'
      ]},
      { id: 'cookies', heading: 'Cookies & analytics', body: [
        'This site does not set non-essential or advertising cookies and does not embed third-party analytics trackers. Where you proceed to checkout, our payment processor may set cookies on its own domain that are strictly necessary to complete and secure the payment. Web fonts are loaded from Google Fonts, which may receive your IP address as part of serving the font files.'
      ]},
      { id: 'automated', heading: 'Automated decision-making', body: [
        'We do not make decisions producing legal or similarly significant effects about you based solely on automated processing.'
      ]},
      { id: 'your-rights', heading: 'Your rights', body: [
        'Subject to law, you may request access to your data; correction; deletion; restriction or objection to processing; and portability. You may also withdraw consent at any time and complain to a supervisory authority (in the UK, the Information Commissioner’s Office).',
        `To exercise any right, email ${CONTACT} or use /contact. We respond within statutory timeframes.`
      ]},
      { id: 'changes', heading: 'Changes to this policy', body: [
        'We may update this policy as our services change. The version and dates at the top of this page always reflect the current edition; material changes will be highlighted here.'
      ]}
    ]
  },

  'dpa-gdpr': {
    key: 'dpa-gdpr', route: '/legal/dpa-gdpr',
    title: 'DPA & GDPR',
    description: 'Data-processing roles, customer DPAs, and how to exercise data rights under UK/EU GDPR.',
    version: VERSION, effectiveDate: EFFECTIVE, lastUpdated: UPDATED,
    intro: `This page explains the data-processing relationship between ${COMPANY} and its customers under the UK GDPR and EU GDPR, and how to put a Data Processing Agreement (DPA) in place.`,
    sections: [
      { id: 'roles', heading: 'Controller & processor roles', body: [
        'For personal data you submit about yourself when enquiring or buying, we act as controller (see the Privacy Policy).',
        'For personal data contained in the systems we build and operate for you — for example contacts in a CRM we deploy on your behalf — you are the controller and we act as your processor, processing that data only on your documented instructions.'
      ]},
      { id: 'dpa', heading: 'Data Processing Agreement', body: [
        'Where we act as your processor, a DPA governs that processing. Our DPA covers the subject-matter, duration, nature and purpose of processing, the types of personal data and categories of data subjects, and the obligations below.',
        ['note', 'A signed, downloadable DPA template is being finalised. Until it is published here, you can request the current DPA and execute it through the process in “How to request a DPA”. We do not present an unsigned placeholder as a binding agreement. [TO CONFIRM]', 'warn']
      ]},
      { id: 'instructions', heading: 'Processing instructions & confidentiality', body: [
        'As processor, we process customer personal data only on your documented instructions, including for transfers, unless required by law. Personnel authorised to process the data are bound by confidentiality obligations.'
      ]},
      { id: 'security-measures', heading: 'Security measures', body: [
        'We apply the technical and organisational measures described on our Security page, including encryption in transit, secret management, and least-privilege access. Measures are reviewed as the service evolves.'
      ]},
      { id: 'subprocessors', heading: 'Subprocessors', body: [
        'We use the subprocessors listed in the Privacy Policy to deliver the service. We impose data-protection terms on each subprocessor consistent with our obligations, and will inform customers of intended changes to give an opportunity to object.'
      ]},
      { id: 'rights', heading: 'Assisting with data-subject rights', body: [
        'Taking into account the nature of processing, we assist you with appropriate technical and organisational measures to respond to data-subject requests, and to meet your obligations around security, breach notification, and impact assessments.'
      ]},
      { id: 'transfers', heading: 'International transfers', body: [
        'Where processing involves transfers outside the UK/EEA, we rely on appropriate safeguards (such as Standard Contractual Clauses) offered by our subprocessors.'
      ]},
      { id: 'breach', heading: 'Personal-data breach handling', body: [
        'We maintain a process to detect and respond to personal-data breaches and will notify affected customers without undue delay after becoming aware of a breach affecting their data, with the information needed to meet their own notification duties.'
      ]},
      { id: 'deletion', heading: 'Return & deletion of data', body: [
        'On termination, and at your choice, we delete or return customer personal data processed on your behalf, and delete existing copies unless retention is required by law.'
      ]},
      { id: 'request', heading: 'How to request or execute a DPA', body: [
        `To put a DPA in place, or to make a data-processing request, contact ${CONTACT} or use /contact and select “DPA / GDPR request”. We will provide the current agreement and walk you through execution.`
      ]}
    ]
  },

  security: {
    key: 'security', route: '/legal/security',
    title: 'Security & SOC 2',
    description: 'The security controls Demiurge Systems actually implements — and an honest statement on certification status.',
    version: VERSION, effectiveDate: EFFECTIVE, lastUpdated: UPDATED,
    intro: 'We describe only controls that are actually implemented or evidenced in our infrastructure and codebase, and we are explicit about what is not yet in place.',
    sections: [
      { id: 'certification-status', heading: 'Certification status — read this first', body: [
        ['note', 'Demiurge Systems is NOT SOC 2 certified, SOC 2 attested, or independently audited at this time. We do not hold a SOC 2 Type I or Type II report, and we make no claim of SOC 2 compliance. We do not display certification badges, audit dates, penetration-test claims, or compliance percentages, because none have been independently verified.', 'warn'],
        'The controls below are those genuinely implemented today. Where a capability is provided by a specialist subprocessor (e.g. payments, database), we say so rather than claim it as our own audited control.'
      ]},
      { id: 'implemented', heading: 'Implemented controls', body: [
        ['list', [
          'Encryption in transit — the entire site and all API endpoints are served over HTTPS/TLS with HTTP Strict Transport Security (HSTS) enabled.',
          'Security headers — responses set HSTS, X-Content-Type-Options: nosniff, X-Frame-Options, and a strict Referrer-Policy.',
          'Payment data isolation — card details are captured and processed entirely by our PCI-DSS-compliant payment processor via its hosted checkout; our systems never receive or store card numbers.',
          'Secret management — API keys and credentials live only in managed server-side environment configuration, never in client-side code, and are redacted from diagnostic responses.',
          'Input validation & sanitisation — all form submissions are validated and sanitised server-side before any downstream use.',
          'Spam & abuse controls — honeypot fields plus server-side rate limiting on intake endpoints.',
          'Audit logging — signup/order events are recorded to an append-style audit log for traceability.',
          'Least-data by design — we avoid placing personal or sensitive data in URLs/query strings.'
        ]]
      ]},
      { id: 'subprocessor-controls', heading: 'Controls provided by our infrastructure providers', body: [
        'The following are delivered and maintained by specialist providers under their own security programmes (several of which hold their own independent certifications):',
        ['list', [
          'Encryption at rest, backups, and database access controls — provided by our managed database/auth provider.',
          'Payment security and PCI-DSS scope reduction — provided by our payment processor.',
          'Platform, network, and edge security, and DDoS mitigation — provided by our hosting/CDN provider.'
        ]],
        'Their certifications are theirs, not ours; we reference them only to describe where a control lives.'
      ]},
      { id: 'in-progress', heading: 'In progress / not yet implemented', body: [
        'We are transparent about gaps. The following are not yet formally established as independent, documented controls:',
        ['list', [
          'A completed SOC 2 (or ISO 27001) audit and report.',
          'A formal, documented incident-response and business-continuity programme.',
          'Scheduled independent penetration testing.',
          'Automated dependency/vulnerability scanning in CI and a formal secure-SDLC policy.',
          'Formal, org-wide access-review and monitoring procedures.'
        ]]
      ]},
      { id: 'report-security-issue', heading: 'Reporting a security issue', body: [
        `If you believe you have found a vulnerability, contact ${CONTACT} with details and we will respond promptly. Please act in good faith, avoid privacy violations and service disruption, and give us reasonable time to remediate before any disclosure.`
      ]},
      { id: 'request-evidence', heading: 'Requesting security information', body: [
        'For a security questionnaire, a summary of controls, or documents available under NDA, use /contact and select “Security enquiry”. We will distinguish clearly between implemented controls, controls in progress, and any third-party attestations that exist.'
      ]}
    ]
  },

  terms: {
    key: 'terms', route: '/legal/terms',
    title: 'Terms of Service',
    description: 'The terms governing use of the Demiurge Systems website and services.',
    version: VERSION, effectiveDate: EFFECTIVE, lastUpdated: UPDATED,
    intro: `These Terms govern your use of the ${COMPANY} website and the services we provide. By using the site or purchasing a service, you agree to these Terms.`,
    sections: [
      { id: 'eligibility', heading: 'Eligibility & accounts', body: [
        'You must be able to form a binding contract and, where you act for an organisation, be authorised to bind it. You are responsible for the accuracy of information you provide and for activity under any account you hold with us.'
      ]},
      { id: 'services', heading: 'Services & scope', body: [
        'We provide deployment of AI “operator” systems and related managed services, as described on the site and confirmed in your order or a written statement of work. Package descriptions are a summary; the specific scope of your engagement is what we agree with you.'
      ]},
      { id: 'acceptable-use', heading: 'Acceptable use', body: [
        'You agree not to misuse the services, including by attempting to breach security, disrupt the service, infringe others’ rights, or use the services for unlawful, deceptive, or harmful purposes, or in a way that violates a third-party provider’s acceptable-use terms.'
      ]},
      { id: 'customer-responsibilities', heading: 'Customer responsibilities', body: [
        'You are responsible for the lawfulness of the data and instructions you provide, for obtaining necessary consents from your own contacts, and for reviewing outputs before relying on them in your business.'
      ]},
      { id: 'ip', heading: 'Intellectual property', body: [
        'We retain all rights in our platform, software, methods, and materials. You retain rights in your own data and content. You receive the rights needed to use the deliverables we provide for your internal business purposes, as set out in your order.'
      ]},
      { id: 'customer-data', heading: 'Customer data & privacy', body: [
        'Our handling of personal data is described in the Privacy Policy, and, where we process data on your behalf, the DPA & GDPR page. Those documents form part of these Terms.'
      ]},
      { id: 'ai-outputs', heading: 'AI-generated outputs & limitations', body: [
        'Parts of the services use AI models. AI outputs can be inaccurate, incomplete, or unsuitable for a given purpose and may require human review. We build human oversight into autonomous actions, but you remain responsible for how you use outputs. We do not warrant that AI outputs are error-free or fit for any particular purpose.'
      ]},
      { id: 'third-party', heading: 'Third-party services', body: [
        'The services rely on third-party providers (for example hosting, payments, CRM, email, and AI providers). Your use may be subject to their terms, and we are not responsible for their acts or omissions beyond our own obligations to you.'
      ]},
      { id: 'fees', heading: 'Fees & payment', body: [
        'Where a service is paid, fees, billing frequency, and any setup charges are those shown at purchase or in your order. Subscriptions renew until cancelled. Unless stated otherwise or required by law, payments are non-refundable, except for any cancellation right expressly offered (such as a stated cancellation window).'
      ]},
      { id: 'availability', heading: 'Availability & changes', body: [
        'We aim to keep the services available but do not guarantee uninterrupted operation. We may modify, suspend, or discontinue features, and will give reasonable notice of material adverse changes where practicable.'
      ]},
      { id: 'disclaimers', heading: 'Disclaimers', body: [
        'Except as expressly stated, the services are provided “as is” and “as available”, and we disclaim all implied warranties to the fullest extent permitted by law. Nothing in these Terms excludes liability that cannot lawfully be excluded.'
      ]},
      { id: 'liability', heading: 'Limitation of liability', body: [
        'To the maximum extent permitted by law, we are not liable for indirect or consequential loss, or for loss of profits, revenue, data, or goodwill. Our total aggregate liability arising from the services is limited to the amounts you paid us for the services in the 12 months before the event giving rise to the claim. These limits do not apply to liability that cannot be limited by law.'
      ]},
      { id: 'termination', heading: 'Suspension & termination', body: [
        'We may suspend or terminate access for material breach, non-payment, or unlawful use. You may stop using the services at any time; cancellation of paid services is governed by your order and the fees section above.'
      ]},
      { id: 'governing-law', heading: 'Governing law & disputes', body: [
        `These Terms are governed by the laws of ${JURIS}, and the courts of ${JURIS} have jurisdiction, except where mandatory local law provides otherwise.`,
        ['note', 'The governing-law jurisdiction is stated on the basis of the company’s England registration and will be confirmed before production release. [TO CONFIRM]', 'warn']
      ]},
      { id: 'contact', heading: 'Contact', body: [
        `Questions about these Terms: ${CONTACT}, or /contact.`
      ]}
    ]
  }
};

const LEGAL_ORDER = ['privacy', 'dpa-gdpr', 'security', 'terms'];

if (typeof window !== 'undefined') {
  window.LEGAL_DOCS = LEGAL_DOCS;
  window.LEGAL_ORDER = LEGAL_ORDER;
}
