// Simple Pro Mobile — Extra screens: Messages, Estimates, Calls, Reports, Dispatch, FollowUps
const { useState } = React;

// ── MESSAGES ──────────────────────────────────────────────────
const THREADS = [
  { id:1, name:'Maria Ramos',      preview:'Got it, see you at 11:30!',              time:'10:42 AM', unread:1, avatar:'MR', color:'#e8f2fd', tc:'#0071e3' },
  { id:2, name:'Steinberg Corp',   preview:'The crew can access through the back.', time:'9:15 AM',  unread:0, avatar:'SC', color:'#e6f7ef', tc:'#1a9e5c' },
  { id:3, name:'Chen Family',      preview:'Thank you! Payment sent.',               time:'Yesterday',unread:0, avatar:'CF', color:'#fef3e2', tc:'#d97706' },
  { id:4, name:'Jake Torres',      preview:'On my way to Steinberg now.',            time:'Yesterday',unread:0, avatar:'JT', color:'#f3f4f6', tc:'#6b7280' },
  { id:5, name:'Nguyen Group',     preview:'Can we reschedule to Friday?',           time:'Apr 19',   unread:2, avatar:'NG', color:'#fef2f2', tc:'#dc2626' },
  { id:6, name:'Park Residence',   preview:'Confirmed for Tuesday at 10 AM.',        time:'Apr 18',   unread:0, avatar:'PR', color:'#f5f0ff', tc:'#7c3aed' },
];

const THREAD_MESSAGES = [
  { from:'customer', text:"Hi, just confirming the appointment for today at 11:30?", time:'10:28 AM' },
  { from:'me',       text:"Yes! I'll be there around 11:30. See you then.", time:'10:31 AM' },
  { from:'customer', text:"Got it, see you at 11:30!", time:'10:42 AM' },
];

function MessagesScreen({ onNav }) {
  const [activeThread, setActiveThread] = useState(null);
  const [draft, setDraft] = useState('');

  if (activeThread) {
    return (
      <div style={{background:'#f5f5f7',minHeight:'100%',display:'flex',flexDirection:'column'}}>
        <NavHeader title={activeThread.name} onBack={() => setActiveThread(null)} backLabel="Messages"
          action={
            <div style={{display:'flex',gap:8}}>
              <div onClick={() => {}} style={{width:32,height:32,borderRadius:'50%',background:'rgba(255,255,255,0.12)',
                display:'flex',alignItems:'center',justifyContent:'center',color:'rgba(255,255,255,0.7)',cursor:'pointer'}}>
                {Icons.phone}
              </div>
            </div>
          }
        />
        <div style={{flex:1,overflowY:'auto',padding:'12px 16px',display:'flex',flexDirection:'column',gap:10}}>
          {THREAD_MESSAGES.map((m,i) => (
            <div key={i} style={{display:'flex',justifyContent: m.from==='me' ? 'flex-end':'flex-start'}}>
              <div style={{
                maxWidth:'78%', padding:'9px 13px',
                borderRadius: m.from==='me' ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                background: m.from==='me' ? '#0071e3' : 'white',
                color: m.from==='me' ? 'white' : '#111',
                fontSize:14, lineHeight:1.5, letterSpacing:'-0.005em',
                boxShadow: m.from==='me' ? 'none' : '0 1px 3px rgba(0,0,0,0.07)',
              }}>
                {m.text}
                <div style={{fontSize:10,color: m.from==='me' ? 'rgba(255,255,255,0.55)':'rgba(0,0,0,0.3)',
                  marginTop:4,textAlign:'right'}}>{m.time}</div>
              </div>
            </div>
          ))}
        </div>
        {/* Belle suggest strip */}
        <div style={{margin:'0 12px 8px',background:'#f5f0ff',borderRadius:10,padding:'8px 12px',
          display:'flex',alignItems:'center',gap:8,border:'0.5px solid rgba(124,58,237,0.15)'}}>
          <div style={{width:18,height:18,borderRadius:'50%',background:'linear-gradient(135deg,#7c3aed,#4f46e5)',
            display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
            <svg width="8" height="8" viewBox="0 0 24 24" fill="white"><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>
          </div>
          <div style={{fontSize:12,color:'#4c1d95',flex:1}}>Suggest: "I'm on my way, see you at 11:30"</div>
          <div onClick={() => setDraft("I'm on my way, see you at 11:30!")}
            style={{fontSize:12,fontWeight:600,color:'#7c3aed',cursor:'pointer'}}>Use</div>
        </div>
        {/* Input */}
        <div style={{padding:'8px 12px 28px',background:'white',borderTop:'0.5px solid rgba(0,0,0,0.08)',
          display:'flex',gap:8,alignItems:'flex-end'}}>
          <div style={{flex:1,minHeight:36,background:'#f2f2f4',borderRadius:18,
            display:'flex',alignItems:'center',padding:'0 13px'}}>
            <input value={draft} onChange={e=>setDraft(e.target.value)}
              placeholder="Message…"
              style={{flex:1,border:'none',background:'transparent',fontSize:14,color:'#111',
                outline:'none',fontFamily:'inherit'}}/>
          </div>
          <div onClick={() => setDraft('')}
            style={{width:36,height:36,borderRadius:'50%',
              background: draft.trim() ? '#0071e3' : '#e2e2e6',
              display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',flexShrink:0}}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill={draft.trim()?'white':'#999'} stroke="none">
              <line x1="22" y1="2" x2="11" y2="13" stroke={draft.trim()?'white':'#999'} strokeWidth="2" fill="none"/>
              <polygon points="22 2 15 22 11 13 2 9 22 2" fill={draft.trim()?'white':'#999'}/>
            </svg>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Messages"
        action={
          <div onClick={() => onNav('belle', {prompt:'Compose a new message'})}
            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>
        }
      />
      <div style={{padding:'10px 16px 4px'}}>
        <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>
          <span style={{fontSize:14,color:'rgba(0,0,0,0.3)'}}>Search messages…</span>
        </div>
      </div>
      <Card style={{marginTop:10}}>
        {THREADS.map((t,i) => (
          <div key={t.id} onClick={() => setActiveThread(t)}
            style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<THREADS.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',cursor:'pointer'}}>
            <div style={{position:'relative',flexShrink:0}}>
              <div style={{width:42,height:42,borderRadius:'50%',background:t.color,
                display:'flex',alignItems:'center',justifyContent:'center',
                fontSize:13,fontWeight:700,color:t.tc}}>{t.avatar}</div>
              {t.unread > 0 && (
                <div style={{position:'absolute',top:-2,right:-2,width:16,height:16,borderRadius:'50%',
                  background:'#0071e3',display:'flex',alignItems:'center',justifyContent:'center',
                  fontSize:10,fontWeight:700,color:'white',border:'1.5px solid #f5f5f7'}}>{t.unread}</div>
              )}
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:2}}>
                <span style={{fontSize:14,fontWeight: t.unread ? 700 : 500,color:'#111',letterSpacing:'-0.01em'}}>{t.name}</span>
                <span style={{fontSize:11,color:'rgba(0,0,0,0.3)',flexShrink:0,marginLeft:8}}>{t.time}</span>
              </div>
              <div style={{fontSize:13,color:'rgba(0,0,0,0.4)',whiteSpace:'nowrap',overflow:'hidden',
                textOverflow:'ellipsis',letterSpacing:'-0.005em'}}>{t.preview}</div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── ESTIMATES ─────────────────────────────────────────────────
const ESTIMATES_DATA = [
  { id:'EST-0098', client:'Nguyen Group',    amount:'$550',   status:'approved', date:'Apr 20', job:'Sewer Line Inspection' },
  { id:'EST-0097', client:'Torres LLC',      amount:'$890',   status:'draft',    date:'Apr 19', job:'Gas Line Repair' },
  { id:'EST-0096', client:'Park Residence',  amount:'$180',   status:'approved', date:'Apr 17', job:'Backflow Preventer Test' },
  { id:'EST-0095', client:'Adams Home',      amount:'$420',   status:'approved', date:'Apr 16', job:'Toilet Replacement' },
  { id:'EST-0094', client:'Steinberg Corp',  amount:'$2,800', status:'draft',    date:'Apr 14', job:'Full Bath Re-pipe' },
  { id:'EST-0093', client:'Chen Family',     amount:'$1,450', status:'approved', date:'Apr 10', job:'Water Heater Install' },
];

function EstimatesScreen({ onNav }) {
  const [filter, setFilter] = useState('All');
  const filtered = filter==='All' ? ESTIMATES_DATA :
    filter==='Draft' ? ESTIMATES_DATA.filter(e=>e.status==='draft') :
    ESTIMATES_DATA.filter(e=>e.status==='approved');

  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Estimates"
        action={
          <div onClick={() => onNav('belle', {prompt:'Create a new estimate'})}
            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>
        }
      />
      <div style={{display:'flex',gap:7,padding:'10px 16px 12px',overflowX:'auto',scrollbarWidth:'none'}}>
        {['All','Draft','Approved'].map(f => (
          <div key={f} onClick={() => setFilter(f)}
            style={{flexShrink:0,height:30,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((est,i) => (
          <div key={est.id} onClick={() => onNav('estimate-detail', {estimate: est})}
            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:38,height:38,borderRadius:10,flexShrink:0,
              background: est.status==='approved' ? '#e6f7ef' : '#f3f4f6',
              display:'flex',alignItems:'center',justifyContent:'center'}}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
                stroke={est.status==='approved' ? '#1a9e5c' : '#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',marginBottom:3}}>
                <span style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>{est.client}</span>
                <span style={{fontSize:15,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums'}}>{est.amount}</span>
              </div>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                <span style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{est.id} · {est.date}</span>
                <Badge status={est.status} small/>
              </div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

function EstimateDetailScreen({ onNav, params }) {
  const est = (params && params.estimate) || ESTIMATES_DATA[0];
  const [converted, setConverted] = useState(false);

  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:120}}>
      <NavHeader title={est.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'}}>{est.amount}</div>
            <div style={{fontSize:13,color:'rgba(0,0,0,0.4)',marginTop:2}}>{est.client} · {est.date}</div>
          </div>
          <Badge status={converted ? 'paid' : est.status}/>
        </div>
        {!converted && est.status==='approved' && (
          <PrimaryButton label="Convert to Invoice" color="#1a9e5c" style={{marginTop:16}}
            onTap={() => setConverted(true)}/>
        )}
        {converted && (
          <div style={{height:52,borderRadius:13,background:'#e6f7ef',display:'flex',alignItems:'center',
            justifyContent:'center',gap:8,color:'#1a9e5c',fontSize:15,fontWeight:600,marginTop:16}}>
            {Icons.check} Invoice Created
          </div>
        )}
        {est.status==='draft' && (
          <div style={{display:'flex',gap:10,marginTop:16}}>
            <PrimaryButton label="Send Estimate" style={{flex:1}} onTap={() => {}}/>
            <SecondaryButton label="Edit" style={{flex:0.6}} onTap={() => {}}/>
          </div>
        )}
      </div>
      <SectionHeader title="Line Items"/>
      <Card>
        {[
          { desc:'Labor — ' + est.job, qty:'3 hrs', rate:'$95/hr', total: '$285' },
          { desc:'Materials',           qty:'—',     rate:'—',      total: est.status==='approved' ? '$165' : '$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.06)':'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}}>Total</span>
          <span style={{fontSize:15,fontWeight:700,fontVariantNumeric:'tabular-nums'}}>{est.amount}</span>
        </div>
      </Card>
      <SectionHeader title="Diagnose with Belle"/>
      <Card>
        <ListCell
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>}
          iconBg="#f5f0ff" title="Run AI Diagnosis"
          subtitle="Let Belle analyze the job and suggest line items"
          onTap={() => onNav('belle', {prompt:'Diagnose job for ' + est.client + ' and suggest estimate items'})}
          isLast
        />
      </Card>
    </div>
  );
}

// ── CALLS ─────────────────────────────────────────────────────
const CALLS_DATA = [
  { id:1, name:'Maria Ramos',    type:'inbound',  duration:'3:42', time:'10:28 AM', status:'answered',  job:'Drain Clog — Kitchen', phone:'(415) 555-0192' },
  { id:2, name:'Steinberg Corp', type:'outbound', duration:'1:15', time:'9:02 AM',  status:'answered',  job:'Full Bath Re-pipe',    phone:'(415) 555-0271' },
  { id:3, name:'Unknown',        type:'inbound',  duration:'—',    time:'8:44 AM',  status:'missed',    job:null,                   phone:'(415) 555-0918' },
  { id:4, name:'Nguyen Group',   type:'outbound', duration:'0:32', time:'Yesterday',status:'voicemail', job:'Sewer Inspection',     phone:'(415) 555-0445' },
  { id:5, name:'Chen Family',    type:'inbound',  duration:'5:11', time:'Yesterday',status:'answered',  job:'Water Heater Install', phone:'(415) 555-0388' },
];

function CallsScreen({ onNav }) {
  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Calls" onBack="__back"/>
      <BelleSuggestion
        text="You missed a call from (415) 555-0918 at 8:44 AM. Want me to look them up or send a text?"
        actions={['Look up caller', 'Send text']}
        onAction={a => onNav('belle', {prompt: a + ' for missed call'})}
      />
      <SectionHeader title="Today's Calls"/>
      <Card>
        {CALLS_DATA.map((c,i) => (
          <div key={c.id} style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
            borderBottom: i<CALLS_DATA.length-1?'0.5px solid rgba(0,0,0,0.06)':'none'}}>
            <div style={{width:38,height:38,borderRadius:10,flexShrink:0,
              background: c.status==='missed' ? '#fef2f2' : c.type==='inbound' ? '#e8f2fd' : '#e6f7ef',
              display:'flex',alignItems:'center',justifyContent:'center'}}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
                stroke={c.status==='missed'?'#dc2626':c.type==='inbound'?'#0071e3':'#1a9e5c'}
                strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.7 10.74 19.79 19.79 0 01.67 2.18 2 2 0 012.65 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.91 7.6a16 16 0 006.29 6.29l.97-1.97a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/>
              </svg>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:2}}>
                <span style={{fontSize:14,fontWeight:500,color: c.status==='missed'?'#dc2626':'#111',
                  letterSpacing:'-0.008em'}}>{c.name}</span>
                <span style={{fontSize:11,color:'rgba(0,0,0,0.35)'}}>{c.time}</span>
              </div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>
                {c.status==='missed' ? '⚠ Missed call' : c.type==='inbound'?'↙ Inbound':'↗ Outbound'} · {c.duration}
                {c.job && ` · ${c.job}`}
              </div>
            </div>
            <div onClick={() => {}}
              style={{width:32,height:32,borderRadius:'50%',background:'#e8f2fd',
                display:'flex',alignItems:'center',justifyContent:'center',
                color:'#0071e3',cursor:'pointer',flexShrink:0}}>
              {Icons.phone}
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── REPORTS ───────────────────────────────────────────────────
function ReportsScreen({ onNav }) {
  const periods = ['This week','This month','Last 30 days','YTD'];
  const [period, setPeriod] = useState('This month');
  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Reports" onBack="__back"/>
      {/* Period selector */}
      <div style={{display:'flex',gap:7,padding:'10px 16px 4px',overflowX:'auto',scrollbarWidth:'none'}}>
        {periods.map(p => (
          <div key={p} onClick={() => setPeriod(p)}
            style={{flexShrink:0,height:30,padding:'0 12px',borderRadius:999,
              background: period===p ? '#0071e3' : 'white',
              color: period===p ? 'white' : 'rgba(0,0,0,0.55)',
              border: `1px solid ${period===p ? '#0071e3' : 'rgba(0,0,0,0.1)'}`,
              fontSize:12,fontWeight: period===p ? 600 : 400,
              display:'flex',alignItems:'center',cursor:'pointer'}}>
            {p}
          </div>
        ))}
      </div>
      {/* Revenue hero */}
      <div style={{margin:'12px 16px 0',background:'#0f172a',borderRadius:16,padding:'18px 20px'}}>
        <div style={{fontSize:11,fontWeight:600,color:'rgba(255,255,255,0.38)',
          letterSpacing:'0.06em',textTransform:'uppercase',marginBottom:6}}>Total Revenue · {period}</div>
        <div style={{fontSize:34,fontWeight:700,color:'white',letterSpacing:'-0.03em',
          fontVariantNumeric:'tabular-nums',marginBottom:4}}>$18,240</div>
        <div style={{display:'flex',alignItems:'center',gap:5}}>
          <div style={{fontSize:13,color:'#34d399',fontWeight:600}}>↑ 12%</div>
          <div style={{fontSize:13,color:'rgba(255,255,255,0.4)'}}>vs previous period</div>
        </div>
      </div>
      {/* KPI grid */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,padding:'12px 16px 0'}}>
        <StatCard label="Jobs Completed" value="24"    color="#0071e3" bg="#e8f2fd"/>
        <StatCard label="Avg Job Value"  value="$760"  color="#1a9e5c" bg="#e6f7ef"/>
        <StatCard label="Invoices Sent"  value="22"    color="#7c3aed" bg="#f5f0ff"/>
        <StatCard label="Collection Rate"value="94%"   color="#d97706" bg="#fef3e2"/>
      </div>
      {/* Belle insight */}
      <BelleSuggestion
        text="Drain cleaning jobs have the highest margin this month at 68%. You have 3 follow-ups pending that could convert."
        actions={['View follow-ups', 'Dismiss']}
        onAction={a => { if(a!=='Dismiss') onNav('follow-ups'); }}
      />
      {/* Top jobs */}
      <SectionHeader title="Top Jobs" action="See all" onAction={() => onNav('jobs')}/>
      <Card>
        {[
          {name:'Full Bath Re-pipe', client:'Steinberg Corp', amount:'$2,800'},
          {name:'Water Heater Install', client:'Chen Family', amount:'$1,450'},
          {name:'Gas Line Repair', client:'Torres LLC', amount:'$890'},
        ].map((j,i,arr) => (
          <div key={j.name} style={{padding:'12px 16px',display:'flex',justifyContent:'space-between',
            alignItems:'center',borderBottom: i<arr.length-1?'0.5px solid rgba(0,0,0,0.06)':'none'}}>
            <div>
              <div style={{fontSize:14,fontWeight:500,color:'#111',marginBottom:2}}>{j.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{j.client}</div>
            </div>
            <div style={{fontSize:15,fontWeight:700,color:'#1a9e5c',fontVariantNumeric:'tabular-nums'}}>{j.amount}</div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ── DISPATCH ──────────────────────────────────────────────────
const DISPATCH_JOBS = [
  { id:1, name:'Drain Clog — Kitchen', client:'Ramos Residence', time:'11:30 AM', tech:'Marcus L.', status:'in progress', urgent:false },
  { id:2, name:'Full Bath Re-pipe',    client:'Steinberg Corp',  time:'2:00 PM',  tech:'Jake T.',  status:'scheduled',   urgent:false },
  { id:3, name:'Leak Inspection',      client:'Nguyen Group',    time:'5:30 PM',  tech:null,       status:'unassigned',  urgent:true },
  { id:4, name:'Gas Line Repair',      client:'Torres LLC',      time:'TBD',      tech:null,       status:'unscheduled', urgent:false },
];
const DISPATCH_TEAM = [
  { name:'Marcus L.', status:'in progress', job:'Drain Clog',        avatar:'ML', color:'#e8f2fd', tc:'#0071e3' },
  { name:'Jake T.',   status:'scheduled',   job:'En route to Steinberg', avatar:'JT', color:'#e6f7ef', tc:'#1a9e5c' },
  { name:'Dani R.',   status:'available',   job:'No job assigned',    avatar:'DR', color:'#f3f4f6', tc:'#6b7280' },
  { name:'Sam P.',    status:'available',   job:'No job assigned',    avatar:'SP', color:'#f3f4f6', tc:'#6b7280' },
];

function DispatchScreen({ onNav }) {
  const [assignOpen, setAssignOpen] = useState(null);
  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Dispatch" onBack="__back"/>

      {/* Urgent alert */}
      <div onClick={() => setAssignOpen(DISPATCH_JOBS[2])}
        style={{margin:'12px 16px 0',background:'#fef2f2',border:'1px solid rgba(220,38,38,0.15)',
          borderRadius:12,padding:'12px 14px',display:'flex',alignItems:'center',gap:10,cursor:'pointer'}}>
        <div style={{width:30,height:30,borderRadius:8,background:'#dc2626',
          display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,color:'white'}}>
          {Icons.warning}
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:13,fontWeight:700,color:'#991b1b'}}>Unassigned job at 5:30 PM</div>
          <div style={{fontSize:12,color:'rgba(153,27,27,0.65)'}}>Leak Inspection · Nguyen Group · needs a tech</div>
        </div>
        <div style={{color:'rgba(153,27,27,0.3)'}}>{Icons.chevronR}</div>
      </div>

      {/* Team status */}
      <SectionHeader title="Team Status"/>
      <Card>
        {DISPATCH_TEAM.map((m,i) => (
          <div key={m.name} style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
            borderBottom: i<DISPATCH_TEAM.length-1?'0.5px solid rgba(0,0,0,0.06)':'none'}}>
            <div style={{width:38,height:38,borderRadius:'50%',background:m.color,
              display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:12,fontWeight:700,color:m.tc,flexShrink:0}}>{m.avatar}</div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:14,fontWeight:500,color:'#111',letterSpacing:'-0.008em'}}>{m.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.4)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{m.job}</div>
            </div>
            <Badge status={m.status==='available'?'scheduled':m.status} small/>
          </div>
        ))}
      </Card>

      {/* Job board */}
      <SectionHeader title="Today's Jobs" action="Add job" onAction={() => onNav('new-job')}/>
      <Card>
        {DISPATCH_JOBS.map((j,i) => (
          <div key={j.id} onClick={() => j.tech ? onNav('job-detail') : setAssignOpen(j)}
            style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<DISPATCH_JOBS.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',cursor:'pointer',
              background: j.urgent ? '#fffbf0' : 'white'}}>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:14,fontWeight:500,color:'#111',letterSpacing:'-0.008em',marginBottom:2}}>{j.name}</div>
              <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>
                {j.client} · {j.time} · {j.tech || '⚠ Unassigned'}
              </div>
            </div>
            <Badge status={j.status==='unassigned'?'urgent':j.status==='unscheduled'?'draft':j.status} small/>
          </div>
        ))}
      </Card>

      {/* Assign sheet */}
      <BottomSheet open={!!assignOpen} onClose={() => setAssignOpen(null)}
        title={assignOpen ? 'Assign: ' + assignOpen.name : 'Assign'}>
        <div style={{padding:'12px 16px'}}>
          {DISPATCH_TEAM.map((m,i) => (
            <div key={m.name} onClick={() => setAssignOpen(null)}
              style={{display:'flex',alignItems:'center',gap:12,padding:'11px 0',
                borderBottom: i<DISPATCH_TEAM.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',cursor:'pointer'}}>
              <div style={{width:36,height:36,borderRadius:'50%',background:m.color,
                display:'flex',alignItems:'center',justifyContent:'center',
                fontSize:12,fontWeight:700,color:m.tc,flexShrink:0}}>{m.avatar}</div>
              <div style={{flex:1}}>
                <div style={{fontSize:14,fontWeight:500,color:'#111'}}>{m.name}</div>
                <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{m.job}</div>
              </div>
              <Badge status={m.status==='available'?'scheduled':m.status} small/>
            </div>
          ))}
        </div>
      </BottomSheet>
    </div>
  );
}

// ── FOLLOW UPS ────────────────────────────────────────────────
const FOLLOWUP_DATA = [
  { id:1, client:'Nguyen Group',    job:'Sewer Line Inspection', due:'Today',   type:'Invoice reminder', status:'pending', amount:'$550' },
  { id:2, client:'Torres LLC',      job:'Gas Line Repair',       due:'Tomorrow',type:'Estimate follow-up',status:'pending', amount:'$890' },
  { id:3, client:'Adams Home',      job:'Toilet Replacement',    due:'Apr 24',  type:'Review request',   status:'pending', amount:null },
  { id:4, client:'Chen Family',     job:'Water Heater Install',  due:'Sent',    type:'Invoice reminder', status:'sent',    amount:'$1,450' },
];

function FollowUpsScreen({ onNav }) {
  const [sent, setSent] = useState([]);
  return (
    <div style={{background:'#f5f5f7',minHeight:'100%',paddingBottom:100}}>
      <NavHeader title="Follow-Ups" onBack="__back"/>
      <BelleSuggestion
        text="3 follow-ups are pending today. Want me to send them all at once?"
        actions={['Send all', 'Review first']}
        onAction={a => { if(a==='Send all') setSent(FOLLOWUP_DATA.map(f=>f.id)); }}
      />
      <SectionHeader title="Pending" />
      <Card>
        {FOLLOWUP_DATA.map((f,i) => {
          const isSent = sent.includes(f.id) || f.status==='sent';
          return (
            <div key={f.id} style={{padding:'13px 16px',display:'flex',alignItems:'center',gap:12,
              borderBottom: i<FOLLOWUP_DATA.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',
              opacity: isSent ? 0.5 : 1}}>
              <div style={{width:38,height:38,borderRadius:10,flexShrink:0,
                background: f.type.includes('Invoice') ? '#fef3e2' : f.type.includes('Review') ? '#f5f0ff' : '#e8f2fd',
                display:'flex',alignItems:'center',justifyContent:'center',
                color: f.type.includes('Invoice') ? '#d97706' : f.type.includes('Review') ? '#7c3aed' : '#0071e3'}}>
                {f.type.includes('Invoice') ? Icons.dollar : f.type.includes('Review') ? Icons.sparkle : Icons.message}
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:14,fontWeight:500,color:'#111',marginBottom:2,letterSpacing:'-0.008em'}}>{f.client}</div>
                <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{f.type} · Due {f.due}</div>
              </div>
              <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:5}}>
                {!isSent ? (
                  <button onClick={() => setSent([...sent, f.id])}
                    style={{height:28,padding:'0 11px',borderRadius:7,background:'#0071e3',
                      color:'white',border:'none',fontSize:12,fontWeight:600,cursor:'pointer'}}>
                    Send
                  </button>
                ) : (
                  <Badge status="completed" small/>
                )}
                {f.amount && <span style={{fontSize:11,color:'rgba(0,0,0,0.35)',fontVariantNumeric:'tabular-nums'}}>{f.amount}</span>}
              </div>
            </div>
          );
        })}
      </Card>
    </div>
  );
}

Object.assign(window, {
  MessagesScreen, EstimatesScreen, EstimateDetailScreen,
  CallsScreen, ReportsScreen, DispatchScreen, FollowUpsScreen,
});
