// Simple Pro Mobile — More menu, Invoices, Customer Detail, Team, Notifications
const { useState } = React;

// ── INVOICES ──────────────────────────────────────────────────
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:'unpaid',   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:'past due', date:'Apr 16', job:'Sewer Line Inspection' },
  { id:'INV-0105', client:'Torres LLC',       amount:'$890',   status:'approved', date:'Apr 14', job:'Gas Line Repair' },
  { id:'INV-0103', client:'Adams Home',       amount:'$420',   status:'paid',     date:'Apr 18', job:'Toilet Replacement' },
];

function InvoicesScreen({ onNav }) {
  const [filter, setFilter] = useState('All');
  const filters = ['All','Unpaid','Draft','Paid'];
  const filtered = filter==='All' ? INVOICES_DATA :
    filter==='Unpaid' ? INVOICES_DATA.filter(i => ['unpaid','past due'].includes(i.status)) :
    filter==='Draft'  ? INVOICES_DATA.filter(i => i.status==='draft') :
    INVOICES_DATA.filter(i => i.status==='paid');

  const unpaidTotal = INVOICES_DATA
    .filter(i=>['unpaid','past due'].includes(i.status))
    .reduce((s,i) => s + parseFloat(i.amount.replace(/[$,]/g,'')), 0);

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Invoices"
        action={
          <div onClick={() => onNav('belle', {prompt:'Create a new invoice'})}
            style={{width:34,height:34,borderRadius:'50%',background:'rgba(255,255,255,0.15)',
              border:'1px solid rgba(255,255,255,0.2)',
              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>
        }
      />

      {/* Unpaid summary */}
      <div style={{margin:'12px 16px 0',background:'#fef3e2',border:'1px solid rgba(217,119,6,0.2)',
        borderRadius:14,padding:'14px 16px',display:'flex',alignItems:'center',gap:12}}>
        <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:28,fontWeight:700,color:'#92520a',letterSpacing:'-0.025em',
            fontVariantNumeric:'tabular-nums'}}>${unpaidTotal.toLocaleString()}</div>
        </div>
        <div onClick={() => onNav('belle', {prompt:'Send invoice reminders'})}
          style={{height:36,padding:'0 14px',borderRadius:10,background:'#d97706',
            color:'white',border:'none',fontSize:13,fontWeight:600,cursor:'pointer',
            display:'flex',alignItems:'center'}}>
          Send reminders
        </div>
      </div>

      {/* Filter chips */}
      <div style={{display:'flex',gap:7,padding:'10px 16px 12px',overflowX:'auto',scrollbarWidth:'none'}}>
        {filters.map(f => (
          <div key={f} onClick={() => setFilter(f)}
            style={{flexShrink:0,height:31,padding:'0 13px',borderRadius:999,
              background: filter===f ? '#0071e3' : 'white',
              color: filter===f ? 'white' : 'rgba(0,0,0,0.6)',
              border: `1px solid ${filter===f ? '#0071e3' : 'rgba(0,0,0,0.1)'}`,
              fontSize:13,fontWeight: filter===f ? 600 : 400,
              display:'flex',alignItems:'center',cursor:'pointer'}}>
            {f}
          </div>
        ))}
      </div>

      <Card>
        {filtered.map((inv, i) => (
          <div key={inv.id} onClick={() => onNav('invoice-detail', {invoice: inv})}
            style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<filtered.length-1 ? '0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{width:38,height:38,borderRadius:10,
              background: inv.status==='paid' ? '#e6f7ef' : inv.status==='past due' ? '#fef2f2' : inv.status==='unpaid' ? '#fef3e2' : '#f3f4f6',
              display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={
                inv.status==='paid' ? '#1a9e5c' : inv.status==='past due' ? '#dc2626' : inv.status==='unpaid' ? '#d97706' : '#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'}}>{inv.client}</div>
                <div style={{fontSize:15,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums'}}>{inv.amount}</div>
              </div>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{inv.id} · {inv.date}</div>
                <Badge status={inv.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);

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:120}}>
      <NavHeader title={inv.id} onBack="__back"/>
      <div style={{background:'white',padding:'16px 20px 20px',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <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>
        {['unpaid','past due'].includes(inv.status) && (
          <PrimaryButton label="Record Payment" color="#1a9e5c" style={{marginTop:16}}
            onTap={() => setPayOpen(true)}/>
        )}
        {inv.status === 'draft' && (
          <div style={{display:'flex',gap:10,marginTop:16}}>
            <PrimaryButton label="Send Invoice" style={{flex:1}} onTap={() => {}}/>
            <SecondaryButton label="Edit" style={{flex:0.6}} onTap={() => {}}/>
          </div>
        )}
      </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'].map((method, i) => (
            <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"
        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 */}
      <Card>
        {filtered.length === 0 ? (
          <div style={{padding:'48px 20px',textAlign:'center',color:'rgba(0,0,0,0.3)'}}>
            <div style={{fontSize:15,fontWeight:500}}>No customers found</div>
          </div>
        ) : 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' };
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title={c.name} onBack="__back"/>
      {/* 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={() => {}}/>
          <QuickTile icon={Icons.message} label="Text"       color="#1a9e5c" onTap={() => onNav('belle', {prompt:'Text ' + c.name})}/>
          <QuickTile icon={Icons.map}     label="Directions" color="#d97706" onTap={() => {}}/>
          <QuickTile icon={Icons.dollar}  label="Invoice"    color="#7c3aed" onTap={() => onNav('invoices')}/>
        </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('new-job')}/>
      <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>
  );
}

// ── TEAM SCREEN ───────────────────────────────────────────────
const TEAM_DATA = [
  { name:'Marcus Leal',   role:'Plumber',          status:'in progress', job:'Drain Clog — Kitchen', avatar:'ML', color:'#e8f2fd', textColor:'#0071e3',  phone:'555-0192' },
  { name:'Dani Rodriguez',role:'Plumber',          status:'on my way',   job:'Full Bath Re-pipe',    avatar:'DR', color:'#f0fdf4', textColor:'#16a34a',  phone:'555-0241' },
  { name:'Jake Torres',   role:'Senior Plumber',   status:'scheduled',   job:'Leak Inspection',      avatar:'JT', color:'#fef3e2', textColor:'#d97706',  phone:'555-0317' },
  { name:'Sam Park',      role:'Apprentice',       status:'scheduled',   job:'—',                    avatar:'SP', color:'#f3f4f6', textColor:'#6b7280',  phone:'555-0408' },
];

function TeamScreen({ onNav }) {
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Team" onBack="__back"/>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,padding:'14px 16px 0'}}>
        <StatCard label="On the job" value="2" color="#1a9e5c" bg="#e6f7ef"/>
        <StatCard label="In transit" value="1" color="#d97706" bg="#fef3e2"/>
      </div>
      <SectionHeader title="Field Team"/>
      <Card>
        {TEAM_DATA.map((m,i) => (
          <div key={m.name}
            style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<TEAM_DATA.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.4)',marginTop:1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{m.role} · {m.job}</div>
            </div>
            <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:6}}>
              <Badge status={m.status} small/>
              <div onClick={() => {}}
                style={{width:28,height:28,borderRadius:'50%',background:'#e8f2fd',
                  display:'flex',alignItems:'center',justifyContent:'center',color:'#0071e3',cursor:'pointer'}}>
                {Icons.phone}
              </div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── NOTIFICATIONS ─────────────────────────────────────────────
const NOTIFS = [
  { id:1, type:'urgent',   icon:'⚠️', title:'Invoice overdue',         body:'Nguyen Group — $550 — 5 days overdue', time:'2m ago',  read:false },
  { id:2, type:'belle',    icon:'✦',  title:'Belle suggestion',         body:'Steinberg Corp job ready to invoice. Convert now?', time:'18m ago', read:false },
  { id:3, type:'job',      icon:'📍', title:'Jake arrived at job site',  body:'Full Bath Re-pipe — Steinberg Corp', time:'34m ago', read:true },
  { id:4, type:'payment',  icon:'💰', title:'Payment received',          body:'Chen Family paid $1,450 — Water Heater Install', time:'2h ago',  read:true },
  { id:5, type:'job',      icon:'✅', title:'Job completed',             body:'Water Heater Install — Chen Family — Marcus L.', time:'3h ago',  read:true },
];

function NotificationsScreen({ onNav }) {
  const [notifs, setNotifs] = useState(NOTIFS);
  function markRead(id) { setNotifs(notifs.map(n => n.id===id ? {...n,read:true} : n)); }
  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Notifications" onBack="__back"
        action={<span onClick={() => setNotifs(notifs.map(n=>({...n,read:true})))}
          style={{fontSize:14,color:'#0071e3',cursor:'pointer',fontWeight:400}}>Mark all read</span>}
      />
      <Card style={{marginTop:14}}>
        {notifs.map((n,i) => (
          <div key={n.id} onClick={() => markRead(n.id)}
            style={{padding:'13px 16px',display:'flex',gap:12,alignItems:'flex-start',
              background: n.read ? 'white' : '#f0f5ff',
              borderBottom: i<notifs.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
            <div style={{width:36,height:36,borderRadius:10,flexShrink:0,
              background: n.type==='urgent'?'#fef2f2':n.type==='belle'?'#f5f0ff':n.type==='payment'?'#e6f7ef':'#e8f2fd',
              display:'flex',alignItems:'center',justifyContent:'center',fontSize:16}}>
              {n.type==='belle'
                ? <svg width="14" height="14" viewBox="0 0 24 24" fill="#7c3aed"><path d="M12 2l2.09 6.26L20 9.27l-4.91 4.73 1.18 6.88L12 17.77l-6.27 3.11 1.18-6.88L2 9.27l5.91-1.01L12 2z"/></svg>
                : n.icon}
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:3}}>
                <span style={{fontSize:14,fontWeight: n.read ? 500 : 600,color:'#111',letterSpacing:'-0.008em'}}>{n.title}</span>
                <span style={{fontSize:11,color:'rgba(0,0,0,0.35)',flexShrink:0,marginLeft:8}}>{n.time}</span>
              </div>
              <div style={{fontSize:13,color:'rgba(0,0,0,0.5)',lineHeight:1.45}}>{n.body}</div>
            </div>
            {!n.read && <div style={{width:8,height:8,borderRadius:'50%',background:'#0071e3',flexShrink:0,marginTop:4}}/>}
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── MORE MENU ─────────────────────────────────────────────────
function MoreScreen({ onNav, role, onRoleChange }) {
  const sections = [
    {
      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: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>, label:'Reports', screen:'reports' },
        { 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: 'Communication',
      items: [
        { icon: Icons.message,  label:'Inbox',       screen:'messages' },
        { icon: Icons.phone,    label:'Calls',        screen:'calls' },
        { 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"/><polyline points="12 6 12 12 16 14"/></svg>, label:'Follow Ups', screen:'follow-ups' },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z"/></svg>, label:'Campaigns', screen:'campaigns' },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>, label:'Diagnose', screen:'belle' },
      ]
    },
    {
      title: 'More',
      items: [
        { icon: Icons.schedule, label:'Schedule',    screen:'schedule' },
        { icon: Icons.dollar,   label:'Estimates',   screen:'estimates' },
        { icon: Icons.invoices, label:'Invoices',    screen:'invoices' },
        { 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', screen:'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', screen:'settings-billing' },
        { icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>, label:'Dispatch', screen:'dispatch' },
      ]
    },
  ];

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="More"/>

      {/* Profile card */}
      <div style={{margin:'0 0 0',background:'#0f172a',
        padding:'16px 20px 20px',borderBottom:'none'}}>
        <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' ? 'JD' : role==='dispatcher' ? 'SA' : 'ML'}
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:17,fontWeight:700,color:'white',letterSpacing:'-0.015em'}}>
              {role==='owner' ? 'Jake Davidson' : role==='dispatcher' ? 'Sarah Admin' : 'Marcus Leal'}
            </div>
            <div style={{fontSize:13,color:'rgba(255,255,255,0.4)',marginTop:1}}>
              {role==='owner' ? 'Owner — Simple Pro Plumbing' : role==='dispatcher' ? 'Dispatcher' : '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>

      {sections.map(sec => (
        <div key={sec.title}>
          <div style={{padding:'14px 20px 6px',fontSize:11,fontWeight:700,
            color:'rgba(0,0,0,0.35)',letterSpacing:'0.07em',textTransform:'uppercase'}}>
            {sec.title}
          </div>
          <Card>
            {sec.items.map((item, i) => (
              <div key={item.label} onClick={() => onNav(item.screen)}
                style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:14,
                  borderBottom: i<sec.items.length-1?'0.5px solid rgba(0,0,0,0.07)':'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>
      ))}
    </div>
  );
}

// ── PAYMENTS RECEIVED ─────────────────────────────────────────
// Paid invoices log — separate from Settings > Payments (processor config)
const PAYMENTS_DATA = [
  { id:'PMT-4821', invoice:'INV-0112', client:'Chen Family',       amount:1450.00, method:'Card',      last4:'4242', date:'Today',       time:'2:14 PM',  daysAgo:0 },
  { id:'PMT-4820', invoice:'INV-0109', client:'Martinez Property', amount:640.00,  method:'ACH',       last4:'6789', date:'Today',       time:'11:42 AM', daysAgo:0 },
  { id:'PMT-4819', invoice:'INV-0108', client:'Lee & Sons',        amount:225.00,  method:'Apple Pay', last4:'—',    date:'Today',       time:'9:08 AM',  daysAgo:0 },
  { id:'PMT-4818', invoice:'INV-0107', client:'Riverside HOA',     amount:1280.00, method:'Check',     last4:'#1042',date:'Yesterday',   time:'4:31 PM',  daysAgo:1 },
  { id:'PMT-4817', invoice:'INV-0106', client:'Park Residence',    amount:385.00,  method:'Zelle',     last4:'—',    date:'Yesterday',   time:'10:12 AM', daysAgo:1 },
  { id:'PMT-4816', invoice:'INV-0105', client:'Greene Bakery',     amount:920.00,  method:'Card',      last4:'1881', date:'Apr 19',      time:'3:45 PM',  daysAgo:2 },
  { id:'PMT-4815', invoice:'INV-0104', client:'Kim Residence',     amount:450.00,  method:'Cash',      last4:'—',    date:'Apr 18',      time:'1:20 PM',  daysAgo:3 },
  { id:'PMT-4814', invoice:'INV-0103', client:'Emerald Dental',    amount:2140.00, method:'ACH',       last4:'3344', date:'Apr 17',      time:'11:05 AM', daysAgo:4 },
  { id:'PMT-4813', invoice:'INV-0102', client:'Thompson House',    amount:175.00,  method:'Venmo',     last4:'—',    date:'Apr 16',      time:'5:50 PM',  daysAgo:5 },
  { id:'PMT-4812', invoice:'INV-0101', client:'Blue Wave Cafe',    amount:680.00,  method:'Card',      last4:'0029', date:'Apr 15',      time:'2:12 PM',  daysAgo:6 },
  { id:'PMT-4811', invoice:'INV-0100', client:'Oakwood Mgmt',      amount:1820.00, method:'ACH',       last4:'8821', date:'Apr 12',      time:'10:30 AM', daysAgo:9 },
  { id:'PMT-4810', invoice:'INV-0099', client:'Silver Creek',      amount:540.00,  method:'Card',      last4:'4242', date:'Apr 10',      time:'3:22 PM',  daysAgo:11 },
  { id:'PMT-4809', invoice:'INV-0098', client:'Martinez Property', amount:320.00,  method:'Check',     last4:'#0877',date:'Apr 8',       time:'9:44 AM',  daysAgo:13 },
  { id:'PMT-4808', invoice:'INV-0097', client:'Chen Family',       amount:260.00,  method:'Apple Pay', last4:'—',    date:'Apr 5',       time:'11:12 AM', daysAgo:16 },
  { id:'PMT-4807', invoice:'INV-0096', client:'Ramos Residence',   amount:890.00,  method:'Card',      last4:'1881', date:'Apr 2',       time:'4:08 PM',  daysAgo:19 },
  { id:'PMT-4806', invoice:'INV-0095', client:'Harbor Vista',      amount:1560.00, method:'ACH',       last4:'2200', date:'Mar 28',      time:'2:41 PM',  daysAgo:24 },
  { id:'PMT-4805', invoice:'INV-0094', client:'Park Residence',    amount:410.00,  method:'Zelle',     last4:'—',    date:'Mar 24',      time:'10:18 AM', daysAgo:28 },
];

const METHOD_COLORS = {
  'Card':      { bg:'#e8f2fd', fg:'#0071e3' },
  'ACH':       { bg:'#eef2ff', fg:'#4f46e5' },
  'Apple Pay': { bg:'#f1f5f9', fg:'#0f172a' },
  'Check':     { bg:'#fef3e2', fg:'#b45309' },
  'Cash':      { bg:'#ecfdf5', fg:'#059669' },
  'Zelle':     { bg:'#f5f0ff', fg:'#7c3aed' },
  'Venmo':     { bg:'#eff9ff', fg:'#0284c7' },
  'PayPal':    { bg:'#eff6ff', fg:'#1d4ed8' },
};

function PaymentsScreen({ onNav }) {
  const [period, setPeriod] = useState('Week');
  const periods = ['Today','Week','Month','Quarter','All'];
  const periodDays = { 'Today':0, 'Week':7, 'Month':30, 'Quarter':90, 'All':9999 };
  const cutoff = periodDays[period];
  const filtered = PAYMENTS_DATA.filter(p => period==='Today' ? p.daysAgo===0 : p.daysAgo < cutoff);

  const total = filtered.reduce((s,p) => s + p.amount, 0);
  const count = filtered.length;
  const avg = count ? total/count : 0;

  // Method breakdown
  const byMethod = {};
  filtered.forEach(p => { byMethod[p.method] = (byMethod[p.method]||0) + p.amount; });
  const methodBars = Object.entries(byMethod).sort((a,b)=>b[1]-a[1]);
  const methodMax = methodBars.reduce((m,x)=>Math.max(m,x[1]),0) || 1;

  // Sparkline — last 14 days
  const spark = Array.from({length:14},(_,i)=>{
    const d = 13-i;
    return PAYMENTS_DATA.filter(p=>p.daysAgo===d).reduce((s,p)=>s+p.amount,0);
  });
  const sparkMax = Math.max(...spark, 1);

  // Group payments by date label
  const groups = {};
  filtered.forEach(p => { (groups[p.date] = groups[p.date] || []).push(p); });

  const fmtCurrency = (n) => '$' + n.toLocaleString(undefined,{minimumFractionDigits:n<100?2:0, maximumFractionDigits:2});

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Payments" onBack="__back"
        action={<div onClick={()=>alert('Exporting payment log…')}
          style={{fontSize:14,color:'#0071e3',fontWeight:500,cursor:'pointer'}}>Export</div>}/>

      {/* Period pills */}
      <div style={{display:'flex',gap:6,padding:'12px 16px 4px',overflowX:'auto'}}>
        {periods.map(p => (
          <div key={p} onClick={()=>setPeriod(p)}
            style={{padding:'7px 14px',borderRadius:999,fontSize:13,fontWeight:500,whiteSpace:'nowrap',
              background: period===p ? '#0f172a' : 'white',
              color: period===p ? 'white' : '#111',
              border: period===p ? 'none' : '0.5px solid rgba(0,0,0,0.1)',
              cursor:'pointer'}}>{p}</div>
        ))}
      </div>

      {/* Hero: total + sparkline */}
      <div style={{margin:'12px 16px',background:'white',borderRadius:16,padding:'20px 20px 18px',border:'0.5px solid rgba(0,0,0,0.06)'}}>
        <div style={{fontSize:11,fontWeight:600,color:'rgba(0,0,0,0.45)',letterSpacing:'0.05em',textTransform:'uppercase'}}>Received · {period}</div>
        <div style={{fontSize:34,fontWeight:700,color:'#111',letterSpacing:'-0.028em',marginTop:4}}>{fmtCurrency(total)}</div>
        <div style={{fontSize:13,color:'rgba(0,0,0,0.55)',marginTop:2}}>
          <span style={{color:'#16a34a',fontWeight:600}}>{count}</span> payments · avg {fmtCurrency(avg)}
        </div>
        {/* Sparkline */}
        <div style={{display:'flex',alignItems:'flex-end',gap:3,height:54,marginTop:14}}>
          {spark.map((v,i)=>(
            <div key={i} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'flex-end'}}>
              <div style={{width:'100%',height: Math.max(2, (v/sparkMax)*48),background: v>0?'#0071e3':'rgba(0,0,0,0.06)',borderRadius:3}}/>
            </div>
          ))}
        </div>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'rgba(0,0,0,0.35)',marginTop:6,fontWeight:500,letterSpacing:'0.03em'}}>
          <span>14 DAYS AGO</span><span>TODAY</span>
        </div>
      </div>

      {/* Method breakdown */}
      {methodBars.length>0 && <>
        <SectionHeader title="By method"/>
        <Card>
          <div style={{padding:'14px 16px',display:'flex',flexDirection:'column',gap:12}}>
            {methodBars.map(([m,v])=>{
              const c = METHOD_COLORS[m] || METHOD_COLORS['Card'];
              return (
                <div key={m}>
                  <div style={{display:'flex',justifyContent:'space-between',marginBottom:5}}>
                    <span style={{fontSize:13,fontWeight:500,color:'#111'}}>{m}</span>
                    <span style={{fontSize:13,color:'rgba(0,0,0,0.55)',fontVariantNumeric:'tabular-nums'}}>{fmtCurrency(v)}</span>
                  </div>
                  <div style={{height:6,borderRadius:3,background:'rgba(0,0,0,0.05)',overflow:'hidden'}}>
                    <div style={{height:'100%',width:((v/methodMax)*100)+'%',background:c.fg,borderRadius:3}}/>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </>}

      {/* Payments list, grouped by date */}
      {Object.entries(groups).map(([date, pmts]) => {
        const dayTotal = pmts.reduce((s,p)=>s+p.amount,0);
        return (
          <div key={date}>
            <div style={{padding:'18px 20px 6px',display:'flex',justifyContent:'space-between',alignItems:'flex-end'}}>
              <div style={{fontSize:11,fontWeight:700,color:'rgba(0,0,0,0.5)',letterSpacing:'0.06em'}}>{date.toUpperCase()}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.45)',fontVariantNumeric:'tabular-nums',fontWeight:500}}>{fmtCurrency(dayTotal)}</div>
            </div>
            <Card>
              {pmts.map((p,i)=>{
                const c = METHOD_COLORS[p.method] || METHOD_COLORS['Card'];
                return (
                  <div key={p.id} onClick={()=>onNav('invoice-detail',{invoice:{id:p.invoice, client:p.client, amount:'$'+p.amount.toFixed(2), status:'paid', date:p.date, job:'—'}})}
                    style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
                      borderBottom:i<pmts.length-1?'0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
                    <div style={{width:36,height:36,borderRadius:10,background:c.bg,color:c.fg,display:'flex',alignItems:'center',justifyContent:'center',fontSize:10,fontWeight:700,letterSpacing:'0.04em',flexShrink:0}}>
                      {p.method==='Card'?'CARD':p.method==='Apple Pay'?'APAY':p.method.slice(0,4).toUpperCase()}
                    </div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:14.5,fontWeight:500,color:'#111',letterSpacing:'-0.008em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.client}</div>
                      <div style={{fontSize:12,color:'rgba(0,0,0,0.5)',marginTop:1,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                        {p.invoice} · {p.method}{p.last4!=='—'?` ···· ${p.last4}`:''} · {p.time}
                      </div>
                    </div>
                    <div style={{textAlign:'right',flexShrink:0}}>
                      <div style={{fontSize:15,fontWeight:600,color:'#16a34a',fontVariantNumeric:'tabular-nums',letterSpacing:'-0.01em'}}>+{fmtCurrency(p.amount)}</div>
                    </div>
                  </div>
                );
              })}
            </Card>
          </div>
        );
      })}
      {count===0 && (
        <div style={{padding:'40px 20px',textAlign:'center'}}>
          <div style={{fontSize:15,color:'rgba(0,0,0,0.45)'}}>No payments in this period</div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { InvoicesScreen, InvoiceDetailScreen, CustomersScreen, CustomerDetailScreen, TeamScreen, NotificationsScreen, MoreScreen, PaymentsScreen });
