// Simple Pro Mobile — Settings sub-screens
const { useState: useStateSet, useEffect: useEffSet, useRef: useRefSet, createContext: createCtxSet, useContext: useCtxSet } = React;

// ═══════════════════════════════════════════════════════════════
// EDITABLE SETTINGS STATE — persisted to localStorage
// ═══════════════════════════════════════════════════════════════
const SETTINGS_DEFAULTS = {
  // Profile
  fullName:'Marcus Leal', email:'marcus@simplepro.app', phone:'(555) 214-8899', title:'Lead Plumber',
  companyName:'Simple Pro Plumbing', employeeId:'EMP-0042', timezone:'PST (UTC−8)', language:'English',
  // Company
  bizName:'Simple Pro Plumbing', bizDba:'—', bizEin:'••-•••8842', bizLicense:'CSLB 1029384',
  bizPhone:'(555) 123-4567', bizEmail:'hello@simplepro-pl.com', bizWebsite:'simplepro-pl.com', bizAddress:'Los Angeles, CA',
  bizServiceZip:'90006', bizServiceRadius:35,
  // Payments (extra processors)
  payZelle:false, payVenmo:false, payPaypal:false,
  zelleHandle:'', venmoHandle:'', paypalEmail:'',
  // Notifications extras
  quietFrom:'21:00', quietTo:'07:00',
  // Security
  twoFA:true, biometric:true,
  // Notifications
  notifPush:true, notifEmail:true, notifSms:false,
  notifNewJob:true, notifScheduleChange:true, notifPayment:true, notifMessage:true, notifBelleCall:false, notifDailyDigest:true,
  quietHours:'9 PM – 7 AM', quietWeekends:true,
  // Payments
  payCard:true, payAch:true, payApplePay:true, payCheck:true, payCash:true,
  cardFee:'2.9% + 30¢', passFeeToCustomer:false, lateFee:'1.5% / mo', depositRequired:'25%',
  // Belle
  belleEnabled:true, belleRings:'3 rings', belleHours:'Mon–Fri 7a–6p', belleAfterHours:'Take message',
  belleVoice:'Belle (warm)', belleGreeting:'Hi, thanks for calling Simple Pro Plumbing!',
  belleBook:true, belleTransfer:true, belleQuote:true, bellePhotos:true, belleDeposit:false,
};

const SettingsCtx = createCtxSet(null);

function useSetting(key) {
  const ctx = useCtxSet(SettingsCtx);
  if (!ctx) return [SETTINGS_DEFAULTS[key], () => {}];
  return [ctx.settings[key], (v) => ctx.setSetting(key, v)];
}

function SettingsProvider({ children }) {
  const [settings, setSettings] = useStateSet(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('sp_settings') || '{}');
      return { ...SETTINGS_DEFAULTS, ...saved };
    } catch(e) { return SETTINGS_DEFAULTS; }
  });
  const [editor, setEditor] = useStateSet(null); // {key, label, type, options?}
  useEffSet(() => {
    try { localStorage.setItem('sp_settings', JSON.stringify(settings)); } catch(e) {}
  }, [settings]);
  const setSetting = (key, val) => setSettings(s => ({ ...s, [key]: val }));
  const openEditor = (cfg) => setEditor(cfg);
  const closeEditor = () => setEditor(null);
  return (
    <SettingsCtx.Provider value={{ settings, setSetting, openEditor, closeEditor }}>
      {children}
      {editor && <EditSheet editor={editor} settings={settings} setSetting={setSetting} onClose={closeEditor}/>}
    </SettingsCtx.Provider>
  );
}

// Time range picker for custom quiet hours
function TimeRangePicker({ editor, setSetting, onClose }) {
  // editor.fromKey and editor.toKey should be present
  const [from, setFrom] = useStateSet('21:00');
  const [to, setTo] = useStateSet('07:00');
  useEffSet(() => {
    try {
      const s = JSON.parse(localStorage.getItem('sp_settings') || '{}');
      if (s[editor.fromKey]) setFrom(s[editor.fromKey]);
      if (s[editor.toKey]) setTo(s[editor.toKey]);
    } catch(e) {}
  }, []);
  const save = () => {
    setSetting(editor.fromKey, from);
    setSetting(editor.toKey, to);
    const fmt = (t) => {
      const [h,m] = t.split(':').map(Number);
      const hr = ((h+11)%12)+1;
      return `${hr}${m?':'+String(m).padStart(2,'0'):''} ${h<12?'AM':'PM'}`;
    };
    setSetting(editor.key, `${fmt(from)} – ${fmt(to)}`);
    onClose();
  };
  return (
    <div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
        <div>
          <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>FROM</div>
          <input type="time" value={from} onChange={e=>setFrom(e.target.value)}
            style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:18,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',fontWeight:600,color:'#111'}}/>
        </div>
        <div>
          <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>TO</div>
          <input type="time" value={to} onChange={e=>setTo(e.target.value)}
            style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:18,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',fontWeight:600,color:'#111'}}/>
        </div>
      </div>
      <button onClick={save} style={{marginTop:18,width:'100%',padding:'13px',background:'#0071e3',color:'white',border:'none',borderRadius:10,fontSize:15,fontWeight:600,cursor:'pointer'}}>Save custom hours</button>
    </div>
  );
}

// Bottom-sheet editor that pops up to edit any field
function EditSheet({ editor, settings, setSetting, onClose }) {
  const [val, setVal] = useStateSet(settings[editor.key] ?? '');
  const inputRef = useRefSet();
  useEffSet(() => {
    const t = setTimeout(() => inputRef.current?.focus(), 60);
    return () => clearTimeout(t);
  }, []);
  const save = () => { setSetting(editor.key, val); onClose(); };
  return (
    <>
      <div onClick={onClose} style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.5)',zIndex:400,animation:'fadeIn 0.15s'}}/>
      <div style={{position:'absolute',left:0,right:0,bottom:0,zIndex:401,background:'white',
        borderTopLeftRadius:20,borderTopRightRadius:20,paddingBottom:30,
        boxShadow:'0 -12px 40px rgba(0,0,0,0.2)',animation:'slideUp 0.2s'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'14px 18px',borderBottom:'0.5px solid rgba(0,0,0,0.08)'}}>
          <button onClick={onClose} style={{background:'none',border:'none',fontSize:15,color:'rgba(0,0,0,0.5)',fontWeight:500,cursor:'pointer',padding:0}}>Cancel</button>
          <div style={{fontSize:15,fontWeight:600,color:'#111'}}>{editor.label}</div>
          <button onClick={save} style={{background:'none',border:'none',fontSize:15,color:'#0071e3',fontWeight:600,cursor:'pointer',padding:0}}>Save</button>
        </div>
        <div style={{padding:'18px'}}>
          {editor.type === 'options' ? (
            <div style={{display:'flex',flexDirection:'column',gap:2}}>
              {editor.options.map(opt => (
                <div key={opt} onClick={()=>{ setSetting(editor.key, opt); onClose(); }}
                  style={{padding:'14px 16px',background: val===opt?'#eff6ff':'#f7f7f8',
                    borderRadius:10,display:'flex',alignItems:'center',justifyContent:'space-between',cursor:'pointer'}}>
                  <span style={{fontSize:15,color:'#111',fontWeight: val===opt?600:500}}>{opt}</span>
                  {val===opt && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#0071e3" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                </div>
              ))}
            </div>
          ) : editor.type === 'timerange' ? (
            <TimeRangePicker editor={editor} setSetting={setSetting} onClose={onClose}/>
          ) : editor.type === 'textarea' ? (
            <textarea ref={inputRef} value={val} onChange={e=>setVal(e.target.value)}
              rows={5}
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',resize:'none',outline:'none',background:'#f7f7f8'}}/>
          ) : (
            <input ref={inputRef} type={editor.type || 'text'} value={val}
              onChange={e=>setVal(e.target.value)}
              onKeyDown={e=>{ if(e.key==='Enter') save(); }}
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',outline:'none',background:'#f7f7f8'}}/>
          )}
          {editor.hint && <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:10,lineHeight:1.45}}>{editor.hint}</div>}
        </div>
      </div>
    </>
  );
}

// Hook to request opening the edit sheet
function useEditor() {
  const ctx = useCtxSet(SettingsCtx);
  return ctx?.openEditor || (()=>{});
}

// Shared toggle
function SettingsToggle({ on, onTap }) {
  return (
    <div onClick={onTap} style={{width:42,height:24,borderRadius:12,cursor:'pointer',flexShrink:0,
      background: on?'#34c759':'#e2e2e6',padding:'0 3px',display:'flex',alignItems:'center',transition:'background 0.18s'}}>
      <div style={{width:18,height:18,borderRadius:'50%',background:'white',
        transform:on?'translateX(18px)':'translateX(0)',transition:'transform 0.2s',boxShadow:'0 1px 4px rgba(0,0,0,0.15)'}}/>
    </div>
  );
}

// Generic list settings page
function buildList(items) {
  return (
    <Card>
      {items.map((item, i) => (
        <div key={item.label + i} onClick={item.onTap}
          style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12,
            borderBottom: i<items.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor: item.onTap?'pointer':'default'}}>
          {item.icon && <div style={{width:22,height:22,display:'flex',alignItems:'center',justifyContent:'center',color:'rgba(0,0,0,0.5)'}}>{item.icon}</div>}
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.01em'}}>{item.label}</div>
            {item.sub && <div style={{fontSize:12,color:'rgba(0,0,0,0.45)',marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{item.sub}</div>}
          </div>
          {item.toggle !== undefined ? (
            <SettingsToggle on={item.toggle} onTap={e=>{ e?.stopPropagation?.(); item.onToggle?.(); }}/>
          ) : (
            <>
              {item.right && <div style={{fontSize:13,color:'rgba(0,0,0,0.45)',maxWidth:160,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{item.right}</div>}
              {(item.onTap || item.chevron) && <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>}
            </>
          )}
        </div>
      ))}
    </Card>
  );
}

// Expose SettingsProvider to other scripts
window.SettingsProvider = SettingsProvider;

// ── SETTINGS HUB ──────────────────────────────────────────
function SettingsScreen({ onNav }) {
  const sections = [
    {
      title:'Account',
      items: [
        { icon: Icons.user, label:'Profile', sub:'Personal info & avatar', onTap:()=>onNav('settings-profile') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>, label:'Security', sub:'Password & 2FA', onTap:()=>onNav('settings-security') },
        { icon: Icons.message, label:'Notifications', sub:'Push, email, SMS', onTap:()=>onNav('settings-notifications') },
      ]
    },
    {
      title:'Business',
      items: [
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M3 21h18M5 21V7l7-4 7 4v14M9 9h1M9 13h1M9 17h1M14 9h1M14 13h1M14 17h1"/></svg>, label:'Company', sub:'Business profile', onTap:()=>onNav('settings-company') },
        { icon: Icons.team, label:'Team', sub:'Members & roles', onTap:()=>onNav('settings-team') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>, label:'Payments', sub:'Stripe, Zelle, Venmo, PayPal', onTap:()=>onNav('settings-payments') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>, label:'Billing', sub:'Plan: Pro · $249/mo', onTap:()=>onNav('settings-billing') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>, label:'Price Book', sub:'Services & rates', onTap:()=>onNav('settings-pricebook') },
      ]
    },
    {
      title:'Automation',
      items: [
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>, label:'Belle AI', sub:'Voice agent settings', onTap:()=>onNav('settings-belle') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>, label:'Templates', sub:'Forms, estimates, invoices', onTap:()=>onNav('settings-templates') },
      ]
    },
    {
      title:'Integrations & Data',
      items: [
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>, label:'Integrations', sub:'QuickBooks, Google, etc.', onTap:()=>onNav('settings-integrations') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0018 0V5M3 12a9 3 0 0018 0"/></svg>, label:'Data & Export', sub:'Backup, export, delete', onTap:()=>onNav('settings-data') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>, label:'Privacy & Policies', onTap:()=>onNav('settings-privacy') },
      ]
    },
    {
      title:'Support',
      items: [
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>, label:'Help Center', onTap:()=>onNav('settings-help') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>, label:'Contact Support', onTap:()=>onNav('settings-contact') },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>, label:'About', right:'v4.12.0', onTap:()=>onNav('settings-about') },
      ]
    },
  ];

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Settings" onBack="__back"/>
      {sections.map(sec => (
        <div key={sec.title}>
          <SectionHeader title={sec.title}/>
          {buildList(sec.items)}
        </div>
      ))}
    </div>
  );
}

// ── PROFILE ──────────────────────────────────────────────────
function SettingsProfileScreen({ onNav }) {
  const openEditor = useEditor();
  const [fullName] = useSetting('fullName');
  const [email] = useSetting('email');
  const [phone] = useSetting('phone');
  const [title] = useSetting('title');
  const [companyName] = useSetting('companyName');
  const [employeeId] = useSetting('employeeId');
  const [timezone] = useSetting('timezone');
  const [language] = useSetting('language');
  const [signed, setSigned] = useStateSet(false);
  const initials = fullName.split(' ').map(s=>s[0]).slice(0,2).join('').toUpperCase();
  const edit = (key, label, type, extra) => openEditor({ key, label, type: type||'text', ...extra });
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Profile" onBack="__back"/>
      <div style={{padding:'24px 20px',display:'flex',flexDirection:'column',alignItems:'center',gap:12,background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{width:84,height:84,borderRadius:'50%',background:'linear-gradient(135deg,#0071e3,#0f172a)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:30,fontWeight:700,color:'white'}}>{initials}</div>
        <div onClick={()=>alert('Open camera / photo library')} style={{fontSize:11,color:'#0071e3',fontWeight:600,letterSpacing:'0.03em',cursor:'pointer'}}>CHANGE PHOTO</div>
      </div>
      <SectionHeader title="Personal"/>
      {buildList([
        { label:'Full name', right:fullName, onTap:()=>edit('fullName','Full name') },
        { label:'Email', right:email, onTap:()=>edit('email','Email','email') },
        { label:'Phone', right:phone, onTap:()=>edit('phone','Phone','tel') },
        { label:'Title', right:title, onTap:()=>edit('title','Title') },
      ])}
      <SectionHeader title="Work"/>
      {buildList([
        { label:'Company', right:companyName, onTap:()=>edit('companyName','Company') },
        { label:'Employee ID', right:employeeId, onTap:()=>edit('employeeId','Employee ID') },
        { label:'Timezone', right:timezone, onTap:()=>edit('timezone','Timezone','options',{ options:['PST (UTC−8)','MST (UTC−7)','CST (UTC−6)','EST (UTC−5)','AKST (UTC−9)','HST (UTC−10)'] }) },
        { label:'Language', right:language, onTap:()=>edit('language','Language','options',{ options:['English','Español','Français','Português'] }) },
      ])}
      <SectionHeader title="Signature"/>
      <div onClick={()=>setSigned(!signed)} style={{margin:'0 16px',background:'white',borderRadius:12,padding:20,border:'0.5px solid rgba(0,0,0,0.06)',cursor:'pointer'}}>
        <div style={{height:90,border:'1px dashed rgba(0,0,0,0.18)',borderRadius:8,display:'flex',alignItems:'center',justifyContent:'center',fontSize: signed?28:13,color:signed?'#0f172a':'rgba(0,0,0,0.4)',fontFamily: signed?"'Brush Script MT','Segoe Script',cursive":'inherit'}}>{signed ? fullName : 'Tap to sign'}</div>
        {signed && <div style={{textAlign:'center',fontSize:11,color:'#0071e3',fontWeight:600,marginTop:8}}>Tap to clear</div>}
      </div>
    </div>
  );
}

// ── SECURITY ─────────────────────────────────────────────────
function SettingsSecurityScreen({ onNav }) {
  const [twoFA, setTwoFA] = useSetting('twoFA');
  const [biometric, setBiometric] = useSetting('biometric');
  const openEditor = useEditor();
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Security" onBack="__back"/>
      <SectionHeader title="Sign-in"/>
      {buildList([
        { label:'Change password', sub:'Last changed 3 months ago', onTap:()=>openEditor({key:'_newPassword',label:'New password',type:'password',hint:'Must be at least 8 characters with one number.'}) },
        { label:'Face ID / Touch ID', toggle: biometric, onToggle:()=>setBiometric(!biometric) },
        { label:'Two-factor auth', toggle: twoFA, onToggle:()=>setTwoFA(!twoFA) },
      ])}
      <SectionHeader title="Active sessions"/>
      {buildList([
        { label:'iPhone 15 Pro', sub:'Los Angeles · Current', right:'Now' },
        { label:'MacBook Pro', sub:'Chrome · Los Angeles', right:'2d ago' },
        { label:'iPad', sub:'Safari · Garage', right:'1w ago' },
      ])}
      <div style={{margin:'14px 16px'}}>
        <button onClick={()=>alert('Signed out other devices')} style={{width:'100%',padding:'14px',background:'white',border:'0.5px solid rgba(0,0,0,0.08)',borderRadius:12,color:'#e11d48',fontSize:15,fontWeight:600,cursor:'pointer'}}>Sign out all other devices</button>
      </div>
    </div>
  );
}

// ── NOTIFICATIONS SETTINGS ───────────────────────────────────
function SettingsNotificationsScreen({ onNav }) {
  const openEditor = useEditor();
  const [push, setPush] = useSetting('notifPush');
  const [email, setEmail] = useSetting('notifEmail');
  const [sms, setSms] = useSetting('notifSms');
  const [newJob, setNewJob] = useSetting('notifNewJob');
  const [sched, setSched] = useSetting('notifScheduleChange');
  const [pay, setPay] = useSetting('notifPayment');
  const [msg, setMsg] = useSetting('notifMessage');
  const [belleCall, setBelleCall] = useSetting('notifBelleCall');
  const [digest, setDigest] = useSetting('notifDailyDigest');
  const [quietHours] = useSetting('quietHours');
  const [quietWeekends, setQuietWeekends] = useSetting('quietWeekends');
  const [emailAddr] = useSetting('email');
  const [phoneNum] = useSetting('phone');
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Notifications" onBack="__back"/>
      <SectionHeader title="Channels"/>
      {buildList([
        { label:'Push notifications', sub:'On this device', toggle:push, onToggle:()=>setPush(!push) },
        { label:'Email', sub:emailAddr, toggle:email, onToggle:()=>setEmail(!email) },
        { label:'SMS', sub:phoneNum, toggle:sms, onToggle:()=>setSms(!sms) },
      ])}
      <SectionHeader title="What to notify me about"/>
      {buildList([
        { label:'New job assigned', toggle:newJob, onToggle:()=>setNewJob(!newJob) },
        { label:'Schedule changes', toggle:sched, onToggle:()=>setSched(!sched) },
        { label:'Payment received', toggle:pay, onToggle:()=>setPay(!pay) },
        { label:'Customer message', toggle:msg, onToggle:()=>setMsg(!msg) },
        { label:'Belle call summary', toggle:belleCall, onToggle:()=>setBelleCall(!belleCall) },
        { label:'Daily digest', sub:'7:00 AM every weekday', toggle:digest, onToggle:()=>setDigest(!digest) },
      ])}
      <SectionHeader title="Do not disturb"/>
      {buildList([
        { label:'Quiet hours', right:quietHours, onTap:()=>openEditor({key:'quietHours',label:'Quiet hours',type:'options',options:['Off','8 PM – 6 AM','9 PM – 7 AM','10 PM – 7 AM','11 PM – 8 AM']}) },
        { label:'Custom hours', sub:'Set a specific from/to window', onTap:()=>openEditor({key:'quietHours',fromKey:'quietFrom',toKey:'quietTo',label:'Custom quiet hours',type:'timerange',hint:'Overrides the preset above.'}) },
        { label:'On weekends', toggle:quietWeekends, onToggle:()=>setQuietWeekends(!quietWeekends) },
      ])}
    </div>
  );
}

// ── COMPANY ──────────────────────────────────────────────────
function SettingsCompanyScreen({ onNav }) {
  const openEditor = useEditor();
  const [bizName] = useSetting('bizName');
  const [bizDba] = useSetting('bizDba');
  const [bizEin] = useSetting('bizEin');
  const [bizLicense] = useSetting('bizLicense');
  const [bizPhone] = useSetting('bizPhone');
  const [bizEmail] = useSetting('bizEmail');
  const [bizWebsite] = useSetting('bizWebsite');
  const [bizAddress] = useSetting('bizAddress');
  const edit = (key, label, type, extra) => openEditor({ key, label, type: type||'text', ...extra });
  const initials = bizName.split(' ').map(s=>s[0]).slice(0,2).join('').toUpperCase();
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Company" onBack="__back"/>
      <div style={{padding:'20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)',display:'flex',alignItems:'center',gap:14}}>
        <div style={{width:56,height:56,borderRadius:12,background:'#0f172a',display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:18,fontWeight:700}}>{initials}</div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:16,fontWeight:600,color:'#111',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{bizName}</div>
          <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>Established 2014 · 12 employees</div>
        </div>
        <div onClick={()=>alert('Upload logo')} style={{fontSize:11,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>EDIT</div>
      </div>
      <SectionHeader title="Details"/>
      {buildList([
        { label:'Business name', right:bizName, onTap:()=>edit('bizName','Business name') },
        { label:'DBA', right:bizDba, onTap:()=>edit('bizDba','Doing business as') },
        { label:'EIN', right:bizEin, onTap:()=>edit('bizEin','EIN') },
        { label:'License #', right:bizLicense, onTap:()=>edit('bizLicense','License number') },
      ])}
      <SectionHeader title="Contact"/>
      {buildList([
        { label:'Main phone', right:bizPhone, onTap:()=>edit('bizPhone','Main phone','tel') },
        { label:'Email', right:bizEmail, onTap:()=>edit('bizEmail','Email','email') },
        { label:'Website', right:bizWebsite, onTap:()=>edit('bizWebsite','Website') },
        { label:'Address', right:bizAddress, onTap:()=>edit('bizAddress','Address') },
      ])}
      <SectionHeader title="Service area"/>
      <ServiceAreaCard/>
    </div>
  );
}

// Service area with ZIP + mile radius + SVG map
function ServiceAreaCard() {
  const openEditor = useEditor();
  const [zip] = useSetting('bizServiceZip');
  const [radius, setRadius] = useSetting('bizServiceRadius');
  // Rough LA-area map as SVG — streets, freeways, water
  return (
    <div style={{margin:'0 16px 20px',background:'white',borderRadius:14,overflow:'hidden',border:'0.5px solid rgba(0,0,0,0.06)'}}>
      {/* Map */}
      <div style={{position:'relative',height:220,background:'#e9f2f9',overflow:'hidden'}}>
        <svg width="100%" height="100%" viewBox="0 0 400 220" preserveAspectRatio="xMidYMid slice" style={{position:'absolute',inset:0}}>
          {/* Ocean */}
          <rect x="0" y="140" width="110" height="80" fill="#bfdbf7"/>
          <path d="M0 140 Q 50 132 110 140 L 110 220 L 0 220 Z" fill="#bfdbf7"/>
          {/* Land base */}
          <rect x="0" y="0" width="400" height="140" fill="#f1f5f3"/>
          <path d="M0 140 L 110 140 Q 160 148 220 140 L 400 130 L 400 0 L 0 0 Z" fill="#f1f5f3"/>
          {/* Parks / green blobs */}
          <ellipse cx="285" cy="55" rx="40" ry="18" fill="#d7e9d2"/>
          <ellipse cx="85" cy="38" rx="28" ry="14" fill="#d7e9d2"/>
          <ellipse cx="340" cy="165" rx="35" ry="12" fill="#d7e9d2"/>
          {/* Freeways (thick) */}
          <path d="M 0 80 L 400 70" stroke="#fbbf24" strokeWidth="3" fill="none"/>
          <path d="M 200 0 L 210 220" stroke="#fbbf24" strokeWidth="3" fill="none"/>
          <path d="M 0 160 Q 150 150 400 175" stroke="#fbbf24" strokeWidth="2.5" fill="none"/>
          {/* Streets (thin) */}
          {Array.from({length:14}).map((_,i) => (
            <line key={'h'+i} x1="0" y1={15+i*15} x2="400" y2={15+i*15} stroke="white" strokeWidth="1" opacity="0.7"/>
          ))}
          {Array.from({length:20}).map((_,i) => (
            <line key={'v'+i} x1={15+i*20} y1="0" x2={15+i*20} y2="220" stroke="white" strokeWidth="1" opacity="0.7"/>
          ))}
          {/* Radius circle — sized so 50mi = ~150px */}
          <circle cx="200" cy="110" r={Math.max(15, radius*3)} fill="#0071e3" fillOpacity="0.12" stroke="#0071e3" strokeWidth="2"/>
          <circle cx="200" cy="110" r={Math.max(15, radius*3)} fill="none" stroke="#0071e3" strokeWidth="1" strokeDasharray="4 4" opacity="0.5"/>
          {/* Pin */}
          <g transform="translate(200,110)">
            <circle cx="0" cy="0" r="10" fill="white"/>
            <circle cx="0" cy="0" r="7" fill="#0071e3"/>
            <circle cx="0" cy="0" r="3" fill="white"/>
          </g>
          {/* Labels */}
          <text x="108" y="205" fontSize="8" fill="rgba(0,0,0,0.45)" fontWeight="600">PACIFIC</text>
          <text x="285" y="50" fontSize="8" fill="rgba(0,0,0,0.45)" fontWeight="600">GRIFFITH</text>
        </svg>
        {/* Overlays */}
        <div style={{position:'absolute',top:12,left:12,background:'white',borderRadius:8,padding:'6px 10px',boxShadow:'0 2px 8px rgba(0,0,0,0.1)',fontSize:11,fontWeight:600,color:'#111'}}>
          <span style={{color:'#0071e3'}}>●</span> {zip} · {radius} mi
        </div>
        <div style={{position:'absolute',bottom:12,right:12,display:'flex',flexDirection:'column',gap:4}}>
          <div style={{width:28,height:28,borderRadius:6,background:'white',boxShadow:'0 1px 4px rgba(0,0,0,0.15)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:16,fontWeight:600,color:'#111',cursor:'pointer'}}>+</div>
          <div style={{width:28,height:28,borderRadius:6,background:'white',boxShadow:'0 1px 4px rgba(0,0,0,0.15)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:16,fontWeight:600,color:'#111',cursor:'pointer'}}>−</div>
        </div>
      </div>
      {/* ZIP row */}
      <div onClick={()=>openEditor({key:'bizServiceZip',label:'Home ZIP code',type:'text',hint:'Service area is centered on this ZIP.'})}
        style={{padding:'14px 16px',display:'flex',alignItems:'center',cursor:'pointer',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{flex:1}}>
          <div style={{fontSize:14,fontWeight:500,color:'#111'}}>Home ZIP</div>
          <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:1}}>Starting point for your radius</div>
        </div>
        <div style={{fontSize:14,fontWeight:600,color:'#111',marginRight:10,fontVariantNumeric:'tabular-nums'}}>{zip}</div>
        <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
      </div>
      {/* Radius slider */}
      <div style={{padding:'14px 16px'}}>
        <div style={{display:'flex',alignItems:'center',marginBottom:10}}>
          <div style={{flex:1}}>
            <div style={{fontSize:14,fontWeight:500,color:'#111'}}>Service radius</div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:1}}>How far you'll drive from {zip}</div>
          </div>
          <div style={{fontSize:22,fontWeight:700,color:'#0071e3',letterSpacing:'-0.02em',fontVariantNumeric:'tabular-nums'}}>{radius} <span style={{fontSize:13,color:'rgba(0,0,0,0.5)',fontWeight:500}}>mi</span></div>
        </div>
        <input type="range" min="5" max="100" step="5" value={radius}
          onChange={e=>setRadius(Number(e.target.value))}
          style={{width:'100%',accentColor:'#0071e3',cursor:'pointer'}}/>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'rgba(0,0,0,0.4)',marginTop:4,fontWeight:500}}>
          <span>5 mi</span><span>50 mi</span><span>100 mi</span>
        </div>
      </div>
    </div>
  );
}

// ── PAYMENTS ─────────────────────────────────────────────────
function SettingsPaymentsScreen({ onNav }) {
  const openEditor = useEditor();
  const [payCard, setPayCard] = useSetting('payCard');
  const [payAch, setPayAch] = useSetting('payAch');
  const [payApplePay, setPayApplePay] = useSetting('payApplePay');
  const [payCheck, setPayCheck] = useSetting('payCheck');
  const [payCash, setPayCash] = useSetting('payCash');
  const [cardFee] = useSetting('cardFee');
  const [passFee, setPassFee] = useSetting('passFeeToCustomer');
  const [lateFee] = useSetting('lateFee');
  const [depositRequired] = useSetting('depositRequired');
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Payments" onBack="__back"/>
      <SectionHeader title="Processors"/>
      <Card>
        <div style={{padding:'16px',display:'flex',alignItems:'center',gap:12,borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
          <div style={{width:40,height:40,borderRadius:8,background:'#635bff',display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:14,fontWeight:700}}>S</div>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:600,color:'#111'}}>Stripe</div>
            <div style={{fontSize:12,color:'#34c759',marginTop:1}}>● Connected · acct_1NvXe…</div>
          </div>
          <div onClick={()=>onNav('settings-integrations')} style={{fontSize:12,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>Manage</div>
        </div>
        <div style={{padding:'16px',display:'flex',alignItems:'center',gap:12}}>
          <div style={{width:40,height:40,borderRadius:8,background:'#f7f7f8',border:'0.5px solid rgba(0,0,0,0.1)',display:'flex',alignItems:'center',justifyContent:'center',color:'rgba(0,0,0,0.4)',fontSize:14,fontWeight:700}}>Sq</div>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:600,color:'#111'}}>Square</div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:1}}>Not connected</div>
          </div>
          <div onClick={()=>alert('Connect Square')} style={{fontSize:12,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>Connect</div>
        </div>
      </Card>
      <SectionHeader title="Peer-to-peer"/>
      <PeerProcessorCard id="zelle" name="Zelle" handleKey="zelleHandle" handleLabel="Email or phone" color="#6c1cd1" initial="Z" tip="Customers pay instantly from their bank app. No fees. Auto-matched to invoices when handle matches."/>
      <PeerProcessorCard id="venmo" name="Venmo" handleKey="venmoHandle" handleLabel="@username" color="#3d95ce" initial="V" tip="Best for smaller service calls. 1.9% + 10¢ for business profiles."/>
      <PeerProcessorCard id="paypal" name="PayPal" handleKey="paypalEmail" handleLabel="Email" color="#003087" initial="PP" tip="Accept PayPal and credit cards. 3.49% + 49¢ for business."/>
      <SectionHeader title="Accepted methods"/>
      {buildList([
        { label:'Credit / debit card', toggle:payCard, onToggle:()=>setPayCard(!payCard) },
        { label:'ACH bank transfer', toggle:payAch, onToggle:()=>setPayAch(!payAch) },
        { label:'Apple Pay / Google Pay', toggle:payApplePay, onToggle:()=>setPayApplePay(!payApplePay) },
        { label:'Check', toggle:payCheck, onToggle:()=>setPayCheck(!payCheck) },
        { label:'Cash', toggle:payCash, onToggle:()=>setPayCash(!payCash) },
      ])}
      <SectionHeader title="Fees & policies"/>
      {buildList([
        { label:'Card processing fee', right:cardFee, onTap:()=>openEditor({key:'cardFee',label:'Card processing fee',type:'options',options:['2.9% + 30¢','2.6% + 10¢','3.5% + 0¢','Custom']}) },
        { label:'Pass fee to customer', toggle:passFee, onToggle:()=>setPassFee(!passFee) },
        { label:'Late fee', right:lateFee, onTap:()=>openEditor({key:'lateFee',label:'Late fee',type:'options',options:['None','1% / mo','1.5% / mo','2% / mo','Flat $25']}) },
        { label:'Deposit required', right:depositRequired, onTap:()=>openEditor({key:'depositRequired',label:'Deposit required',type:'options',options:['None','10%','25%','50%','100%']}) },
      ])}
      <SectionHeader title="Terminal"/>
      {buildList([
        { label:'Stripe Reader M2', sub:'Paired · Marcus iPhone', right:'Ready' },
        { label:'Order new reader', onTap:()=>alert('Redirect to Stripe hardware store') },
      ])}
    </div>
  );
}

// Peer-to-peer processor card (Zelle, Venmo, PayPal)
function PeerProcessorCard({ id, name, handleKey, handleLabel, color, initial, tip }) {
  const openEditor = useEditor();
  const enabledKey = id==='zelle' ? 'payZelle' : id==='venmo' ? 'payVenmo' : 'payPaypal';
  const [enabled, setEnabled] = useSetting(enabledKey);
  const [handle] = useSetting(handleKey);
  const configured = handle && handle.length > 0;
  return (
    <div style={{margin:'0 16px 10px',background:'white',borderRadius:12,overflow:'hidden',border:'0.5px solid rgba(0,0,0,0.06)'}}>
      <div style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12,borderBottom: configured ? '0.5px solid rgba(0,0,0,0.07)' : 'none'}}>
        <div style={{width:40,height:40,borderRadius:10,background:color,display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:14,fontWeight:700}}>{initial}</div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:15,fontWeight:600,color:'#111'}}>{name}</div>
          <div style={{fontSize:12,color: configured ? '#34c759' : 'rgba(0,0,0,0.5)',marginTop:1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
            {configured ? `● ${handle}` : 'Not connected'}
          </div>
        </div>
        {configured ? (
          <SettingsToggle on={enabled} onTap={()=>setEnabled(!enabled)}/>
        ) : (
          <button onClick={()=>openEditor({key:handleKey,label:`${name} ${handleLabel}`,type:'text',hint:tip})}
            style={{padding:'7px 14px',background:color,border:'none',borderRadius:8,color:'white',fontSize:12,fontWeight:600,cursor:'pointer'}}>Connect</button>
        )}
      </div>
      {configured && (
        <div onClick={()=>openEditor({key:handleKey,label:`${name} ${handleLabel}`,type:'text',hint:tip})}
          style={{padding:'10px 16px',fontSize:12,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>Edit handle</div>
      )}
    </div>
  );
}

// ── BILLING ──────────────────────────────────────────────────
function SettingsBillingScreen({ onNav }) {
  const [cancelOpen, setCancelOpen] = useStateSet(false);
  const invoices = [
    { id:'SP-202603', month:'Mar 2026', amt:'$249.00', date:'Mar 28, 2026' },
    { id:'SP-202602', month:'Feb 2026', amt:'$249.00', date:'Feb 28, 2026' },
    { id:'SP-202601', month:'Jan 2026', amt:'$249.00', date:'Jan 28, 2026' },
    { id:'SP-202512', month:'Dec 2025', amt:'$249.00', date:'Dec 28, 2025' },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Billing" onBack="__back"/>
      <div style={{padding:'20px',background:'linear-gradient(135deg,#0f172a,#1e293b)',color:'white'}}>
        <div style={{fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',opacity:0.6}}>Current plan</div>
        <div style={{display:'flex',alignItems:'baseline',gap:10,marginTop:8}}>
          <div style={{fontSize:26,fontWeight:700,letterSpacing:'-0.02em'}}>Pro</div>
          <div style={{fontSize:14,opacity:0.6}}>Standard · $249 / month</div>
        </div>
        <div style={{fontSize:13,opacity:0.7,marginTop:6}}>Renews April 28, 2026</div>
        <div style={{display:'flex',gap:8,marginTop:16}}>
          <button onClick={()=>onNav('plans')} style={{flex:1,padding:'11px',background:'white',color:'#0f172a',border:'none',borderRadius:10,fontSize:14,fontWeight:600,cursor:'pointer'}}>Change plan</button>
          <button onClick={()=>setCancelOpen(true)} style={{flex:1,padding:'11px',background:'rgba(255,255,255,0.12)',color:'white',border:'none',borderRadius:10,fontSize:14,fontWeight:600,cursor:'pointer'}}>Cancel</button>
        </div>
      </div>
      <SectionHeader title="Payment method"/>
      <Card>
        <div style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12}}>
          <div style={{width:40,height:28,borderRadius:4,background:'#1a1f71',display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:10,fontWeight:700}}>VISA</div>
          <div style={{flex:1,fontSize:14,color:'#111'}}>Visa ending in 4242</div>
          <div style={{fontSize:12,color:'rgba(0,0,0,0.45)'}}>Exp 08/28</div>
        </div>
      </Card>
      <SectionHeader title="Invoices"/>
      <Card>
        {invoices.map((r,i,a) => (
          <div key={r.id} style={{padding:'13px 16px',display:'flex',alignItems:'center',borderBottom:i<a.length-1?'0.5px solid rgba(0,0,0,0.07)':'none'}}>
            <div style={{flex:1,fontSize:14,color:'#111'}}>{r.month}</div>
            <div style={{fontSize:14,color:'rgba(0,0,0,0.7)',marginRight:12}}>{r.amt}</div>
            <div onClick={()=>onNav('billing-pdf',{invoice:r})} style={{fontSize:12,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>PDF</div>
          </div>
        ))}
      </Card>

      {/* Cancel confirm sheet */}
      {cancelOpen && (
        <>
          <div onClick={()=>setCancelOpen(false)} style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.5)',zIndex:300}}/>
          <div style={{position:'absolute',left:12,right:12,bottom:100,zIndex:301,background:'white',borderRadius:18,overflow:'hidden',boxShadow:'0 12px 40px rgba(0,0,0,0.25)'}}>
            <div style={{padding:'22px 22px 14px',textAlign:'center'}}>
              <div style={{width:44,height:44,borderRadius:'50%',background:'#fff1f1',display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:12}}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#e11d48" strokeWidth="2" strokeLinecap="round"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
              </div>
              <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.015em'}}>Cancel Pro plan?</div>
              <div style={{fontSize:13,color:'rgba(0,0,0,0.55)',marginTop:6,lineHeight:1.5}}>You'll keep access until <strong style={{color:'#111'}}>April 28, 2026</strong>. After that, Belle, Campaigns, and team seats over 2 will be disabled. Data stays safe.</div>
            </div>
            <div style={{padding:'6px 16px 16px',display:'flex',flexDirection:'column',gap:8}}>
              <button onClick={()=>setCancelOpen(false)} style={{padding:'12px',background:'#e11d48',border:'none',borderRadius:10,color:'white',fontSize:14,fontWeight:600,cursor:'pointer'}}>Cancel subscription</button>
              <button onClick={()=>{ setCancelOpen(false); onNav('plans'); }} style={{padding:'12px',background:'#f7f7f8',border:'none',borderRadius:10,color:'#0071e3',fontSize:14,fontWeight:600,cursor:'pointer'}}>Switch plan instead</button>
              <button onClick={()=>setCancelOpen(false)} style={{padding:'12px',background:'transparent',border:'none',color:'rgba(0,0,0,0.55)',fontSize:14,fontWeight:500,cursor:'pointer'}}>Keep my plan</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// ── PLANS ────────────────────────────────────────────────────
function PlansScreen({ onNav }) {
  const [tier, setTier] = useStateSet('standard');
  const [period, setPeriod] = useStateSet('monthly');
  const currentPlan = 'pro';
  const plans = [
    {
      id:'solo', name:'Solo', tag:'1 user',
      standard:99, premium:149,
      yStandard:89, yPremium:129,
      blurb:'Everything you need to run your own book.',
      features:{
        standard:['1 user seat','Unlimited jobs & customers','Estimates & invoices','Mobile payments','Scheduling','Email support'],
        premium:['Everything in Standard','Belle AI voice agent','Follow-ups automation','QuickBooks sync','Priority support'],
      },
      color:'#64748b',
    },
    {
      id:'pro', name:'Pro', tag:'2–5 users · Most popular',
      standard:249, premium:349,
      yStandard:229, yPremium:319,
      blurb:'Grow a small team with automation.',
      features:{
        standard:['Everything in Solo','2–5 user seats','Belle AI voice agent','Follow-ups & campaigns','QuickBooks sync','Priority support'],
        premium:['Everything in Standard','2–5 user seats','Advanced reporting','Custom automations','Dedicated onboarding','Phone support'],
      },
      color:'#0071e3', highlight:true,
    },
    {
      id:'enterprise', name:'Enterprise', tag:'6–10 users',
      standard:449, premium:599,
      yStandard:419, yPremium:549,
      blurb:'Dispatching, reporting, multi-location.',
      features:{
        standard:['Everything in Pro','6–10 user seats','Dispatch board','Advanced reporting','Custom roles','Dedicated CSM'],
        premium:['Everything in Standard','Multi-location management','Custom dashboards','API access','24/7 support','Quarterly business review'],
      },
      color:'#0f172a',
    },
    {
      id:'enterprise-plus', name:'Enterprise+', tag:'11+ users, usage-based',
      standard:449, standardExtra:50, premium:599, premiumExtra:75,
      yStandard:419, yPremium:549,
      blurb:'Scales per user beyond your first 10 seats.',
      features:{
        standard:['Everything in Enterprise Standard','For 11+ users','+$50 / user (no cap)','White-glove onboarding','Custom integrations','SOC 2 reports'],
        premium:['Everything in Enterprise Premium','For 11+ users','+$75 / user (no cap)','Dedicated account team','99.95% SLA','Custom contracts'],
      },
      color:'#7c3aed',
    },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:120}}>
      <NavHeader title="Plans" onBack="__back"/>
      <div style={{padding:'22px 20px 10px'}}>
        <div style={{fontSize:24,fontWeight:700,color:'#111',letterSpacing:'-0.025em',lineHeight:1.15}}>Choose a plan that scales with you.</div>
        <div style={{fontSize:14,color:'rgba(0,0,0,0.55)',marginTop:8,lineHeight:1.5}}>Switch anytime. We'll prorate the difference.</div>
      </div>
      {/* Billing period toggle */}
      <div style={{margin:'18px 20px 10px',background:'#e8e8ed',borderRadius:10,padding:3,display:'flex'}}>
        {['monthly','yearly'].map(p => (
          <div key={p} onClick={()=>setPeriod(p)} style={{
            flex:1,padding:'9px 0',textAlign:'center',borderRadius:8,cursor:'pointer',
            background: period===p ? 'white' : 'transparent',
            boxShadow: period===p ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',
            fontSize:13,fontWeight: period===p?600:500,
            color: period===p?'#111':'rgba(0,0,0,0.55)',
            textTransform:'capitalize',transition:'all 0.18s',
            display:'flex',alignItems:'center',justifyContent:'center',gap:6,
          }}>
            <span>{p}</span>
            {p==='yearly' && <span style={{fontSize:9,color:'#16a34a',fontWeight:700,letterSpacing:'0.04em',padding:'2px 5px',background:'#dcfce7',borderRadius:4}}>SAVE 10%</span>}
          </div>
        ))}
      </div>
      {/* Standard / Premium toggle */}
      <div style={{margin:'0 20px 18px',background:'#e8e8ed',borderRadius:10,padding:3,display:'flex'}}>
        {['standard','premium'].map(p => (
          <div key={p} onClick={()=>setTier(p)} style={{
            flex:1,padding:'9px 0',textAlign:'center',borderRadius:8,cursor:'pointer',
            background: tier===p ? 'white' : 'transparent',
            boxShadow: tier===p ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',
            fontSize:13,fontWeight: tier===p?600:500,
            color: tier===p?'#111':'rgba(0,0,0,0.55)',
            textTransform:'capitalize',transition:'all 0.18s',
          }}>
            {p}{p==='premium' && <span style={{fontSize:10,color:'#d97706',fontWeight:700,marginLeft:6,letterSpacing:'0.03em'}}>★</span>}
          </div>
        ))}
      </div>
      {/* Plan cards */}
      <div style={{padding:'0 16px',display:'flex',flexDirection:'column',gap:12}}>
        {plans.map(p => {
          const monthlyPrice = tier==='standard' ? p.standard : p.premium;
          const yearlyPrice = tier==='standard' ? p.yStandard : p.yPremium;
          const price = period==='monthly' ? monthlyPrice : yearlyPrice;
          const extra = tier==='standard' ? p.standardExtra : p.premiumExtra;
          const features = p.features[tier];
          const isCurrent = p.id===currentPlan;
          return (
            <div key={p.id} style={{
              background:'white',borderRadius:16,padding:18,
              border: p.highlight ? `1.5px solid ${p.color}` : '0.5px solid rgba(0,0,0,0.07)',
              position:'relative',
            }}>
              {p.highlight && (
                <div style={{position:'absolute',top:-10,left:18,padding:'3px 10px',background:p.color,color:'white',fontSize:10,fontWeight:700,letterSpacing:'0.05em',borderRadius:6}}>MOST POPULAR</div>
              )}
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
                <div style={{flex:1,paddingRight:12}}>
                  <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{p.name}</div>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>{p.tag}</div>
                </div>
                <div style={{textAlign:'right',flexShrink:0}}>
                  <div style={{display:'flex',alignItems:'baseline',gap:3,justifyContent:'flex-end'}}>
                    <span style={{fontSize:12,color:'rgba(0,0,0,0.5)'}}>$</span>
                    <span style={{fontSize:26,fontWeight:700,color:'#111',letterSpacing:'-0.025em',lineHeight:1}}>{price}</span>
                  </div>
                  <div style={{fontSize:11,color:'rgba(0,0,0,0.45)'}}>per month{period==='yearly' ? ', billed yearly' : ''}</div>
                  {period==='yearly' && (
                    <div style={{fontSize:10,color:'#16a34a',fontWeight:600,marginTop:3}}>Save ${(monthlyPrice-yearlyPrice)*12}/yr</div>
                  )}
                  {extra && (
                    <div style={{fontSize:10,color:p.color,fontWeight:600,marginTop:4,lineHeight:1.3}}>+${extra}/user<br/>(11+ users)</div>
                  )}
                </div>
              </div>
              <div style={{fontSize:13,color:'rgba(0,0,0,0.6)',marginTop:10,lineHeight:1.45}}>{p.blurb}</div>
              <div style={{marginTop:14,display:'flex',flexDirection:'column',gap:7}}>
                {features.map(f => (
                  <div key={f} style={{display:'flex',alignItems:'flex-start',gap:8}}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={p.color} strokeWidth="2.5" strokeLinecap="round" style={{flexShrink:0,marginTop:2}}><polyline points="20 6 9 17 4 12"/></svg>
                    <div style={{fontSize:13,color:'#111',lineHeight:1.4}}>{f}</div>
                  </div>
                ))}
              </div>
              <button disabled={isCurrent} style={{
                marginTop:16,width:'100%',padding:'12px',
                background: isCurrent ? '#f7f7f8' : p.color,
                color: isCurrent ? 'rgba(0,0,0,0.45)' : 'white',
                border:'none',borderRadius:10,fontSize:14,fontWeight:600,
                cursor: isCurrent ? 'default':'pointer',
              }}>{isCurrent ? 'Current plan' : p.id==='solo' ? 'Downgrade to Solo' : 'Switch to '+p.name}</button>
            </div>
          );
        })}
      </div>
      <div style={{padding:'18px 24px',fontSize:12,color:'rgba(0,0,0,0.45)',textAlign:'center',lineHeight:1.5}}>
        Questions? <span style={{color:'#0071e3',fontWeight:600}}>Talk to sales</span> · Prices in USD · Cancel any time
      </div>
    </div>
  );
}

// ── BILLING INVOICE PDF VIEWER ───────────────────────────────
function BillingPdfScreen({ onNav, params }) {
  const inv = params?.invoice || { id:'SP-202603', month:'Mar 2026', amt:'$89.00', date:'Mar 28, 2026' };
  return (
    <div style={{background:'#52525b',minHeight:'100%',paddingBottom:60}}>
      <NavHeader title={inv.id} onBack="__back" right={
        <div style={{display:'flex',gap:14,alignItems:'center'}}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.9" strokeLinecap="round"><path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.9" strokeLinecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        </div>
      }/>
      {/* "PDF" paper */}
      <div style={{margin:'20px 18px',background:'white',borderRadius:4,padding:'36px 32px',
        boxShadow:'0 12px 32px rgba(0,0,0,0.35)',fontFamily:"'Inter',-apple-system,sans-serif",color:'#111'}}>
        {/* Header */}
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:30}}>
          <div>
            <div style={{width:40,height:40,borderRadius:8,background:'#0f172a',display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:14,fontWeight:700}}>SP</div>
            <div style={{fontSize:10,fontWeight:700,color:'#111',marginTop:8,letterSpacing:'-0.01em'}}>Simple Pro, Inc.</div>
            <div style={{fontSize:8,color:'rgba(0,0,0,0.55)',marginTop:1,lineHeight:1.4}}>
              1435 Market St, Suite 800<br/>
              San Francisco, CA 94103<br/>
              billing@simplepro.app
            </div>
          </div>
          <div style={{textAlign:'right'}}>
            <div style={{fontSize:18,fontWeight:700,letterSpacing:'-0.02em',color:'#111'}}>INVOICE</div>
            <div style={{fontSize:9,color:'rgba(0,0,0,0.6)',marginTop:4}}>#{inv.id}</div>
            <div style={{fontSize:9,color:'rgba(0,0,0,0.6)',marginTop:2}}>Issued {inv.date}</div>
            <div style={{display:'inline-block',marginTop:8,padding:'2px 8px',background:'#dcfce7',color:'#16a34a',fontSize:8,fontWeight:700,borderRadius:4,letterSpacing:'0.04em'}}>PAID</div>
          </div>
        </div>
        {/* Billed to */}
        <div style={{display:'flex',gap:24,marginBottom:24}}>
          <div style={{flex:1}}>
            <div style={{fontSize:8,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:4}}>BILLED TO</div>
            <div style={{fontSize:10,fontWeight:600,color:'#111'}}>Simple Pro Plumbing</div>
            <div style={{fontSize:8,color:'rgba(0,0,0,0.65)',marginTop:2,lineHeight:1.5}}>
              Attn: Jake Davidson<br/>
              2840 W Olympic Blvd<br/>
              Los Angeles, CA 90006
            </div>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:8,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:4}}>DETAILS</div>
            <div style={{fontSize:8,color:'rgba(0,0,0,0.65)',lineHeight:1.7}}>
              Period: {inv.month}<br/>
              Plan: Pro (monthly)<br/>
              Payment: Visa •••• 4242
            </div>
          </div>
        </div>
        {/* Line items */}
        <div style={{borderTop:'1px solid rgba(0,0,0,0.12)',borderBottom:'1px solid rgba(0,0,0,0.12)',padding:'10px 0',display:'flex',fontSize:7,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em'}}>
          <div style={{flex:2}}>DESCRIPTION</div>
          <div style={{width:40,textAlign:'right'}}>QTY</div>
          <div style={{width:60,textAlign:'right'}}>RATE</div>
          <div style={{width:60,textAlign:'right'}}>AMOUNT</div>
        </div>
        {[
          { desc:'Simple Pro — Pro Standard plan', qty:1, rate:249, sub:'Monthly subscription · '+inv.month },
          { desc:'Belle AI minutes overage', qty:0, rate:0, sub:'Included this month' },
        ].map((li,i) => (
          <div key={i} style={{padding:'10px 0',borderBottom:'0.5px solid rgba(0,0,0,0.08)',display:'flex',alignItems:'flex-start'}}>
            <div style={{flex:2}}>
              <div style={{fontSize:10,fontWeight:500,color:'#111'}}>{li.desc}</div>
              <div style={{fontSize:8,color:'rgba(0,0,0,0.5)',marginTop:1}}>{li.sub}</div>
            </div>
            <div style={{width:40,textAlign:'right',fontSize:9,color:'#111'}}>{li.qty}</div>
            <div style={{width:60,textAlign:'right',fontSize:9,color:'#111'}}>${li.rate.toFixed(2)}</div>
            <div style={{width:60,textAlign:'right',fontSize:9,color:'#111'}}>${(li.qty*li.rate).toFixed(2)}</div>
          </div>
        ))}
        {/* Totals */}
        <div style={{marginTop:14,display:'flex',justifyContent:'flex-end'}}>
          <div style={{width:180}}>
            {[
              { l:'Subtotal', v:'$249.00' },
              { l:'Tax (0%)', v:'$0.00' },
            ].map(r => (
              <div key={r.l} style={{display:'flex',justifyContent:'space-between',padding:'4px 0',fontSize:9,color:'rgba(0,0,0,0.7)'}}>
                <span>{r.l}</span><span>{r.v}</span>
              </div>
            ))}
            <div style={{display:'flex',justifyContent:'space-between',padding:'8px 0',marginTop:4,borderTop:'1px solid rgba(0,0,0,0.15)',fontSize:11,fontWeight:700,color:'#111'}}>
              <span>Total paid</span><span>{inv.amt}</span>
            </div>
          </div>
        </div>
        {/* Footer */}
        <div style={{marginTop:36,paddingTop:12,borderTop:'0.5px solid rgba(0,0,0,0.08)',fontSize:7,color:'rgba(0,0,0,0.45)',textAlign:'center',lineHeight:1.6}}>
          Thank you for your business. · Questions? billing@simplepro.app · Simple Pro, Inc. · EIN 84-••••••
        </div>
      </div>
      <div style={{padding:'0 18px 30px',display:'flex',gap:10}}>
        <button style={{flex:1,padding:'13px',background:'rgba(255,255,255,0.15)',border:'none',borderRadius:10,color:'white',fontSize:14,fontWeight:600,cursor:'pointer',backdropFilter:'blur(12px)'}}>Email receipt</button>
        <button style={{flex:1,padding:'13px',background:'white',border:'none',borderRadius:10,color:'#0f172a',fontSize:14,fontWeight:600,cursor:'pointer'}}>Download</button>
      </div>
    </div>
  );
}

// ── PRICEBOOK ────────────────────────────────────────────────
const PRICEBOOK_DATA = {
  'drain-sewer': {
    name:'Drain & Sewer', color:'#0071e3',
    items: [
      { name:'Drain clearing — kitchen/bath', price:245, time:'1h', desc:'Clear simple clog, K-50 or C-100.' },
      { name:'Hydro-jetting — residential', price:675, time:'2h', desc:'Up to 100 ft of line, 3500 PSI.' },
      { name:'Sewer camera inspection', price:325, time:'1h', desc:'Full lateral with DVD/video.' },
      { name:'Main line clearing', price:495, time:'2h', desc:'Power rodding up to 100 ft.' },
      { name:'Trenchless pipe repair', price:2850, time:'1 day', desc:'Per section, up to 25 ft.' },
    ],
  },
  'water-heater': {
    name:'Water Heater', color:'#e11d48',
    items: [
      { name:'40 gal electric install', price:1450, time:'3h', desc:'Standard install, permit included.' },
      { name:'50 gal gas install', price:1850, time:'4h', desc:'Includes expansion tank & venting.' },
      { name:'Tankless water heater install', price:3850, time:'6h', desc:'Whole-home gas tankless.' },
      { name:'Anode rod replacement', price:195, time:'1h', desc:'Extends tank life 5+ years.' },
      { name:'Flush & tune-up', price:145, time:'45m', desc:'Annual service recommended.' },
    ],
  },
  'fixtures': {
    name:'Fixtures & Faucets', color:'#0a84ff',
    items: [
      { name:'Kitchen faucet replacement', price:225, time:'1h', desc:'Customer-supplied faucet.' },
      { name:'Bathroom faucet replacement', price:185, time:'1h', desc:'Customer-supplied faucet.' },
      { name:'Toilet install', price:425, time:'2h', desc:'Standard install + wax ring.' },
      { name:'Toilet rebuild', price:195, time:'1h', desc:'Fill valve, flapper, flush handle.' },
      { name:'Garbage disposal install', price:285, time:'1.5h', desc:'1/2 HP standard unit.' },
    ],
  },
  'emergency': {
    name:'Emergency Service', color:'#d97706',
    items: [
      { name:'After-hours trip charge', price:195, time:'—', desc:'6pm–6am + weekends.' },
      { name:'Water shutoff / leak triage', price:285, time:'1h', desc:'Isolate and assess.' },
      { name:'Burst pipe — temp fix', price:495, time:'2h', desc:'Stop-gap repair with follow-up.' },
      { name:'Flooded basement pump-out', price:650, time:'3h', desc:'Up to 500 gal.' },
    ],
  },
  'installations': {
    name:'Installations', color:'#16a34a',
    items: [
      { name:'Full bath re-pipe', price:4850, time:'2 days', desc:'PEX or copper, permits included.' },
      { name:'Whole-home water filter', price:1950, time:'4h', desc:'Under-sink or whole-home.' },
      { name:'Water softener install', price:2450, time:'5h', desc:'Salt-based, whole-home.' },
      { name:'Outdoor spigot', price:285, time:'1.5h', desc:'Frost-free hose bib.' },
      { name:'Laundry rough-in', price:650, time:'3h', desc:'Supply + drain connections.' },
    ],
  },
  'inspections': {
    name:'Inspections', color:'#7c3aed',
    items: [
      { name:'Pre-purchase home inspection', price:385, time:'2h', desc:'Full plumbing report + photos.' },
      { name:'Sewer lateral inspection', price:325, time:'1h', desc:'Camera + written report.' },
      { name:'Annual maintenance visit', price:165, time:'1h', desc:'Check supply, drain, fixtures.' },
      { name:'Insurance claim inspection', price:225, time:'1h', desc:'Documented for carrier.' },
    ],
  },
};

function SettingsPriceBookScreen({ onNav }) {
  const cats = Object.entries(PRICEBOOK_DATA).map(([id, c]) => ({ id, ...c, count: c.items.length }));
  const totalItems = cats.reduce((a,c)=>a+c.count, 0);
  const popular = [
    { name:'Drain clearing — kitchen/bath', price:'$245' },
    { name:'50 gal gas install', price:'$1,850' },
    { name:'Toilet install', price:'$425' },
    { name:'Hydro-jetting', price:'$675' },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Price Book" onBack="__back" right={<div onClick={()=>alert('Add service')} style={{fontSize:14,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>+ Add</div>}/>
      <div style={{padding:'14px 16px 4px'}}>
        <input placeholder="Search services…" style={{width:'100%',padding:'11px 14px',border:'0.5px solid rgba(0,0,0,0.1)',borderRadius:10,fontSize:14,background:'white',boxSizing:'border-box',outline:'none'}}/>
      </div>
      <div style={{padding:'8px 16px 0',display:'flex',gap:8}}>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'10px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
          <div style={{fontSize:17,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{totalItems}</div>
          <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>Services</div>
        </div>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'10px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
          <div style={{fontSize:17,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{cats.length}</div>
          <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>Categories</div>
        </div>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'10px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
          <div style={{fontSize:17,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>$485</div>
          <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>Avg ticket</div>
        </div>
      </div>
      <SectionHeader title="Categories"/>
      <Card>
        {cats.map((c,i) => (
          <div key={c.id} onClick={()=>onNav('pricebook-category',{catId:c.id})}
            style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12,borderBottom:i<cats.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{width:36,height:36,borderRadius:10,background:`${c.color}15`,display:'flex',alignItems:'center',justifyContent:'center'}}>
              <div style={{width:10,height:10,borderRadius:3,background:c.color}}/>
            </div>
            <div style={{flex:1}}>
              <div style={{fontSize:15,color:'#111',fontWeight:600}}>{c.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>{c.count} service{c.count!==1?'s':''} · from ${Math.min(...c.items.map(x=>x.price))}</div>
            </div>
            <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
          </div>
        ))}
      </Card>
      <SectionHeader title="Popular services"/>
      <Card>
        {popular.map((s,i,a) => (
          <div key={s.name} style={{padding:'13px 16px',display:'flex',alignItems:'center',borderBottom:i<a.length-1?'0.5px solid rgba(0,0,0,0.07)':'none'}}>
            <div style={{flex:1,fontSize:14,color:'#111'}}>{s.name}</div>
            <div style={{fontSize:14,fontWeight:600,color:'#111'}}>{s.price}</div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// Price book category detail
function SettingsPriceBookCategoryScreen({ onNav, params }) {
  const catId = params?.catId || 'drain-sewer';
  const cat = PRICEBOOK_DATA[catId] || PRICEBOOK_DATA['drain-sewer'];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title={cat.name} onBack="__back"
        right={<div onClick={()=>alert('Add service to '+cat.name)} style={{fontSize:14,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>+ Add</div>}/>
      <div style={{padding:'18px 20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)',display:'flex',alignItems:'center',gap:12}}>
        <div style={{width:48,height:48,borderRadius:12,background:`${cat.color}15`,display:'flex',alignItems:'center',justifyContent:'center'}}>
          <div style={{width:14,height:14,borderRadius:4,background:cat.color}}/>
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.015em'}}>{cat.name}</div>
          <div style={{fontSize:12,color:'rgba(0,0,0,0.55)',marginTop:2}}>{cat.items.length} services · ${Math.min(...cat.items.map(i=>i.price))} – ${Math.max(...cat.items.map(i=>i.price)).toLocaleString()}</div>
        </div>
      </div>
      <SectionHeader title="Services"/>
      <Card>
        {cat.items.map((it, i) => (
          <div key={it.name} onClick={()=>alert(`Edit: ${it.name}\n\n$${it.price} · ${it.time}\n${it.desc}`)}
            style={{padding:'14px 16px',display:'flex',alignItems:'flex-start',gap:12,borderBottom:i<cat.items.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{flex:1,minWidth:0,paddingRight:8}}>
              <div style={{fontSize:15,fontWeight:600,color:'#111',letterSpacing:'-0.005em'}}>{it.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.55)',marginTop:3,lineHeight:1.45}}>{it.desc}</div>
              <div style={{display:'flex',gap:8,marginTop:6,alignItems:'center'}}>
                <span style={{fontSize:11,padding:'2px 7px',borderRadius:5,background:'#f7f7f8',color:'rgba(0,0,0,0.6)',fontWeight:500}}>⏱ {it.time}</span>
              </div>
            </div>
            <div style={{textAlign:'right',flexShrink:0}}>
              <div style={{fontSize:16,fontWeight:700,color:'#111',letterSpacing:'-0.015em'}}>${it.price.toLocaleString()}</div>
              <div style={{fontSize:10,color:'rgba(0,0,0,0.4)',marginTop:2}}>flat rate</div>
            </div>
          </div>
        ))}
      </Card>
      <div style={{margin:'14px 16px'}}>
        <button onClick={()=>alert('Add service to '+cat.name)} style={{width:'100%',padding:'13px',background:'white',border:`1.2px dashed ${cat.color}`,borderRadius:12,color:cat.color,fontSize:14,fontWeight:600,cursor:'pointer'}}>+ Add service to {cat.name}</button>
      </div>
    </div>
  );
}

// ── CAMPAIGNS ────────────────────────────────────────────────
function CampaignsScreen({ onNav }) {
  const active = [
    { name:'Spring tune-up promo', type:'SMS', status:'Active', sent:'412 sent', open:'72% open', color:'#16a34a' },
    { name:'Water heater warranty', type:'Email', status:'Active', sent:'1,204 sent', open:'38% open', color:'#16a34a' },
    { name:'Lapsed customer win-back', type:'SMS + Email', status:'Scheduled', sent:'Starts Fri', open:'—', color:'#0071e3' },
  ];
  const drafts = [
    { name:'Summer AC plumbing combo', type:'Email', status:'Draft' },
    { name:'New customer welcome', type:'SMS', status:'Draft' },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Campaigns" onBack="__back" right={<div style={{fontSize:14,color:'#0071e3',fontWeight:600}}>New</div>}/>
      <div style={{padding:'14px 16px',display:'flex',gap:8}}>
        {[
          { l:'Active', v:2 },
          { l:'Scheduled', v:1 },
          { l:'Sent this mo.', v:'3.2k' },
          { l:'Revenue', v:'$12.4k' },
        ].map(s => (
          <div key={s.l} style={{flex:1,background:'white',borderRadius:10,padding:'10px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
            <div style={{fontSize:17,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{s.v}</div>
            <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>{s.l}</div>
          </div>
        ))}
      </div>
      <SectionHeader title="Active & scheduled"/>
      <Card>
        {active.map((c,i) => (
          <div key={c.name} onClick={()=>onNav('campaign-detail',{campaign:c})} style={{padding:'14px 16px',borderBottom:i<active.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
              <div>
                <div style={{fontSize:15,fontWeight:600,color:'#111'}}>{c.name}</div>
                <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:3}}>{c.type} · {c.sent}</div>
              </div>
              <div style={{padding:'3px 8px',borderRadius:6,background:`${c.color}15`,color:c.color,fontSize:11,fontWeight:600}}>{c.status}</div>
            </div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.55)',marginTop:6}}>{c.open}</div>
          </div>
        ))}
      </Card>
      <SectionHeader title="Drafts"/>
      <Card>
        {drafts.map((c,i) => (
          <div key={c.name} style={{padding:'14px 16px',display:'flex',alignItems:'center',borderBottom:i<drafts.length-1?'0.5px solid rgba(0,0,0,0.07)':'none'}}>
            <div style={{flex:1}}>
              <div style={{fontSize:15,fontWeight:500,color:'#111'}}>{c.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>{c.type}</div>
            </div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.4)',fontWeight:500}}>Draft</div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── BELLE SETTINGS ───────────────────────────────────────────
function SettingsBelleScreen({ onNav }) {
  const openEditor = useEditor();
  const [enabled, setEnabled] = useSetting('belleEnabled');
  const [rings] = useSetting('belleRings');
  const [hours] = useSetting('belleHours');
  const [afterHours] = useSetting('belleAfterHours');
  const [voice] = useSetting('belleVoice');
  const [greeting] = useSetting('belleGreeting');
  const [book, setBook] = useSetting('belleBook');
  const [transfer, setTransfer] = useSetting('belleTransfer');
  const [quote, setQuote] = useSetting('belleQuote');
  const [photos, setPhotos] = useSetting('bellePhotos');
  const [deposit, setDeposit] = useSetting('belleDeposit');
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Belle AI" onBack="__back"/>
      <div style={{padding:'20px',background:'linear-gradient(135deg,#0071e3,#0a84ff)',color:'white'}}>
        <div style={{fontSize:12,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',opacity:0.85}}>AI Voice Agent</div>
        <div style={{fontSize:22,fontWeight:700,marginTop:6,letterSpacing:'-0.02em'}}>Belle answers calls when you can't.</div>
        <div style={{fontSize:13,opacity:0.85,marginTop:6,lineHeight:1.5}}>She books jobs, qualifies leads, and texts you a summary.</div>
      </div>
      <div style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12,background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{flex:1,fontSize:15,fontWeight:600,color:'#111'}}>Belle enabled</div>
        <SettingsToggle on={enabled} onTap={()=>setEnabled(!enabled)}/>
      </div>
      <SectionHeader title="Call handling"/>
      {buildList([
        { label:'Answer after', right:rings, onTap:()=>openEditor({key:'belleRings',label:'Answer after',type:'options',options:['1 ring','2 rings','3 rings','4 rings','5 rings','Voicemail only']}) },
        { label:'Business hours', right:hours, onTap:()=>openEditor({key:'belleHours',label:'Business hours',type:'options',options:['24/7','Mon–Fri 8a–5p','Mon–Fri 7a–6p','Mon–Sat 7a–7p','Custom']}) },
        { label:'After hours behavior', right:afterHours, onTap:()=>openEditor({key:'belleAfterHours',label:'After hours behavior',type:'options',options:['Take message','Book only emergencies','Forward to me','Play hours recording']}) },
        { label:'Voice', right:voice, onTap:()=>openEditor({key:'belleVoice',label:'Voice',type:'options',options:['Belle (warm)','Belle (professional)','Ben (warm)','Ben (professional)']}) },
        { label:'Greeting script', sub: greeting.length > 50 ? greeting.slice(0,50)+'…' : greeting, onTap:()=>openEditor({key:'belleGreeting',label:'Greeting script',type:'textarea',hint:'Belle will read this to every caller. Keep it under 15 seconds.'}) },
      ])}
      <SectionHeader title="What Belle can do"/>
      {buildList([
        { label:'Book appointments', toggle:book, onToggle:()=>setBook(!book) },
        { label:'Transfer urgent calls', toggle:transfer, onToggle:()=>setTransfer(!transfer) },
        { label:'Quote pricing from Price Book', toggle:quote, onToggle:()=>setQuote(!quote) },
        { label:'Collect photos via SMS', toggle:photos, onToggle:()=>setPhotos(!photos) },
        { label:'Take deposits', toggle:deposit, onToggle:()=>setDeposit(!deposit) },
      ])}
      <SectionHeader title="Performance (30d)"/>
      <div style={{margin:'0 16px',display:'flex',gap:8}}>
        {[
          { l:'Calls', v:'184' },
          { l:'Booked', v:'112' },
          { l:'Transferred', v:'38' },
          { l:'Conv. rate', v:'61%' },
        ].map(s => (
          <div key={s.l} style={{flex:1,background:'white',borderRadius:10,padding:'12px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
            <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{s.v}</div>
            <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>{s.l}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── TEMPLATES ────────────────────────────────────────────────
const TEMPLATES_DATA = {
  estimates: [
    { id:'est-std', name:'Standard service estimate', sub:'Default · 4 line items', fields:'Customer · service · parts · labor · total' },
    { id:'est-gbb', name:'Major install (3-tier)', sub:'Good / Better / Best', fields:'3 side-by-side tiers with feature comparison' },
    { id:'est-emerg', name:'Emergency call-out', sub:'Flat-fee', fields:'Trip charge · diagnosis · same-day multiplier' },
  ],
  invoices: [
    { id:'inv-std', name:'Standard invoice', sub:'Default', fields:'Customer · line items · tax · payment link' },
    { id:'inv-net30', name:'Net-30 commercial', sub:'30-day terms', fields:'PO field · terms block · late fee notice' },
    { id:'inv-recurring', name:'Service plan recurring', sub:'Monthly auto-charge', fields:'Plan · period · auto-renew · cancellation policy' },
  ],
  forms: [
    { id:'form-auth', name:'Customer authorization', sub:'Work approval signature', fields:'Scope · price cap · signature block' },
    { id:'form-complete', name:'Work completion checklist', sub:'Post-job sign-off', fields:'Tasks completed · photos · customer satisfaction' },
    { id:'form-pre', name:'Pre-job inspection', sub:'Before work begins', fields:'Access · existing damage · hazards' },
    { id:'form-wh', name:'Water heater safety', sub:'Code compliance', fields:'T&P valve · venting · combustion air · expansion tank' },
  ],
  snippets: [
    { id:'sn-otw', name:'On the way', sub:'"Heading your way now…"', fields:'"Hi {first_name}! {tech} is on the way, ETA {eta}. Track: {link}"' },
    { id:'sn-late', name:'Running late', sub:'"Apologies, ETA 15 min…"', fields:'"Hi {first_name}, running about {delay} min behind. New ETA {eta}."' },
    { id:'sn-done', name:'Job complete', sub:'"All done. Invoice attached…"', fields:'"All done! Invoice {invoice_id} attached. Pay here: {pay_link}"' },
  ],
};

function SettingsTemplatesScreen({ onNav }) {
  const groups = [
    { title:'Estimates', key:'estimates', color:'#0071e3' },
    { title:'Invoices', key:'invoices', color:'#16a34a' },
    { title:'Forms', key:'forms', color:'#7c3aed' },
    { title:'SMS snippets', key:'snippets', color:'#d97706' },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Templates" onBack="__back" right={<div onClick={()=>alert('New template')} style={{fontSize:14,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>+ New</div>}/>
      {groups.map(g => (
        <div key={g.key}>
          <SectionHeader title={g.title}/>
          <Card>
            {TEMPLATES_DATA[g.key].map((t,i,a) => (
              <div key={t.id} onClick={()=>onNav('template-detail',{template:t, group:g})}
                style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,borderBottom:i<a.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
                <div style={{width:32,height:32,borderRadius:8,background:`${g.color}15`,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={g.color} strokeWidth="2" strokeLinecap="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:15,fontWeight:500,color:'#111'}}>{t.name}</div>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{t.sub}</div>
                </div>
                <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
              </div>
            ))}
          </Card>
        </div>
      ))}
    </div>
  );
}

// Template detail editor
function SettingsTemplateDetailScreen({ onNav, params }) {
  const t = params?.template || TEMPLATES_DATA.estimates[0];
  const g = params?.group || { title:'Estimates', color:'#0071e3' };
  const [name, setName] = useStateSet(t.name);
  const [body, setBody] = useStateSet(t.fields);
  const [isDefault, setIsDefault] = useStateSet(t.sub?.includes('Default'));
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title={g.title.replace(/s$/,'')} onBack="__back"
        right={<div onClick={()=>{ alert('Template saved'); onNav('settings-templates'); }} style={{fontSize:14,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>Save</div>}/>
      {/* Header */}
      <div style={{padding:'18px 20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)',display:'flex',alignItems:'center',gap:12}}>
        <div style={{width:44,height:44,borderRadius:11,background:`${g.color}15`,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={g.color} strokeWidth="2" strokeLinecap="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.45)',letterSpacing:'0.07em',textTransform:'uppercase'}}>{g.title.replace(/s$/,'')} template</div>
          <div style={{fontSize:16,fontWeight:700,color:'#111',marginTop:2,letterSpacing:'-0.015em'}}>{t.name}</div>
        </div>
      </div>
      <SectionHeader title="Template name"/>
      <div style={{margin:'0 16px'}}>
        <input value={name} onChange={e=>setName(e.target.value)}
          style={{width:'100%',padding:'14px 16px',border:'none',borderRadius:12,fontSize:15,background:'white',boxSizing:'border-box',outline:'none',color:'#111',fontWeight:500}}/>
      </div>
      <SectionHeader title={g.key==='snippets' ? 'Message body' : 'Content / fields'}/>
      <div style={{margin:'0 16px'}}>
        <textarea value={body} onChange={e=>setBody(e.target.value)}
          rows={g.key==='snippets' ? 4 : 6}
          style={{width:'100%',padding:'14px 16px',border:'none',borderRadius:12,fontSize:14,fontFamily:'inherit',background:'white',boxSizing:'border-box',outline:'none',color:'#111',resize:'none',lineHeight:1.55}}/>
        <div style={{fontSize:11,color:'rgba(0,0,0,0.45)',marginTop:8,lineHeight:1.5,paddingLeft:4}}>Use variables: {'{first_name}, {tech}, {eta}, {invoice_id}, {pay_link}'}</div>
      </div>
      <SectionHeader title="Options"/>
      {buildList([
        { label:'Set as default', sub: isDefault ? 'Used when no template selected' : 'Other templates will remain available', toggle:isDefault, onToggle:()=>setIsDefault(!isDefault) },
        { label:'Include company logo', toggle:true, onToggle:()=>{} },
        { label:'Auto-attach to jobs', toggle:g.key==='forms', onToggle:()=>{} },
      ])}
      <SectionHeader title="Preview"/>
      <div style={{margin:'0 16px 18px',background:'white',borderRadius:12,padding:18,border:'0.5px solid rgba(0,0,0,0.06)'}}>
        <div style={{fontSize:13,color:'#111',lineHeight:1.6,fontFamily:g.key==='snippets' ? 'inherit':'ui-monospace,SFMono-Regular,Menlo,monospace'}}>
          {body}
        </div>
      </div>
      <div style={{margin:'0 16px',display:'flex',gap:8}}>
        <button onClick={()=>alert('Template duplicated')} style={{flex:1,padding:'12px',background:'white',border:'0.5px solid rgba(0,0,0,0.1)',borderRadius:10,color:'#111',fontSize:14,fontWeight:600,cursor:'pointer'}}>Duplicate</button>
        <button onClick={()=>{ if(confirm('Delete this template?')) onNav('settings-templates'); }} style={{flex:1,padding:'12px',background:'white',border:'0.5px solid rgba(225,29,72,0.3)',borderRadius:10,color:'#e11d48',fontSize:14,fontWeight:600,cursor:'pointer'}}>Delete</button>
      </div>
    </div>
  );
}

// ── INTEGRATIONS ─────────────────────────────────────────────
function SettingsIntegrationsScreen({ onNav }) {
  const connected = [
    { name:'QuickBooks Online', sub:'Syncing invoices & customers', color:'#2ca01c', initials:'QB' },
    { name:'Google Calendar', sub:'Schedule 2-way sync', color:'#4285f4', initials:'G' },
    { name:'Stripe', sub:'Payment processing', color:'#635bff', initials:'S' },
    { name:'Twilio', sub:'SMS + voice', color:'#f22f46', initials:'T' },
  ];
  const available = [
    { name:'Xero', color:'#13b5ea', initials:'X' },
    { name:'Google Local Services', color:'#34a853', initials:'Gl' },
    { name:'Angi Leads', color:'#e11d48', initials:'A' },
    { name:'Zapier', color:'#ff4a00', initials:'Z' },
    { name:'Slack', color:'#4a154b', initials:'Sl' },
    { name:'HubSpot', color:'#ff7a59', initials:'H' },
  ];
  const Tile = ({item, state}) => (
    <div style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12}}>
      <div style={{width:40,height:40,borderRadius:10,background:item.color,display:'flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:13,fontWeight:700}}>{item.initials}</div>
      <div style={{flex:1}}>
        <div style={{fontSize:15,fontWeight:600,color:'#111'}}>{item.name}</div>
        {item.sub && <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>{item.sub}</div>}
      </div>
      {state==='connected' ? (
        <div style={{fontSize:12,color:'#34c759',fontWeight:600}}>● Connected</div>
      ) : (
        <button style={{padding:'7px 14px',background:'#0071e3',border:'none',borderRadius:8,color:'white',fontSize:12,fontWeight:600}}>Connect</button>
      )}
    </div>
  );
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Integrations" onBack="__back"/>
      <SectionHeader title="Connected"/>
      <Card>{connected.map((it,i) => (<div key={it.name} style={{borderBottom:i<connected.length-1?'0.5px solid rgba(0,0,0,0.07)':'none'}}><Tile item={it} state="connected"/></div>))}</Card>
      <SectionHeader title="Available"/>
      <Card>{available.map((it,i) => (<div key={it.name} style={{borderBottom:i<available.length-1?'0.5px solid rgba(0,0,0,0.07)':'none'}}><Tile item={it}/></div>))}</Card>
    </div>
  );
}

// ── DATA & EXPORT ────────────────────────────────────────────
function SettingsDataScreen({ onNav }) {
  const [exporting, setExporting] = useStateSet(null);
  const [confirmArchive, setConfirmArchive] = useStateSet(false);
  const [confirmDelete, setConfirmDelete] = useStateSet(false);
  const [lastExport, setLastExport] = useStateSet(null);
  const doExport = (kind, count) => {
    setExporting(kind);
    setTimeout(() => {
      setExporting(null);
      setLastExport(`${kind} · ${count} records · ${new Date().toLocaleTimeString([], {hour:'numeric',minute:'2-digit'})}`);
    }, 1400);
  };
  const exports = [
    { key:'Customers', count:'1,284', color:'#0071e3' },
    { key:'Jobs', count:'5,302', color:'#16a34a' },
    { key:'Invoices', count:'4,981', color:'#d97706' },
    { key:'Estimates', count:'1,820', color:'#7c3aed' },
  ];
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Data & Export" onBack="__back"/>
      {lastExport && (
        <div style={{margin:'12px 16px 0',padding:'10px 14px',background:'#e6f7ef',borderRadius:10,display:'flex',alignItems:'center',gap:8,border:'0.5px solid rgba(22,163,74,0.2)'}}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#16a34a" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>
          <div style={{flex:1,fontSize:13,color:'#15803d',fontWeight:500}}>Exported {lastExport}</div>
          <div onClick={()=>setLastExport(null)} style={{fontSize:12,color:'#16a34a',fontWeight:600,cursor:'pointer'}}>Dismiss</div>
        </div>
      )}
      <SectionHeader title="Export as CSV"/>
      <div style={{padding:'0 16px',display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
        {exports.map(ex => {
          const isExporting = exporting===ex.key;
          return (
            <div key={ex.key} onClick={()=>!isExporting && doExport(ex.key, ex.count)}
              style={{background:'white',borderRadius:12,padding:16,border:'0.5px solid rgba(0,0,0,0.06)',cursor:'pointer',opacity:isExporting?0.65:1,transition:'opacity 0.2s'}}>
              <div style={{width:36,height:36,borderRadius:9,background:`${ex.color}15`,display:'flex',alignItems:'center',justifyContent:'center',marginBottom:10}}>
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={ex.color} strokeWidth="2" strokeLinecap="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              </div>
              <div style={{fontSize:14,fontWeight:600,color:'#111'}}>{ex.key}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>{ex.count} records</div>
              <div style={{fontSize:11,fontWeight:600,color:ex.color,marginTop:8}}>
                {isExporting ? 'Exporting…' : 'Download CSV →'}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{padding:'10px 16px 0'}}>
        <div onClick={()=>doExport('Full account',12387)} style={{background:'linear-gradient(135deg,#0f172a,#1e293b)',color:'white',borderRadius:12,padding:16,display:'flex',alignItems:'center',gap:12,cursor:'pointer'}}>
          <div style={{width:40,height:40,borderRadius:10,background:'rgba(255,255,255,0.15)',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:700,letterSpacing:'-0.01em'}}>Full account export</div>
            <div style={{fontSize:12,opacity:0.65,marginTop:2}}>ZIP · all data · emailed when ready</div>
          </div>
          <div style={{fontSize:12,fontWeight:600,color:'#0a84ff'}}>Request →</div>
        </div>
      </div>
      <SectionHeader title="Backup"/>
      {buildList([
        { label:'Auto-backup', right:'Daily · 2 AM' },
        { label:'Last backup', right:'Today, 2:04 AM' },
        { label:'Run backup now', onTap:()=>{ doExport('Backup', '12,387'); }, sub:'Snapshots all data' },
        { label:'Storage used', right:'2.4 GB of 50 GB' },
      ])}
      <SectionHeader title="Danger zone"/>
      <div style={{margin:'0 16px',background:'white',borderRadius:12,overflow:'hidden',border:'0.5px solid rgba(225,29,72,0.2)'}}>
        <div onClick={()=>setConfirmArchive(true)} style={{padding:'14px 16px',borderBottom:'0.5px solid rgba(0,0,0,0.07)',cursor:'pointer',display:'flex',alignItems:'center'}}>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:600,color:'#e11d48'}}>Archive account</div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>Read-only access. Reversible within 30 days.</div>
          </div>
          <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
        </div>
        <div onClick={()=>setConfirmDelete(true)} style={{padding:'14px 16px',cursor:'pointer',display:'flex',alignItems:'center'}}>
          <div style={{flex:1}}>
            <div style={{fontSize:15,fontWeight:600,color:'#e11d48'}}>Delete account</div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:2}}>Permanent. All data erased.</div>
          </div>
          <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
        </div>
      </div>

      {/* Confirm archive */}
      {confirmArchive && <ConfirmSheet title="Archive account?" body="Your team will lose access in 24 hrs. You'll have 30 days to restore from this screen." cta="Archive account" ctaColor="#d97706" onCancel={()=>setConfirmArchive(false)} onConfirm={()=>{ setConfirmArchive(false); alert('Account archived — you have 30 days to restore.'); }}/>}
      {confirmDelete && <ConfirmSheet title="Delete forever?" body="This erases every job, customer, invoice, and payment record. Cannot be undone." cta="Yes, delete everything" ctaColor="#e11d48" onCancel={()=>setConfirmDelete(false)} onConfirm={()=>{ setConfirmDelete(false); alert('Deletion queued. You will receive a confirmation email.'); }}/>}
    </div>
  );
}

function ConfirmSheet({ title, body, cta, ctaColor, onCancel, onConfirm }) {
  return (
    <>
      <div onClick={onCancel} style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.5)',zIndex:300}}/>
      <div style={{position:'absolute',left:12,right:12,bottom:80,zIndex:301,background:'white',borderRadius:18,overflow:'hidden',boxShadow:'0 12px 40px rgba(0,0,0,0.25)'}}>
        <div style={{padding:'22px 22px 14px',textAlign:'center'}}>
          <div style={{width:44,height:44,borderRadius:'50%',background:`${ctaColor}15`,display:'inline-flex',alignItems:'center',justifyContent:'center',marginBottom:12}}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={ctaColor} strokeWidth="2" strokeLinecap="round"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          </div>
          <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.015em'}}>{title}</div>
          <div style={{fontSize:13,color:'rgba(0,0,0,0.55)',marginTop:6,lineHeight:1.5}}>{body}</div>
        </div>
        <div style={{padding:'6px 16px 16px',display:'flex',flexDirection:'column',gap:8}}>
          <button onClick={onConfirm} style={{padding:'12px',background:ctaColor,border:'none',borderRadius:10,color:'white',fontSize:14,fontWeight:600,cursor:'pointer'}}>{cta}</button>
          <button onClick={onCancel} style={{padding:'12px',background:'#f7f7f8',border:'none',borderRadius:10,color:'#111',fontSize:14,fontWeight:600,cursor:'pointer'}}>Cancel</button>
        </div>
      </div>
    </>
  );
}

// ── TEAM (settings) ──────────────────────────────────────────
const TEAM_MEMBERS_DATA = [
  { id:'t1', name:'Marcus Leal',   role:'Lead Plumber',    email:'marcus@simplepro.app',  phone:'(555) 214-8899', employeeId:'EMP-0042', status:'Active', color:'#e8f2fd', textColor:'#0071e3' },
  { id:'t2', name:'Dani Rodriguez',role:'Plumber',         email:'dani@simplepro.app',    phone:'(555) 241-0317', employeeId:'EMP-0051', status:'Active', color:'#f0fdf4', textColor:'#16a34a' },
  { id:'t3', name:'Jake Torres',   role:'Senior Plumber',  email:'jake.t@simplepro.app',  phone:'(555) 317-8844', employeeId:'EMP-0029', status:'Active', color:'#fef3e2', textColor:'#d97706' },
  { id:'t4', name:'Sam Park',      role:'Apprentice',      email:'sam.p@simplepro.app',   phone:'(555) 408-2156', employeeId:'EMP-0063', status:'Active', color:'#f3f4f6', textColor:'#6b7280' },
  { id:'t5', name:'Sarah Admin',   role:'Dispatcher',      email:'sarah@simplepro.app',   phone:'(555) 102-3344', employeeId:'EMP-0007', status:'Active', color:'#f5f0ff', textColor:'#7c3aed' },
  { id:'t6', name:'Jake Davidson', role:'Owner',           email:'jake@simplepro.app',    phone:'(555) 888-0001', employeeId:'EMP-0001', status:'Active', color:'#0f172a', textColor:'#fff' },
];

function SettingsTeamScreen({ onNav }) {
  const [members, setMembers] = useStateSet(()=>{
    try { return JSON.parse(localStorage.getItem('sp_team') || 'null') || TEAM_MEMBERS_DATA; }
    catch(e) { return TEAM_MEMBERS_DATA; }
  });
  useEffSet(()=>{ try { localStorage.setItem('sp_team', JSON.stringify(members)); } catch(e){} }, [members]);
  const [addOpen, setAddOpen] = useStateSet(false);
  const active = members.filter(m=>m.status==='Active').length;
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Team" onBack="__back"
        right={<div onClick={()=>setAddOpen(true)} style={{fontSize:14,color:'#0071e3',fontWeight:600,cursor:'pointer'}}>+ Add</div>}/>
      <div style={{padding:'14px 16px 0',display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:8}}>
        {[
          { l:'Members', v:members.length, color:'#111' },
          { l:'Active', v:active, color:'#16a34a' },
          { l:'Seats', v:'8 / 10', color:'#0071e3' },
        ].map(s => (
          <div key={s.l} style={{background:'white',borderRadius:10,padding:'10px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
            <div style={{fontSize:17,fontWeight:700,color:s.color,letterSpacing:'-0.02em'}}>{s.v}</div>
            <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>{s.l}</div>
          </div>
        ))}
      </div>
      <SectionHeader title="Members"/>
      <Card>
        {members.map((m,i) => (
          <div key={m.id} onClick={()=>onNav('team-member',{memberId:m.id})}
            style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,borderBottom:i<members.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <Avatar name={m.name} size={40} color={m.color} textColor={m.textColor}/>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>{m.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.45)',marginTop:1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{m.role} · {m.email}</div>
            </div>
            <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
          </div>
        ))}
      </Card>
      <div style={{margin:'14px 16px'}}>
        <button onClick={()=>setAddOpen(true)} style={{width:'100%',padding:'13px',background:'white',border:'1.2px dashed rgba(0,0,0,0.18)',borderRadius:12,color:'#0071e3',fontSize:14,fontWeight:600,cursor:'pointer'}}>+ Invite team member</button>
      </div>
      <SectionHeader title="Roles & permissions"/>
      {buildList([
        { label:'Owner', right:'1 member' },
        { label:'Dispatcher', right:'1 member' },
        { label:'Plumber', right:'3 members' },
        { label:'Apprentice', right:'1 member' },
      ])}

      {addOpen && <AddMemberSheet onClose={()=>setAddOpen(false)} onAdd={(m)=>{ setMembers([...members, m]); setAddOpen(false); }}/>}
    </div>
  );
}

function AddMemberSheet({ onClose, onAdd }) {
  const [name, setName] = useStateSet('');
  const [email, setEmail] = useStateSet('');
  const [phone, setPhone] = useStateSet('');
  const [role, setRole] = useStateSet('Plumber');
  const roles = ['Owner','Dispatcher','Senior Plumber','Plumber','Apprentice','Office Admin'];
  const canSave = name.trim() && email.trim();
  const save = () => {
    const colors = [['#e8f2fd','#0071e3'],['#f0fdf4','#16a34a'],['#fef3e2','#d97706'],['#f5f0ff','#7c3aed'],['#fff1f2','#e11d48']];
    const [bg, fg] = colors[Math.floor(Math.random()*colors.length)];
    onAdd({
      id:'t'+Date.now(), name:name.trim(), role, email:email.trim(), phone:phone.trim()||'—',
      employeeId:'EMP-'+String(1000+Math.floor(Math.random()*9000)), status:'Invited',
      color:bg, textColor:fg,
    });
  };
  return (
    <>
      <div onClick={onClose} style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.5)',zIndex:400,animation:'fadeIn 0.15s'}}/>
      <div style={{position:'absolute',left:0,right:0,bottom:0,zIndex:401,background:'white',borderTopLeftRadius:20,borderTopRightRadius:20,paddingBottom:30,boxShadow:'0 -12px 40px rgba(0,0,0,0.2)',animation:'slideUp 0.2s'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'14px 18px',borderBottom:'0.5px solid rgba(0,0,0,0.08)'}}>
          <button onClick={onClose} style={{background:'none',border:'none',fontSize:15,color:'rgba(0,0,0,0.5)',fontWeight:500,cursor:'pointer',padding:0}}>Cancel</button>
          <div style={{fontSize:15,fontWeight:600,color:'#111'}}>Invite member</div>
          <button onClick={save} disabled={!canSave} style={{background:'none',border:'none',fontSize:15,color:canSave?'#0071e3':'rgba(0,0,0,0.25)',fontWeight:600,cursor:canSave?'pointer':'default',padding:0}}>Send</button>
        </div>
        <div style={{padding:'18px',display:'flex',flexDirection:'column',gap:14}}>
          <div>
            <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>FULL NAME</div>
            <input autoFocus value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Alex Morgan"
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',outline:'none'}}/>
          </div>
          <div>
            <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>EMAIL</div>
            <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="alex@company.com"
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',outline:'none'}}/>
          </div>
          <div>
            <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>PHONE (OPTIONAL)</div>
            <input type="tel" value={phone} onChange={e=>setPhone(e.target.value)} placeholder="(555) 123-4567"
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',outline:'none'}}/>
          </div>
          <div>
            <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em',marginBottom:6}}>ROLE</div>
            <div style={{display:'flex',flexWrap:'wrap',gap:6}}>
              {roles.map(r => (
                <div key={r} onClick={()=>setRole(r)} style={{padding:'9px 14px',borderRadius:999,background:role===r?'#0071e3':'#f7f7f8',color:role===r?'white':'#111',fontSize:13,fontWeight:500,cursor:'pointer'}}>{r}</div>
              ))}
            </div>
          </div>
          <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',lineHeight:1.5}}>We'll email an invite link. They'll set their own password and get access based on role.</div>
        </div>
      </div>
    </>
  );
}

function SettingsTeamMemberScreen({ onNav, params }) {
  const memberId = params?.memberId;
  const [members, setMembers] = useStateSet(()=>{
    try { return JSON.parse(localStorage.getItem('sp_team') || 'null') || TEAM_MEMBERS_DATA; }
    catch(e) { return TEAM_MEMBERS_DATA; }
  });
  const member = members.find(m=>m.id===memberId) || members[0];
  const update = (patch) => {
    const next = members.map(m => m.id===member.id ? {...m, ...patch} : m);
    setMembers(next);
    try { localStorage.setItem('sp_team', JSON.stringify(next)); } catch(e){}
  };
  const openEditor = useEditor();
  // Use a sub-editor: we pass an ad-hoc settings shape to the global editor by using its 'options' mode only, or just use prompt for simplicity. Better: local edit state.
  const [localEditor, setLocalEditor] = useStateSet(null);
  const edit = (field, label, type, options) => setLocalEditor({ field, label, type:type||'text', options });
  const commit = (val) => {
    update({ [localEditor.field]: val });
    setLocalEditor(null);
  };
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Member" onBack="__back"/>
      <div style={{padding:'24px 20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)',display:'flex',flexDirection:'column',alignItems:'center',gap:10}}>
        <Avatar name={member.name} size={80} color={member.color} textColor={member.textColor}/>
        <div style={{fontSize:19,fontWeight:700,color:'#111',letterSpacing:'-0.015em',marginTop:4}}>{member.name}</div>
        <div style={{fontSize:13,color:'rgba(0,0,0,0.55)'}}>{member.role} · {member.employeeId}</div>
        <div style={{display:'flex',gap:8,marginTop:6}}>
          <button onClick={()=>alert(`Calling ${member.phone}`)} style={{padding:'8px 16px',background:'#e8f2fd',border:'none',borderRadius:8,color:'#0071e3',fontSize:13,fontWeight:600,cursor:'pointer',display:'flex',alignItems:'center',gap:6}}>{Icons.phone} Call</button>
          <button onClick={()=>alert(`Texting ${member.phone}`)} style={{padding:'8px 16px',background:'#e8f2fd',border:'none',borderRadius:8,color:'#0071e3',fontSize:13,fontWeight:600,cursor:'pointer',display:'flex',alignItems:'center',gap:6}}>{Icons.message} Message</button>
        </div>
      </div>
      <SectionHeader title="Profile"/>
      {buildList([
        { label:'Full name', right:member.name, onTap:()=>edit('name','Full name') },
        { label:'Role', right:member.role, onTap:()=>edit('role','Role','options',['Owner','Dispatcher','Senior Plumber','Plumber','Apprentice','Office Admin']) },
        { label:'Employee ID', right:member.employeeId, onTap:()=>edit('employeeId','Employee ID') },
      ])}
      <SectionHeader title="Contact"/>
      {buildList([
        { label:'Email', right:member.email, onTap:()=>edit('email','Email') },
        { label:'Phone', right:member.phone, onTap:()=>edit('phone','Phone') },
      ])}
      <SectionHeader title="Status"/>
      {buildList([
        { label:'Status', right:member.status, onTap:()=>edit('status','Status','options',['Active','Suspended','Invited']) },
      ])}
      <div style={{margin:'14px 16px',display:'flex',gap:8}}>
        <button onClick={()=>alert('Password reset email sent')} style={{flex:1,padding:'12px',background:'white',border:'0.5px solid rgba(0,0,0,0.1)',borderRadius:10,color:'#111',fontSize:14,fontWeight:600,cursor:'pointer'}}>Reset password</button>
        <button onClick={()=>{
          if(confirm(`Remove ${member.name} from team?`)) {
            const next = members.filter(m=>m.id!==member.id);
            setMembers(next);
            try { localStorage.setItem('sp_team', JSON.stringify(next)); } catch(e){}
            onNav('settings-team');
          }
        }} style={{flex:1,padding:'12px',background:'white',border:'0.5px solid rgba(225,29,72,0.3)',borderRadius:10,color:'#e11d48',fontSize:14,fontWeight:600,cursor:'pointer'}}>Remove</button>
      </div>

      {localEditor && <LocalEditSheet editor={localEditor} value={member[localEditor.field]} onClose={()=>setLocalEditor(null)} onSave={commit}/>}
    </div>
  );
}

function LocalEditSheet({ editor, value, onClose, onSave }) {
  const [val, setVal] = useStateSet(value ?? '');
  return (
    <>
      <div onClick={onClose} style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.5)',zIndex:400,animation:'fadeIn 0.15s'}}/>
      <div style={{position:'absolute',left:0,right:0,bottom:0,zIndex:401,background:'white',borderTopLeftRadius:20,borderTopRightRadius:20,paddingBottom:30,boxShadow:'0 -12px 40px rgba(0,0,0,0.2)',animation:'slideUp 0.2s'}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'14px 18px',borderBottom:'0.5px solid rgba(0,0,0,0.08)'}}>
          <button onClick={onClose} style={{background:'none',border:'none',fontSize:15,color:'rgba(0,0,0,0.5)',fontWeight:500,cursor:'pointer',padding:0}}>Cancel</button>
          <div style={{fontSize:15,fontWeight:600,color:'#111'}}>{editor.label}</div>
          <button onClick={()=>onSave(val)} style={{background:'none',border:'none',fontSize:15,color:'#0071e3',fontWeight:600,cursor:'pointer',padding:0}}>Save</button>
        </div>
        <div style={{padding:'18px'}}>
          {editor.type==='options' ? (
            <div style={{display:'flex',flexDirection:'column',gap:2}}>
              {editor.options.map(opt => (
                <div key={opt} onClick={()=>onSave(opt)} style={{padding:'14px 16px',background: val===opt?'#eff6ff':'#f7f7f8',borderRadius:10,display:'flex',alignItems:'center',justifyContent:'space-between',cursor:'pointer'}}>
                  <span style={{fontSize:15,color:'#111',fontWeight: val===opt?600:500}}>{opt}</span>
                  {val===opt && <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#0071e3" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                </div>
              ))}
            </div>
          ) : (
            <input autoFocus value={val} onChange={e=>setVal(e.target.value)} onKeyDown={e=>{if(e.key==='Enter') onSave(val);}}
              style={{width:'100%',padding:'14px 16px',border:'0.5px solid rgba(0,0,0,0.12)',borderRadius:10,fontSize:15,fontFamily:'inherit',boxSizing:'border-box',background:'#f7f7f8',outline:'none'}}/>
          )}
        </div>
      </div>
    </>
  );
}

// ── PRIVACY ──────────────────────────────────────────────────
function SettingsPrivacyScreen({ onNav }) {
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Privacy & Policies" onBack="__back"/>
      <SectionHeader title="Policies"/>
      {buildList([
        { label:'Privacy policy' },
        { label:'Terms of service' },
        { label:'Data processing addendum' },
        { label:'SMS compliance (TCPA)' },
      ])}
      <SectionHeader title="Your data"/>
      {buildList([
        { label:'Request my data' },
        { label:'Who has access', right:'12 team members' },
        { label:'Audit log' },
      ])}
      <SectionHeader title="Permissions"/>
      {buildList([
        { label:'Location', right:'While using app' },
        { label:'Camera', right:'Allowed' },
        { label:'Microphone', right:'Allowed' },
        { label:'Contacts', right:'Allowed' },
      ])}
    </div>
  );
}

// ── HELP ─────────────────────────────────────────────────────
function SettingsHelpScreen({ onNav }) {
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Help Center" onBack="__back"/>
      <div style={{padding:'14px 16px'}}>
        <input placeholder="Search help articles…" style={{width:'100%',padding:'11px 14px',border:'0.5px solid rgba(0,0,0,0.1)',borderRadius:10,fontSize:14,background:'white',boxSizing:'border-box'}}/>
      </div>
      <SectionHeader title="Getting started"/>
      {buildList([
        { label:'Your first job', sub:'4 min read' },
        { label:'Setting up Belle', sub:'6 min read' },
        { label:'Invoicing & payments', sub:'5 min read' },
        { label:'Adding team members', sub:'3 min read' },
      ])}
      <SectionHeader title="Popular articles"/>
      {buildList([
        { label:'How to connect QuickBooks' },
        { label:'Setting up service plans' },
        { label:'Using the mobile terminal' },
        { label:'Editing invoice templates' },
      ])}
      <SectionHeader title="Videos"/>
      {buildList([
        { label:'Daily workflow walkthrough', sub:'12:04' },
        { label:'Belle best practices', sub:'8:32' },
      ])}
    </div>
  );
}

// ── CONTACT SUPPORT ──────────────────────────────────────────
function SettingsContactScreen({ onNav }) {
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Contact Support" onBack="__back"/>
      <div style={{padding:'20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{fontSize:20,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>We're here to help.</div>
        <div style={{fontSize:14,color:'rgba(0,0,0,0.55)',marginTop:4,lineHeight:1.5}}>Avg response: under 2 min on chat, 3 hrs on email.</div>
      </div>
      <SectionHeader title="Reach us"/>
      {buildList([
        { icon: Icons.message, label:'Live chat', sub:'Online now · fastest', right:'Start' },
        { icon: Icons.phone, label:'Call us', right:'(888) 555-0199' },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>, label:'Email', right:'support@simplepro.app' },
      ])}
      <SectionHeader title="Status"/>
      <Card>
        <div style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:10}}>
          <div style={{width:10,height:10,borderRadius:'50%',background:'#34c759'}}/>
          <div style={{flex:1,fontSize:14,color:'#111'}}>All systems operational</div>
          <div style={{fontSize:12,color:'#0071e3',fontWeight:600}}>status.simplepro.app</div>
        </div>
      </Card>
      <SectionHeader title="Recent tickets"/>
      {buildList([
        { label:'#4812 — Invoice PDF not generating', sub:'Resolved · 2d ago', right:'View' },
        { label:'#4781 — QuickBooks sync', sub:'Resolved · 1w ago', right:'View' },
      ])}
    </div>
  );
}

// ── ABOUT ────────────────────────────────────────────────────
function SettingsAboutScreen({ onNav }) {
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="About" onBack="__back"/>
      <div style={{padding:'30px 20px',background:'white',textAlign:'center',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{width:68,height:68,borderRadius:16,background:'#0f172a',display:'inline-flex',alignItems:'center',justifyContent:'center',color:'white',fontSize:22,fontWeight:700,letterSpacing:'-0.02em'}}>SP</div>
        <div style={{fontSize:20,fontWeight:700,color:'#111',marginTop:14,letterSpacing:'-0.02em'}}>Simple Pro</div>
        <div style={{fontSize:13,color:'rgba(0,0,0,0.5)',marginTop:3}}>Version 4.12.0 (build 4120.8)</div>
      </div>
      <SectionHeader title=""/>
      {buildList([
        { label:"What's new" },
        { label:'Rate on App Store' },
        { label:'Follow @simplepro' },
        { label:'Careers' },
      ])}
      <div style={{padding:'20px',textAlign:'center',fontSize:12,color:'rgba(0,0,0,0.35)'}}>
        © 2026 Simple Pro, Inc.
      </div>
    </div>
  );
}

// ── CAMPAIGN DETAIL ──────────────────────────────────────────
function CampaignDetailScreen({ onNav, params }) {
  const c = params?.campaign || { name:'Spring tune-up promo', type:'SMS', status:'Active' };
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Campaign" onBack="__back"/>
      <div style={{padding:'20px',background:'white',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{fontSize:20,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{c.name}</div>
        <div style={{fontSize:13,color:'rgba(0,0,0,0.55)',marginTop:4}}>{c.type} · {c.status}</div>
      </div>
      <div style={{margin:'14px 16px',display:'flex',gap:8}}>
        {[
          { l:'Sent', v:'412' },
          { l:'Delivered', v:'408' },
          { l:'Opened', v:'293' },
          { l:'Booked', v:'47' },
        ].map(s => (
          <div key={s.l} style={{flex:1,background:'white',borderRadius:10,padding:'12px 8px',textAlign:'center',border:'0.5px solid rgba(0,0,0,0.06)'}}>
            <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.02em'}}>{s.v}</div>
            <div style={{fontSize:10,color:'rgba(0,0,0,0.5)',marginTop:2,fontWeight:500,letterSpacing:'0.03em',textTransform:'uppercase'}}>{s.l}</div>
          </div>
        ))}
      </div>
      <SectionHeader title="Message"/>
      <div style={{margin:'0 16px',background:'white',borderRadius:12,padding:16,border:'0.5px solid rgba(0,0,0,0.06)'}}>
        <div style={{fontSize:14,color:'#111',lineHeight:1.55}}>Hi {'{first_name}'} — spring's here! Get $29 off a full plumbing tune-up this month. Reply YES to book.</div>
        <div style={{display:'flex',gap:8,marginTop:12}}>
          <button style={{flex:1,padding:'10px',background:'#f7f7f8',border:'none',borderRadius:8,fontSize:13,fontWeight:600,color:'#111'}}>Edit</button>
          <button style={{flex:1,padding:'10px',background:'#f7f7f8',border:'none',borderRadius:8,fontSize:13,fontWeight:600,color:'#111'}}>Duplicate</button>
        </div>
      </div>
      <SectionHeader title="Audience"/>
      {buildList([
        { label:'Segment', right:'Residential · past 12mo' },
        { label:'Size', right:'412 recipients' },
        { label:'Excluded', right:'Unsubscribed (34)' },
      ])}
      <SectionHeader title="Schedule"/>
      {buildList([
        { label:'Started', right:'Apr 12, 2026 · 9:00 AM' },
        { label:'Ends', right:'Apr 30, 2026' },
        { label:'Frequency', right:'One-time' },
      ])}
    </div>
  );
}

Object.assign(window, {
  SettingsScreen, SettingsProfileScreen, SettingsSecurityScreen, SettingsNotificationsScreen,
  SettingsCompanyScreen, SettingsPaymentsScreen, SettingsBillingScreen, SettingsPriceBookScreen,
  SettingsBelleScreen, SettingsTemplatesScreen, SettingsIntegrationsScreen, SettingsDataScreen,
  SettingsPrivacyScreen, SettingsHelpScreen, SettingsContactScreen, SettingsAboutScreen,
  CampaignsScreen, CampaignDetailScreen,
  PlansScreen, BillingPdfScreen,
  SettingsTeamScreen, SettingsTeamMemberScreen,
});
