// ─────────────────────────────────────────
// Hidrogen App — root with auth + data boot
// ─────────────────────────────────────────
const { useState: uS, useEffect: uE } = React;
const HDR  = window.HDR_DATA;
const API  = window.HDR_API;
const C    = window.HDR_CONSTANTS;
const U    = window.HDR_UTIL;

function App() {
  const [me, setMe]         = uS(null);
  const [loading, setLoading]   = uS(true);
  const [mode, setMode]     = uS(() => localStorage.getItem('hdr.mode') || 'user');
  const [route, setRoute]   = uS(() => localStorage.getItem('hdr.route') || 'overview');
  const [theme, setTheme]   = uS(() => localStorage.getItem('hdr.theme') || 'dark');
  const [accent, setAccent] = uS(() => localStorage.getItem('hdr.accent') || 'saffron');
  const [density, setDensity]=uS(() => localStorage.getItem('hdr.density') || 'comfortable');
  const [showTweaks, setShowTweaks] = uS(false);

  // Load user + initial data
  uE(() => {
    (async () => {
      try {
        const user = await API.me();
        setMe(user);

        // Force user mode if not admin
        if (!user.is_admin && localStorage.getItem('hdr.mode') === 'admin') {
          setMode('user'); localStorage.setItem('hdr.mode', 'user');
        }
        window.HDR_USER = user;
      } catch (e) {
        if (e.message !== 'unauthorized') console.error(e);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  uE(() => { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('hdr.theme', theme); }, [theme]);
  uE(() => { document.documentElement.setAttribute('data-density', density); localStorage.setItem('hdr.density', density); }, [density]);
  uE(() => { localStorage.setItem('hdr.mode', mode); localStorage.setItem('hdr.route', route); }, [mode, route]);
  uE(() => {
    const map = {
      saffron: { h: '62',  c: '0.16' },
      indigo:  { h: '265', c: '0.15' },
      emerald: { h: '155', c: '0.14' },
      coral:   { h: '30',  c: '0.16' },
    };
    const v = map[accent] || map.saffron;
    document.documentElement.style.setProperty('--accent', `oklch(0.745 ${v.c} ${v.h})`);
    document.documentElement.style.setProperty('--accent-soft', `oklch(0.745 ${v.c} ${v.h} / 0.14)`);
    document.documentElement.style.setProperty('--accent-line', `oklch(0.745 ${v.c} ${v.h} / 0.32)`);
    localStorage.setItem('hdr.accent', accent);
  }, [accent]);

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--bg)', color: 'var(--text)' }}>
        <div style={{ textAlign: 'center' }}>
          <div className="brand-mark" style={{ width: 48, height: 48, fontSize: 24, margin: '0 auto 16px' }}>H</div>
          <div className="muted" style={{ fontSize: 13 }}>Loading Hidrogen…</div>
        </div>
      </div>
    );
  }

  if (!me) {
    return <AuthScreen onAuth={() => location.reload()} />;
  }

  const userScreens = {
    overview:   <UserOverview goto={setRoute}/>,
    playground: <UserPlayground/>,
    agents:     <UserAgents/>,
    skills:     <UserSkills/>,
    keys:       <UserKeys/>,
    billing:    <UserBilling/>,
    logs:       <UserLogs admin={false}/>,
    docs:       <UserDocs/>,
  };
  const adminScreens = {
    overview:   <AdminOverview/>,
    analytics:  <AdminAnalytics/>,
    users:      <AdminUsers/>,
    alllogs:    <UserLogs admin={true}/>,
    models:     <AdminModels/>,
    skills:     <AdminSkills/>,
    tools:      <AdminTools/>,
    settings:   <AdminSettings/>,
  };
  const screen = (mode === 'admin' ? adminScreens : userScreens)[route] || <UserOverview goto={setRoute}/>;

  return (
    <ToastProvider>
      <div className="app" data-screen-label={`${mode}/${route}`}>
        <Sidebar mode={mode} setMode={setMode} route={route} setRoute={setRoute} me={me}/>
        <div className="main">
          <Topbar mode={mode} route={route} theme={theme} setTheme={setTheme} me={me}/>
          <div className="content"><div className="content-narrow">{screen}</div></div>
        </div>
        {showTweaks && (
          <Tweaks
            theme={theme} setTheme={setTheme} accent={accent} setAccent={setAccent}
            density={density} setDensity={setDensity}
            onClose={() => setShowTweaks(false)}
          />
        )}
      </div>
    </ToastProvider>
  );
}

// ─────────────────────────────────────────
// Auth screen (login + signup combined)
// ─────────────────────────────────────────
function AuthScreen({ onAuth }) {
  const [tab, setTab]   = uS('login');
  const [email, setEmail] = uS('');
  const [pwd, setPwd]   = uS('');
  const [name, setName] = uS('');
  const [busy, setBusy] = uS(false);
  const [err, setErr]   = uS('');
  const [legalDoc, setLegalDoc] = uS(null); // 'tc' | 'privacy' | 'refund' | null
  const [agree, setAgree] = uS(false);

  const submit = async (e) => {
    e?.preventDefault();
    if (busy) return;
    if (tab === 'signup' && !agree) { setErr('Please accept the Terms & Privacy Policy'); return; }
    setBusy(true); setErr('');
    try {
      const fn = tab === 'login' ? API.login : API.signup;
      const r = await fn({ email, password: pwd, ...(tab === 'signup' ? { name } : {}) });
      if (r.error) throw new Error(r.error.message || r.error);
      if (r.id || r.ok) onAuth();
      else throw new Error('Auth failed');
    } catch (e) { setErr(e.message || 'Failed'); }
    finally { setBusy(false); }
  };

  return (
    <div className="auth-screen">
      <div className="auth-marketing">
        <div className="row" style={{gap:10}}>
          <div className="brand-mark">H</div>
          <div>
            <div className="brand-name">Hidrogen<span className="brand-suffix">.in</span></div>
            <div className="dim" style={{fontSize:11, fontFamily:'var(--font-mono)'}}>v2.4 · ap-south-1</div>
          </div>
        </div>
        <div className="auth-marketing-content">
          <h1 style={{ fontFamily:'var(--font-display)', fontSize: 40, fontWeight: 300, letterSpacing: '-0.02em', lineHeight: 1.15, margin: 0, marginBottom: 18 }}>
            India's smartest AI API.<br/>
            <span style={{color: 'var(--accent)'}}>One key, every task.</span>
          </h1>
          <p className="muted" style={{ fontSize: 15, lineHeight: 1.6, margin: 0, maxWidth: 480 }}>
            Built in India, for India. Hidrogen routes every request through the right
            model automatically — chat, voice, images, Indian languages — with INR
            billing and zero vendor lock-in.
          </p>

          {/* Hidrogen model aliases — NOT provider names */}
          <div className="model-tiles" style={{marginTop: 36}}>
            <div className="dim" style={{fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12}}>
              Hidrogen Models
            </div>
            <div className="row" style={{gap: 8, flexWrap:'wrap'}}>
              {[
                { alias: 'smart',     tag: 'Default' },
                { alias: 'smart-pro', tag: 'Pro reasoning' },
                { alias: 'fast',      tag: 'Lowest latency' },
                { alias: 'creative',  tag: 'Long-form' },
                { alias: 'image',     tag: 'Visual' },
                { alias: 'voice',     tag: 'TTS' },
                { alias: 'stt-in',    tag: 'Indian STT' },
              ].map(m => (
                <div key={m.alias} style={{
                  padding: '6px 10px',
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-md)',
                  fontSize: 11.5,
                }}>
                  <span className="mono" style={{fontWeight: 500}}>{m.alias}</span>
                  <span className="dim" style={{marginLeft: 6, fontSize: 10.5}}>· {m.tag}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Trust strip */}
          <div className="trust-strip row" style={{marginTop: 28, gap: 22, flexWrap: 'wrap', fontSize: 12}}>
            <div className="row" style={{gap: 6}}>
              <span className="tag-dot" style={{background: 'var(--pos)'}}/>
              <span className="muted">INR billing · GST invoice</span>
            </div>
            <div className="row" style={{gap: 6}}>
              <span className="tag-dot" style={{background: 'var(--accent)'}}/>
              <span className="muted">99.9% uptime · ap-south-1</span>
            </div>
            <div className="row" style={{gap: 6}}>
              <span className="tag-dot" style={{background: 'var(--info)'}}/>
              <span className="muted">Smart fallback · No vendor lock-in</span>
            </div>
          </div>
        </div>
        <div className="legal-links" style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: '6px 14px',
          fontSize: 11.5,
          alignItems: 'center',
          color: 'var(--text-muted)',
        }}>
          <span>© Hidrogen, Lucknow</span>
          <button onClick={() => setLegalDoc('tc')}
                  style={{background:'none', border:'none', color:'var(--text-muted)', cursor:'pointer', padding: 0, fontSize: 11.5, fontFamily: 'inherit'}}>
            Terms & Conditions
          </button>
          <button onClick={() => setLegalDoc('privacy')}
                  style={{background:'none', border:'none', color:'var(--text-muted)', cursor:'pointer', padding: 0, fontSize: 11.5, fontFamily: 'inherit'}}>
            Privacy Policy
          </button>
          <button onClick={() => setLegalDoc('refund')}
                  style={{background:'none', border:'none', color:'var(--text-muted)', cursor:'pointer', padding: 0, fontSize: 11.5, fontFamily: 'inherit'}}>
            Refund Policy
          </button>
        </div>
      </div>

      <div className="auth-form-pane">
        <div style={{ width:'100%', maxWidth: 380 }}>
          <div className="seg" style={{marginBottom: 28}}>
            <button className={tab==='login'  ? 'active' : ''} onClick={()=>{setTab('login');setErr('')}}>Log in</button>
            <button className={tab==='signup' ? 'active' : ''} onClick={()=>{setTab('signup');setErr('')}}>Sign up</button>
          </div>

          <h2 style={{ fontFamily:'var(--font-display)', fontSize: 24, fontWeight: 300, letterSpacing: '-0.01em', margin:'0 0 6px' }}>
            {tab === 'login' ? 'Welcome back' : 'Create your account'}
          </h2>
          <p className="muted" style={{margin:'0 0 24px', fontSize:13}}>
            {tab === 'login' ? 'Sign in to your dashboard.' : 'Free ₹50 credits on signup, no card needed.'}
          </p>

          <form onSubmit={submit} className="col" style={{gap:14}}>
            {tab === 'signup' && (
              <div className="field">
                <div className="label">Name</div>
                <input className="input" type="text" placeholder="Your name" value={name} onChange={e=>setName(e.target.value)} autoFocus/>
              </div>
            )}
            <div className="field">
              <div className="label">Email</div>
              <input className="input" type="email" placeholder="you@example.com" value={email} onChange={e=>setEmail(e.target.value)} autoFocus={tab==='login'} required/>
            </div>
            <div className="field">
              <div className="label">Password</div>
              <input className="input" type="password" placeholder="••••••••" value={pwd} onChange={e=>setPwd(e.target.value)} required minLength={6}/>
            </div>
            {err && <div style={{ padding:'10px 12px', borderRadius:'var(--r-md)', fontSize:12.5, background:'var(--neg-soft)', color:'var(--neg)', border:'1px solid var(--neg-soft)' }}>{err}</div>}

            {tab === 'signup' && (
              <label className="row" style={{gap: 8, cursor: 'pointer', alignItems: 'flex-start', fontSize: 12, lineHeight: 1.55, padding: '4px 0'}}>
                <input type="checkbox" checked={agree} onChange={e => setAgree(e.target.checked)}
                       style={{marginTop: 2, accentColor: 'var(--accent)'}}/>
                <span className="muted">
                  I agree to Hidrogen's{' '}
                  <button type="button" onClick={() => setLegalDoc('tc')} style={{background:'none',border:'none',color:'var(--accent)',cursor:'pointer',padding:0,fontSize:'inherit',fontFamily:'inherit'}}>Terms & Conditions</button>{' '}
                  and{' '}
                  <button type="button" onClick={() => setLegalDoc('privacy')} style={{background:'none',border:'none',color:'var(--accent)',cursor:'pointer',padding:0,fontSize:'inherit',fontFamily:'inherit'}}>Privacy Policy</button>.
                </span>
              </label>
            )}

            <button type="submit" className="btn primary" disabled={busy} style={{justifyContent:'center', height:42, marginTop: 4}}>
              {busy ? 'Please wait…' : (tab === 'login' ? 'Log in →' : 'Create account →')}
            </button>
          </form>

          <div className="muted" style={{ fontSize:12, marginTop: 18, textAlign:'center' }}>
            {tab === 'login'
              ? <>New here? <a href="#" onClick={(e)=>{e.preventDefault();setTab('signup');setErr('')}} style={{color:'var(--accent)'}}>Create an account</a></>
              : <>Already have an account? <a href="#" onClick={(e)=>{e.preventDefault();setTab('login');setErr('')}} style={{color:'var(--accent)'}}>Log in</a></>
            }
          </div>
        </div>
      </div>

      {/* Legal document modal */}
      <LegalModal doc={legalDoc} onClose={() => setLegalDoc(null)}/>
    </div>
  );
}

// ───────── Legal documents modal (T&C, Privacy, Refund) ─────────
function LegalModal({ doc, onClose }) {
  if (!doc) return null;

  const docs = {
    tc: {
      title: 'Terms & Conditions',
      subtitle: 'Last updated: ' + new Date().toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' }),
      content: (
        <>
          <h4>1. Acceptance of Terms</h4>
          <p>By accessing or using the Hidrogen API platform ("Service"), provided by Hidrogen, Lucknow, India ("Hidrogen", "we", "us", "our"), you ("User", "you", "your") agree to be bound by these Terms & Conditions. If you do not agree, do not use the Service.</p>

          <h4>2. The Service</h4>
          <p>Hidrogen provides a unified API gateway for AI services (chat, image, voice, speech-to-text). The Service routes requests intelligently across underlying AI infrastructure, bills in INR, and is intended primarily for Indian developers and businesses.</p>

          <h4>3. Account & Eligibility</h4>
          <p>You must be at least 18 years old and capable of forming a legally binding contract under the Indian Contract Act, 1872. You are responsible for keeping your account credentials and API keys secure. Any activity through your account is your responsibility.</p>

          <h4>4. Acceptable Use</h4>
          <p>You agree NOT to use the Service to:</p>
          <ul>
            <li>Generate, distribute, or facilitate illegal content, hate speech, harassment, or content harming minors</li>
            <li>Reverse-engineer, scrape, or circumvent the API or rate limits</li>
            <li>Resell raw API access without adding substantial value</li>
            <li>Violate any applicable Indian law including the IT Act 2000 and its rules</li>
            <li>Build applications that mislead users about being human (without disclosure)</li>
          </ul>

          <h4>5. Billing & Payments</h4>
          <p>All charges are in Indian Rupees (INR). You pre-fund your wallet via Razorpay (UPI, cards, net-banking) or set up Auto-Pay for recurring monthly recharges. API usage is metered per request and deducted from your wallet balance. Pricing is published in the dashboard and may change with 30 days' notice.</p>
          <p>Auto-Pay: If you enable Auto-Pay, you authorize Razorpay to charge your selected payment instrument every month for the configured amount until you pause or cancel the mandate from your bank/UPI app or Hidrogen dashboard.</p>

          <h4>6. API Keys & Security</h4>
          <p>API keys (prefix <code>hi_</code>) are sensitive credentials. Never commit them to version control, share publicly, or expose them client-side. Compromised keys must be revoked immediately. Hidrogen is not liable for unauthorized usage resulting from your key disclosure.</p>

          <h4>7. Service Availability</h4>
          <p>We target 99.9% uptime but do not guarantee uninterrupted service. Maintenance windows, third-party provider outages, and force-majeure events may cause temporary unavailability. No service credits are issued unless explicitly mentioned in a separate SLA agreement.</p>

          <h4>8. Intellectual Property</h4>
          <p>The Hidrogen platform, branding, and documentation are owned by Hidrogen. You retain ownership of your prompts and the outputs you generate (subject to applicable law on AI-generated content). You grant Hidrogen a limited license to process your inputs solely to deliver the Service.</p>

          <h4>9. Privacy</h4>
          <p>Your data is handled per our Privacy Policy. We do not train models on your data.</p>

          <h4>10. Limitation of Liability</h4>
          <p>To the maximum extent permitted by law, Hidrogen's total aggregate liability for any claims relating to the Service shall not exceed the amount paid by you to Hidrogen in the three (3) months preceding the claim. We are not liable for indirect, incidental, consequential, or punitive damages.</p>

          <h4>11. Termination</h4>
          <p>You may close your account anytime. We may suspend or terminate access for violations of these Terms, prolonged inactivity (12+ months), or if required by law. Unused wallet balance may be refunded per the Refund Policy on closure.</p>

          <h4>12. Governing Law & Jurisdiction</h4>
          <p>These Terms are governed by the laws of India. Any disputes shall be subject to the exclusive jurisdiction of courts at Lucknow, Uttar Pradesh.</p>

          <h4>13. Changes</h4>
          <p>We may update these Terms; continued use after updates means acceptance. Material changes will be notified by email.</p>

          <h4>14. Contact</h4>
          <p>Hidrogen, Lucknow, Uttar Pradesh, India · <a href="mailto:hello@hidrogen.in" style={{color: 'var(--accent)'}}>hello@hidrogen.in</a></p>
        </>
      )
    },
    privacy: {
      title: 'Privacy Policy',
      subtitle: 'Last updated: ' + new Date().toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' }),
      content: (
        <>
          <h4>1. Who We Are</h4>
          <p>Hidrogen is operated by Hidrogen, based in Lucknow, Uttar Pradesh, India. This Privacy Policy describes how we collect, use, and protect your information.</p>

          <h4>2. Information We Collect</h4>
          <p><strong>Account information:</strong> Name, email, password (hashed), phone (optional).</p>
          <p><strong>Payment information:</strong> Processed entirely by Razorpay. We store transaction IDs and amounts but never see or store your card numbers, UPI PINs, or bank credentials.</p>
          <p><strong>Usage data:</strong> API request metadata (endpoint, model alias, latency, token counts, status codes). We do NOT log the content of your prompts or model responses in plain text by default.</p>
          <p><strong>Technical data:</strong> IP address, user agent, timestamps — used for security and rate limiting.</p>

          <h4>3. How We Use Your Information</h4>
          <ul>
            <li>To operate the Service and process API requests</li>
            <li>To bill you accurately and prevent fraud</li>
            <li>To send transactional emails (receipts, security alerts, important updates)</li>
            <li>To respond to support queries</li>
            <li>To comply with legal obligations under Indian law</li>
          </ul>

          <h4>4. We Do NOT</h4>
          <ul>
            <li>Train AI models on your prompts or outputs</li>
            <li>Sell your data to third parties</li>
            <li>Send unsolicited marketing without your consent</li>
            <li>Share data with underlying AI providers beyond what is needed to fulfill your request (and even then, anonymized where possible)</li>
          </ul>

          <h4>5. Third-Party Processors</h4>
          <p>We use the following processors strictly to deliver the Service:</p>
          <ul>
            <li><strong>Razorpay</strong> — payments (PCI-DSS Level 1 certified)</li>
            <li><strong>Hostinger</strong> — application hosting (ap-south-1, Mumbai region)</li>
            <li>Underlying AI inference providers — solely for processing your requests, not data analytics</li>
          </ul>

          <h4>6. Data Storage & Security</h4>
          <p>Data is stored in India (Mumbai, ap-south-1). We use industry-standard encryption (TLS in transit, hashed credentials at rest). Despite our efforts, no system is 100% secure — please use strong passwords and rotate API keys regularly.</p>

          <h4>7. Data Retention</h4>
          <p>Account data is retained while your account is active and for 12 months after closure (for audit/tax compliance). Usage logs are retained for 90 days. You can request earlier deletion by emailing us, subject to legal retention requirements.</p>

          <h4>8. Your Rights (DPDP Act 2023)</h4>
          <p>Under the Digital Personal Data Protection Act, 2023, you have the right to:</p>
          <ul>
            <li>Access the personal data we hold about you</li>
            <li>Correct inaccurate information</li>
            <li>Request erasure (subject to legal retention requirements)</li>
            <li>Withdraw consent for processing</li>
            <li>File a grievance — contact <a href="mailto:privacy@hidrogen.in" style={{color: 'var(--accent)'}}>privacy@hidrogen.in</a></li>
          </ul>

          <h4>9. Cookies</h4>
          <p>We use only essential cookies (session JWT for authentication). No tracking, advertising, or third-party analytics cookies.</p>

          <h4>10. Children's Privacy</h4>
          <p>Hidrogen is not directed at children under 18. We do not knowingly collect data from minors.</p>

          <h4>11. Changes to This Policy</h4>
          <p>We will notify users by email of material changes. Continued use after updates means acceptance.</p>

          <h4>12. Grievance Officer</h4>
          <p>Per Indian IT Rules, our designated Grievance Officer is reachable at: <a href="mailto:grievance@hidrogen.in" style={{color: 'var(--accent)'}}>grievance@hidrogen.in</a> · Hidrogen, Lucknow, Uttar Pradesh, India. Response within 30 days.</p>
        </>
      )
    },
    refund: {
      title: 'Refund & Cancellation Policy',
      subtitle: 'Last updated: ' + new Date().toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' }),
      content: (
        <>
          <h4>1. Wallet Recharges</h4>
          <p>Hidrogen wallet recharges (one-time or via Auto-Pay) are non-refundable once credited, except in the following cases:</p>
          <ul>
            <li>Duplicate payment due to technical error (full refund within 7 working days)</li>
            <li>Wallet credited but service unavailable for &gt;48 consecutive hours (pro-rata refund of unused balance)</li>
            <li>Account closure within 7 days of first recharge with no API usage (full refund minus payment gateway charges)</li>
          </ul>

          <h4>2. API Usage</h4>
          <p>API charges are metered per successful request and deducted from your wallet at the time of use. Once a request is successfully processed, the deduction is final. Failed requests (HTTP 5xx errors caused by Hidrogen) are not billed; failed requests due to client errors (4xx) may or may not be billed depending on whether work was performed.</p>

          <h4>3. Auto-Pay Cancellation</h4>
          <p>You may pause or cancel Auto-Pay anytime from:</p>
          <ul>
            <li>The Hidrogen Billing dashboard (Pause button)</li>
            <li>Your bank app or UPI app where you authorized the mandate (full revocation)</li>
          </ul>
          <p>Cancellation stops future charges but does not refund prior cycles.</p>

          <h4>4. How to Request a Refund</h4>
          <p>Email <a href="mailto:billing@hidrogen.in" style={{color: 'var(--accent)'}}>billing@hidrogen.in</a> within 14 days of the disputed charge with:</p>
          <ul>
            <li>Your account email</li>
            <li>Razorpay payment ID</li>
            <li>Reason for refund request</li>
          </ul>
          <p>We respond within 3 working days. Approved refunds are processed via Razorpay to the original payment method within 5-7 working days.</p>

          <h4>5. Chargebacks</h4>
          <p>If you initiate a chargeback without first contacting us, we reserve the right to suspend your account pending resolution.</p>
        </>
      )
    }
  };

  const d = docs[doc] || docs.tc;

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)',
      display: 'grid', placeItems: 'center', zIndex: 9999, padding: 20,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--surface)',
        borderRadius: 'var(--r-xl)',
        maxWidth: 760, width: '100%', maxHeight: '88vh',
        display: 'flex', flexDirection: 'column',
        border: '1px solid var(--border)',
        boxShadow: '0 24px 60px rgba(0,0,0,0.3)',
      }}>
        <div style={{padding: '20px 28px', borderBottom: '1px solid var(--border)', display:'flex', alignItems:'center'}}>
          <div style={{flex: 1}}>
            <h2 style={{margin: '0 0 4px', fontSize: 22, fontWeight: 500, fontFamily: 'var(--font-display)'}}>{d.title}</h2>
            <div className="muted" style={{fontSize: 12.5}}>{d.subtitle}</div>
          </div>
          <button onClick={onClose} style={{
            background: 'var(--surface-2)', border: '1px solid var(--border)',
            width: 32, height: 32, borderRadius: 8, cursor: 'pointer', color: 'var(--text)',
            display: 'grid', placeItems: 'center', fontSize: 18,
          }}>×</button>
        </div>
        <div style={{padding: '20px 28px 28px', overflow: 'auto', fontSize: 13.5, lineHeight: 1.65}} className="legal-content">
          {d.content}
        </div>
        <div style={{padding: '14px 28px', borderTop: '1px solid var(--border)', display: 'flex', gap: 12, justifyContent: 'flex-end'}}>
          <button className="btn primary sm" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  );
}

function Tweaks({ theme, setTheme, accent, setAccent, density, setDensity, onClose }) {
  const accents = [
    { id: 'saffron', color: 'oklch(0.745 0.16 62)' },
    { id: 'indigo',  color: 'oklch(0.745 0.15 265)' },
    { id: 'emerald', color: 'oklch(0.745 0.14 155)' },
    { id: 'coral',   color: 'oklch(0.745 0.16 30)' },
  ];
  return (
    <div className="tweaks-panel">
      <div className="tweaks-head">
        <I.cog/><h4>Tweaks</h4><div className="spacer"/>
        <button className="icon-btn" onClick={onClose}><I.x/></button>
      </div>
      <div className="tweaks-body">
        <div><div className="tweak-label" style={{marginBottom:6}}>Theme</div>
          <div className="seg">
            <button className={theme === 'dark' ? 'active' : ''} onClick={() => setTheme('dark')}>Dark</button>
            <button className={theme === 'light' ? 'active' : ''} onClick={() => setTheme('light')}>Light</button>
          </div>
        </div>
        <div><div className="tweak-label" style={{marginBottom:6}}>Accent</div>
          <div className="swatch-grid">
            {accents.map(a => (
              <div key={a.id} className={'swatch' + (accent === a.id ? ' active' : '')}
                   style={{ background: a.color }} onClick={() => setAccent(a.id)}/>
            ))}
          </div>
        </div>
        <div><div className="tweak-label" style={{marginBottom:6}}>Density</div>
          <div className="seg">
            <button className={density === 'compact' ? 'active' : ''} onClick={() => setDensity('compact')}>Compact</button>
            <button className={density === 'comfortable' ? 'active' : ''} onClick={() => setDensity('comfortable')}>Comfy</button>
            <button className={density === 'roomy' ? 'active' : ''} onClick={() => setDensity('roomy')}>Roomy</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function pickColor(seed) {
  const colors = ['#4285F4','#10A37F','#D97757','#8E44EC','#E91E63','#FF9800','#00BCD4','#795548'];
  let h = 0;
  for (let i = 0; i < (seed||'').length; i++) h = (h * 31 + seed.charCodeAt(i)) & 0xff;
  return colors[h % colors.length];
}
window.pickColor = pickColor;

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
