// ARC Proofing — menu pages: Verify, Docs, API, Sign In
const { useState: useP, useEffect: useEP, useRef: useRP } = React;

// ── VERIFY ────────────────────────────────────────────────────────────────

function VerifyPage() {
  const [input, setInput] = useP('');
  const [state, setState] = useP('idle'); // idle | verifying | found | notfound
  const [result, setResult] = useP(null);
  const [dragOver, setDragOver] = useP(false);
  const fileRef = useRP(null);

  async function hashFile(file) {
    const buf = await file.arrayBuffer();
    const digest = await crypto.subtle.digest('SHA-256', buf);
    return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join('');
  }

  async function handleDrop(e) {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files[0];
    if (!file) return;
    setInput(await hashFile(file));
  }

  async function handleFileChange(e) {
    const file = e.target.files[0];
    if (!file) return;
    setInput(await hashFile(file));
  }

  function verify() {
    const q = input.trim();
    if (!q) return;
    setState('verifying');
    setResult(null);
    setTimeout(() => {
      const found = parseInt(q[0], 16) < 8;
      if (found) {
        setState('found');
        setResult({
          hash: q.length === 64 ? q : '8f3a2b1c9d4e7f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a',
          txid: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2',
          block: 879211,
          timestamp: '2025-10-14T07:42:18Z',
          confirmations: 1204,
          anchors: ['Bitcoin', 'Ethereum', 'IPFS'],
        });
      } else {
        setState('notfound');
      }
    }, 1600);
  }

  return (
    <main className="vfy-page lp-wrap">
      <div className="vfy-head">
        <p className="lp-eyebrow">Public Verification</p>
        <h1 className="vfy-h1">Verify a Record</h1>
        <p className="vfy-sub">
          No account required. Drop a file to compute its SHA-256 fingerprint, or paste a
          hash or transaction ID. Any ARC Proof record is verifiable by anyone, forever.
        </p>
      </div>

      <div
        className={'vfy-drop' + (dragOver ? ' over' : '')}
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={handleDrop}
        onClick={() => fileRef.current.click()}
      >
        <input ref={fileRef} type="file" style={{ display: 'none' }} onChange={handleFileChange} />
        <div className="vfy-drop-icon">⊞</div>
        <p className="vfy-drop-label">Drop any file to compute its hash</p>
        <p className="vfy-drop-sub">SHA-256 computed locally — file never leaves your device</p>
      </div>

      <div className="vfy-or"><span>or paste a hash / transaction ID</span></div>

      <div className="vfy-input-row">
        <input
          className="vfy-input mono"
          placeholder="SHA-256 hash or Bitcoin txid…"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && verify()}
          spellCheck={false}
        />
        <button className="btn-fill vfy-btn" onClick={verify} disabled={state === 'verifying' || !input.trim()}>
          {state === 'verifying' ? 'Verifying…' : 'Verify →'}
        </button>
      </div>

      {state === 'verifying' && (
        <div className="vfy-status">
          <div className="vfy-spinner" />
          <p className="mono">Querying blockchain anchors…</p>
        </div>
      )}

      {state === 'found' && result && (
        <div className="vfy-result found">
          <div className="vfy-badge found-badge">✓ Verified</div>
          <div className="vr-grid">
            <div className="vr-row"><span className="vr-k">SHA-256 Hash</span><span className="vr-v mono">{result.hash.slice(0, 32)}…</span></div>
            <div className="vr-row"><span className="vr-k">Transaction ID</span><span className="vr-v mono">{result.txid.slice(0, 32)}…</span></div>
            <div className="vr-row"><span className="vr-k">Block Height</span><span className="vr-v mono">{result.block.toLocaleString()}</span></div>
            <div className="vr-row"><span className="vr-k">Timestamp</span><span className="vr-v mono">{result.timestamp}</span></div>
            <div className="vr-row"><span className="vr-k">Confirmations</span><span className="vr-v mono">{result.confirmations.toLocaleString()}</span></div>
            <div className="vr-row">
              <span className="vr-k">Anchors</span>
              <span className="vr-v">{result.anchors.map(a => <span key={a} className="pill" style={{ marginRight: 6 }}>{a}</span>)}</span>
            </div>
          </div>
          <p className="vfy-note">
            This record is permanently anchored to Bitcoin block {result.block.toLocaleString()}.
            It cannot be altered or removed.
          </p>
        </div>
      )}

      {state === 'notfound' && (
        <div className="vfy-result notfound">
          <div className="vfy-badge notfound-badge">✗ Not Found</div>
          <p className="vfy-note">
            No ARC Proof record found for this hash. The file may not have been anchored,
            or the hash may be incorrect.
          </p>
        </div>
      )}
    </main>
  );
}

// ── DOCS ──────────────────────────────────────────────────────────────────

const DOC_SECTIONS = [
  { id: 'overview',    label: 'Overview' },
  { id: 'quickstart',  label: 'Quickstart' },
  { id: 'protocol',    label: 'How It Works' },
  { id: 'verification',label: 'Verification' },
  { id: 'sdks',        label: 'SDKs' },
  { id: 'compliance',  label: 'Compliance Guides' },
];

function DocsPage() {
  const [active, setActive] = useP('overview');

  useEP(() => {
    const onScroll = () => {
      for (const s of DOC_SECTIONS) {
        const el = document.getElementById('doc-' + s.id);
        if (el && el.getBoundingClientRect().top <= 120) setActive(s.id);
      }
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const scrollTo = (id) => {
    document.getElementById('doc-' + id)?.scrollIntoView({ behavior: 'smooth' });
    setActive(id);
  };

  return (
    <div className="docs-layout lp-wrap">
      <aside className="docs-aside">
        <p className="docs-aside-label">Documentation</p>
        <nav>
          {DOC_SECTIONS.map(s => (
            <button key={s.id} className={'docs-link' + (active === s.id ? ' on' : '')}
              onClick={() => scrollTo(s.id)}>{s.label}</button>
          ))}
        </nav>
      </aside>

      <article className="docs-body">

        <section id="doc-overview" className="doc-sec">
          <p className="lp-eyebrow">Overview</p>
          <h2 className="doc-h2">What is ARC Proof?</h2>
          <p className="doc-p">ARC Proof (A Record of ___) is a Bitcoin-anchored cryptographic timestamping system. It creates verifiable, permanent records of any digital content — documents, images, contracts, research data — without requiring a trusted third party.</p>
          <p className="doc-p">Each proof is a SHA-256 hash of your content anchored to the Bitcoin blockchain via OpenTimestamps. Timestamps are mathematically verifiable by anyone, forever.</p>
          <div className="doc-callout">
            <p className="callout-k">Core Guarantee</p>
            <p className="callout-v">Once anchored, an ARC Proof record is immutable. No authority — including ARC Knowware — can alter or remove it.</p>
          </div>
        </section>

        <section id="doc-quickstart" className="doc-sec">
          <p className="lp-eyebrow">Quickstart</p>
          <h2 className="doc-h2">Create your first proof</h2>
          <div className="doc-steps">
            {[
              { n: '01', t: 'Install the SDK', code: 'npm install @arcproof/sdk' },
              { n: '02', t: 'Initialize', code: `import { ArcProof } from '@arcproof/sdk';\n\nconst arc = new ArcProof({ apiKey: 'arc_sk_...' });` },
              { n: '03', t: 'Anchor a file', code: `const proof = await arc.anchor(file);\nconsole.log(proof.txid); // Bitcoin transaction ID` },
              { n: '04', t: 'Verify anytime', code: `const status = await arc.verify(proof.hash);\nconsole.log(status.confirmations); // 1,204` },
            ].map(s => (
              <div className="doc-step" key={s.n}>
                <span className="ds-n">{s.n}</span>
                <div className="ds-body">
                  <h4>{s.t}</h4>
                  <pre className="doc-code">{s.code}</pre>
                </div>
              </div>
            ))}
          </div>
        </section>

        <section id="doc-protocol" className="doc-sec">
          <p className="lp-eyebrow">How It Works</p>
          <h2 className="doc-h2">The protocol</h2>
          <p className="doc-p">ARC Proof uses OpenTimestamps — an open protocol for distributed, trust-free timestamps. Here's what happens when you anchor a file:</p>
          <div className="doc-flow">
            {[
              { n: '1', t: 'SHA-256 hash', d: 'Your file is hashed locally. Content never leaves your device.' },
              { n: '2', t: 'Merkle aggregation', d: 'Your hash is batched with thousands of others, reducing blockchain footprint.' },
              { n: '3', t: 'Bitcoin OP_RETURN', d: 'The Merkle root is committed to Bitcoin via an OP_RETURN transaction. Permanent.' },
              { n: '4', t: 'Confirmation', d: 'After 6 confirmations (~1 hour), your proof is irreversibly anchored. Verifiable forever.' },
            ].map(s => (
              <div className="doc-flow-step" key={s.n}>
                <span className="dfs-n">{s.n}</span>
                <div><strong>{s.t}</strong><p>{s.d}</p></div>
              </div>
            ))}
          </div>
          <div className="doc-impl">
            {[
              ['Hash algorithm', 'SHA-256'],
              ['Primary anchor', 'Bitcoin OP_RETURN'],
              ['Protocol', 'OpenTimestamps'],
              ['Redundancy', '6 networks'],
              ['Avg. confirmation', '< 1 hour'],
            ].map(([k, v]) => (
              <div key={k} className="di-row">
                <span className="di-k">{k}</span>
                <span className="di-v mono">{v}</span>
              </div>
            ))}
          </div>
        </section>

        <section id="doc-verification" className="doc-sec">
          <p className="lp-eyebrow">Verification</p>
          <h2 className="doc-h2">Independent verification</h2>
          <p className="doc-p">Verification requires no account and no trust in ARC Knowware. Any observer can verify a proof using only the original file (or its SHA-256 hash) and the Bitcoin blockchain.</p>
          <pre className="doc-code">{`# Verify via CLI\nnpx @arcproof/cli verify --file ./contract.pdf\n\n# Output:\n# ✓ Verified\n# Hash:          8f3a2b1c9d4e…\n# Block:         879,211\n# Confirmations: 1,204\n# Timestamp:     2025-10-14T07:42:18Z`}</pre>
        </section>

        <section id="doc-sdks" className="doc-sec">
          <p className="lp-eyebrow">SDKs</p>
          <h2 className="doc-h2">Available SDKs</h2>
          <div className="doc-sdks">
            {[
              { name: 'JavaScript / TypeScript', pkg: '@arcproof/sdk', status: 'Stable' },
              { name: 'Python', pkg: 'arcproof-python', status: 'Stable' },
              { name: 'Go', pkg: 'github.com/arcproof/go-sdk', status: 'Beta' },
              { name: 'REST API', pkg: 'api.arcproof.ing/v1', status: 'Stable' },
            ].map(s => (
              <div className="doc-sdk" key={s.name}>
                <div className="sdk-top">
                  <span className="sdk-name">{s.name}</span>
                  <span className={'sdk-status ' + s.status.toLowerCase()}>{s.status}</span>
                </div>
                <span className="sdk-pkg mono">{s.pkg}</span>
              </div>
            ))}
          </div>
        </section>

        <section id="doc-compliance" className="doc-sec">
          <p className="lp-eyebrow">Compliance Guides</p>
          <h2 className="doc-h2">Framework-specific guides</h2>
          <div className="doc-guides">
            {[
              { v: 'IP', fw: 'USPTO / EPO', desc: 'Establishing prior art for patent applications and IP disputes.' },
              { v: 'Legal', fw: 'FRCP / FRE', desc: 'Creating legally admissible evidence for US federal proceedings.' },
              { v: 'Science', fw: 'FDA 21 CFR Part 11', desc: 'Electronic records for regulated research.' },
              { v: 'Media', fw: 'C2PA / CAI', desc: 'Content provenance and authenticity standards.' },
              { v: 'Finance', fw: 'SOX / GDPR', desc: 'Financial document integrity and audit trail requirements.' },
              { v: 'Trade', fw: 'ICC / WTO', desc: 'International trade documentation and chain of custody.' },
            ].map(g => (
              <div className="doc-guide" key={g.v}>
                <div className="dg-top">
                  <span className="dg-v">{g.v}</span>
                  <span className="dg-fw mono">{g.fw}</span>
                </div>
                <p className="dg-d">{g.desc}</p>
              </div>
            ))}
          </div>
        </section>

      </article>
    </div>
  );
}

// ── API ───────────────────────────────────────────────────────────────────

const API_SECTIONS = [
  { id: 'intro',  label: 'Introduction' },
  { id: 'auth',   label: 'Authentication' },
  { id: 'anchor', label: 'POST /anchor' },
  { id: 'verify', label: 'GET /verify/:hash' },
  { id: 'proof',  label: 'GET /proof/:id' },
  { id: 'errors', label: 'Errors' },
  { id: 'limits', label: 'Rate Limits' },
];

function APIPage() {
  const [active, setActive] = useP('intro');

  useEP(() => {
    const onScroll = () => {
      for (const s of API_SECTIONS) {
        const el = document.getElementById('api-' + s.id);
        if (el && el.getBoundingClientRect().top <= 120) setActive(s.id);
      }
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const scrollTo = (id) => {
    document.getElementById('api-' + id)?.scrollIntoView({ behavior: 'smooth' });
    setActive(id);
  };

  return (
    <div className="docs-layout lp-wrap">
      <aside className="docs-aside">
        <p className="docs-aside-label">API Reference</p>
        <p className="api-base mono">api.arcproof.ing/v1</p>
        <nav>
          {API_SECTIONS.map(s => (
            <button key={s.id} className={'docs-link' + (active === s.id ? ' on' : '')}
              onClick={() => scrollTo(s.id)}>{s.label}</button>
          ))}
        </nav>
      </aside>

      <article className="docs-body">

        <section id="api-intro" className="doc-sec">
          <p className="lp-eyebrow">API Reference</p>
          <h1 className="doc-h1">ARC Proof REST API</h1>
          <p className="doc-p">Base URL: <span className="mono">https://api.arcproof.ing/v1</span></p>
          <p className="doc-p">All responses are JSON. HTTPS only. Timestamps are ISO 8601 UTC.</p>
        </section>

        <section id="api-auth" className="doc-sec">
          <p className="lp-eyebrow">Authentication</p>
          <h2 className="doc-h2">API Keys</h2>
          <p className="doc-p">Authenticate using a Bearer token. Keys are prefixed <span className="mono">arc_sk_</span> (secret) or <span className="mono">arc_pk_</span> (publishable). Secret keys carry full write access — never expose them client-side.</p>
          <pre className="doc-code">{`curl https://api.arcproof.ing/v1/verify/8f3a2b1c… \\\n  -H "Authorization: Bearer arc_sk_live_..."`}</pre>
          <div className="doc-callout warn">
            <p className="callout-k">Key security</p>
            <p className="callout-v">Use publishable keys (<span className="mono">arc_pk_</span>) for browser-side verification requests. Reserve secret keys for server environments.</p>
          </div>
        </section>

        <section id="api-anchor" className="doc-sec">
          <div className="api-method-head">
            <span className="method-badge post">POST</span>
            <span className="mono api-path">/anchor</span>
          </div>
          <h2 className="doc-h2">Anchor a record</h2>
          <p className="doc-p">Submit a SHA-256 hash for Bitcoin anchoring. Hashes are batched and committed to the next available block (~10 min cadence).</p>
          <h4 className="doc-h4">Request body</h4>
          <pre className="doc-code">{`{\n  "hash": "8f3a2b1c9d4e7f0a…",  // SHA-256 hex (required)\n  "metadata": {               // optional\n    "label": "contract-q4.pdf",\n    "vertical": "legal"\n  }\n}`}</pre>
          <h4 className="doc-h4">Response</h4>
          <pre className="doc-code">{`{\n  "id": "arc_pr_01HX…",\n  "hash": "8f3a2b1c9d4e7f0a…",\n  "status": "pending",\n  "submitted_at": "2025-10-14T07:40:00Z",\n  "estimated_confirmation": "2025-10-14T08:40:00Z"\n}`}</pre>
        </section>

        <section id="api-verify" className="doc-sec">
          <div className="api-method-head">
            <span className="method-badge get">GET</span>
            <span className="mono api-path">/verify/:hash</span>
          </div>
          <h2 className="doc-h2">Verify a hash</h2>
          <p className="doc-p">Check whether a SHA-256 hash has an ARC Proof record. Returns anchoring details if found.</p>
          <h4 className="doc-h4">Request</h4>
          <pre className="doc-code">{`curl https://api.arcproof.ing/v1/verify/8f3a2b1c… \\\n  -H "Authorization: Bearer arc_pk_live_..."`}</pre>
          <h4 className="doc-h4">Response (found)</h4>
          <pre className="doc-code">{`{\n  "found": true,\n  "hash": "8f3a2b1c9d4e…",\n  "txid": "a1b2c3d4e5f6…",\n  "block_height": 879211,\n  "block_time": "2025-10-14T07:42:18Z",\n  "confirmations": 1204,\n  "anchors": ["bitcoin","ethereum","ipfs"]\n}`}</pre>
          <h4 className="doc-h4">Response (not found)</h4>
          <pre className="doc-code">{`{ "found": false }`}</pre>
        </section>

        <section id="api-proof" className="doc-sec">
          <div className="api-method-head">
            <span className="method-badge get">GET</span>
            <span className="mono api-path">/proof/:id</span>
          </div>
          <h2 className="doc-h2">Get proof by ID</h2>
          <p className="doc-p">Retrieve a complete proof record. Includes the OpenTimestamps <span className="mono">.ots</span> file for independent verification.</p>
          <h4 className="doc-h4">Response</h4>
          <pre className="doc-code">{`{\n  "id": "arc_pr_01HX…",\n  "hash": "8f3a2b1c9d4e…",\n  "status": "confirmed",\n  "txid": "a1b2c3d4e5f6…",\n  "block_height": 879211,\n  "confirmations": 1204,\n  "ots_proof": "base64…",\n  "certificate_url": "https://arcproof.ing/cert/arc_pr_01HX…"\n}`}</pre>
        </section>

        <section id="api-errors" className="doc-sec">
          <p className="lp-eyebrow">Errors</p>
          <h2 className="doc-h2">Error codes</h2>
          <div className="error-table">
            {[
              ['400', 'invalid_hash',    'The hash is not a valid 64-char SHA-256 hex string.'],
              ['401', 'unauthorized',    'Missing or invalid API key.'],
              ['404', 'not_found',       'No record found for this hash or ID.'],
              ['429', 'rate_limited',    'Too many requests. See X-RateLimit-* headers.'],
              ['500', 'internal_error',  'Unexpected error. Retrying with backoff is safe.'],
            ].map(([code, type, msg]) => (
              <div className="err-row" key={code}>
                <span className="err-code mono">{code}</span>
                <span className="err-type mono">{type}</span>
                <span className="err-msg">{msg}</span>
              </div>
            ))}
          </div>
        </section>

        <section id="api-limits" className="doc-sec">
          <p className="lp-eyebrow">Rate Limits</p>
          <h2 className="doc-h2">Request limits</h2>
          <div className="doc-impl">
            {[
              ['Entry plan',          '100 req / hour'],
              ['Professional',        '10,000 req / hour'],
              ['Enterprise',          'Custom'],
              ['Public verification', '1,000 req / hour / IP'],
            ].map(([k, v]) => (
              <div key={k} className="di-row">
                <span className="di-k">{k}</span>
                <span className="di-v mono">{v}</span>
              </div>
            ))}
          </div>
          <p className="doc-p" style={{ marginTop: 24 }}>Headers on every response: <span className="mono">X-RateLimit-Limit</span>, <span className="mono">X-RateLimit-Remaining</span>, <span className="mono">X-RateLimit-Reset</span>.</p>
        </section>

      </article>
    </div>
  );
}

// ── SIGN IN ───────────────────────────────────────────────────────────────

function SignInPage() {
  const [mode, setMode] = useP('in'); // 'in' | 'up'
  const [email, setEmail] = useP('');
  const [password, setPassword] = useP('');
  const [submitting, setSubmitting] = useP(false);
  const [done, setDone] = useP(false);

  function submit(e) {
    e.preventDefault();
    if (!email || !password) return;
    setSubmitting(true);
    setTimeout(() => { setSubmitting(false); setDone(true); }, 1200);
  }

  return (
    <div className="signin-page">
      <div className="signin-card">
        {done ? (
          <div className="signin-done">
            <div className="done-mark">✓</div>
            <h2>{mode === 'in' ? 'Signed in.' : 'Account created.'}</h2>
            <p>Redirecting to your dashboard…</p>
          </div>
        ) : (
          <>
            <div className="signin-head">
              <h2 className="si-title">{mode === 'in' ? 'Sign in' : 'Create account'}</h2>
              <p className="si-sub">{mode === 'in' ? 'Welcome back.' : 'Start anchoring records.'}</p>
            </div>
            <form className="signin-form" onSubmit={submit}>
              <label className="si-label">
                <span>Email</span>
                <input className="si-input" type="email" placeholder="you@example.com"
                  value={email} onChange={e => setEmail(e.target.value)} autoFocus />
              </label>
              <label className="si-label">
                <span>Password</span>
                <input className="si-input" type="password"
                  placeholder={mode === 'up' ? 'Choose a strong password' : '············'}
                  value={password} onChange={e => setPassword(e.target.value)} />
              </label>
              <button className="btn-fill si-submit" type="submit" disabled={submitting || !email || !password}>
                {submitting ? 'One moment…' : (mode === 'in' ? 'Sign in →' : 'Create account →')}
              </button>
            </form>
            <div className="si-or-wrap"><div className="si-or-line"><span>or continue with</span></div></div>
            <div className="si-sso-btns">
              <button className="sso-btn">GitHub</button>
              <button className="sso-btn">Google</button>
            </div>
            <div className="si-switch">
              {mode === 'in'
                ? <p>No account? <button className="si-tog" onClick={() => setMode('up')}>Create one →</button></p>
                : <p>Have an account? <button className="si-tog" onClick={() => setMode('in')}>Sign in →</button></p>
              }
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── TERMS ─────────────────────────────────────────────────────────────────

function TermsPage() {
  return (
    <main className="legal-page lp-wrap">
      <div className="legal-head">
        <p className="lp-eyebrow">Legal</p>
        <h1 className="legal-h1">Terms of Service</h1>
        <p className="legal-meta mono">Effective: 1 January 2025 · ARC Knowware, Inc.</p>
      </div>
      <div className="legal-body">

        <section className="legal-sec">
          <h2>1. Acceptance</h2>
          <p>By accessing or using ARC Proof (the "Service"), you agree to be bound by these Terms of Service. If you do not agree, do not use the Service. ARC Knowware, Inc. ("ARC Knowware", "we", "us") reserves the right to update these terms; continued use after notice constitutes acceptance.</p>
        </section>

        <section className="legal-sec">
          <h2>2. Description of Service</h2>
          <p>ARC Proof provides Bitcoin-anchored cryptographic timestamping. The Service computes SHA-256 hashes of user-submitted content and commits those hashes to the Bitcoin blockchain via the OpenTimestamps protocol. ARC Knowware does not store the content of your files — only the hash.</p>
          <p>Anchoring creates a verifiable, immutable timestamp. It does not constitute legal advice, and ARC Knowware makes no representation as to the legal admissibility of any record in any jurisdiction.</p>
        </section>

        <section className="legal-sec">
          <h2>3. Permitted Use</h2>
          <p>You may use the Service only for lawful purposes. You agree not to:</p>
          <ul className="legal-list">
            <li>Submit hashes derived from content that violates applicable law or third-party rights</li>
            <li>Attempt to reverse-engineer, scrape, or abuse the API beyond your plan's rate limits</li>
            <li>Misrepresent a timestamp record or use it to fabricate evidence</li>
            <li>Resell or sublicense API access without a written enterprise agreement</li>
          </ul>
        </section>

        <section className="legal-sec">
          <h2>4. Intellectual Property</h2>
          <p>The Service, including all software, protocols, and documentation, is the property of ARC Knowware or its licensors. The OpenTimestamps protocol is open-source under the MIT License. Your content remains yours; by anchoring a hash you grant no rights to ARC Knowware in the underlying content.</p>
        </section>

        <section className="legal-sec">
          <h2>5. Disclaimer of Warranties</h2>
          <p>THE SERVICE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ARC KNOWWARE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. WE DO NOT WARRANT THAT THE SERVICE WILL BE UNINTERRUPTED, ERROR-FREE, OR THAT ANY PARTICULAR RECORD WILL BE LEGALLY ADMISSIBLE.</p>
        </section>

        <section className="legal-sec">
          <h2>6. Limitation of Liability</h2>
          <p>TO THE MAXIMUM EXTENT PERMITTED BY LAW, ARC KNOWWARE'S TOTAL LIABILITY FOR ANY CLAIM ARISING OUT OF OR RELATING TO THESE TERMS OR THE SERVICE SHALL NOT EXCEED THE AMOUNT YOU PAID IN THE TWELVE MONTHS PRECEDING THE CLAIM. ARC KNOWWARE SHALL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES.</p>
        </section>

        <section className="legal-sec">
          <h2>7. Governing Law</h2>
          <p>These Terms are governed by the laws of the State of Delaware, USA, without regard to conflict of law principles. Any dispute shall be resolved by binding arbitration under the AAA Commercial Arbitration Rules, with proceedings in English.</p>
        </section>

        <section className="legal-sec">
          <h2>8. Contact</h2>
          <p>Questions about these Terms: <a className="legal-link" href="mailto:legal@arcproof.ing">legal@arcproof.ing</a></p>
        </section>

      </div>
    </main>
  );
}

// ── PRIVACY ───────────────────────────────────────────────────────────────

function PrivacyPage() {
  return (
    <main className="legal-page lp-wrap">
      <div className="legal-head">
        <p className="lp-eyebrow">Legal</p>
        <h1 className="legal-h1">Privacy Policy</h1>
        <p className="legal-meta mono">Effective: 1 January 2025 · ARC Knowware, Inc.</p>
      </div>
      <div className="legal-body">

        <section className="legal-sec">
          <h2>1. What We Collect</h2>
          <p>We collect only what is necessary to operate the Service:</p>
          <ul className="legal-list">
            <li><strong>SHA-256 hashes</strong> — submitted for anchoring. Never the underlying content.</li>
            <li><strong>Account data</strong> — email address and hashed password if you create an account.</li>
            <li><strong>API usage logs</strong> — timestamps, endpoint, response code, and plan tier. No request bodies.</li>
            <li><strong>Payment data</strong> — processed by Stripe. We receive only a token; no card numbers are stored.</li>
          </ul>
          <p>No analytics SDKs, tracking pixels, or third-party advertising is embedded in the Service.</p>
        </section>

        <section className="legal-sec">
          <h2>2. How We Use It</h2>
          <p>We use collected data to: deliver and improve the Service, authenticate users, enforce rate limits, process payments, and respond to support requests. We do not sell your data, use it for advertising, or share it with third parties except as described below.</p>
        </section>

        <section className="legal-sec">
          <h2>3. Third-Party Processors</h2>
          <div className="legal-table">
            {[
              ['Stripe', 'Payment processing', 'stripe.com/privacy'],
              ['Cloudflare', 'CDN and DDoS protection', 'cloudflare.com/privacypolicy'],
              ['Bitcoin network', 'Blockchain anchoring (public)', 'Open protocol — no personal data transmitted'],
            ].map(([name, role, policy]) => (
              <div className="lt-row" key={name}>
                <span className="lt-name">{name}</span>
                <span className="lt-role">{role}</span>
                <span className="lt-pol mono">{policy}</span>
              </div>
            ))}
          </div>
        </section>

        <section className="legal-sec">
          <h2>4. Data Retention</h2>
          <p>Anchored hashes and their blockchain references are retained indefinitely — they are public by design. Account data is retained for the life of your account plus 90 days after deletion. API logs are retained for 90 days.</p>
        </section>

        <section className="legal-sec">
          <h2>5. Your Rights</h2>
          <p>Depending on your jurisdiction you may have rights to access, correct, or delete your personal data. Note that anchored hashes on the Bitcoin blockchain are irremovable by design — this is fundamental to the integrity of the Service. Account data can be deleted on request.</p>
          <p>To exercise your rights: <a className="legal-link" href="mailto:privacy@arcproof.ing">privacy@arcproof.ing</a></p>
        </section>

        <section className="legal-sec">
          <h2>6. Security</h2>
          <p>Data in transit is encrypted with TLS 1.3. Passwords are hashed with bcrypt (cost factor 12). API keys are stored as HMAC-SHA256 digests. We conduct annual penetration tests and maintain a responsible disclosure program at <a className="legal-link" href="mailto:security@arcproof.ing">security@arcproof.ing</a>.</p>
        </section>

        <section className="legal-sec">
          <h2>7. Contact</h2>
          <p>Privacy inquiries: <a className="legal-link" href="mailto:privacy@arcproof.ing">privacy@arcproof.ing</a><br />
          ARC Knowware, Inc. · 2261 Market Street #4667 · San Francisco, CA 94114</p>
        </section>

      </div>
    </main>
  );
}

// ── STATUS ────────────────────────────────────────────────────────────────

const SERVICES = [
  { name: 'Anchoring API',        ok: true,  latency: '38ms',  uptime: '99.98%' },
  { name: 'Verification API',     ok: true,  latency: '22ms',  uptime: '99.99%' },
  { name: 'Bitcoin relay',        ok: true,  latency: '410ms', uptime: '99.97%' },
  { name: 'Web portal',           ok: true,  latency: '61ms',  uptime: '100%'   },
  { name: 'Certificate delivery', ok: true,  latency: '88ms',  uptime: '99.95%' },
  { name: 'OpenTimestamps relay', ok: true,  latency: '190ms', uptime: '99.92%' },
];

const INCIDENTS = [
  { date: '2025-10-09', title: 'Elevated anchoring latency', status: 'Resolved', detail: 'Bitcoin mempool congestion caused a 4-hour delay in anchor confirmations. Records remained queued and were confirmed after the backlog cleared. No data loss.' },
  { date: '2025-08-22', title: 'Certificate delivery degraded', status: 'Resolved', detail: 'A CDN misconfiguration caused intermittent 503 errors on certificate downloads for approximately 40 minutes. No anchoring data was affected.' },
  { date: '2025-06-14', title: 'Planned maintenance', status: 'Completed', detail: 'Database migration to improve API response times. Zero downtime. Scheduled 02:00–03:00 UTC.' },
];

function StatusPage() {
  const [now, setNow] = useP(() => new Date());
  useEP(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  const allOk = SERVICES.every(s => s.ok);

  return (
    <main className="status-page lp-wrap">
      <div className="status-head">
        <p className="lp-eyebrow">System Status</p>
        <div className={'status-overall' + (allOk ? ' ok' : ' deg')}>
          <div className={'so-dot' + (allOk ? ' ok' : ' deg')} />
          <h1 className="so-label">{allOk ? 'All systems operational' : 'Degraded performance'}</h1>
        </div>
        <p className="status-time mono">{now.toUTCString()}</p>
      </div>

      <section className="status-sec">
        <p className="status-sec-label">Services</p>
        <div className="svc-list">
          {SERVICES.map(s => (
            <div className="svc-row" key={s.name}>
              <div className="svc-left">
                <div className={'svc-dot' + (s.ok ? ' ok' : ' down')} />
                <span className="svc-name">{s.name}</span>
              </div>
              <div className="svc-right">
                <span className="svc-lat mono">{s.latency}</span>
                <span className="svc-up mono">{s.uptime}</span>
                <span className={'svc-status' + (s.ok ? ' ok' : ' down')}>{s.ok ? 'Operational' : 'Degraded'}</span>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="status-sec">
        <p className="status-sec-label">90-day uptime</p>
        <div className="uptime-bars">
          {SERVICES.map(s => (
            <div className="uptime-row" key={s.name}>
              <span className="ur-name">{s.name}</span>
              <div className="ur-track">
                {Array.from({ length: 90 }, (_, i) => (
                  <div key={i} className={'ur-day' + (i === 9 || i === 52 ? ' miss' : '')} />
                ))}
              </div>
              <span className="ur-pct mono">{s.uptime}</span>
            </div>
          ))}
        </div>
      </section>

      <section className="status-sec">
        <p className="status-sec-label">Incident history</p>
        <div className="incident-list">
          {INCIDENTS.map(inc => (
            <div className="incident" key={inc.date}>
              <div className="inc-top">
                <span className="inc-date mono">{inc.date}</span>
                <span className={'inc-status ' + inc.status.toLowerCase()}>{inc.status}</span>
              </div>
              <p className="inc-title">{inc.title}</p>
              <p className="inc-detail">{inc.detail}</p>
            </div>
          ))}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { VerifyPage, DocsPage, APIPage, SignInPage, TermsPage, PrivacyPage, StatusPage });
