// ─────────────────────────────────────────────────────────────
// screens-compliance.jsx — DPDPA + privacy hardening
// DPDPAConsent (boot-time + version-stamped), AgeGate (verifiable parental
// consent for minors), PrivacyCenter (richer than the existing screen),
// DataExport, DataDeletion, LeaderboardPrivacy, CustodyAccess
// ─────────────────────────────────────────────────────────────
const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

// ─────────────────────────────────────────────────────────────
// DPDPAConsentScreen — first-launch consent with granular toggles.
// India's DPDP Act, 2023 (effective via DPDPA Rules, 2025) requires:
//   • clear notice of purposes
//   • verifiable consent for processing of children's data
//   • ability to withdraw consent as easily as it was given
//   • notification of data fiduciary (Scholiq) and grievance officer
// ─────────────────────────────────────────────────────────────
function DPDPAConsentScreen({ nav, params }) {
  const [page, setPage] = useStateC(0); // 0 = notice, 1 = granular, 2 = parental
  const [draft, setDraft, hyd] = useDraft('dpdpa-consent', {
    essential: true, // mandatory
    analytics: true,
    marketing: false,
    aiPersonalization: true,
    thirdPartyShare: false,
    dob: '',
    parentName: '',
    parentRelation: 'Mother',
    consented: false
  });
  const minor = useMemoC(() => {
    if (!draft.dob) return null;
    const d = new Date(draft.dob);
    if (isNaN(d.getTime())) return null;
    const age = (Date.now() - d.getTime()) / (365.25 * 24 * 3600 * 1000);
    return age < 18;
  }, [draft.dob]);

  if (!hyd) return <div className="screen-bg" style={{ padding: 20 }}><SkeletonList n={3}/></div>;

  return (
    <div className="screen-bg" style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }} data-screen-label="DPDPAConsent">
      <div style={{ position: 'sticky', top: 0, background: '#fff', borderBottom: '1px solid var(--n100)', padding: '52px 16px 12px' }}>
        <div className="spread">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="shield" size={18} color="var(--p600)"/>
            <div>
              <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--n900)' }}>Privacy notice</div>
              <div style={{ fontSize: 10.5, color: 'var(--n500)' }}>DPDP Act, 2023 · v2.4 · 14 Mar 2026</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            {[0, 1, 2].map((i) => <span key={i} style={{ width: 18, height: 3, borderRadius: 2, background: i <= page ? 'var(--p500)' : 'var(--n100)' }}/>)}
          </div>
        </div>
      </div>

      <div style={{ padding: '20px 16px 100px', flex: 1 }}>
        {page === 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', lineHeight: 1.2 }}>Here's what we collect — and why.</div>
              <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 8, lineHeight: 1.6 }}>
                Plain English first. The legal text is at the bottom and you can re-open it any time from Privacy Center.
              </div>
            </div>

            {[
              { ic: 'grad', t: 'Academic data', s: 'Attendance, grades, homework — required by your school to run the academic record. Stored on Indian servers. Never sold.' },
              { ic: 'rupee', t: 'Payment data', s: "Fee dues, receipts. Card / UPI tokens are held by our RBI-licensed gateway, not by us." },
              { ic: 'message', t: 'Communications', s: 'Chats with teachers and announcements. Encrypted in transit. Auto-purged after 18 months unless you save.' },
              { ic: 'pin', t: 'Location (optional)', s: "Only when you open Transport. Never tracked in the background. You can disable in OS settings." },
              { ic: 'sparkles', t: 'AI personalization (optional)', s: 'Weak-topic suggestions and practice are generated from your performance. Toggle off any time.' }
            ].map((row, i) => (
              <div key={i} className="row" style={{ gap: 12, padding: '4px 4px' }}>
                <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <Icon name={row.ic} size={16}/>
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{row.t}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--n500)', marginTop: 2, lineHeight: 1.5 }}>{row.s}</div>
                </div>
              </div>
            ))}

            <div className="card" style={{ padding: 14, background: 'var(--p50)', borderColor: 'var(--p200)' }}>
              <div style={{ fontSize: 11, color: 'var(--p700)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em' }}>Your rights, on demand</div>
              <div style={{ fontSize: 11.5, color: 'var(--n700)', marginTop: 6, lineHeight: 1.6 }}>
                Access · Correction · Erasure · Portability · Withdraw consent · Lodge a grievance with our DPO (dpo@scholiq.in) within 7 days. We respond within 30.
              </div>
            </div>

            <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 11, color: 'var(--p600)', textDecoration: 'underline' }}>Read the full privacy policy →</a>
          </div>
        )}

        {page === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', lineHeight: 1.2 }}>Choose what's optional.</div>
              <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 6 }}>You can change these any time in Privacy Center.</div>
            </div>

            <ConsentToggle
              ic="lock" locked t="Essentials" s="Account, attendance, fees, communications. Required to use Scholiq." on={true}
            />
            <ConsentToggle
              ic="chart" t="Anonymous analytics" s="Helps us spot crashes and slow screens. No personal data leaves your device unhashed." on={draft.analytics}
              onChange={(v) => setDraft((d) => ({ ...d, analytics: v }))}
            />
            <ConsentToggle
              ic="sparkles" t="AI personalization" s="Weak-topic detection, practice suggestions, smart reminders. Disabling does not block features — just makes them generic."
              on={draft.aiPersonalization}
              onChange={(v) => setDraft((d) => ({ ...d, aiPersonalization: v }))}
            />
            <ConsentToggle
              ic="bell" t="Marketing communications" s="Tips, product updates, occasional school-system news. Off by default."
              on={draft.marketing}
              onChange={(v) => setDraft((d) => ({ ...d, marketing: v }))}
            />
            <ConsentToggle
              ic="link" t="Share with verified third parties" s="Coaching tie-ups, EMI partners. Each share asks again. Off by default."
              on={draft.thirdPartyShare}
              onChange={(v) => setDraft((d) => ({ ...d, thirdPartyShare: v }))}
            />
          </div>
        )}

        {page === 2 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', lineHeight: 1.2 }}>Age check.</div>
              <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 6, lineHeight: 1.6 }}>
                If you're under 18, the law requires a parent or guardian's verifiable consent before we can process your data.
              </div>
            </div>

            <FormField label="Date of birth" required>
              <input type="date" value={draft.dob} onChange={(e) => setDraft((d) => ({ ...d, dob: e.target.value }))} max={new Date().toISOString().slice(0, 10)} style={{ padding: '12px 14px', borderRadius: 12, border: '1.5px solid var(--n200)', fontSize: 14, fontFamily: 'inherit' }}/>
            </FormField>

            {minor === false && (
              <div className="card" style={{ padding: 14, background: 'var(--success-50)', borderColor: 'var(--success-200)', display: 'flex', gap: 10 }}>
                <Icon name="check" size={16} color="#065F46"/>
                <div style={{ fontSize: 11.5, color: '#065F46', lineHeight: 1.5 }}>You're 18+. You can give consent yourself. Tap "I agree" to finish.</div>
              </div>
            )}

            {minor === true && (
              <>
                <div className="card" style={{ padding: 14, background: 'var(--warn-50)', borderColor: 'var(--warn-200)', display: 'flex', gap: 10 }}>
                  <Icon name="info" size={16} color="#92400E"/>
                  <div style={{ fontSize: 11.5, color: '#92400E', lineHeight: 1.5 }}>You're under 18. We'll send a verification request to your parent / guardian. Until they approve, only basic features (attendance, homework) are available.</div>
                </div>
                <FormField label="Parent / guardian name" required>
                  <input type="text" value={draft.parentName} onChange={(e) => setDraft((d) => ({ ...d, parentName: e.target.value }))} placeholder="Name as on ID" style={{ padding: '12px 14px', borderRadius: 12, border: '1.5px solid var(--n200)', fontSize: 14, fontFamily: 'inherit' }}/>
                </FormField>
                <FormField label="Relationship">
                  <Segmented value={draft.parentRelation} onChange={(v) => setDraft((d) => ({ ...d, parentRelation: v }))} options={['Mother', 'Father', 'Guardian']}/>
                </FormField>
                <div style={{ fontSize: 10.5, color: 'var(--n400)', display: 'flex', gap: 6, marginTop: 4 }}>
                  <Icon name="lock" size={11}/>
                  <span>Verification is via your school's record + an OTP to the parent's registered number. We never ask for ID uploads.</span>
                </div>
              </>
            )}
          </div>
        )}
      </div>

      {/* Footer actions */}
      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px', display: 'flex', gap: 10 }}>
        {page > 0 && <button onClick={() => setPage(page - 1)} className="btn btn-outline" style={{ flex: 1 }}>Back</button>}
        {page < 2 && <button onClick={() => setPage(page + 1)} className="btn" style={{ flex: 2 }}>Continue</button>}
        {page === 2 && (
          <button
            disabled={!draft.dob || (minor && (!draft.parentName.trim()))}
            onClick={() => { setDraft((d) => ({ ...d, consented: true, consentedAt: new Date().toISOString(), version: '2.4' })); nav.replace(params?.next || 'home'); }}
            className="btn"
            style={{ flex: 2, opacity: (!draft.dob || (minor && !draft.parentName.trim())) ? .5 : 1 }}
          >I agree</button>
        )}
      </div>
    </div>
  );
}

function ConsentToggle({ ic, t, s, on, onChange, locked }) {
  return (
    <button onClick={() => !locked && onChange(!on)} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', opacity: locked ? .8 : 1 }}>
      <div style={{ width: 38, height: 38, borderRadius: 11, background: on ? 'var(--p50)' : 'var(--n50)', color: on ? 'var(--p600)' : 'var(--n400)', display: 'grid', placeItems: 'center' }}><Icon name={ic} size={16}/></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', display: 'flex', alignItems: 'center', gap: 6 }}>
          {t}
          {locked && <span style={{ fontSize: 9, fontWeight: 800, color: 'var(--n500)', background: 'var(--n50)', padding: '2px 6px', borderRadius: 6, letterSpacing: '.05em', textTransform: 'uppercase' }}>Required</span>}
        </div>
        <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2, lineHeight: 1.45 }}>{s}</div>
      </div>
      {!locked && (
        <div style={{ width: 38, height: 22, borderRadius: 999, background: on ? 'var(--p500)' : 'var(--n200)', position: 'relative', flexShrink: 0 }}>
          <div style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(15,23,42,.18)' }}/>
        </div>
      )}
      {locked && <Icon name="lock" size={14} color="var(--n400)"/>}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// AgeGateSheet — quick "are you 18?" gate inside flows that touch
// sensitive surfaces (e.g. leaderboards, public sharing).
// ─────────────────────────────────────────────────────────────
function AgeGateSheet({ open, onClose, onMinor, onAdult }) {
  const [dob, setDob] = useStateC('');
  return (
    <BottomSheet open={open} onClose={onClose} title="Quick age check">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ fontSize: 12, color: 'var(--n500)', lineHeight: 1.5 }}>This feature shows your name publicly. We need to confirm you can consent to that.</div>
        <FormField label="Date of birth">
          <input type="date" value={dob} onChange={(e) => setDob(e.target.value)} max={new Date().toISOString().slice(0, 10)} style={{ padding: '12px 14px', borderRadius: 12, border: '1.5px solid var(--n200)', fontSize: 14, fontFamily: 'inherit' }}/>
        </FormField>
        <button className="btn" disabled={!dob} onClick={() => {
          const age = (Date.now() - new Date(dob).getTime()) / (365.25 * 86400000);
          if (age < 18) onMinor?.(); else onAdult?.();
          onClose();
        }} style={{ opacity: dob ? 1 : .5 }}>Confirm</button>
      </div>
    </BottomSheet>
  );
}

// ─────────────────────────────────────────────────────────────
// PrivacyCenterScreen — the upgraded surface (PrivacyDataScreen routes here)
// ─────────────────────────────────────────────────────────────
function PrivacyCenterScreen({ nav }) {
  const [draft, setDraft] = useDraft('dpdpa-consent', { essential: true, analytics: true, marketing: false, aiPersonalization: true, thirdPartyShare: false, leaderboardOptIn: true });

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="PrivacyCenter">
      <PageHeader title="Privacy center" subtitle="DPDPA-compliant" onBack={() => nav.pop()}/>

      <div style={{ padding: '14px 16px 80px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card" style={{ padding: 16, background: 'linear-gradient(135deg, var(--p500) 0%, var(--p600) 100%)', color: '#fff', border: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'rgba(255,255,255,.18)', display: 'grid', placeItems: 'center' }}><Icon name="shield" size={18}/></div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 800 }}>Your data, your terms</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,.78)', marginTop: 2 }}>India DPDP Act, 2023 · ISO 27001 · SOC 2 Type II</div>
            </div>
          </div>
        </div>

        <SectionLabel label="Consent settings" sub="Withdraw any time. Essentials are required to use the service."/>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <ConsentRow ic="lock" t="Essentials" s="Account, fees, attendance" locked/>
          <ConsentRow ic="chart" t="Anonymous analytics" s="Crash reports, slow-screen telemetry" on={draft.analytics} onChange={(v) => setDraft((d) => ({ ...d, analytics: v }))}/>
          <ConsentRow ic="sparkles" t="AI personalization" s="Weak-topic detection · smart reminders" on={draft.aiPersonalization} onChange={(v) => setDraft((d) => ({ ...d, aiPersonalization: v }))}/>
          <ConsentRow ic="bell" t="Marketing communications" s="Tips, school-system news" on={draft.marketing} onChange={(v) => setDraft((d) => ({ ...d, marketing: v }))}/>
          <ConsentRow ic="link" t="Verified third-party sharing" s="Coaching, EMI partners — asked per share" on={draft.thirdPartyShare} onChange={(v) => setDraft((d) => ({ ...d, thirdPartyShare: v }))}/>
          <ConsentRow ic="trophy" t="Public leaderboards" s="Show real name on class rankings" on={draft.leaderboardOptIn} onChange={(v) => setDraft((d) => ({ ...d, leaderboardOptIn: v }))} last/>
        </div>

        <SectionLabel label="Your data rights"/>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <button onClick={() => nav.push('dataExport')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="download" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Download my data</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>JSON + PDFs · ready in ≤ 24 hours</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button onClick={() => nav.push('dataDeletion')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--danger-50)', color: 'var(--danger-600)', display: 'grid', placeItems: 'center' }}><Icon name="trash" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Delete my account</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>30-day cooldown · academic records retained per CBSE rule</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button onClick={() => {}} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="edit" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Correct my information</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Open a request — school will verify</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
        </div>

        <SectionLabel label="Trust & access"/>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <button onClick={() => nav.push('custodyAccess')} className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="users" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Custody & co-parent access</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>Add another guardian · split scopes</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left', borderBottom: '1px solid var(--n100)' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="history" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Activity log</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>See every login, share, export</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
          <button className="row" style={{ width: '100%', padding: '14px 16px', gap: 12, background: 'transparent', textAlign: 'left' }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="message" size={16}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Grievance officer</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>dpo@scholiq.in · response within 30 days</div>
            </div>
            <Icon name="chevron-right" size={16} color="var(--n300)"/>
          </button>
        </div>

        <div style={{ fontSize: 10.5, color: 'var(--n400)', textAlign: 'center', padding: '8px 12px', lineHeight: 1.5 }}>
          Data fiduciary: Scholiq Technologies Pvt Ltd · Bengaluru · CIN U72900KA2024PTC180329 · Servers: Mumbai (ap-south-1)
        </div>
      </div>
    </div>
  );
}

function ConsentRow({ ic, t, s, on, onChange, locked, last }) {
  return (
    <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: last ? 'none' : '1px solid var(--n100)' }}>
      <div style={{ width: 34, height: 34, borderRadius: 10, background: on ? 'var(--p50)' : 'var(--n50)', color: on ? 'var(--p600)' : 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name={ic} size={15}/></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{t}</div>
        <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{s}</div>
      </div>
      {locked
        ? <Icon name="lock" size={14} color="var(--n400)"/>
        : <button onClick={() => onChange(!on)} role="switch" aria-checked={on} aria-label={t} style={{ width: 38, height: 22, borderRadius: 999, background: on ? 'var(--p500)' : 'var(--n200)', position: 'relative', border: 'none', cursor: 'pointer' }}>
            <span aria-hidden="true" style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(15,23,42,.18)' }}/>
          </button>}
    </div>
  );
}

function SectionLabel({ label, sub }) {
  return (
    <div style={{ padding: '4px 4px' }}>
      <div style={{ fontSize: 10.5, fontWeight: 800, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.08em' }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DataExportScreen — request packaged data
// ─────────────────────────────────────────────────────────────
function DataExportScreen({ nav }) {
  const [scope, setScope] = useStateC({ academic: true, attendance: true, fees: true, chats: true, files: false });
  const [submitted, setSubmitted] = useStateC(false);

  const total = Object.values(scope).filter(Boolean).length;

  if (submitted) {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="DataExportSubmitted">
        <PageHeader title="Export requested" onBack={() => nav.pop()}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--success-50)', color: '#065F46', display: 'grid', placeItems: 'center' }}><Icon name="check" size={36}/></div>
          <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--n900)' }}>We're packaging your data</div>
          <div style={{ fontSize: 13, color: 'var(--n500)', maxWidth: 280, lineHeight: 1.6 }}>You'll get a secure download link by email within 24 hours. The link expires in 7 days.</div>
          <div className="card" style={{ padding: 14, marginTop: 8, width: '100%', display: 'flex', gap: 10, alignItems: 'center', textAlign: 'left' }}>
            <Icon name="mail" size={18} color="var(--n500)"/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 700 }}>shekar@gmail.com</div>
              <div style={{ fontSize: 10.5, color: 'var(--n500)' }}>Update in Settings if needed</div>
            </div>
          </div>
          <button onClick={() => nav.pop()} className="btn" style={{ marginTop: 12, width: '100%' }}>Done</button>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="DataExport">
      <PageHeader title="Download my data" subtitle="DPDPA Article 11 · portability" onBack={() => nav.pop()}/>
      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 12.5, color: 'var(--n600)', lineHeight: 1.6 }}>
          Choose what to include. We'll bundle it as a ZIP with JSON + PDFs and email a secure download link.
        </div>

        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {[
            { k: 'academic', ic: 'grad', t: 'Academic record', s: 'Grades, results, analytics · 22 records' },
            { k: 'attendance', ic: 'calendar', t: 'Attendance', s: '186 days · 3 academic years' },
            { k: 'fees', ic: 'rupee', t: 'Fees & receipts', s: '24 transactions · GST invoices' },
            { k: 'chats', ic: 'message', t: 'Communications', s: '136 messages · last 18 months' },
            { k: 'files', ic: 'paperclip', t: 'Files I uploaded', s: 'Homework photos, ID docs · ~340 MB', warn: 'Larger export · may take 6+ hours' }
          ].map((row, i, arr) => (
            <button key={row.k} onClick={() => setScope((s) => ({ ...s, [row.k]: !s[row.k] }))} style={{ width: '100%', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, background: 'transparent', textAlign: 'left', border: 'none', borderBottom: i < arr.length - 1 ? '1px solid var(--n100)' : 'none' }}>
              <div style={{ width: 22, height: 22, borderRadius: 7, border: scope[row.k] ? '2px solid var(--p500)' : '2px solid var(--n200)', background: scope[row.k] ? 'var(--p500)' : '#fff', display: 'grid', placeItems: 'center' }}>
                {scope[row.k] && <Icon name="check" size={12} color="#fff"/>}
              </div>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name={row.ic} size={15}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{row.t}</div>
                <div style={{ fontSize: 11, color: 'var(--n500)' }}>{row.s}</div>
                {row.warn && scope[row.k] && <div style={{ fontSize: 10.5, color: '#92400E', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="info" size={10}/> {row.warn}</div>}
              </div>
            </button>
          ))}
        </div>

        <div className="card" style={{ padding: 14, background: 'var(--n50)', borderColor: 'var(--n100)', display: 'flex', gap: 10 }}>
          <Icon name="info" size={16} color="var(--n500)"/>
          <div style={{ fontSize: 11, color: 'var(--n600)', lineHeight: 1.5 }}>
            We don't include other people's messages to you (privacy protection). Receipts include only line items addressed to you.
          </div>
        </div>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px' }}>
        <button onClick={() => setSubmitted(true)} disabled={total === 0} className="btn" style={{ height: 50, opacity: total === 0 ? .5 : 1 }}>
          <Icon name="download" size={16}/> Request export ({total} {total === 1 ? 'category' : 'categories'})
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DataDeletionScreen — right to be forgotten with cooldown
// ─────────────────────────────────────────────────────────────
function DataDeletionScreen({ nav }) {
  const [reason, setReason] = useStateC('');
  const [confirm, setConfirm] = useStateC('');
  const [stage, setStage] = useStateC('form'); // form → review → confirmed

  if (stage === 'confirmed') {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="DataDeletionConfirmed">
        <PageHeader title="Deletion scheduled" onBack={() => nav.pop()}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--warn-50)', color: '#92400E', display: 'grid', placeItems: 'center' }}><Icon name="history" size={36}/></div>
          <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--n900)' }}>30-day cooling period started</div>
          <div style={{ fontSize: 13, color: 'var(--n500)', maxWidth: 300, lineHeight: 1.6 }}>Your account will be permanently deleted on <strong>14 Apr 2026</strong>. Sign in any time before then to cancel.</div>
          <div className="card" style={{ padding: 14, marginTop: 8, textAlign: 'left' }}>
            <div style={{ fontSize: 11, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.06em' }}>What happens next</div>
            <ul style={{ fontSize: 11.5, color: 'var(--n600)', marginTop: 8, paddingLeft: 18, lineHeight: 1.7 }}>
              <li>Day 0: account paused — chats hidden</li>
              <li>Day 14: reminder email</li>
              <li>Day 30: hard delete from active stores</li>
              <li>Day 30+: academic records retained per CBSE bye-law 31.4 (legal obligation)</li>
            </ul>
          </div>
          <button onClick={() => nav.replace('home')} className="btn btn-outline" style={{ marginTop: 12, width: '100%' }}>Back to home</button>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="DataDeletion">
      <PageHeader title="Delete my account" onBack={() => nav.pop()}/>
      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="card" style={{ padding: 14, background: 'var(--danger-50)', borderColor: 'var(--danger-200)', display: 'flex', gap: 10 }}>
          <Icon name="alert" size={16} color="var(--danger-600)"/>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--danger-700)' }}>This is permanent.</div>
            <div style={{ fontSize: 11, color: 'var(--danger-700)', marginTop: 4, lineHeight: 1.5 }}>After 30 days, you can't recover access. Some academic records are kept by your school as a legal requirement.</div>
          </div>
        </div>

        <FormField label="Why are you leaving? (optional)" hint="Helps us improve">
          <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={3} placeholder="One line is enough" style={{ padding: 12, borderRadius: 12, border: '1.5px solid var(--n200)', fontSize: 13, fontFamily: 'inherit', resize: 'vertical' }}/>
        </FormField>

        <FormField label='Type "DELETE" to confirm' required>
          <input value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="DELETE" style={{ padding: '12px 14px', borderRadius: 12, border: '1.5px solid ' + (confirm === 'DELETE' ? 'var(--danger-300)' : 'var(--n200)'), fontSize: 14, fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '.1em' }}/>
        </FormField>

        <div className="card" style={{ padding: 14, background: 'var(--n50)', borderColor: 'var(--n100)' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>Before you go</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
            <button onClick={() => nav.push('dataExport')} className="row" style={{ background: '#fff', padding: 10, borderRadius: 10, gap: 10, textAlign: 'left' }}>
              <Icon name="download" size={16} color="var(--n500)"/>
              <div style={{ flex: 1, fontSize: 12, fontWeight: 600, color: 'var(--n900)' }}>Download my data first</div>
              <Icon name="chevron-right" size={14} color="var(--n300)"/>
            </button>
            <button onClick={() => nav.push('notifPrefs')} className="row" style={{ background: '#fff', padding: 10, borderRadius: 10, gap: 10, textAlign: 'left' }}>
              <Icon name="bell" size={16} color="var(--n500)"/>
              <div style={{ flex: 1, fontSize: 12, fontWeight: 600, color: 'var(--n900)' }}>Pause notifications instead</div>
              <Icon name="chevron-right" size={14} color="var(--n300)"/>
            </button>
          </div>
        </div>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px' }}>
        <button disabled={confirm !== 'DELETE'} onClick={() => setStage('confirmed')} className="btn" style={{ background: 'var(--danger-600)', borderColor: 'var(--danger-600)', height: 50, opacity: confirm === 'DELETE' ? 1 : .5 }}>
          <Icon name="trash" size={16}/> Schedule deletion
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CustodyAccessScreen — model second guardian / split-family scopes
// ─────────────────────────────────────────────────────────────
const DEFAULT_GUARDIANS = [
  { id: 'self', name: 'You (Shekar Mehra)', role: 'Father · primary', clr: '#6366F1', initial: 'S', scopes: { academic: true, fees: true, comms: true, transport: true, attendance: true, edit: true } },
  { id: 'mother', name: 'Priya Mehra', role: 'Mother · co-guardian', clr: '#EC4899', initial: 'P', scopes: { academic: true, fees: false, comms: true, transport: true, attendance: true, edit: false } },
  { id: 'gp', name: 'Sharad Mehra', role: 'Grandfather · view-only', clr: '#10B981', initial: 'SM', scopes: { academic: true, fees: false, comms: false, transport: true, attendance: true, edit: false } }
];

function CustodyAccessScreen({ nav }) {
  const [guardians, setGuardians] = useStateC(DEFAULT_GUARDIANS);
  const [editing, setEditing] = useStateC(null); // guardian id
  const editingG = guardians.find((g) => g.id === editing);

  const setScope = (gid, key, val) => {
    setGuardians((arr) => arr.map((g) => g.id === gid ? { ...g, scopes: { ...g.scopes, [key]: val } } : g));
  };

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="CustodyAccess">
      <PageHeader title="Custody & co-parent access" onBack={() => nav.pop()}/>

      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 12.5, color: 'var(--n600)', lineHeight: 1.6 }}>
          Both parents (and grandparents / nannies) can have their own login with different scopes. Useful for split-family or remote-parent setups.
        </div>

        {guardians.map((g, i) => (
          <button key={g.id} onClick={() => setEditing(g.id === editing ? null : g.id)} className="card" style={{ padding: 14, display: 'flex', alignItems: 'flex-start', gap: 12, textAlign: 'left' }}>
            <div aria-hidden="true" style={{ width: 44, height: 44, borderRadius: 13, background: g.clr, color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 14, flexShrink: 0 }}>{g.initial}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--n900)' }}>{g.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--n500)', marginTop: 2 }}>{g.role}</div>
              <div className="row" style={{ gap: 4, marginTop: 8, flexWrap: 'wrap' }}>
                {Object.entries(g.scopes).filter(([, v]) => v).map(([k]) => (
                  <span key={k} className="chip" style={{ fontSize: 9.5, fontWeight: 700, background: 'var(--n50)', color: 'var(--n600)', padding: '3px 7px', borderRadius: 6, textTransform: 'capitalize' }}>{k}</span>
                ))}
              </div>
            </div>
            <Icon name={editing === g.id ? 'chevron-left' : 'chevron-right'} size={16} color="var(--n300)"/>
          </button>
        ))}

        {editingG && (
          <div className="card" style={{ padding: 16, background: 'var(--p50)', borderColor: 'var(--p200)' }}>
            <div style={{ fontSize: 11, color: 'var(--p700)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.08em' }}>Editing scopes for {editingG.name}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
              {[
                { k: 'academic', t: 'Academic data', s: 'Grades, results, report cards' },
                { k: 'attendance', t: 'Attendance', s: 'Mark in/out, request leave' },
                { k: 'fees', t: 'Fees & payments', s: 'View, pay, receipts' },
                { k: 'comms', t: 'Chat with teachers', s: 'Messages with school staff' },
                { k: 'transport', t: 'Transport', s: 'Bus location, driver contact' },
                { k: 'edit', t: 'Edit child profile', s: 'Update contact, photo, address' }
              ].map((row) => (
                <div key={row.k} className="spread" style={{ alignItems: 'center', padding: '8px 0' }}>
                  <div>
                    <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{row.t}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 1 }}>{row.s}</div>
                  </div>
                  <button onClick={(e) => { e.stopPropagation(); setScope(editingG.id, row.k, !editingG.scopes[row.k]); }} aria-label={row.t} role="switch" aria-checked={!!editingG.scopes[row.k]} style={{ width: 38, height: 22, borderRadius: 999, background: editingG.scopes[row.k] ? 'var(--p500)' : 'var(--n200)', border: 'none', position: 'relative' }}>
                    <span aria-hidden="true" style={{ position: 'absolute', top: 2, left: editingG.scopes[row.k] ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(15,23,42,.18)', transition: 'left .2s' }}/>
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        <button className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', borderStyle: 'dashed', borderColor: 'var(--n200)' }}>
          <div style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--n50)', color: 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name="plus" size={18}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Invite another guardian</div>
            <div style={{ fontSize: 11, color: 'var(--n500)' }}>Email or phone · they confirm before access starts</div>
          </div>
          <Icon name="chevron-right" size={16} color="var(--n300)"/>
        </button>

        <div className="card" style={{ padding: 14, background: 'var(--warn-50)', borderColor: 'var(--warn-200)', display: 'flex', gap: 10 }}>
          <Icon name="info" size={16} color="#92400E"/>
          <div style={{ fontSize: 11, color: '#92400E', lineHeight: 1.5 }}>
            <strong>Court-ordered custody?</strong> Upload the order under <a href="#" onClick={(e) => e.preventDefault()} style={{ color: '#92400E', textDecoration: 'underline' }}>Settings → Documents</a> and we'll lock the other parent's edit scope.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  DPDPAConsentScreen, AgeGateSheet,
  PrivacyCenterScreen, DataExportScreen, DataDeletionScreen,
  CustodyAccessScreen
});
