// Simple Pro Mobile — Jobs List + Job Detail screens
const { useState } = React;

const JOB_ICONS = {
  'Drain Cleaning':   <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M12 22V12M12 12C12 12 8 10 8 6a4 4 0 018 0c0 4-4 6-4 6z"/><circle cx="12" cy="6" r="1" fill="currentColor" stroke="none"/></svg>,
  'Piping':           <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M3 9h18M3 15h18"/><path d="M3 9a2 2 0 000 6M21 9a2 2 0 010 6"/></svg>,
  'Installation':     <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0018 9h-1.26A8 8 0 103 16.3"/></svg>,
  'Inspection':       <svg width="16" height="16" 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>,
  'Testing':          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>,
  'Gas Work':         <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M12 2c0 0-4 4-4 8a4 4 0 008 0c0-4-4-8-4-8z"/><path d="M12 14v4M10 20h4"/></svg>,
  'Fixture Install':  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="3"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/></svg>,
  'default':          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>,
};

const JOB_ICON_COLORS = {
  'completed': { bg:'#e6f7ef', color:'#1a9e5c' },
  'paid':      { bg:'#e6f7ef', color:'#1a9e5c' },
  'overdue':   { bg:'#fef3e2', color:'#d97706' },
  'urgent':    { bg:'#fef2f2', color:'#dc2626' },
  'in progress':{ bg:'#eff6ff', color:'#2563eb' },
  'scheduled': { bg:'#f3f4f6', color:'#6b7280' },
  'draft':     { bg:'#f3f4f6', color:'#9ca3af' },
  'default':   { bg:'#f3f4f6', color:'#6b7280' },
};
const JOBS_DATA = [
  { id:1, name:'Drain Clog — Kitchen',     client:'Ramos Residence',  address:'104 Oakmont Ave',      amount:'$320',   status:'in progress', time:'11:30 AM', date:'Today',      type:'Drain Cleaning',  tech:'Marcus L.',  phone:'(415) 555-0192' },
  { id:2, name:'Full Bathroom Re-pipe',     client:'Steinberg Corp',   address:'901 Park Ave, Suite 3',amount:'$2,800', status:'scheduled',   time:'2:00 PM',  date:'Today',      type:'Piping',          tech:'Marcus L.',  phone:'(415) 555-0271' },
  { id:3, name:'Water Heater Install',      client:'Chen Family',      address:'2847 Riverside Dr',    amount:'$1,450', status:'completed',   time:'8:00 AM',  date:'Today',      type:'Installation',    tech:'Marcus L.',  phone:'(415) 555-0388' },
  { id:4, name:'Sewer Line Inspection',     client:'Nguyen Group',     address:'55 Marina Blvd',       amount:'$550',   status:'overdue',     time:'9:00 AM',  date:'Apr 19',     type:'Inspection',      tech:'Jake T.',    phone:'(415) 555-0445' },
  { id:5, name:'Backflow Preventer Test',   client:'Park Residence',   address:'18 Sunset Blvd',       amount:'$180',   status:'scheduled',   time:'10:00 AM', date:'Apr 22',     type:'Testing',         tech:'Dani R.',    phone:'(415) 555-0519' },
  { id:6, name:'Gas Line Repair',           client:'Torres LLC',       address:'77 Commercial St',     amount:'$890',   status:'draft',       time:'—',        date:'Unscheduled',type:'Gas Work',        tech:'Unassigned', phone:'(415) 555-0623' },
  { id:7, name:'Toilet Replacement',        client:'Adams Home',       address:'239 Birch Lane',       amount:'$420',   status:'paid',        time:'1:00 PM',  date:'Apr 18',     type:'Fixture Install', tech:'Dani R.',    phone:'(415) 555-0701' },
];

const JOB_NOTES = [
  { author:'Marcus L.', time:'9:15 AM', text:'Customer mentioned slow drain in master bath as well — may need separate visit.' },
  { author:'System',    time:'8:00 AM', text:'Job created from estimate #EST-0091.' },
];

// ── JOBS LIST ─────────────────────────────────────────────────
function JobsScreen({ onNav, initialFilter }) {
  const [filter, setFilter] = useState(initialFilter || 'All');
  const [search, setSearch] = useState('');
  const filters = ['All','Active','Overdue','Completed','Unscheduled'];

  const filtered = JOBS_DATA.filter(j => {
    const matchSearch = !search || j.name.toLowerCase().includes(search.toLowerCase()) || j.client.toLowerCase().includes(search.toLowerCase());
    const matchFilter =
      filter === 'All' ? true :
      filter === 'Active' ? ['in progress','scheduled','on my way','arrived'].includes(j.status) :
      filter === 'Overdue' ? j.status === 'overdue' :
      filter === 'Completed' ? ['paid','completed'].includes(j.status) :
      filter === 'Unscheduled' ? j.status === 'draft' : true;
    return matchSearch && matchFilter;
  });

  return (
    <div style={{background:'#f7f7f8', minHeight:'100%', paddingBottom:100}}>
      <NavHeader title="Jobs"
        action={
          <div onClick={() => onNav('new-job')}
            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>
        }
      />

      {/* Search bar */}
      <div style={{padding:'10px 16px 4px'}}>
        <div style={{height:38,background:'rgba(0,0,0,0.06)',borderRadius:10,
          display:'flex',alignItems:'center',gap:8,padding:'0 12px'}}>
          <svg width="14" height="14" 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 jobs or clients…"
            style={{flex:1,border:'none',background:'transparent',fontSize:15,color:'#111',outline:'none',
              fontFamily:'inherit',letterSpacing:'-0.008em'}}/>
        </div>
      </div>

      {/* Filter chips */}
      <div style={{display:'flex',gap:7,padding:'8px 16px 12px',overflowX:'auto',
        scrollbarWidth:'none',msOverflowStyle:'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>

      {filtered.length === 0 ? (
        <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'60px 20px',
          color:'rgba(0,0,0,0.3)',gap:12}}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>
          <div style={{fontSize:15,fontWeight:500}}>No jobs found</div>
        </div>
      ) : (
        <Card style={{marginBottom:0}}>
          {filtered.map((j, i) => (
            <div key={j.id} onClick={() => onNav('job-detail', {job: j})}
              style={{padding:'13px 16px', display:'flex', alignItems:'center', gap:12,
                background:'white', borderBottom: i < filtered.length-1 ? '0.5px solid rgba(0,0,0,0.07)' : 'none',
                cursor:'pointer'}}>
              <div style={{width:42,height:42,borderRadius:11,flexShrink:0,
                display:'flex',alignItems:'center',justifyContent:'center',
                background:(JOB_ICON_COLORS[j.status]||JOB_ICON_COLORS.default).bg,
                color:(JOB_ICON_COLORS[j.status]||JOB_ICON_COLORS.default).color}}>
                {JOB_ICONS[j.type]||JOB_ICONS.default}
              </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',
                    whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',flex:1,marginRight:8}}>{j.name}</div>
                  <div style={{fontSize:14,fontWeight:600,color:'#111',fontVariantNumeric:'tabular-nums',flexShrink:0}}>{j.amount}</div>
                </div>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                  <div style={{fontSize:12,color:'rgba(0,0,0,0.45)'}}>{j.client} · {j.date}</div>
                  <Badge status={j.status} small/>
                </div>
              </div>
            </div>
          ))}
        </Card>
      )}
    </div>
  );
}

// ── JOB DETAIL ────────────────────────────────────────────────
function JobDetailScreen({ onNav, params }) {
  const job = (params && params.job) || JOBS_DATA[0];
  const [jobStatus, setJobStatus] = useState(params?.action === 'onmyway' ? 'on my way' : job.status);
  const [notesOpen, setNotesOpen] = useState(false);
  const [paymentOpen, setPaymentOpen] = useState(false);
  const [photosOpen, setPhotosOpen] = useState(false);
  const [confirmAction, setConfirmAction] = useState(null);
  const [noteText, setNoteText] = useState('');
  const [notes, setNotes] = useState(JOB_NOTES);
  const [photos, setPhotos] = useState([
    { id:1, label:'Before', color:'#e8f2fd' },
    { id:2, label:'Before', color:'#fef3e2' },
  ]);

  // Status flow for field tech
  const statusFlow = {
    'scheduled':   { next: 'on my way',  label: 'Start Driving',  color: '#0071e3' },
    'on my way':   { next: 'arrived',    label: 'Mark Arrived',   color: '#7c3aed' },
    'arrived':     { next: 'in progress',label: 'Start Job',      color: '#d97706' },
    'in progress': { next: 'completed',  label: 'Complete Job',   color: '#1a9e5c' },
    'completed':   { next: null,         label: 'Job Complete',   color: '#1a9e5c' },
    'overdue':     { next: 'in progress',label: 'Start Job',      color: '#dc2626' },
    'paid':        { next: null,         label: 'Invoice Paid',   color: '#1a9e5c' },
    'draft':       { next: 'scheduled',  label: 'Schedule Job',   color: '#0071e3' },
  };

  const flow = statusFlow[jobStatus] || statusFlow.draft;

  function advanceStatus() {
    if (jobStatus === 'in progress') {
      setConfirmAction('complete');
    } else if (flow.next) {
      setJobStatus(flow.next);
    }
  }

  return (
    <div style={{background:'#f7f7f8', minHeight:'100%', paddingBottom:120}}>
      <NavHeader
        title={job.name}
        onBack="__back"
      />

      {/* Status + address hero */}
      <div style={{background:'white',padding:'16px 20px',borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12}}>
          <div style={{width:44,height:44,borderRadius:12,flexShrink:0,
            display:'flex',alignItems:'center',justifyContent:'center',
            background:(JOB_ICON_COLORS[job.status]||JOB_ICON_COLORS.default).bg,
            color:(JOB_ICON_COLORS[job.status]||JOB_ICON_COLORS.default).color}}>
            {JOB_ICONS[job.type]||JOB_ICONS.default}
          </div>
          <div style={{flex:1}}>
            <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:3}}>
              <Badge status={jobStatus}/>
            </div>
            <div style={{fontSize:12,color:'rgba(0,0,0,0.45)'}}>{job.type} · {job.time}, {job.date}</div>
          </div>
        </div>

        {/* Primary action button */}
        {flow.next ? (
          <PrimaryButton
            label={flow.label}
            color={flow.color}
            onTap={advanceStatus}
            icon={
              jobStatus === 'scheduled' ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> :
              jobStatus === 'in progress' ? Icons.check : null
            }
          />
        ) : (
          <div style={{height:52,borderRadius:13,background:'#e6f7ef',display:'flex',alignItems:'center',
            justifyContent:'center',gap:8,color:'#1a9e5c',fontSize:16,fontWeight:600}}>
            {Icons.check} {flow.label}
          </div>
        )}
      </div>

      {/* Quick actions row */}
      <div style={{background:'white',padding:'12px 16px',display:'flex',gap:8,borderBottom:'0.5px solid rgba(0,0,0,0.07)'}}>
        <QuickTile icon={Icons.phone}   label="Call"      color="#0071e3" onTap={() => {}}/>
        <QuickTile icon={Icons.message} label="Text"      color="#1a9e5c" onTap={() => onNav('belle', {prompt:`Text ${job.client} I'm on my way`})}/>
        <QuickTile icon={Icons.map}     label="Directions" color="#d97706" onTap={() => {}}/>
        <QuickTile icon={Icons.dollar}  label="Invoice"   color="#7c3aed" onTap={() => setPaymentOpen(true)}/>
      </div>

      {/* Belle contextual */}
      <BelleSuggestion
        text={`Need to update ${job.client}? I can text them your ETA or send a job summary when done.`}
        actions={['Ask Belle', 'Dismiss']}
        onAction={(a) => { if(a!=='Dismiss') onNav('belle', {context: job}); }}
      />

      {/* Map preview */}
      <div style={{margin:'14px 16px 0'}}>
        <div onClick={() => {}}
          style={{borderRadius:14,overflow:'hidden',border:'1px solid rgba(0,0,0,0.07)',cursor:'pointer',
            height:120,background:'linear-gradient(135deg, #e8f2fd 0%, #dde8f5 100%)',
            display:'flex',alignItems:'center',justifyContent:'center',position:'relative'}}>
          {/* Simulated map */}
          <svg width="100%" height="120" viewBox="0 0 360 120" style={{position:'absolute',top:0,left:0}}>
            <rect width="360" height="120" fill="#e8eef5"/>
            <line x1="0" y1="60" x2="360" y2="60" stroke="#d0dae5" strokeWidth="12"/>
            <line x1="180" y1="0" x2="180" y2="120" stroke="#d0dae5" strokeWidth="8"/>
            <line x1="0" y1="30" x2="360" y2="90" stroke="#dce5f0" strokeWidth="6"/>
            <rect x="60" y="20" width="80" height="40" rx="4" fill="#d4e0ed"/>
            <rect x="200" y="55" width="100" height="50" rx="4" fill="#d4e0ed"/>
            <circle cx="180" cy="60" r="12" fill="#dc2626"/>
            <circle cx="180" cy="60" r="5" fill="white"/>
          </svg>
          <div style={{position:'absolute',bottom:10,right:10,background:'white',borderRadius:8,
            padding:'6px 12px',fontSize:13,fontWeight:600,color:'#0071e3',
            boxShadow:'0 2px 8px rgba(0,0,0,0.12)'}}>
            Get Directions →
          </div>
        </div>
      </div>

      {/* Details card */}
      <SectionHeader title="Job Details"/>
      <Card>
        {[
          { label:'Client',   value: job.client },
          { label:'Address',  value: job.address },
          { label:'Phone',    value: job.phone },
          { label:'Technician', value: job.tech },
          { label:'Amount',   value: job.amount },
        ].map((r, i, arr) => (
          <div key={r.label} style={{padding:'13px 16px',display:'flex',justifyContent:'space-between',alignItems:'center',
            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:'#111',fontWeight:400,textAlign:'right',maxWidth:'60%'}}>{r.value}</span>
          </div>
        ))}
      </Card>

      {/* Job Checklist (Jobber-inspired) */}
      {(() => {
        const [checks, setChecks] = React.useState([
          { id:1, label:'Inspect existing setup', done:true },
          { id:2, label:'Shut off water supply', done:true },
          { id:3, label:'Remove old unit', done:false },
          { id:4, label:'Install new components', done:false },
          { id:5, label:'Test for leaks', done:false },
          { id:6, label:'Clean up work area', done:false },
        ]);
        const toggle = id => setChecks(checks.map(c => c.id===id ? {...c,done:!c.done} : c));
        const done = checks.filter(c=>c.done).length;
        return (
          <>
            <SectionHeader title={`Checklist · ${done}/${checks.length}`}/>
            <Card>
              {checks.map((c,i) => (
                <div key={c.id} onClick={() => toggle(c.id)}
                  style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
                    borderBottom: i<checks.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',
                    cursor:'pointer',opacity: c.done ? 0.5 : 1}}>
                  <div style={{width:22,height:22,borderRadius:'50%',flexShrink:0,
                    background: c.done ? '#0071e3' : 'transparent',
                    border: `1.5px solid ${c.done ? '#0071e3' : 'rgba(0,0,0,0.2)'}`,
                    display:'flex',alignItems:'center',justifyContent:'center'}}>
                    {c.done && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                  </div>
                  <span style={{fontSize:14,fontWeight:400,color:'#111',
                    textDecoration: c.done ? 'line-through' : 'none',
                    letterSpacing:'-0.008em'}}>{c.label}</span>
                </div>
              ))}
            </Card>
          </>
        );
      })()}

      {/* Notes */}
      <SectionHeader title="Notes" action="Add note" onAction={() => setNotesOpen(true)}/>
      <Card>
        {notes.map((n, i) => (
          <div key={i} style={{padding:'12px 16px',borderBottom: i < notes.length-1 ? '0.5px solid rgba(0,0,0,0.07)' : 'none'}}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:4}}>
              <span style={{fontSize:12,fontWeight:600,color:'#0071e3'}}>{n.author}</span>
              <span style={{fontSize:12,color:'rgba(0,0,0,0.35)'}}>{n.time}</span>
            </div>
            <div style={{fontSize:14,color:'#111',lineHeight:1.5}}>{n.text}</div>
          </div>
        ))}
      </Card>

      <SectionHeader title="Related"/>
      <Card style={{marginBottom:16}}>
        <ListCell icon={Icons.dollar} iconBg="#e6f7ef" title="View / Create Estimate"
          subtitle="Convert job scope into an estimate" isLast={false}
          onTap={() => onNav('estimates')}/>
        <ListCell icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" 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="Diagnose with Belle"
          subtitle="AI-guided diagnosis → auto-generate estimate"
          onTap={() => onNav('belle', {prompt:'Diagnose ' + job.name + ' for ' + job.client})} isLast/>
      </Card>
      <SectionHeader title="Photos" action="Add photo" onAction={() => setPhotosOpen(true)}/>
      <div style={{display:'flex',gap:10,padding:'0 16px',overflowX:'auto',scrollbarWidth:'none'}}>
        {photos.map(p => (
          <div key={p.id} style={{width:100,height:100,borderRadius:12,background:p.color,
            flexShrink:0,display:'flex',flexDirection:'column',alignItems:'center',
            justifyContent:'center',gap:4,border:'1px solid rgba(0,0,0,0.07)'}}>
            <div style={{color:'rgba(0,0,0,0.25)'}}>{Icons.camera}</div>
            <span style={{fontSize:11,color:'rgba(0,0,0,0.35)',fontWeight:500}}>{p.label}</span>
          </div>
        ))}
        <div onClick={() => setPhotosOpen(true)}
          style={{width:100,height:100,borderRadius:12,background:'white',flexShrink:0,
            border:'1.5px dashed rgba(0,0,0,0.15)',display:'flex',flexDirection:'column',
            alignItems:'center',justifyContent:'center',gap:4,cursor:'pointer'}}>
          <div style={{color:'rgba(0,0,0,0.3)'}}>{Icons.plus}</div>
          <span style={{fontSize:11,color:'rgba(0,0,0,0.35)',fontWeight:500}}>Add</span>
        </div>
      </div>

      {/* Add Note sheet */}
      <BottomSheet open={notesOpen} onClose={() => setNotesOpen(false)} title="Add Note">
        <div style={{padding:'16px'}}>
          <textarea value={noteText} onChange={e => setNoteText(e.target.value)}
            placeholder="Type your note…"
            style={{width:'100%',minHeight:120,borderRadius:12,border:'1.5px solid rgba(0,0,0,0.12)',
              padding:'12px',fontSize:15,fontFamily:'inherit',resize:'none',outline:'none',
              color:'#111',letterSpacing:'-0.005em',boxSizing:'border-box'}}/>
          <PrimaryButton label="Save Note" style={{marginTop:12}}
            onTap={() => {
              if(noteText.trim()) {
                setNotes([{author:'Marcus L.',time:'Just now',text:noteText}, ...notes]);
                setNoteText('');
                setNotesOpen(false);
              }
            }}/>
        </div>
      </BottomSheet>

      {/* Payment sheet */}
      <BottomSheet open={paymentOpen} onClose={() => setPaymentOpen(false)} title="Record Payment">
        <div style={{padding:'16px'}}>
          <div style={{fontSize:36,fontWeight:700,color:'#111',textAlign:'center',
            letterSpacing:'-0.03em',marginBottom:4,fontVariantNumeric:'tabular-nums'}}>{job.amount}</div>
          <div style={{fontSize:13,color:'rgba(0,0,0,0.4)',textAlign:'center',marginBottom:20}}>Outstanding balance</div>
          {[['Cash','#1a9e5c'],['Tap to Pay','#0071e3'],['Credit Card','#0071e3'],['Check','#7c3aed'],['Financing','#d97706']].map(([method, color]) => (
            <div key={method} onClick={() => { setPaymentOpen(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>
              <div style={{width:28,height:28,borderRadius:'50%',background:color,display:'flex',
                alignItems:'center',justifyContent:'center',color:'white',fontSize:12}}>{Icons.chevronR}</div>
            </div>
          ))}
        </div>
      </BottomSheet>

      {/* Complete confirmation */}
      <BottomSheet open={confirmAction==='complete'} onClose={() => setConfirmAction(null)} title="Complete Job?" halfHeight>
        <div style={{padding:'16px'}}>
          <div style={{fontSize:14,color:'rgba(0,0,0,0.55)',marginBottom:20,lineHeight:1.5}}>
            Mark this job as complete? This will send a completion notification to {job.client}.
          </div>
          <PrimaryButton label="Yes, Complete Job" color="#1a9e5c"
            onTap={() => { setJobStatus('completed'); setConfirmAction(null); }}/>
          <SecondaryButton label="Cancel" style={{marginTop:10}}
            onTap={() => setConfirmAction(null)}/>
        </div>
      </BottomSheet>

      {/* Photos sheet */}
      <BottomSheet open={photosOpen} onClose={() => setPhotosOpen(false)} title="Add Photo">
        <div style={{padding:'16px',display:'flex',flexDirection:'column',gap:10}}>
          {['Take Photo — Before','Take Photo — After','Choose from Library'].map(label => (
            <div key={label} onClick={() => {
              const colors = ['#e8f2fd','#fef3e2','#e6f7ef','#f5f0ff'];
              setPhotos([...photos, {id:Date.now(), label: label.includes('Before')?'Before':'After', color: colors[photos.length%colors.length]}]);
              setPhotosOpen(false);
            }}
            style={{height:52,borderRadius:12,background:'#f7f7f8',display:'flex',alignItems:'center',
              padding:'0 16px',fontSize:15,fontWeight:500,color:'#111',cursor:'pointer',
              border:'1px solid rgba(0,0,0,0.07)'}}>
              {label}
            </div>
          ))}
        </div>
      </BottomSheet>
    </div>
  );
}

// ── NEW JOB SCREEN ────────────────────────────────────────────
function NewJobScreen({ onNav }) {
  const [form, setForm] = useState({ client:'', type:'', date:'', time:'', description:'' });
  const update = (k, v) => setForm({...form, [k]:v});
  return (
    <div style={{background:'#f7f7f8', minHeight:'100%', paddingBottom:120}}>
      <NavHeader title="New Job" onBack="__back"
        action={<span onClick={() => onNav('jobs')} style={{fontSize:15,color:'#0071e3',cursor:'pointer',fontWeight:500}}>Save</span>}
      />
      <BelleSuggestion
        text="I can prefill this job from your last visit to a client. Who is this job for?"
        actions={['Use Belle', 'Skip']}
        onAction={(a) => { if(a==='Use Belle') onNav('belle', {prompt:'Create a new job'}); }}
      />
      <SectionHeader title="Job Info"/>
      <Card>
        {[
          { label:'Client', placeholder:'Search clients…', key:'client' },
          { label:'Service type', placeholder:'e.g. Drain Cleaning', key:'type' },
          { label:'Date', placeholder:'Select date', key:'date' },
          { label:'Time', placeholder:'Select time', key:'time' },
        ].map((f, i, arr) => (
          <div key={f.key} style={{padding:'13px 16px',borderBottom: i<arr.length-1 ? '0.5px solid rgba(0,0,0,0.07)':'none',
            display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <span style={{fontSize:14,color:'rgba(0,0,0,0.45)',fontWeight:500,flexShrink:0,marginRight:12}}>{f.label}</span>
            <input value={form[f.key]} onChange={e => update(f.key, e.target.value)}
              placeholder={f.placeholder}
              style={{border:'none',background:'transparent',fontSize:14,color:'#111',outline:'none',
                fontFamily:'inherit',textAlign:'right',flex:1,minWidth:0}}/>
          </div>
        ))}
      </Card>
      <SectionHeader title="Description"/>
      <div style={{margin:'0 16px'}}>
        <textarea value={form.description} onChange={e => update('description', e.target.value)}
          placeholder="Describe the job…"
          style={{width:'100%',minHeight:96,borderRadius:12,border:'1px solid rgba(0,0,0,0.1)',
            background:'white',padding:'13px 16px',fontSize:14,fontFamily:'inherit',
            resize:'none',outline:'none',color:'#111',boxSizing:'border-box'}}/>
      </div>
      <div style={{padding:'16px'}}>
        <PrimaryButton label="Create Job" onTap={() => onNav('jobs')}/>
      </div>
    </div>
  );
}

Object.assign(window, { JobsScreen, JobDetailScreen, NewJobScreen, JOBS_DATA });
