import { h, clear } from '../core/dom';
import { goHome, openEditor } from '../core/nav';

export type LegalPage = 'privacy' | 'terms';

const YEAR = new Date().getFullYear();
const UPDATED = 'July 6, 2026';
const CONTACT = 'hello@yeetpdf.com';

export function mountLegal(root: HTMLElement, page: LegalPage) {
  clear(root);
  root.appendChild(
    h(
      'div.landing.legal',
      nav(),
      h('div.legal-wrap', h('div.legal-card glass', page === 'privacy' ? privacyContent() : termsContent())),
      footer(),
    ),
  );
  document.title =
    page === 'privacy' ? 'Privacy Policy — YeetPDF' : 'Terms of Use — YeetPDF';
  window.scrollTo(0, 0);
}

function logo(size = 30): HTMLElement {
  return h('img.logo', {
    src: '/favicon.svg',
    alt: 'YeetPDF logo',
    width: size,
    height: size,
    style: { width: `${size}px`, height: `${size}px` },
  });
}

function nav(): HTMLElement {
  return h(
    'div.nav-wrap',
    h(
      'nav.nav glass',
      h(
        'div.nav-brand',
        { onclick: () => goHome(), title: 'Back to home', style: { cursor: 'pointer' } },
        logo(30),
        h('span.brand-name', h('span.wm', h('span.wm-yeet', 'Yeet'), h('span.wm-pdf', 'PDF'))),
      ),
      h('a.nav-link', { href: '#/' }, 'Home'),
      h('a.nav-link', { href: '#/privacy' }, 'Privacy'),
      h('a.nav-link', { href: '#/terms' }, 'Terms'),
      h('button.btn btn-primary btn-sm nav-cta', { onclick: () => openEditor() }, 'Open the editor'),
    ),
  );
}

function footer(): HTMLElement {
  return h(
    'footer.footer',
    h('div.footer-brand', logo(28), h('span.brand-name', h('span.wm', h('span.wm-yeet', 'Yeet'), h('span.wm-pdf', 'PDF'))), h('span.footer-tag', 'Free PDF editor · runs on your machine')),
    h(
      'div.footer-links',
      h('a', { href: '#/' }, 'Home'),
      h('a', { href: '#/privacy' }, 'Privacy'),
      h('a', { href: '#/terms' }, 'Terms'),
      h('a', { href: '/yeetpdf-source.zip' }, 'Source'),
      h('a', { href: `mailto:${CONTACT}` }, 'Contact'),
    ),
    h('div.footer-copy', `© ${YEAR} YeetPDF. No accounts, no tracking, no kidding.`),
  );
}

function head(title: string): HTMLElement {
  return h('div.legal-head', h('div.eyebrow', 'Legal'), h('h1.legal-title', title), h('p.legal-updated', `Last updated: ${UPDATED}`));
}

function p(...children: (string | HTMLElement)[]): HTMLElement {
  return h('p', ...children);
}
function ul(...items: (string | HTMLElement)[]): HTMLElement {
  return h('ul', ...items.map((i) => h('li', i)));
}
function mail(): HTMLElement {
  return h('a', { href: `mailto:${CONTACT}` }, CONTACT);
}

function privacyContent(): HTMLElement {
  return h(
    'div.legal-body',
    head('Privacy Policy'),
    p(
      'YeetPDF (“YeetPDF”, “we”, “us”) is a free, browser-based PDF editor available at yeetpdf.com (the “Service”). This policy explains, in plain language, what happens — and just as importantly, what doesn’t happen — to your data when you use it.',
    ),

    h('h2', '1. The short version'),
    ul(
      'Your files never leave your device — every PDF operation runs locally in your browser.',
      'There are no accounts, so we don’t collect names, emails, or passwords.',
      'YeetPDF does not use cookies.',
      'We don’t run analytics, advertising trackers, or tracking pixels of any kind.',
      'The only data stored anywhere is a small amount of app settings and optional saved signatures, kept locally in your own browser and never transmitted to us.',
    ),

    h('h2', '2. What actually happens to your files'),
    p(
      'When you open, edit, sign, merge, or convert a PDF in YeetPDF, the entire operation happens inside your browser tab using JavaScript and WebAssembly running on your own device. There is no upload step — YeetPDF has no server component that receives, stores, or processes your documents. Closing the tab without exporting discards your work exactly as it would with a native desktop app; we have no way to recover it, because we never had a copy of it.',
    ),

    h('h2', '3. What we store locally on your device'),
    p('To make the app usable, your browser stores a small amount of data locally, using standard browser storage APIs. None of it is transmitted to us or anyone else:'),
    ul(
      h('span', h('strong', 'Local Storage'), ' — editor preferences, such as zoom level, tool defaults, and toggles like “uniform scaling.”'),
      h('span', h('strong', 'IndexedDB'), ' — signatures you’ve drawn, typed, or uploaded and chosen to save for reuse, plus a record of your last-used signature.'),
      h('span', h('strong', 'Cache Storage'), ' (via a service worker) — a cached copy of the app’s own code and assets so YeetPDF works offline and loads instantly. This is application caching, not tracking.'),
    ),
    p('You can clear any of this at any time through your browser’s site-data settings. Doing so has no effect on us, because we never held a copy of it in the first place.'),

    h('h2', '4. Cookies'),
    p(
      'YeetPDF does not use cookies — not for sessions, not for preferences, not for advertising, not for analytics, not for anything. Nothing on this site requires a cookie-consent banner, because nothing on this site sets a cookie. The local-storage mechanisms described in Section 3 are not cookies: they are never attached to outgoing requests, and they never leave your browser.',
    ),

    h('h2', '5. What we don’t collect'),
    p(
      'We do not collect file contents, filenames, extracted text or images, names, email addresses, account credentials (there are no accounts), payment information (the app is free), device identifiers used for tracking, or behavioral/analytics data. We do not run Google Analytics, Meta Pixel, or any comparable service. Fonts are self-hosted and bundled with the app specifically so your browser never has to call out to Google Fonts or any other third-party font CDN.',
    ),

    h('h2', '6. Hosting & server logs'),
    p(
      'YeetPDF is a static site served over a content-delivery network (Cloudflare). Like virtually every website, the infrastructure that delivers these files to your browser generates standard connection-level logs — for example, IP address, user-agent string, request timestamp, and requested path — for security, abuse prevention, and operating the CDN. That is the hosting provider operating its network, not YeetPDF building a profile of you: we do not maintain a database of visitors, and we do not cross-reference these logs with anything else. See Cloudflare’s own privacy policy for how they handle this infrastructure-level data.',
    ),

    h('h2', '7. Third-party services'),
    p(
      'On-device features — OCR (Tesseract.js), encryption and file repair (qpdf, compiled to WebAssembly), and PDF parsing/rendering (pdf.js, pdf-lib) — run entirely inside your browser. None of them send your document content to any external API or third-party service. YeetPDF does not embed any third-party advertising, analytics, or tracking scripts.',
    ),

    h('h2', '8. Children’s privacy'),
    p('YeetPDF is not directed at children under 13, and we do not knowingly collect personal information from anyone — a fact that holds for every user, not just children, since we don’t collect personal information at all.'),

    h('h2', '9. Your rights & choices'),
    p(
      'Because YeetPDF does not collect or store your personal data on any server, there is generally nothing for us to access, export, correct, or delete on your behalf under laws such as the GDPR or CCPA — the data simply isn’t held by us. You remain in full control of the local data described in Section 3 through your own browser settings. If you have questions about how a specific privacy law applies to your use of YeetPDF, contact us using the details below.',
    ),

    h('h2', '10. International use'),
    p('Because processing happens entirely on your device, using YeetPDF from any country does not result in your file content being transferred across any border by us — it never leaves your machine to begin with.'),

    h('h2', '11. Security'),
    p(
      'Processing everything locally is itself a strong security property: there is no server-side database of user files that could be breached. That said, no device or browser is completely immune to compromise; you’re responsible for keeping your own device, browser, and any exported files reasonably secure.',
    ),

    h('h2', '12. Changes to this policy'),
    p('We may update this policy as the app evolves. The “last updated” date at the top will change whenever it does, and revisions take effect as soon as they’re posted here — we have no account or email list through which to notify you individually.'),

    h('h2', '13. Contact'),
    p('Questions about this policy? Reach us at ', mail(), '.'),
  );
}

function termsContent(): HTMLElement {
  return h(
    'div.legal-body',
    head('Terms of Use'),
    p(
      'Please read these Terms of Use (“Terms”) carefully before using YeetPDF at yeetpdf.com (the “Service”). By accessing or using the Service, you agree to be bound by these Terms. If you don’t agree to them, please don’t use the Service.',
    ),

    h('h2', '1. About the Service'),
    p('YeetPDF is provided free of charge, with no account requirement, as a browser-based tool for viewing, editing, annotating, signing, converting, and otherwise manipulating PDF files entirely on your own device.'),

    h('h2', '2. Eligibility'),
    p('You must be at least 18 years old, or the age of majority in your jurisdiction, or be using the Service with the involvement of a parent or guardian. The Service is not directed at children under 13.'),

    h('h2', '3. Your files, your responsibility'),
    p(
      'All processing happens locally in your browser; we never receive or store a copy of your files. You are solely responsible for keeping your own backups. YeetPDF is not a substitute for regular backups, and we are not responsible for any loss of, damage to, or inability to recover any file, whether caused by a browser crash, a closed tab, device failure, a software bug, or any other reason.',
    ),

    h('h2', '4. Not legal, tax, or professional advice'),
    p(
      'YeetPDF is a general-purpose editing tool, not a lawyer, notary, or compliance service. Features such as electronic signatures, redaction, encryption, and password protection are provided “as-is” and do not constitute legal advice or any guarantee of legal validity, evidentiary weight, enforceability, security, or regulatory compliance (including under ESIGN, UETA, eIDAS, HIPAA, or any comparable law) in any jurisdiction. You are solely responsible for determining whether a given feature meets the legal, regulatory, or contractual requirements applicable to your document and situation — including independently verifying that redacted content is not recoverable and that a signed document meets the standard required for its intended use — before relying on it.',
    ),

    h('h2', '5. Acceptable use'),
    p('You agree not to use the Service to:'),
    ul(
      'create, sign, or alter documents for fraudulent, deceptive, or forged purposes;',
      'infringe any intellectual property or other right of a third party;',
      'violate any applicable law or regulation;',
      'attempt to reverse-engineer, disrupt, or gain unauthorized access to the Service beyond normal client-side browser use; or',
      'upload, process, or transmit malicious code.',
    ),
    p('Because everything runs locally, we have no ability to monitor how you use the Service — you bear full responsibility for compliance with this section.'),

    h('h2', '6. Open-source license'),
    p(
      'YeetPDF’s source code is not proprietary. Because it bundles MuPDF, a PDF library from Artifex Software, Inc., to power native content editing, the application as a whole — including YeetPDF’s own original code — is distributed under the ',
      h('a', { href: '/LICENSE.txt', target: '_blank', rel: 'noopener' }, 'GNU Affero General Public License, version 3 or later'),
      ' (“AGPL”), not a permissive license. Copyright and attribution notices, including for MuPDF, are at ',
      h('a', { href: '/NOTICE.txt', target: '_blank', rel: 'noopener' }, 'NOTICE.txt'),
      '.',
    ),
    p(
      'In short: you may use, study, modify, and redistribute YeetPDF’s code, including commercially, provided you comply with the AGPL. Its key obligation, beyond what a permissive license would require: if you run a modified version of YeetPDF as a service that users access over a network, you must offer those users the complete corresponding source of your modified version, under the same license, at no charge — you can’t take YeetPDF, modify it, and operate it as closed-source software. See LICENSE.txt §13 for the precise terms.',
    ),
    p(
      'The complete corresponding source — every module, build configuration, and installation script needed to build YeetPDF from scratch — is available for download at ',
      h('a', { href: '/yeetpdf-source.zip' }, '/yeetpdf-source.zip'),
      '. See also the ',
      h('a', { href: '/THIRD-PARTY-NOTICES.md', target: '_blank', rel: 'noopener' }, 'third-party notices'),
      ' for the licenses of the individual open-source components used to build it (including pdf.js, pdf-lib, qpdf, MuPDF, and Tesseract.js), each governed by its own respective license.',
    ),
    p(
      'The YeetPDF name, logo, and website content (excluding the open-source code itself) remain the property of their respective owner. Nothing in these Terms grants you any right to the YeetPDF name or branding beyond fair use.',
    ),

    h('h2', '7. Disclaimer of warranties'),
    p(
      h(
        'strong',
        'THE SERVICE IS PROVIDED “AS IS” AND “AS AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT, OR ANY WARRANTY THAT THE SERVICE WILL BE ACCURATE, UNINTERRUPTED, ERROR-FREE, SECURE, OR FREE OF HARMFUL COMPONENTS. YOU USE THE SERVICE ENTIRELY AT YOUR OWN RISK.',
      ),
    ),

    h('h2', '8. Limitation of liability'),
    p(
      h(
        'strong',
        'TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL YEETPDF, ITS OPERATOR, CONTRIBUTORS, OR LICENSORS BE LIABLE FOR ANY DAMAGES OF ANY KIND — WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE, AND INCLUDING WITHOUT LIMITATION ANY LOSS OF DATA, FILES, PROFITS, REVENUE, OR GOODWILL — ARISING FROM OR RELATING TO YOUR USE OF, OR INABILITY TO USE, THE SERVICE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND EVEN IF A REMEDY FAILS OF ITS ESSENTIAL PURPOSE. BECAUSE THE SERVICE IS PROVIDED ENTIRELY FREE OF CHARGE, YOU AGREE THAT YOUR SOLE AND EXCLUSIVE REMEDY FOR ANY DISSATISFACTION WITH, OR DAMAGE ARISING FROM, THE SERVICE IS TO STOP USING IT, AND THAT OUR TOTAL AGGREGATE LIABILITY TO YOU FOR ANY AND ALL CLAIMS RELATING TO THE SERVICE SHALL NOT EXCEED $0.00 (ZERO U.S. DOLLARS).',
      ),
    ),

    h('h2', '9. Indemnification'),
    p(
      'You agree to defend, indemnify, and hold harmless YeetPDF and its operator from and against any claims, damages, losses, liabilities, and expenses (including reasonable legal fees) arising out of or related to: (a) your use or misuse of the Service; (b) any document or file you create, edit, sign, or process using the Service; (c) your violation of these Terms; or (d) your violation of any law or the rights of a third party.',
    ),

    h('h2', '10. Export & sanctions compliance'),
    p(
      'The Service includes encryption and password-protection functionality. You represent that you are not located in, and are not a national or resident of, any country or region subject to comprehensive U.S. or other applicable trade sanctions, and that you do not appear on any restricted-party or denied-persons list. You are responsible for complying with any import, export, or use restrictions on encryption software that apply in your own country.',
    ),

    h('h2', '11. Changes, suspension & termination'),
    p('We may modify, suspend, or discontinue the Service, or any part of it, temporarily or permanently, at any time, with or without notice, and without liability to you — the Service is provided free of charge, with no ongoing obligation to maintain it.'),

    h('h2', '12. Dispute resolution; arbitration; class action waiver'),
    p(
      'Before filing any claim, you agree to first contact us at the email below and attempt in good faith to resolve the dispute informally for at least 30 days. If the dispute remains unresolved, you and YeetPDF agree that it will be resolved by binding, individual arbitration administered under the rules of the American Arbitration Association, rather than in court — except that either party may bring an individual claim in small-claims court where available. ',
      h('strong', 'YOU AND YEETPDF EACH WAIVE ANY RIGHT TO A JURY TRIAL AND TO PARTICIPATE IN A CLASS ACTION, CLASS ARBITRATION, OR REPRESENTATIVE PROCEEDING.'),
      ' You may opt out of this arbitration clause by emailing us within 30 days of first using the Service, stating your intent to opt out.',
    ),

    h('h2', '13. Governing law'),
    p('These Terms are governed by the laws of the State of Delaware, USA, without regard to its conflict-of-laws principles, except where a mandatory consumer-protection law of your own jurisdiction requires otherwise.'),

    h('h2', '14. General provisions'),
    p(
      'If any provision of these Terms is found unenforceable, the remaining provisions remain in full effect. These Terms, together with the Privacy Policy, form the entire agreement between you and YeetPDF regarding the Service. Our failure to enforce any provision is not a waiver of it. You may not assign these Terms; we may assign them freely. Neither party is liable for delays or failures caused by circumstances beyond its reasonable control.',
    ),

    h('h2', '15. Changes to these Terms'),
    p('We may update these Terms from time to time; the “last updated” date above reflects the most recent revision. Continuing to use the Service after a change takes effect means you accept the revised Terms.'),

    h('h2', '16. Contact'),
    p('Questions about these Terms? Reach us at ', mail(), '.'),
  );
}
