// screens-account.jsx — Account, support, and settings screens linked from Profile.
// All real screens (no placeholders). Uses primitives + tokens from screens.jsx + tokens.css.

const { useState: useStateAcc } = React;

// ── Shared row primitives ─────────────────────────────────────
function ListRow({ ic, lab, sub, badge, value, onClick, accent, danger, last }) {
  const tone = danger ? { bg: 'var(--c50)', clr: 'var(--c700)' }
    : accent ? { bg: 'var(--p50)', clr: 'var(--p700)' }
    : { bg: 'var(--n50)', clr: 'var(--n700)' };
  return (
    <button onClick={onClick} className="row" style={{
      width: '100%', padding: '12px 14px', gap: 12, textAlign: 'left',
      borderBottom: last ? 'none' : '1px solid var(--n100)',
    }}>
      {ic && <div style={{ width: 36, height: 36, borderRadius: 10, background: tone.bg, color: tone.clr, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={ic} size={18}/></div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: danger ? 'var(--c700)' : 'var(--n900)' }}>{lab}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{sub}</div>}
      </div>
      {value && <span style={{ fontSize: 12, color: 'var(--n500)', fontVariantNumeric: 'tabular-nums' }}>{value}</span>}
      {badge && <span className="pill pill-s" style={{ fontSize: 10 }}>{badge}</span>}
      {onClick && <Icon name="chev-r" size={16} style={{ color: 'var(--n400)' }}/>}
    </button>
  );
}

function ListCard({ children }) {
  return (
    <div style={{ background: '#fff', border: '1px solid var(--n100)', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--el-1)' }}>
      {children}
    </div>
  );
}

function SectionLabel({ label, hint, right }) {
  return (
    <div style={{ padding: '0 4px 8px' }}>
      <div className="spread">
        <div style={{ fontSize: 11, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 700, fontFamily: 'var(--mono)' }}>{label}</div>
        {right}
      </div>
      {hint && <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 4, lineHeight: 1.45 }}>{hint}</div>}
    </div>
  );
}

function Toggle({ value, onChange }) {
  return (
    <button onClick={(e) => { e.stopPropagation(); onChange(!value); }} style={{
      width: 40, height: 24, borderRadius: 99, padding: 2, background: value ? 'var(--p600)' : 'var(--n200)',
      transition: 'background .15s', position: 'relative', flexShrink: 0,
    }}>
      <div style={{ width: 20, height: 20, borderRadius: '50%', background: '#fff', transform: value ? 'translateX(16px)' : 'translateX(0)', transition: 'transform .15s', boxShadow: '0 1px 3px rgba(0,0,0,.15)' }}/>
    </button>
  );
}

function ToggleRow({ ic, lab, sub, value, onChange, last }) {
  return (
    <div className="row" style={{ padding: '12px 14px', gap: 12, borderBottom: last ? 'none' : '1px solid var(--n100)' }}>
      {ic && <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', color: 'var(--n700)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={ic} size={18}/></div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--n900)' }}>{lab}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{sub}</div>}
      </div>
      <Toggle value={value} onChange={onChange}/>
    </div>
  );
}

function FieldRow({ lab, value, onChange, type = 'text', placeholder, last }) {
  return (
    <div style={{ padding: '12px 14px', borderBottom: last ? 'none' : '1px solid var(--n100)' }}>
      <div style={{ fontSize: 11, color: 'var(--n500)', fontWeight: 700, letterSpacing: '.05em', fontFamily: 'var(--mono)', textTransform: 'uppercase', marginBottom: 4 }}>{lab}</div>
      <input type={type} value={value || ''} onChange={(e) => onChange && onChange(e.target.value)} placeholder={placeholder} style={{
        width: '100%', border: 'none', outline: 'none', background: 'transparent',
        fontSize: 14, fontWeight: 500, color: 'var(--n900)', padding: 0, fontFamily: 'inherit',
      }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SHARE PROFILE — QR card with name/contact, share + copy actions
// ─────────────────────────────────────────────────────────────
function ShareProfileScreen({ nav, role }) {
  const person = role === 'student' ? { name: 'Aarav Reddy', sub: 'Class 8-B · DPS Hyderabad', initial: 'A', clr: '' }
    : role === 'teacher' ? { name: 'Sneha Reddy', sub: 'Class teacher 8-B · DPS Hyderabad', initial: 'SR', clr: 'violet' }
    : role === 'driver' ? { name: 'Arjun R.', sub: 'Driver · Sai Travels · Route 14', initial: 'AR', clr: 'sky' }
    : role === 'operator' ? { name: 'Priya Menon', sub: 'Owner · Sai Travels', initial: 'PM', clr: 'coral' }
    : { name: 'Priya Reddy', sub: 'Parent · 3 children · DPS Hyderabad', initial: 'PR', clr: 'coral' };
  const link = `scholiq.app/u/${person.name.toLowerCase().replace(/\W+/g, '')}`;
  const [copied, setCopied] = useStateAcc(false);

  // Pseudo-QR — deterministic 21x21 pattern from the name string
  const cells = [];
  let h = 0;
  for (let i = 0; i < person.name.length; i++) h = ((h << 5) - h + person.name.charCodeAt(i)) | 0;
  for (let r = 0; r < 21; r++) {
    for (let c = 0; c < 21; c++) {
      h = (h * 1103515245 + 12345) & 0x7fffffff;
      const finder = (r < 7 && c < 7) || (r < 7 && c > 13) || (r > 13 && c < 7);
      const finderInner = (r >= 1 && r <= 5 && c >= 1 && c <= 5) || (r >= 1 && r <= 5 && c >= 15 && c <= 19) || (r >= 15 && r <= 19 && c >= 1 && c <= 5);
      const finderCore = (r >= 2 && r <= 4 && c >= 2 && c <= 4) || (r >= 2 && r <= 4 && c >= 16 && c <= 18) || (r >= 16 && r <= 18 && c >= 2 && c <= 4);
      const on = finderCore ? true : (finderInner ? false : (finder ? true : ((h >> 8) & 1) === 1));
      cells.push({ r, c, on });
    }
  }

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Share profile" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card" style={{ padding: 20, textAlign: 'center' }}>
          <div className={`av av-56 ${person.clr || ''}`} style={{ width: 56, height: 56, fontSize: 20, margin: '0 auto 10px' }}>{person.initial}</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--n900)' }}>{person.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--n500)', marginTop: 2 }}>{person.sub}</div>
          <div style={{ width: 220, height: 220, margin: '20px auto 14px', padding: 14, background: '#fff', border: '1px solid var(--n200)', borderRadius: 14, position: 'relative' }}>
            <svg viewBox="0 0 21 21" width="100%" height="100%" shapeRendering="crispEdges">
              {cells.map(({ r, c, on }, i) => on && <rect key={i} x={c} y={r} width="1" height="1" fill="var(--n900)"/>)}
            </svg>
            <div style={{ position: 'absolute', inset: '50% 50%', width: 36, height: 36, marginLeft: -18, marginTop: -18, background: '#fff', border: '2px solid var(--n900)', borderRadius: 8, display: 'grid', placeItems: 'center' }}>
              <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--n900)', letterSpacing: '-.02em' }}>S</div>
            </div>
          </div>
          <div style={{ fontSize: 11, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>Scan to view {person.name.split(' ')[0]}'s profile</div>
        </div>

        <SectionLabel label="Share via"/>
        <ListCard>
          <ListRow ic="whatsapp" lab="WhatsApp" sub="Send to a contact"/>
          <ListRow ic="mail" lab="Email" sub="Compose a message"/>
          <ListRow ic="message" lab="SMS" sub="Send as text" last/>
        </ListCard>

        <SectionLabel label="Profile link"/>
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 10 }}>
            <Icon name="globe" size={16} style={{ color: 'var(--n500)' }}/>
            <span style={{ flex: 1, fontSize: 12.5, color: 'var(--n800)', fontFamily: 'var(--mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{link}</span>
            <button onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }} className="btn-sm" style={{ background: copied ? 'var(--success)' : 'var(--n900)', color: '#fff', height: 28, padding: '0 10px', fontSize: 11, fontWeight: 700 }}>{copied ? 'Copied' : 'Copy'}</button>
          </div>
        </div>

        <button className="btn"><Icon name="download" size={16}/> Save QR as image</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// APP SETTINGS — flat index of all profile-level settings
// ─────────────────────────────────────────────────────────────
function AppSettingsScreen({ nav, lang }) {
  const langLabel = lang === 'en' ? 'English' : lang === 'hi' ? 'हिन्दी' : 'తెలుగు';
  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Settings" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <SectionLabel label="Account"/>
        <ListCard>
          <ListRow ic="user" lab="Personal info" sub="Name, photo, date of birth" onClick={() => nav.push('personalInfo')}/>
          <ListRow ic="edit" lab="Edit profile" sub="Update your details" onClick={() => nav.push('editProfile')}/>
          <ListRow ic="shield" lab="Security" sub="PIN, biometric, sessions" badge="Strong" onClick={() => nav.push('security')}/>
          <ListRow ic="qr" lab="Share profile" sub="QR code · invite link" onClick={() => nav.push('shareProfile')} last/>
        </ListCard>

        <SectionLabel label="Preferences"/>
        <ListCard>
          <ListRow ic="bell" lab="Notifications" sub="3 of 5 channels on" onClick={() => nav.push('notifPrefs')}/>
          <ListRow ic="globe" lab="Language" value={langLabel} onClick={() => nav.push('language')} accent/>
          <ListRow ic="palette" lab="Appearance" value="System" onClick={() => nav.push('appearance')} last/>
        </ListCard>

        <SectionLabel label="Support & legal"/>
        <ListCard>
          <ListRow ic="help" lab="Help center" sub="FAQs, video tutorials" onClick={() => nav.push('helpCenter')}/>
          <ListRow ic="message" lab="Contact support" sub="Avg reply in 4 min" onClick={() => nav.push('contactSupport')}/>
          <ListRow ic="shield" lab="Privacy & data" sub="DPDPA compliant" onClick={() => nav.push('privacy')}/>
          <ListRow ic="info" lab="About Scholiq" sub="v2.4.1" onClick={() => nav.push('about')} last/>
        </ListCard>

        <SectionLabel label="Session"/>
        <ListCard>
          <ListRow ic="logout" lab="Sign out" sub="End this session on this device" onClick={() => nav.push('signOut')} danger last/>
        </ListCard>
        <div style={{ textAlign: 'center', fontSize: 10, color: 'var(--n400)', margin: '14px 0 4px', fontFamily: 'var(--mono)', letterSpacing: '.08em' }}>SCHOLIQ v2.4.1 · BUILD 8421</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EDIT PROFILE — editable form
// ─────────────────────────────────────────────────────────────
function EditProfileScreen({ nav, role }) {
  const initial = role === 'student' ? { name: 'Aarav Reddy', email: 'aarav.r@dpshyd.in', phone: '', dob: '03 Aug 2010' }
    : role === 'teacher' ? { name: 'Sneha Reddy', email: 'sneha.r@dpshyd.in', phone: '+91 98765 12345', dob: '12 Jun 1986' }
    : role === 'driver' ? { name: 'Arjun R.', email: 'arjun.r@saitravels.in', phone: '+91 98765 11111', dob: '22 Apr 1988' }
    : role === 'operator' ? { name: 'Priya Menon', email: 'priya@saitravels.in', phone: '+91 98765 22000', dob: '04 Sep 1980' }
    : { name: 'Priya Reddy', email: 'priya.r@gmail.com', phone: '+91 98765 43210', dob: '15 Mar 1984' };
  const [form, setForm] = useStateAcc(initial);
  const [saved, setSaved] = useStateAcc(false);
  const set = (k) => (v) => { setForm(f => ({ ...f, [k]: v })); setSaved(false); };

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Edit profile" onBack={() => nav.pop()} right={<button onClick={() => { setSaved(true); setTimeout(() => nav.pop(), 600); }} className="btn-ghost" style={{ fontSize: 12, fontWeight: 700, color: saved ? 'var(--success)' : 'var(--p600)' }}>{saved ? 'Saved' : 'Save'}</button>}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card" style={{ padding: 18, alignItems: 'center', display: 'flex', flexDirection: 'column' }}>
          <div className={`av av-56 ${initial.clr || ''}`} style={{ width: 80, height: 80, fontSize: 28 }}>{(form.name || 'U').charAt(0)}</div>
          <button className="btn-ghost" style={{ marginTop: 10, fontSize: 12, fontWeight: 700, color: 'var(--p600)' }}><Icon name="camera" size={14}/> Change photo</button>
        </div>

        <SectionLabel label="Identity"/>
        <ListCard>
          <FieldRow lab="Full name" value={form.name} onChange={set('name')}/>
          <FieldRow lab="Email" type="email" value={form.email} onChange={set('email')}/>
          <FieldRow lab="Phone" type="tel" value={form.phone} onChange={set('phone')} placeholder="+91 …"/>
          <FieldRow lab="Date of birth" value={form.dob} onChange={set('dob')} last/>
        </ListCard>

        <SectionLabel label="Address"/>
        <ListCard>
          <FieldRow lab="Address line 1" value={form.addr1 || '12-3-456 Banjara Hills'} onChange={set('addr1')}/>
          <FieldRow lab="City" value={form.city || 'Hyderabad'} onChange={set('city')}/>
          <FieldRow lab="PIN code" type="tel" value={form.pin || '500034'} onChange={set('pin')} last/>
        </ListCard>

        <button onClick={() => { setSaved(true); setTimeout(() => nav.pop(), 600); }} className="btn">{saved ? <><Icon name="check" size={16}/> Saved</> : 'Save changes'}</button>
        <button onClick={() => nav.pop()} className="btn btn-outline" style={{ marginTop: 0 }}>Cancel</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PERSONAL INFO — read-only summary with quick edit
// ─────────────────────────────────────────────────────────────
function PersonalInfoScreen({ nav, role }) {
  const person = role === 'student' ? { name: 'Aarav Reddy', email: 'aarav.r@dpshyd.in', phone: 'Not added', dob: '03 Aug 2010 · Age 14', gender: 'Male', addr: '12-3-456 Banjara Hills, Hyderabad 500034' }
    : role === 'teacher' ? { name: 'Sneha Reddy', email: 'sneha.r@dpshyd.in', phone: '+91 98765 12345', dob: '12 Jun 1986 · Age 38', gender: 'Female', addr: 'Plot 84 Madhapur, Hyderabad 500081' }
    : role === 'driver' ? { name: 'Arjun R.', email: 'arjun.r@saitravels.in', phone: '+91 98765 11111', dob: '22 Apr 1988 · Age 36', gender: 'Male', addr: 'Quarters B-12 Ameerpet, Hyderabad 500016' }
    : role === 'operator' ? { name: 'Priya Menon', email: 'priya@saitravels.in', phone: '+91 98765 22000', dob: '04 Sep 1980 · Age 44', gender: 'Female', addr: 'Sai Towers, Madhapur, Hyderabad 500081' }
    : { name: 'Priya Reddy', email: 'priya.r@gmail.com', phone: '+91 98765 43210', dob: '15 Mar 1984 · Age 41', gender: 'Female', addr: '12-3-456 Banjara Hills, Hyderabad 500034' };

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Personal info" onBack={() => nav.pop()} right={<button onClick={() => nav.push('editProfile')} className="btn-ghost" style={{ fontSize: 12, fontWeight: 700, color: 'var(--p600)' }}><Icon name="edit" size={12}/> Edit</button>}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <SectionLabel label="Identity"/>
        <ListCard>
          <ListRow lab="Full name" value={person.name}/>
          <ListRow lab="Email" value={person.email}/>
          <ListRow lab="Phone" value={person.phone}/>
          <ListRow lab="Date of birth" value={person.dob}/>
          <ListRow lab="Gender" value={person.gender} last/>
        </ListCard>

        <SectionLabel label="Address"/>
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
            <Icon name="pin" size={16} style={{ color: 'var(--n500)', marginTop: 2 }}/>
            <span style={{ flex: 1, fontSize: 13, color: 'var(--n800)', lineHeight: 1.5 }}>{person.addr}</span>
          </div>
        </div>

        <SectionLabel label="Verification" hint="Verifying contact details unlocks fee receipts and instant alerts."/>
        <ListCard>
          <ListRow ic="check" lab="Email verified" sub="Verified Mar 2024" badge="Verified"/>
          <ListRow ic="phone" lab="Phone verified" sub="Verified Mar 2024" badge="Verified" last/>
        </ListCard>

        <button onClick={() => nav.push('editProfile')} className="btn"><Icon name="edit" size={16}/> Edit personal info</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SECURITY — PIN, biometric, sessions
// ─────────────────────────────────────────────────────────────
function SecurityScreen({ nav }) {
  const [biometric, setBiometric] = useStateAcc(true);
  const [twoFA, setTwoFA] = useStateAcc(false);
  const [autoLock, setAutoLock] = useStateAcc(true);

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Security" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card-tinted" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 10 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--success)', color: '#fff', display: 'grid', placeItems: 'center' }}><Icon name="shield" size={18}/></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Strong protection</div>
              <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 2 }}>PIN + biometric · 3 active sessions</div>
            </div>
          </div>
        </div>

        <SectionLabel label="Sign-in"/>
        <ListCard>
          <ListRow ic="key" lab="Change PIN" sub="6-digit · last set 14 Feb" onClick={() => {}}/>
          <ToggleRow ic="lock" lab="Face ID / fingerprint" sub="Quick unlock with biometrics" value={biometric} onChange={setBiometric}/>
          <ToggleRow ic="shield" lab="2-factor authentication" sub="OTP sent to +91 98765 43210" value={twoFA} onChange={setTwoFA}/>
          <ListRow ic="lock" lab="Change password" sub="Last changed 4 months ago" onClick={() => {}} last/>
        </ListCard>

        <SectionLabel label="Active sessions"/>
        <ListCard>
          <ListRow ic="phone" lab="iPhone 14 · Hyderabad" sub="This device · 2h ago" badge="Current"/>
          <ListRow ic="phone" lab="iPad Air · Home" sub="Yesterday 9:14 PM"/>
          <ListRow ic="globe" lab="Chrome on macOS" sub="Bengaluru · 3 days ago" last/>
        </ListCard>

        <SectionLabel label="More"/>
        <ListCard>
          <ToggleRow ic="lock" lab="Auto-lock on background" sub="Lock when app loses focus" value={autoLock} onChange={setAutoLock} last/>
        </ListCard>

        <button className="btn btn-outline" style={{ color: 'var(--c600)', borderColor: 'var(--c200)' }}>Sign out of all devices</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// NOTIFICATIONS PREFERENCES — channels + categories
// ─────────────────────────────────────────────────────────────
function NotificationPreferencesScreen({ nav }) {
  const [channels, setChannels] = useStateAcc({ push: true, email: true, sms: false, whatsapp: true, inApp: true });
  const [cats, setCats] = useStateAcc({ fees: true, attendance: true, homework: true, results: true, transport: true, announcements: false, marketing: false });
  const [quiet, setQuiet] = useStateAcc(true);
  const set = (kind) => (k) => (v) => kind === 'channel' ? setChannels(s => ({ ...s, [k]: v })) : setCats(s => ({ ...s, [k]: v }));

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Notifications" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <SectionLabel label="Channels" hint="Where Scholiq is allowed to reach you."/>
        <ListCard>
          <ToggleRow ic="bell" lab="Push notifications" sub="Lock screen + banners" value={channels.push} onChange={(v) => set('channel')('push')(v)}/>
          <ToggleRow ic="mail" lab="Email" sub="priya.r@gmail.com" value={channels.email} onChange={(v) => set('channel')('email')(v)}/>
          <ToggleRow ic="message" lab="SMS" sub="Standard rates" value={channels.sms} onChange={(v) => set('channel')('sms')(v)}/>
          <ToggleRow ic="whatsapp" lab="WhatsApp" sub="+91 98765 43210" value={channels.whatsapp} onChange={(v) => set('channel')('whatsapp')(v)}/>
          <ToggleRow ic="bell" lab="In-app inbox" sub="Always available" value={channels.inApp} onChange={(v) => set('channel')('inApp')(v)} last/>
        </ListCard>

        <SectionLabel label="What to send" hint="Category-level controls override channel choices."/>
        <ListCard>
          <ToggleRow ic="rupee" lab="Fees & payments" sub="Due dates, receipts, refunds" value={cats.fees} onChange={(v) => set('cat')('fees')(v)}/>
          <ToggleRow ic="check" lab="Attendance" sub="Mark-in, late, absent" value={cats.attendance} onChange={(v) => set('cat')('attendance')(v)}/>
          <ToggleRow ic="clipboard" lab="Homework & assignments" sub="Due dates, returned work" value={cats.homework} onChange={(v) => set('cat')('homework')(v)}/>
          <ToggleRow ic="trophy" lab="Results & report cards" sub="Test scores, term reports" value={cats.results} onChange={(v) => set('cat')('results')(v)}/>
          <ToggleRow ic="bus" lab="Transport" sub="Bus arrival, route changes" value={cats.transport} onChange={(v) => set('cat')('transport')(v)}/>
          <ToggleRow ic="megaphone" lab="School announcements" sub="Events, holidays" value={cats.announcements} onChange={(v) => set('cat')('announcements')(v)}/>
          <ToggleRow ic="sparkles" lab="Newsletters & tips" sub="Weekly digest" value={cats.marketing} onChange={(v) => set('cat')('marketing')(v)} last/>
        </ListCard>

        <SectionLabel label="Quiet hours"/>
        <ListCard>
          <ToggleRow ic="clock" lab="Mute non-urgent at night" sub="10:00 PM – 7:00 AM" value={quiet} onChange={setQuiet} last/>
        </ListCard>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LANGUAGE — radio that ACTUALLY updates the lang tweak
// ─────────────────────────────────────────────────────────────
function LanguageScreen({ nav, lang, setLang }) {
  const opts = [
    { v: 'en', name: 'English', native: 'English', sub: 'Default · 100% translated' },
    { v: 'hi', name: 'Hindi', native: 'हिन्दी', sub: '100% translated' },
    { v: 'te', name: 'Telugu', native: 'తెలుగు', sub: '100% translated' },
  ];
  const upcoming = [
    { name: 'Tamil', native: 'தமிழ்', sub: 'Coming Q3 2026' },
    { name: 'Kannada', native: 'ಕನ್ನಡ', sub: 'Coming Q3 2026' },
    { name: 'Malayalam', native: 'മലയാളം', sub: 'Coming 2026' },
    { name: 'Marathi', native: 'मराठी', sub: 'Coming 2026' },
  ];

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Language" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <SectionLabel label="App language" hint="Changes apply immediately across all screens. School communication may stay in the school's chosen language."/>
        <ListCard>
          {opts.map((o, i) => (
            <button key={o.v} onClick={() => setLang && setLang(o.v)} className="row" style={{ width: '100%', padding: '12px 14px', gap: 12, textAlign: 'left', borderBottom: i < opts.length - 1 ? '1px solid var(--n100)' : 'none', background: lang === o.v ? 'var(--p50)' : 'transparent' }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: lang === o.v ? 'var(--p600)' : 'var(--n100)', color: lang === o.v ? '#fff' : 'var(--n700)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 14 }}>{o.v.toUpperCase()}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{o.native} <span style={{ fontWeight: 500, color: 'var(--n500)' }}>· {o.name}</span></div>
                <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{o.sub}</div>
              </div>
              {lang === o.v ? <Icon name="check" size={18} style={{ color: 'var(--p600)' }}/> : <div style={{ width: 18, height: 18, border: '2px solid var(--n200)', borderRadius: 99 }}/>}
            </button>
          ))}
        </ListCard>

        <SectionLabel label="Coming soon" hint="Vote for your language from Help → Feedback."/>
        <ListCard>
          {upcoming.map((u, i) => (
            <div key={i} className="row" style={{ padding: '12px 14px', gap: 12, opacity: .6, borderBottom: i < upcoming.length - 1 ? '1px solid var(--n100)' : 'none' }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', color: 'var(--n400)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12 }}>{u.name.slice(0,2).toUpperCase()}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--n700)' }}>{u.native} <span style={{ fontWeight: 500, color: 'var(--n500)' }}>· {u.name}</span></div>
                <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 1 }}>{u.sub}</div>
              </div>
            </div>
          ))}
        </ListCard>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// APPEARANCE — theme + text size
// ─────────────────────────────────────────────────────────────
function AppearanceScreen({ nav }) {
  const [theme, setTheme] = useStateAcc('system');
  const [size, setSize] = useStateAcc(2);
  const [reduceMotion, setReduceMotion] = useStateAcc(false);
  const [highContrast, setHighContrast] = useStateAcc(false);

  const themes = [
    { v: 'light', lab: 'Light', sub: 'Always bright', bg: '#FFFFFF', fg: 'var(--n900)' },
    { v: 'dark', lab: 'Dark', sub: 'Always dim', bg: '#0F172A', fg: '#FFFFFF' },
    { v: 'system', lab: 'System', sub: 'Match device', bg: 'linear-gradient(90deg,#FFF 50%,#0F172A 50%)', fg: 'var(--n900)' },
  ];
  const sizes = ['S', 'M', 'L', 'XL'];

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Appearance" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <SectionLabel label="Theme"/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
          {themes.map((th) => (
            <button key={th.v} onClick={() => setTheme(th.v)} style={{
              padding: 12, borderRadius: 14, background: '#fff',
              border: theme === th.v ? '2px solid var(--p600)' : '1px solid var(--n100)',
              boxShadow: theme === th.v ? 'var(--el-glow)' : 'var(--el-1)', textAlign: 'left',
            }}>
              <div style={{ height: 56, borderRadius: 10, background: th.bg, border: '1px solid var(--n100)', marginBottom: 10, padding: 8, display: 'flex', alignItems: 'flex-end' }}>
                <div style={{ width: 16, height: 4, borderRadius: 2, background: th.v === 'dark' ? '#fff' : 'var(--n900)', opacity: .6 }}/>
              </div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>{th.lab}</div>
              <div style={{ fontSize: 10, color: 'var(--n500)' }}>{th.sub}</div>
            </button>
          ))}
        </div>

        <SectionLabel label="Text size" hint="Affects body and supporting text. Headings stay constant."/>
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 10, marginBottom: 12 }}>
            <span style={{ fontSize: 11, color: 'var(--n500)', fontWeight: 600 }}>A</span>
            <input type="range" min="0" max="3" value={size} onChange={(e) => setSize(+e.target.value)} style={{ flex: 1, accentColor: 'var(--p600)' }}/>
            <span style={{ fontSize: 16, color: 'var(--n900)', fontWeight: 700 }}>A</span>
          </div>
          <div className="row" style={{ gap: 6 }}>
            {sizes.map((s, i) => (
              <button key={s} onClick={() => setSize(i)} style={{ flex: 1, padding: '6px 10px', fontSize: 11, fontWeight: 700, borderRadius: 8, background: size === i ? 'var(--n900)' : 'var(--n50)', color: size === i ? '#fff' : 'var(--n700)' }}>{s}</button>
            ))}
          </div>
          <div className="card-flat" style={{ marginTop: 14, padding: 12 }}>
            <div style={{ fontSize: 11, color: 'var(--n500)', fontWeight: 700, fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>PREVIEW</div>
            <div style={{ fontSize: 13 + size * 1.5, color: 'var(--n900)', marginTop: 6, lineHeight: 1.5 }}>Aarav scored 92 on the Math UT-2 — well above the class average of 78.</div>
          </div>
        </div>

        <SectionLabel label="Accessibility"/>
        <ListCard>
          <ToggleRow ic="zap" lab="Reduce motion" sub="Disable transitions and animations" value={reduceMotion} onChange={setReduceMotion}/>
          <ToggleRow ic="eye" lab="High contrast" sub="Stronger borders and dividers" value={highContrast} onChange={setHighContrast} last/>
        </ListCard>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HELP CENTER — search + categories + popular
// ─────────────────────────────────────────────────────────────
function HelpCenterScreen({ nav }) {
  const [q, setQ] = useStateAcc('');
  const cats = [
    { ic: 'rupee', lab: 'Fees & payments', sub: '24 articles', clr: 'var(--c600)', bg: 'var(--c50)' },
    { ic: 'bus', lab: 'Transport & routes', sub: '12 articles', clr: 'var(--p600)', bg: 'var(--p50)' },
    { ic: 'clipboard', lab: 'Homework & marks', sub: '18 articles', clr: '#1E40AF', bg: 'var(--info-50)' },
    { ic: 'shield', lab: 'Account & security', sub: '9 articles', clr: 'var(--success)', bg: 'var(--success-50)' },
    { ic: 'bell', lab: 'Notifications', sub: '7 articles', clr: '#854D0E', bg: '#FEFCE8' },
    { ic: 'message', lab: 'Chat with school', sub: '11 articles', clr: '#8B5CF6', bg: '#FAF5FF' },
  ];
  const popular = [
    'How do I pay fees in instalments?',
    'Why is my child marked absent today?',
    'How to switch between Parent and Teacher?',
    'My bus tracker is showing the wrong route',
    'How do I download a fee receipt for tax?',
  ];
  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Help center" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card" style={{ padding: 12 }}>
          <div className="row" style={{ gap: 10 }}>
            <Icon name="search" size={18} style={{ color: 'var(--n400)' }}/>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search help articles…" style={{ flex: 1, border: 'none', outline: 'none', fontSize: 13, background: 'transparent', fontFamily: 'inherit' }}/>
          </div>
        </div>

        <SectionLabel label="Browse by topic"/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
          {cats.map((c, i) => (
            <button key={i} className="card" style={{ padding: 14, textAlign: 'left' }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: c.bg, color: c.clr, display: 'grid', placeItems: 'center' }}><Icon name={c.ic} size={18}/></div>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)', marginTop: 10 }}>{c.lab}</div>
              <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 2 }}>{c.sub}</div>
            </button>
          ))}
        </div>

        <SectionLabel label="Popular questions"/>
        <ListCard>
          {popular.map((p, i) => (
            <button key={i} className="row" style={{ width: '100%', padding: '12px 14px', gap: 12, textAlign: 'left', borderBottom: i < popular.length - 1 ? '1px solid var(--n100)' : 'none' }}>
              <Icon name="help" size={16} style={{ color: 'var(--p600)' }}/>
              <div style={{ flex: 1, fontSize: 12.5, color: 'var(--n800)', fontWeight: 500 }}>{p}</div>
              <Icon name="chev-r" size={14} style={{ color: 'var(--n400)' }}/>
            </button>
          ))}
        </ListCard>

        <div className="card-tinted" style={{ padding: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Still stuck?</div>
          <div style={{ fontSize: 11.5, color: 'var(--n600)', marginTop: 4 }}>Our support team replies in under 4 minutes during school hours.</div>
          <button onClick={() => nav.push('contactSupport')} className="btn btn-sm" style={{ marginTop: 10, height: 34, fontSize: 12, width: '100%' }}>Contact support →</button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CONTACT SUPPORT — channels + recent tickets
// ─────────────────────────────────────────────────────────────
function ContactSupportScreen({ nav }) {
  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Contact support" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card-grad" style={{ padding: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em', fontFamily: 'var(--mono)', opacity: .85 }}>WE ARE OPEN</div>
          <div style={{ fontSize: 17, fontWeight: 800, marginTop: 6 }}>Avg reply in <span style={{ fontVariantNumeric: 'tabular-nums' }}>4 min</span></div>
          <div style={{ fontSize: 12, opacity: .9, marginTop: 4 }}>Mon–Sat · 7 AM – 9 PM IST</div>
        </div>

        <SectionLabel label="Talk to us"/>
        <ListCard>
          <ListRow ic="message" lab="Chat with us" sub="Fastest · usually < 5 min" badge="Online" onClick={() => {}}/>
          <ListRow ic="whatsapp" lab="WhatsApp" sub="+91 90000 12345" onClick={() => {}}/>
          <ListRow ic="phone" lab="Call us" sub="1800 200 5005 · toll free" onClick={() => {}}/>
          <ListRow ic="mail" lab="Email" sub="help@scholiq.in · within 24h" onClick={() => {}} last/>
        </ListCard>

        <SectionLabel label="Your recent tickets"/>
        <ListCard>
          <ListRow ic="check" lab="Fee receipt for Term 1" sub="#SQ-3382 · resolved 2 days ago" badge="Closed" onClick={() => {}}/>
          <ListRow ic="clock" lab="Bus tracker showing old route" sub="#SQ-3401 · open · 3h ago" onClick={() => {}}/>
          <ListRow ic="check" lab="Cannot login on iPad" sub="#SQ-3338 · resolved · last week" badge="Closed" onClick={() => {}} last/>
        </ListCard>

        <SectionLabel label="Self-serve"/>
        <ListCard>
          <ListRow ic="help" lab="Browse the help center" sub="Most answers are 1 click away" onClick={() => nav.push('helpCenter')}/>
          <ListRow ic="info" lab="System status" sub="All systems operational" onClick={() => {}} last/>
        </ListCard>

        <button className="btn"><Icon name="message" size={16}/> Start a new conversation</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PRIVACY & DATA — DPDPA-style controls
// ─────────────────────────────────────────────────────────────
function PrivacyDataScreen({ nav }) {
  const [analytics, setAnalytics] = useStateAcc(true);
  const [crash, setCrash] = useStateAcc(true);
  const [share, setShare] = useStateAcc(false);
  const [marketing, setMarketing] = useStateAcc(false);

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Privacy & data" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card-tinted" style={{ padding: 14 }}>
          <div className="row" style={{ gap: 10 }}>
            <Icon name="shield" size={18} style={{ color: 'var(--p600)' }}/>
            <span style={{ flex: 1, fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>DPDPA 2023 compliant</span>
            <span className="pill pill-s" style={{ fontSize: 10 }}>Verified</span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--n600)', marginTop: 8, lineHeight: 1.5 }}>You control what we collect, how we use it, and can export or delete your data at any time.</div>
        </div>

        <SectionLabel label="Data we collect" hint="Granular controls — toggle off anything that's not essential to running the app."/>
        <ListCard>
          <ToggleRow ic="zap" lab="Usage analytics" sub="Helps us improve the app" value={analytics} onChange={setAnalytics}/>
          <ToggleRow ic="info" lab="Crash & error reports" sub="Anonymous · helps fix bugs" value={crash} onChange={setCrash}/>
          <ToggleRow ic="globe" lab="Share with school for personalisation" sub="Tailored homework reminders" value={share} onChange={setShare}/>
          <ToggleRow ic="megaphone" lab="Marketing communications" sub="Newsletters · feature launches" value={marketing} onChange={setMarketing} last/>
        </ListCard>

        <SectionLabel label="Your data"/>
        <ListCard>
          <ListRow ic="download" lab="Download my data" sub="ZIP with all your info · ready in 24h" onClick={() => {}}/>
          <ListRow ic="document" lab="Activity log" sub="See what's been recorded" onClick={() => {}}/>
          <ListRow ic="edit" lab="Correct my data" sub="Submit a correction request" onClick={() => {}} last/>
        </ListCard>

        <SectionLabel label="Documents"/>
        <ListCard>
          <ListRow ic="document" lab="Privacy policy" sub="Updated 12 Jan 2026" onClick={() => {}}/>
          <ListRow ic="document" lab="Terms of service" sub="Updated 12 Jan 2026" onClick={() => {}}/>
          <ListRow ic="document" lab="Cookie policy" sub="No tracking cookies in app" onClick={() => {}}/>
          <ListRow ic="document" lab="Data processing agreement" sub="For school administrators" onClick={() => {}} last/>
        </ListCard>

        <SectionLabel label="Danger zone" hint="Deleting your account is permanent. School records may be retained per CBSE rules."/>
        <ListCard>
          <ListRow ic="x" lab="Delete account" sub="Permanently remove all personal data" onClick={() => {}} danger last/>
        </ListCard>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ABOUT — version, mission, team, legal
// ─────────────────────────────────────────────────────────────
function AboutScreen({ nav }) {
  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="About Scholiq" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card" style={{ padding: 24, textAlign: 'center' }}>
          <div style={{ width: 72, height: 72, margin: '0 auto 14px', borderRadius: 18, background: 'var(--grad-cool)', display: 'grid', placeItems: 'center', color: '#fff', fontSize: 28, fontWeight: 800, letterSpacing: '-.02em', boxShadow: 'var(--el-glow)' }}>S</div>
          <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)', letterSpacing: '-.02em' }}>Scholiq</div>
          <div style={{ fontSize: 12, color: 'var(--n500)', marginTop: 4, fontFamily: 'var(--mono)' }}>v2.4.1 · build 8421 · Jan 2026</div>
          <div style={{ fontSize: 12.5, color: 'var(--n600)', marginTop: 14, lineHeight: 1.6, maxWidth: 280, margin: '14px auto 0' }}>One app for school life. Built so parents, teachers, students, drivers and operators stop juggling five tools.</div>
        </div>

        <SectionLabel label="By the numbers"/>
        <div className="card-flat" style={{ padding: 14, display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
          {[
            { v: '184k', l: 'Students' },
            { v: '420', l: 'Schools' },
            { v: '12', l: 'States' },
          ].map((s, i) => (
            <div key={i} style={{ textAlign: 'center', borderRight: i < 2 ? '1px solid var(--n200)' : 'none' }}>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em' }}>{s.v}</div>
              <div style={{ fontSize: 10, color: 'var(--n500)', marginTop: 2, fontWeight: 600 }}>{s.l}</div>
            </div>
          ))}
        </div>

        <SectionLabel label="Made by"/>
        <ListCard>
          <ListRow ic="pin" lab="Scholiq Education Pvt. Ltd." sub="HSR Layout, Bengaluru · Hyderabad office"/>
          <ListRow ic="users" lab="42 humans · 11 schools-in-residence" sub="Founded 2020 · backed by Blume + Sequoia" last/>
        </ListCard>

        <SectionLabel label="Resources"/>
        <ListCard>
          <ListRow ic="globe" lab="scholiq.in" sub="Open in browser" onClick={() => {}}/>
          <ListRow ic="document" lab="Release notes" sub="What's new in 2.4.1" onClick={() => {}}/>
          <ListRow ic="star" lab="Rate Scholiq" sub="Help us reach more schools" onClick={() => {}}/>
          <ListRow ic="message" lab="Send feedback" sub="We read everything" onClick={() => nav.push('contactSupport')} last/>
        </ListCard>

        <SectionLabel label="Legal"/>
        <ListCard>
          <ListRow ic="document" lab="Privacy policy" onClick={() => nav.push('privacy')}/>
          <ListRow ic="document" lab="Terms of service" onClick={() => nav.push('privacy')}/>
          <ListRow ic="document" lab="Open-source licenses" sub="The libraries we depend on" onClick={() => {}} last/>
        </ListCard>

        <div style={{ textAlign: 'center', fontSize: 10, color: 'var(--n400)', margin: '14px 0 4px', fontFamily: 'var(--mono)', letterSpacing: '.08em' }}>♥ MADE IN HYDERABAD &amp; BENGALURU</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SIGN OUT — confirmation card
// ─────────────────────────────────────────────────────────────
function SignOutScreen({ nav, role }) {
  const person = role === 'student' ? { name: 'Aarav Reddy', initial: 'A', clr: '' }
    : role === 'teacher' ? { name: 'Sneha Reddy', initial: 'SR', clr: 'violet' }
    : role === 'driver' ? { name: 'Arjun R.', initial: 'AR', clr: 'sky' }
    : role === 'operator' ? { name: 'Priya Menon', initial: 'PM', clr: 'coral' }
    : { name: 'Priya Reddy', initial: 'PR', clr: 'coral' };
  const [done, setDone] = useStateAcc(false);

  return (
    <div className="app screen-in">
      <StatusBar/>
      <NavHeader title="Sign out" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 12 }}>
        <div className="card" style={{ padding: 22, textAlign: 'center' }}>
          <div className={`av av-56 ${person.clr || ''}`} style={{ width: 72, height: 72, fontSize: 24, margin: '0 auto 14px' }}>{person.initial}</div>
          <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)' }}>Sign out as {person.name}?</div>
          <div style={{ fontSize: 12.5, color: 'var(--n500)', marginTop: 8, lineHeight: 1.5 }}>You'll be logged out on this device. Your memberships and data stay safe — sign back in any time.</div>
        </div>

        <SectionLabel label="Before you go"/>
        <ListCard>
          <ListRow ic="download" lab="Download my data" sub="ZIP with all your records" onClick={() => nav.push('privacy')}/>
          <ListRow ic="bell" lab="Pause notifications instead" sub="Quiet without signing out" onClick={() => nav.push('notifPrefs')}/>
          <ListRow ic="user" lab="Switch account" sub="Use a different login" onClick={() => nav.pop()} last/>
        </ListCard>

        {done ? (
          <div className="card-tinted" style={{ padding: 16, textAlign: 'center' }}>
            <Icon name="check" size={20} style={{ color: 'var(--success)' }}/>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', marginTop: 8 }}>Signed out</div>
            <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 4 }}>Returning to login screen…</div>
          </div>
        ) : (
          <>
            <button onClick={() => { setDone(true); setTimeout(() => nav.replace('home'), 1100); }} className="btn btn-coral"><Icon name="logout" size={16}/> Sign out now</button>
            <button onClick={() => nav.pop()} className="btn btn-outline">Cancel</button>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  ShareProfileScreen, AppSettingsScreen, EditProfileScreen, PersonalInfoScreen,
  SecurityScreen, NotificationPreferencesScreen, LanguageScreen, AppearanceScreen,
  HelpCenterScreen, ContactSupportScreen, PrivacyDataScreen, AboutScreen, SignOutScreen,
});
