// Simple Pro Mobile — More menu, Billing (unified), Invoice+Customer detail
const { useState } = React;

// ── INVOICES DATA (used by BillingScreen and InvoiceDetail) ───
const INVOICES_DATA = [
  { id:'INV-0112', client:'Chen Family',      amount:'$1,450', status:'paid',     date:'Apr 21', job:'Water Heater Install' },
  { id:'INV-0111', client:'Ramos Residence',  amount:'$320',   status:'sent',     date:'Apr 21', job:'Drain Clog — Kitchen' },
  { id:'INV-0109', client:'Steinberg Corp',   amount:'$2,800', status:'draft',    date:'Apr 20', job:'Full Bath Re-pipe' },
  { id:'INV-0107', client:'Nguyen Group',     amount:'$550',   status:'overdue',  date:'Apr 16', job:'Sewer Line Inspection' },
  { id:'INV-0105', client:'Torres LLC',       amount:'$890',   status:'sent',     date:'Apr 14', job:'Gas Line Repair' },
  { id:'INV-0103', client:'Adams Home',       amount:'$420',   status:'paid',     date:'Apr 18', job:'Toilet Replacement' },
];

// ── BILLING SCREEN (unified estimates + invoices) ─────────────
// IA spec: merge EstimatesScreen + InvoicesScreen into a single BillingScreen
// with type filter (All / Estimates / Invoices). Tap routes to existing details.
function BillingScreen({ onNav, params, plan='standard' }) {
  const [typeFilter, setTypeFilter] = useState('All');   // All / Estimates / Invoices
  const [statusFilter, setStatusFilter] = useState(params?.filter || 'All');

  const estimates = (window.ESTIMATES_DATA || []).map(e => ({...e, _kind:'estimate'}));
  const invoices = INVOICES_DATA.map(i => ({...i, _kind:'invoice'}));

  let items =
    typeFilter === 'Estimates' ? estimates :
    typeFilter === 'Invoices'  ? invoices :
    [...invoices, ...estimates];

  if (statusFilter === 'Unpaid') {
    items = items.filter(x => ['sent','overdue'].includes(x.status));
  } else if (statusFilter !== 'All') {
    items = items.filter(x => x.status === statusFilter.toLowerCase());
  }

  const unpaidTotal = invoices
    .filter(i=>['sent','overdue'].includes(i.status))
    .reduce((s,i) => s + parseFloat(i.amount.replace(/[$,]/g,'')), 0);

  const statusFilters = ['All','Draft','Sent','Paid','Overdue','Approved','Unpaid'];
  const premium = (typeof isPremiumPlan === 'function') ? isPremiumPlan(plan) : !!String(plan||'').toLowerCase().match(/premium|pro|ops/);

  return (
    <div style={screenBg({paddingBottom:100})}>
      <NavHeader title="Billing" subtitle="Money and proposals" onBack="__back"
        action={<IOSPlusButton onTap={() => onNav('belle', {prompt:'Create a new estimate or invoice'})} label="Create billing item"/>}
      />

      {/* Type filter — primary pill group */}
      <div style={{display:'flex',gap:0,padding:'14px 16px 6px'}}>
        <div style={{display:'flex',background:'rgba(255,255,255,0.78)',borderRadius:16,padding:3,flex:1,border:IOS.line,boxShadow:IOS.shadow}}>
          {['All','Estimates','Invoices'].map(t => (
            <div key={t} onClick={() => setTypeFilter(t)}
              style={{flex:1,height:32,borderRadius:8,display:'flex',alignItems:'center',justifyContent:'center',
                background: typeFilter===t ? 'white' : 'transparent',
                boxShadow: typeFilter===t ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                fontSize:13,fontWeight: typeFilter===t ? 600 : 500,
                color: typeFilter===t ? '#111' : 'rgba(0,0,0,0.55)',cursor:'pointer'}}>
              {t}
            </div>
          ))}
        </div>
      </div>

      {/* Unpaid summary */}
      {(typeFilter === 'All' || typeFilter === 'Invoices') && unpaidTotal > 0 && (
        <div style={{margin:'10px 16px 0',background:'#fef3e2',border:'1px solid rgba(217,119,6,0.2)',
          borderRadius:22,padding:'14px 16px',display:'flex',alignItems:'center',gap:12,boxShadow:IOS.shadow}}>
          <div style={{flex:1}}>
            <div style={{fontSize:12,fontWeight:600,color:'rgba(146,82,10,0.7)',marginBottom:2}}>Outstanding Balance</div>
            <div style={{fontSize:24,fontWeight:700,color:'#92520a',letterSpacing:'-0.025em',
              fontVariantNumeric:'tabular-nums'}}>${unpaidTotal.toLocaleString()}</div>
          </div>
          <div onClick={() => onNav('belle', {prompt:'Send invoice reminders'})}
            style={{height:34,padding:'0 12px',borderRadius:10,background:'#d97706',
              color:'white',border:'none',fontSize:12,fontWeight:600,cursor:'pointer',
              display:'flex',alignItems:'center'}}>
            Ask Belle to remind
          </div>
        </div>
      )}

      {/* Premium money operations */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,padding:'10px 16px 2px'}}>
        {[{label:'Job costing',sub:'Margin per job',route:premium?'job-costing':'feature-detail',params:{feature:'job-costing'}},{label:'Financing',sub:'Offer on proposals',route:premium?'customer-financing':'feature-detail',params:{feature:'customer-financing'}}].map(x=>(
          <div key={x.label} className="sp-pressable" onClick={()=>onNav(x.route,x.params)} style={{borderRadius:20,background:'rgba(255,255,255,.86)',border:IOS.line,padding:13,cursor:'pointer',boxShadow:IOS.shadow,opacity:premium?1:.68}}>
            <div style={{fontSize:14,fontWeight:850,letterSpacing:'-.02em'}}>{x.label}{!premium?' 🔒':''}</div>
            <div style={{fontSize:12,color:'rgba(17,24,39,.5)',marginTop:4}}>{x.sub}</div>
          </div>
        ))}
      </div>

      {/* Status filter chips */}
      <div style={{display:'flex',gap:7,padding:'10px 16px 12px',overflowX:'auto',scrollbarWidth:'none'}}>
        {statusFilters.map(f => (
          <div key={f} className="sp-pressable" onClick={() => setStatusFilter(f)}
            style={{flexShrink:0,height:28,padding:'0 11px',borderRadius:999,
              background: statusFilter===f ? IOS.blue : 'rgba(255,255,255,0.78)',
              color: statusFilter===f ? 'white' : 'rgba(17,24,39,0.62)',
              border: statusFilter===f ? `1px solid ${IOS.blue}` : IOS.line,
              boxShadow: statusFilter===f ? '0 8px 16px rgba(0,122,255,0.16)' : 'none',
              fontSize:12,fontWeight: statusFilter===f ? 750 : 600,
              display:'flex',alignItems:'center',cursor:'pointer'}}>
            {f}
          </div>
        ))}
      </div>

      {items.length === 0 ? (
        <EmptyState
          verb="send your first estimate"
          manualLabel="Create it manually"
          onAsk={() => onNav('belle', {prompt:'Create a new estimate for a customer'})}
          onManual={() => onNav('belle', {prompt:'Create a new estimate manually'})}
          icon={<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" 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"/><line x1="16" y1="13" x2="8" y2="13"/></svg>}
        />
      ) : (
        <Card style={{borderRadius:24}}>
          {items.map((x, i) => (
            <div key={x.id} onClick={() =>
                onNav(x._kind === 'estimate' ? 'estimate-detail' : 'invoice-detail',
                  x._kind === 'estimate' ? {estimate: x} : {invoice: x})
              }
              style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
                borderBottom: i<items.length-1 ? IOS.line:'none',cursor:'pointer'}}>
              <div style={{width:38,height:38,borderRadius:10,flexShrink:0,
                background:
                  x.status==='paid'     ? '#e6f7ef' :
                  x.status==='overdue'  ? '#fef2f2' :
                  x.status==='approved' ? '#e6f7ef' :
                  x.status==='sent'     ? '#eff6ff' : '#f3f4f6',
                display:'flex',alignItems:'center',justifyContent:'center'}}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
                  stroke={
                    x.status==='paid'?'#1a9e5c':
                    x.status==='overdue'?'#dc2626':
                    x.status==='approved'?'#1a9e5c':
                    x.status==='sent'?'#2563eb':'#6b7280'
                  }
                  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"/>
                  <line x1="16" y1="13" x2="8" y2="13"/>
                </svg>
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:3}}>
                  <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>{x.client}</div>
                  <div style={{fontSize:15,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums'}}>{x.amount}</div>
                </div>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>
                    <span style={{
                      display:'inline-block',padding:'1px 6px',borderRadius:4,
                      background: x._kind==='estimate' ? '#f5f0ff' : '#eff6ff',
                      color: x._kind==='estimate' ? '#7c3aed' : '#2563eb',
                      fontSize:10,fontWeight:600,letterSpacing:'0.04em',textTransform:'uppercase',marginRight:6
                    }}>{x._kind}</span>
                    {x.id} · {x.date}
                  </div>
                  <Badge status={x.status} small/>
                </div>
              </div>
            </div>
          ))}
        </Card>
      )}
    </div>
  );
}

// ── INVOICE DETAIL ────────────────────────────────────────────
function InvoiceDetailScreen({ onNav, params }) {
  const inv = (params && params.invoice) || INVOICES_DATA[1];
  const [payOpen, setPayOpen] = useState(false);

  // Tier-2 overflow: void, refund, mark paid manually, edit line items, resend
  const overflow = (
    <OverflowMenu title="Invoice overrides" items={[
      { label:'Resend invoice', sub:'(manual) — send the PDF again' },
      { label:'Mark paid manually', sub:'(manual) — record payment without processing',
        onTap:()=>setPayOpen(true) },
      { label:'Edit line items', sub:'(manual)' },
      { label:'Refund', sub:'(manual)', destructive:true },
      { label:'Void invoice', sub:'(manual) — cancel this invoice', destructive:true },
    ]}/>
  );

  return (
    <div style={screenBg({paddingBottom:120})}>
      <NavHeader title={inv.id} onBack="__back" action={overflow}/>
      <div style={{margin:'12px 16px 0',...glassStyle({padding:'16px 16px 20px'})}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:4}}>
          <div>
            <div style={{fontSize:22,fontWeight:700,color:'#111',letterSpacing:'-0.02em',fontVariantNumeric:'tabular-nums'}}>{inv.amount}</div>
            <div style={{fontSize:13,color:'rgba(0,0,0,0.4)',marginTop:2}}>{inv.client} · {inv.date}</div>
          </div>
          <Badge status={inv.status}/>
        </div>
        {['sent','overdue'].includes(inv.status) && (
          <BelleCTA style={{marginTop:16}}
            askLabel="Ask Belle to collect"
            manualLabel="Record payment manually"
            color="#1a9e5c"
            onAsk={() => onNav('belle', {prompt:`Collect payment on ${inv.id} from ${inv.client}`})}
            onManual={() => setPayOpen(true)}/>
        )}
        {inv.status === 'draft' && (
          <BelleCTA style={{marginTop:16}}
            askLabel="Ask Belle to send"
            manualLabel="Send invoice manually"
            onAsk={() => onNav('belle', {prompt:`Send ${inv.id} to ${inv.client}`})}
            onManual={() => onNav('belle', {prompt:`Manually send ${inv.id} to ${inv.client}`})}/>
        )}
      </div>

      <SectionHeader title="Line Items"/>
      <Card>
        {[
          { desc:'Labor — ' + inv.job, qty:'3 hrs', rate:'$95/hr', total:'$285' },
          { desc:'Materials & Parts',   qty:'—',     rate:'—',      total:'$35'  },
        ].map((line, i, arr) => (
          <div key={i} style={{padding:'12px 16px',borderBottom: i<arr.length-1 ? '0.5px solid rgba(0,0,0,0.07)':'none'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
              <div style={{fontSize:14,fontWeight:500,color:'#111',flex:1,marginRight:8}}>{line.desc}</div>
              <div style={{fontSize:14,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums'}}>{line.total}</div>
            </div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.4)',marginTop:2}}>{line.qty} · {line.rate}</div>
          </div>
        ))}
        <div style={{padding:'12px 16px',display:'flex',justifyContent:'space-between',background:'#f7f7f8'}}>
          <span style={{fontSize:15,fontWeight:600,color:'#111'}}>Total</span>
          <span style={{fontSize:15,fontWeight:700,color:'#111',fontVariantNumeric:'tabular-nums'}}>{inv.amount}</span>
        </div>
      </Card>

      <SectionHeader title="Customer"/>
      <Card>
        <ListCell icon={Icons.user} iconBg="#e8f2fd" title={inv.client}
          subtitle="Tap to view full profile" onTap={() => onNav('customer-detail')} isLast/>
      </Card>

      <BottomSheet open={payOpen} onClose={() => setPayOpen(false)} title="Record Payment" halfHeight>
        <div style={{padding:'16px'}}>
          {['Cash','Credit Card','Check','Financing','Zelle','Venmo','PayPal'].map((method) => (
            <div key={method} onClick={() => setPayOpen(false)}
              style={{height:52,borderRadius:12,background:'#f7f7f8',display:'flex',
                alignItems:'center',justifyContent:'space-between',padding:'0 16px',
                marginBottom:8,cursor:'pointer',border:'1px solid rgba(0,0,0,0.07)'}}>
              <span style={{fontSize:16,fontWeight:500,color:'#111'}}>{method}</span>
              {Icons.chevronR}
            </div>
          ))}
        </div>
      </BottomSheet>
    </div>
  );
}

// ── CUSTOMERS LIST ────────────────────────────────────────────
const CUSTOMERS_DATA = [
  { id:1, name:'Maria Ramos',    company:'Ramos Residence',  phone:'(415) 555-0192', jobs:3,  unpaid:'$320',  lastJob:'Apr 21' },
  { id:2, name:'David Steinberg',company:'Steinberg Corp',   phone:'(415) 555-0271', jobs:5,  unpaid:'$2,800',lastJob:'Apr 20' },
  { id:3, name:'Lisa Chen',      company:'Chen Family',      phone:'(415) 555-0388', jobs:4,  unpaid:null,    lastJob:'Apr 21' },
  { id:4, name:'Kevin Nguyen',   company:'Nguyen Group',     phone:'(415) 555-0445', jobs:2,  unpaid:'$550',  lastJob:'Apr 16' },
  { id:5, name:'Sofia Park',     company:'Park Residence',   phone:'(415) 555-0519', jobs:1,  unpaid:null,    lastJob:'Apr 22' },
  { id:6, name:'Carlos Torres',  company:'Torres LLC',       phone:'(415) 555-0623', jobs:2,  unpaid:'$890',  lastJob:'Apr 14' },
  { id:7, name:'James Adams',    company:'Adams Home',       phone:'(415) 555-0701', jobs:3,  unpaid:null,    lastJob:'Apr 18' },
  { id:8, name:'Rachel Lewis',   company:'Lewis Property',   phone:'(415) 555-0812', jobs:1,  unpaid:null,    lastJob:'Apr 25' },
];

const AVATAR_COLORS = [
  { bg:'#e8f2fd', color:'#0071e3' },
  { bg:'#e6f7ef', color:'#1a9e5c' },
  { bg:'#fef3e2', color:'#d97706' },
  { bg:'#f5f0ff', color:'#7c3aed' },
  { bg:'#fef2f2', color:'#dc2626' },
];

function CustomersScreen({ onNav }) {
  const [search, setSearch] = useState('');
  const filtered = CUSTOMERS_DATA.filter(c =>
    !search ||
    c.name.toLowerCase().includes(search.toLowerCase()) ||
    c.company.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div style={{background:'#f5f5f7', minHeight:'100%', paddingBottom:100}}>
      <NavHeader title="Customers" onBack="__back"
        action={
          <div onClick={() => onNav('belle', {prompt:'Add a new customer'})}
            style={{width:32,height:32,borderRadius:'50%',background:'rgba(255,255,255,0.12)',
              display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer'}}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="white"><line x1="7" y1="1" x2="7" y2="13" strokeWidth="2" stroke="white" strokeLinecap="round"/><line x1="1" y1="7" x2="13" y2="7" strokeWidth="2" stroke="white" strokeLinecap="round"/></svg>
          </div>
        }
      />

      {/* Search */}
      <div style={{padding:'10px 16px 8px'}}>
        <div style={{height:36,background:'rgba(0,0,0,0.06)',borderRadius:10,
          display:'flex',alignItems:'center',gap:8,padding:'0 12px'}}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="rgba(0,0,0,0.35)" strokeWidth="2.2" strokeLinecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search customers…"
            style={{flex:1,border:'none',background:'transparent',fontSize:15,color:'#111',
              outline:'none',fontFamily:'inherit',letterSpacing:'-0.008em'}}/>
        </div>
      </div>

      {/* Summary strip */}
      <div style={{display:'flex',gap:10,padding:'4px 16px 12px'}}>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'9px 12px',
          boxShadow:'0 0 0 0.5px rgba(0,0,0,0.07)'}}>
          <div style={{fontSize:18,fontWeight:700,color:'#111',letterSpacing:'-0.02em',fontVariantNumeric:'tabular-nums'}}>{CUSTOMERS_DATA.length}</div>
          <div style={{fontSize:10,fontWeight:500,color:'rgba(0,0,0,0.35)',textTransform:'uppercase',letterSpacing:'0.05em',marginTop:2}}>Total</div>
        </div>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'9px 12px',
          boxShadow:'0 0 0 0.5px rgba(0,0,0,0.07)'}}>
          <div style={{fontSize:18,fontWeight:700,color:'#dc2626',letterSpacing:'-0.02em',fontVariantNumeric:'tabular-nums'}}>4</div>
          <div style={{fontSize:10,fontWeight:500,color:'rgba(0,0,0,0.35)',textTransform:'uppercase',letterSpacing:'0.05em',marginTop:2}}>Unpaid</div>
        </div>
        <div style={{flex:1,background:'white',borderRadius:10,padding:'9px 12px',
          boxShadow:'0 0 0 0.5px rgba(0,0,0,0.07)'}}>
          <div style={{fontSize:18,fontWeight:700,color:'#0071e3',letterSpacing:'-0.02em',fontVariantNumeric:'tabular-nums'}}>12</div>
          <div style={{fontSize:10,fontWeight:500,color:'rgba(0,0,0,0.35)',textTransform:'uppercase',letterSpacing:'0.05em',marginTop:2}}>Open jobs</div>
        </div>
      </div>

      {/* List */}
      {filtered.length === 0 ? (
        <EmptyState
          verb="add your first customer"
          manualLabel="Add them manually"
          onAsk={() => onNav('belle', {prompt:'Add a new customer'})}
          onManual={() => onNav('new-customer')}
          icon={<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>}
        />
      ) : (
        <Card>
          {filtered.map((c, i) => {
            const av = AVATAR_COLORS[i % AVATAR_COLORS.length];
            const initials = c.name.split(' ').map(w=>w[0]).join('').slice(0,2);
            return (
              <div key={c.id} onClick={() => onNav('customer-detail', {customer: c})}
                style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
                  borderBottom: i<filtered.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',
                  cursor:'pointer'}}>
                <div style={{width:40,height:40,borderRadius:'50%',background:av.bg,
                  display:'flex',alignItems:'center',justifyContent:'center',
                  fontSize:13,fontWeight:700,color:av.color,flexShrink:0}}>
                  {initials}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:15,fontWeight:500,color:'#111',
                    letterSpacing:'-0.01em',marginBottom:2}}>{c.name}</div>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>
                    {c.jobs} job{c.jobs!==1?'s':''} · Last: {c.lastJob}
                  </div>
                </div>
                <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:4,flexShrink:0}}>
                  {c.unpaid && (
                    <div style={{fontSize:12,fontWeight:600,color:'#dc2626',
                      fontVariantNumeric:'tabular-nums'}}>{c.unpaid}</div>
                  )}
                  <div style={{color:'rgba(0,0,0,0.2)'}}>
                    <svg width="6" height="11" viewBox="0 0 7 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M1 1l5 5-5 5"/></svg>
                  </div>
                </div>
              </div>
            );
          })}
        </Card>
      )}
    </div>
  );
}

// ── CUSTOMER DETAIL ───────────────────────────────────────────
function CustomerDetailScreen({ onNav, params }) {
  const c = (params && params.customer) || { name:'Maria Ramos', company:'Ramos Residence', phone:'(415) 555-0192' };

  // Tier-2 overflow: new job, new estimate, new invoice, send custom SMS
  const overflow = (
    <OverflowMenu title="Customer overrides" items={[
      { label:'New job',          sub:'(manual)', onTap:()=>onNav('new-job', {customer: c}) },
      { label:'New estimate',     sub:'(manual)', onTap:()=>onNav('billing') },
      { label:'New invoice',      sub:'(manual)', onTap:()=>onNav('billing') },
      { label:'Send custom SMS',  sub:'(manual) — compose yourself' },
      { label:'Edit customer',    sub:'(manual)', onTap:()=>onNav('edit-customer', {customer: c}) },
    ]}/>
  );

  return (
    <div style={screenBg({paddingBottom:100})}>
      <NavHeader title={c.name} onBack="__back" action={overflow}/>
      {/* Contact hero */}
      <div style={{background:'white',padding:'14px 20px 16px',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:14}}>
          <Avatar name={c.name} size={42} color="#e8f2fd" textColor="#0071e3"/>
          <div>
            <div style={{fontSize:13,color:'rgba(0,0,0,0.4)'}}>{c.company}</div>
            <div style={{fontSize:13,color:'rgba(0,0,0,0.4)',marginTop:1}}>Customer since 2024</div>
          </div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <QuickTile icon={Icons.phone}   label="Call"       color="#0071e3" onTap={() => onNav('conversation-detail', {conversation:{kind:'call',name:c.name,id:'call-customer'}})}/>
          <QuickTile icon={Icons.message} label="Text"       color="#1a9e5c" onTap={() => onNav('belle', {prompt:'Text ' + c.name})}/>
          <QuickTile icon={Icons.map}     label="Directions" color="#d97706" onTap={() => onNav('schedule')}/>
          <QuickTile icon={Icons.dollar}  label="Invoice"    color="#7c3aed" onTap={() => onNav('billing')}/>
        </div>
      </div>

      <SectionHeader title="Contact Info"/>
      <Card>
        {[
          { label:'Phone',   value: c.phone || '—' },
          { label:'Email',   value: c.name.split(' ')[0].toLowerCase() + '@email.com' },
          { label:'Address', value:'104 Oakmont Ave, SF' },
        ].map((r,i,arr)=>(
          <div key={r.label} style={{padding:'13px 16px',display:'flex',justifyContent:'space-between',
            borderBottom: i<arr.length-1 ? '0.5px solid rgba(0,0,0,0.07)':'none'}}>
            <span style={{fontSize:14,color:'rgba(0,0,0,0.45)',fontWeight:500}}>{r.label}</span>
            <span style={{fontSize:14,color:'#0071e3'}}>{r.value}</span>
          </div>
        ))}
      </Card>

      <SectionHeader title="Job History" action="New job" onAction={() => onNav('belle', {prompt:`Book a new job for ${c.name}`})}/>
      <Card>
        {[
          { name:'Drain Clog — Kitchen', date:'Apr 21, 2026', amount:'$320', status:'in progress' },
          { name:'Shower Valve Replace',  date:'Nov 12, 2025', amount:'$480', status:'paid' },
          { name:'Water Softener Install',date:'Jun 8,  2025', amount:'$980', status:'paid' },
        ].map((j,i,arr)=>(
          <div key={j.name} onClick={() => onNav('job-detail')}
            style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<arr.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:14,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>{j.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.4)',marginTop:2}}>{j.date}</div>
            </div>
            <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:4}}>
              <span style={{fontSize:14,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums'}}>{j.amount}</span>
              <Badge status={j.status} small/>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── MORE MENU (in-tab screen, distinct from the MenuOverlay sheet) ─
function MoreScreen({ onNav, role, onRoleChange, belleOnline, onToggleBelle }) {
  // IA spec: More menu → Jobs, Customers, Billing, Conversations, Settings.
  // Technician fallback route is field-safe even if an older saved state opens this screen.
  const isTech = role === 'technician';
  const sections = isTech ? [
    {
      title: 'Field work',
      items: [
        { icon: Icons.home,     label:'Home',        screen:'home' },
        { icon: Icons.jobs,     label:'My Jobs',     screen:'jobs' },
        { icon: Icons.schedule, label:'My Schedule', screen:'schedule' },
        { icon: Icons.note,     label:'Belle handoff', screen:'handoff' },
      ]
    },
    {
      title: 'Report',
      items: [
        { icon: Icons.message,  label:'Job messages', screen:'conversations' },
        { icon: Icons.sparkle,  label:'Report scope / price issue', screen:'belle' },
      ]
    },
    {
      title: 'System',
      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="3"/><path d="M19.07 4.93l-1.41 1.41M5.93 5.93l-1.41-1.41M4 12H2M22 12h-2M19.07 19.07l-1.41-1.41M5.93 18.07l-1.41 1.41M12 22v-2M12 4V2"/></svg>, label:'Settings', screen:'settings' },
      ]
    },
  ] : [
    {
      title: 'Core',
      items: [
        { icon: Icons.home,     label:'Home',         screen:'home' },
        { icon: Icons.jobs,     label:'Jobs',         screen:'jobs' },
        { icon: Icons.user,     label:'Customers',    screen:'customers' },
        { icon: Icons.schedule, label:'Schedule',     screen:'schedule' },
      ]
    },
    {
      title: 'Money & Comms',
      items: [
        { icon: Icons.invoices, label:'Billing',       screen:'billing' },
        { icon: Icons.message,  label:'Conversations', screen:'conversations' },
      ]
    },
    {
      title: 'System',
      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="3"/><path d="M19.07 4.93l-1.41 1.41M5.93 5.93l-1.41-1.41M4 12H2M22 12h-2M19.07 19.07l-1.41-1.41M5.93 18.07l-1.41 1.41M12 22v-2M12 4V2"/></svg>, label:'Settings', screen:'settings' },
      ]
    },
  ];

  return (
    <div style={screenBg({paddingBottom:100})}>
      <NavHeader title="More" subtitle="Everything else"/>

      {/* Profile card */}
      <div style={{margin:'10px 16px 0',padding:'16px',borderRadius:24,background:'linear-gradient(145deg,rgba(15,23,42,0.98),rgba(49,46,129,0.94))',boxShadow:'0 14px 30px rgba(15,23,42,0.14)'}}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <div style={{width:52,height:52,borderRadius:'50%',
            background:'rgba(255,255,255,0.15)',
            border:'1.5px solid rgba(255,255,255,0.2)',
            display:'flex',alignItems:'center',justifyContent:'center',
            fontSize:18,fontWeight:700,color:'white'}}>
            {role==='owner-solo' ? 'JO' : (role==='owner' || role==='owner-team' || role==='dispatcher') ? 'JD' : 'ML'}
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:17,fontWeight:700,color:'white',letterSpacing:'-0.015em'}}>
              {role==='owner-solo' ? 'Jake Owner' : (role==='owner' || role==='owner-team' || role==='dispatcher') ? 'Jake Davidson' : 'Marcus Leal'}
            </div>
            <div style={{fontSize:13,color:'rgba(255,255,255,0.4)',marginTop:1}}>
              {role==='owner-solo' ? 'Solo Owner — Simple Pro Plumbing' : (role==='owner' || role==='owner-team' || role==='dispatcher') ? 'Team Owner — Simple Pro Plumbing' : 'Lead Plumber'}
            </div>
          </div>
          <div style={{height:26,padding:'0 10px',borderRadius:999,
            background:'rgba(255,255,255,0.12)',color:'rgba(255,255,255,0.7)',fontSize:11,fontWeight:600,
            display:'flex',alignItems:'center',textTransform:'capitalize'}}>{role}</div>
        </div>
      </div>

      {/* Visible role switcher for mobile preview */}
      <div style={{padding:'14px 20px 6px',fontSize:11,fontWeight:700,
        color:IOS.faint,letterSpacing:'0.07em',textTransform:'uppercase'}}>
        View as
      </div>
      <Card>
        <div style={{padding:'10px',display:'grid',gridTemplateColumns:'1fr',gap:8}}>
          {[
            { id:'technician', label:'Technician', sub:'Next job + schedule, no revenue' },
            { id:'owner-solo', label:'Solo Owner', sub:'Field workflow plus revenue' },
            { id:'owner-team', label:'Team Owner', sub:'Dispatch, team schedule, revenue' },
          ].map(opt => {
            const active = role === opt.id || (opt.id === 'owner-team' && (role === 'owner' || role === 'dispatcher'));
            return (
              <div key={opt.id} className="sp-pressable" onClick={() => { onRoleChange && onRoleChange(opt.id); onNav('home'); }}
                style={{padding:'12px 12px',borderRadius:16,border: active ? `1.5px solid ${IOS.blue}` : IOS.line,
                  background: active ? '#eef6ff' : 'rgba(255,255,255,0.74)',display:'flex',alignItems:'center',gap:11,cursor:'pointer'}}>
                <div style={{width:24,height:24,borderRadius:'50%',border: active ? 'none' : '1.5px solid rgba(0,0,0,0.18)',
                  background: active ? '#007aff' : 'white',display:'flex',alignItems:'center',justifyContent:'center',color:'white'}}>
                  {active && Icons.check}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:15,fontWeight:700,color:'#111',letterSpacing:'-0.014em'}}>{opt.label}</div>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.45)',marginTop:2}}>{opt.sub}</div>
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {sections.map(sec => (
        <div key={sec.title}>
          <div style={{padding:'14px 20px 6px',fontSize:11,fontWeight:700,
            color:IOS.faint,letterSpacing:'0.07em',textTransform:'uppercase'}}>
            {sec.title}
          </div>
          <Card>
            {sec.items.map((item, i) => (
              <div key={item.label} className="sp-row" onClick={() => onNav(item.screen)}
                style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:14,
                  borderBottom: i<sec.items.length-1?IOS.line:'none',cursor:'pointer'}}>
                <div style={{width:22,height:22,display:'flex',alignItems:'center',
                  justifyContent:'center',color:'rgba(0,0,0,0.5)',flexShrink:0}}>
                  {React.cloneElement(item.icon, {width:20,height:20})}
                </div>
                <div style={{flex:1,fontSize:16,fontWeight:400,color:'#111',letterSpacing:'-0.01em'}}>{item.label}</div>
                <div style={{color:'rgba(0,0,0,0.2)'}}>{Icons.chevronR}</div>
              </div>
            ))}
          </Card>
        </div>
      ))}

      {/* Belle-health dev toggle (spec: flip belleOnline from More for demo) */}
      {typeof onToggleBelle === 'function' && (
        <>
          <div style={{padding:'14px 20px 6px',fontSize:11,fontWeight:700,
            color:IOS.faint,letterSpacing:'0.07em',textTransform:'uppercase'}}>
            Demo controls
          </div>
          <Card>
            <div onClick={onToggleBelle}
              style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:14,cursor:'pointer'}}>
              <div style={{width:22,height:22,display:'flex',alignItems:'center',justifyContent:'center',
                fontSize:15,flexShrink:0}}>
                {belleOnline ? '🟢' : '🟡'}
              </div>
              <div style={{flex:1}}>
                <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>
                  Belle is {belleOnline ? 'online' : 'offline'}
                </div>
                <div style={{fontSize:12,color:'rgba(0,0,0,0.45)',marginTop:2}}>
                  Flip to preview manual-mode banner + CTA flips
                </div>
              </div>
              <div style={{width:42,height:24,borderRadius:12,
                background: belleOnline ? '#34c759' : '#e2e2e6',
                padding:'0 3px',display:'flex',alignItems:'center'}}>
                <div style={{width:18,height:18,borderRadius:'50%',background:'white',
                  transform: belleOnline ? 'translateX(18px)' : 'translateX(0)',
                  transition:'transform 0.2s',boxShadow:'0 1px 4px rgba(0,0,0,0.15)'}}/>
              </div>
            </div>
          </Card>
        </>
      )}
    </div>
  );
}

Object.assign(window, {
  BillingScreen, InvoiceDetailScreen, CustomersScreen, CustomerDetailScreen, MoreScreen,
  INVOICES_DATA,
});
