function ProcessedView({ processed, onRefresh, pushToast, folderFilter }) {
  const [activeTab,     setActiveTab]     = useState('all');
  const [search,        setSearch]        = useState('');
  const [catFilter,     setCatFilter]     = useState('all');
  const [fromDate,      setFromDate]      = useState('');
  const [toDate,        setToDate]        = useState('');
  // Action date filter — for Daily Log tab (filters by when actioned, not email date)
  const [actionFrom,    setActionFrom]    = useState('');
  const [actionTo,      setActionTo]      = useState('');
  const [expandedId, setExpandedId] = useState(null);
  const [editFields, setEditFields] = useState({});
  const [saving,     setSaving]     = useState(null);

  const ALL_CATS = ['invoice','statement','docket','urgent-payment','supplier-query',
    'route-fleet','route-estimator','route-hr','route-other','noise'];

  const PROC_META = {
    flag:      { icon:'🚨', label:'Alert' },
    file:      { icon:'📁', label:'Saved to' },
    forward:   { icon:'➡️', label:'Forwarded to' },
    pay:       { icon:'💰', label:'Payment arranged' },
    reply:     { icon:'✉️', label:'Replied' },
    folder:    { icon:'📂', label:'Moved to' },
    alert:     { icon:'🔔', label:'Notified' },
    processed: { icon:'⚡', label:'Auto-processed' },
  };
  const IRREV = ['forward','reply','alert'];

  const parseActs = (p) => {
    try { return typeof p.actions==='string' ? JSON.parse(p.actions) : (p.actions||[]); }
    catch { return []; }
  };

  // Base filter (applies to All, Auto, Manual tabs)
  const baseFiltered = (processed || []).filter(p => {
    const q = search.toLowerCase();
    const matchSearch = !q || p.subject?.toLowerCase().includes(q) ||
      p.supplier?.toLowerCase().includes(q) || (p.fromName||p.fromEmail||'').toLowerCase().includes(q);
    const matchCat = catFilter === 'all' || p.category === catFilter;
    if (fromDate) { const d = p.emailDate||p.processedAt ? new Date(p.emailDate||p.processedAt) : null; if (!d || d < new Date(fromDate)) return false; }
    if (toDate)   { const d = p.emailDate||p.processedAt ? new Date(p.emailDate||p.processedAt) : null; if (!d || d > new Date(toDate + 'T23:59:59')) return false; }
    if (folderFilter) {
      const ff = folderFilter.toLowerCase();
      if (!(p.suggestedFolder||'').toLowerCase().includes(ff) &&
          !(p.movedToFolder||'').toLowerCase().includes(ff)) return false;
    }
    return matchSearch && matchCat;
  });

  const allItems      = baseFiltered;
  const botItems      = baseFiltered.filter(p => !p.approvedManually);
  const manualItems   = baseFiltered.filter(p =>  p.approvedManually);
  const cats          = ['all', ...new Set((processed||[]).map(p=>p.category).filter(Boolean))];

  // Daily log entries — use ALL processed items (not baseFiltered) so email date filter
  // doesn't hide items actioned today that have an old email date.
  // Instead, filter by actionFrom/actionTo (when actioned).
  const logEntries = useMemo(() => {
    const entries = [];
    (processed || []).forEach(p => {
      // Also apply search + category filter from main filters
      const q = search.toLowerCase();
      const matchSearch = !q || p.subject?.toLowerCase().includes(q) ||
        p.supplier?.toLowerCase().includes(q) || (p.fromName||p.fromEmail||'').toLowerCase().includes(q);
      const matchCat = catFilter === 'all' || p.category === catFilter;
      if (!matchSearch || !matchCat) return;

      const acts = parseActs(p);
      acts.filter(a => a.done && a.doneAt).forEach(a => {
        const d = new Date(a.doneAt);
        if (actionFrom && d < new Date(actionFrom)) return;
        if (actionTo   && d > new Date(actionTo + 'T23:59:59')) return;
        entries.push({ doneAt:a.doneAt, subject:p.subject, supplier:p.supplier||p.fromName||'—',
          type:a.type, target:a.target||a.label||'—', category:p.category, amount:p.invoiceAmount,
          manual:!!p.approvedManually, emailDate:p.emailDate });
      });
      if (p.processedAt) {
        const d = new Date(p.processedAt);
        if (actionFrom && d < new Date(actionFrom)) return;
        if (actionTo   && d > new Date(actionTo + 'T23:59:59')) return;
        entries.push({ doneAt:p.processedAt, subject:p.subject, supplier:p.supplier||p.fromName||'—',
          type:'processed', target: fmtCatLabel(p.category)+(p.suggestedFolder?` → ${p.suggestedFolder}`:''),
          category:p.category, amount:p.invoiceAmount, manual:!!p.approvedManually, emailDate:p.emailDate });
      }
    });
    return entries.sort((a,b) => new Date(b.doneAt)-new Date(a.doneAt));
  }, [processed, search, catFilter, actionFrom, actionTo]);

  const logByDate = useMemo(() => {
    const g = {};
    logEntries.forEach(e => {
      const day = new Date(e.doneAt).toLocaleDateString('en-AU',{weekday:'long',day:'numeric',month:'long',year:'numeric'});
      if (!g[day]) g[day] = [];
      g[day].push(e);
    });
    return g;
  }, [logEntries]);

  const TABS = [
    { key:'all',    label:'All Processed',  count: allItems.length    },
    { key:'auto',   label:'🤖 Auto',         count: botItems.length    },
    { key:'manual', label:'👤 Manual',       count: manualItems.length },
    { key:'log',    label:'📋 Daily Log',    count: logEntries.length  },
  ];

  const toggleExpand = (id) => {
    if (expandedId === id) { setExpandedId(null); return; }
    setExpandedId(id);
    const item = (processed||[]).find(p => p.id === id);
    if (item) setEditFields(f => ({ ...f, [id]: {
      category: item.category, action: item.action,
      suggestedFolder: item.suggestedFolder, forwardTo: item.forwardTo,
      actions: parseActs(item),
    }}));
  };

  const handleSave = async (item) => {
    setSaving(item.id);
    try {
      await api.post('/api/processed/update', { id: item.id, ...editFields[item.id] });
      pushToast('✅ Updated');
      onRefresh();
      setExpandedId(null);
    } catch(e) { pushToast('Error: ' + e.message); }
    setSaving(null);
  };

  const handleRequeue = async (item) => {
    setSaving(item.id);
    try {
      await api.post('/api/processed/requeue', { id: item.id });
      pushToast('↩ Moved back to Review Queue');
      onRefresh();
      setExpandedId(null);
    } catch(e) { pushToast('Error: ' + e.message); }
    setSaving(null);
  };

  const exportCSV = (items) => {
    const rows = [
      ['Date','Supplier','Subject','Category','Confidence','Reason','Folder','Amount','Method'],
      ...items.map(p => [
        p.emailDate ? new Date(p.emailDate).toLocaleString('en-AU') : p.processedAt?.slice(0,10)||'—',
        p.supplier||'', p.subject||'', p.category||'',
        p.confidence!=null?p.confidence+'%':'—',
        (p.classificationReason||'').replace(/,/g,';'),
        p.suggestedFolder||'', p.invoiceAmount!=null?p.invoiceAmount:'',
        p.approvedManually?'Manual':'Bot',
      ])
    ];
    const csv = rows.map(r=>r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
    const blob = new Blob([csv],{type:'text/csv'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href=url;
    a.download=`accounts-processed-${new Date().toISOString().slice(0,10)}.csv`;
    a.click(); URL.revokeObjectURL(url);
  };

  const renderItem = (p) => {
    const isExpanded = expandedId === p.id;
    const ef = editFields[p.id] || {};
    return (
      <div key={p.id} style={{border:`1px solid ${p.isDuplicate?'#fca5a5':'#e5e7eb'}`,borderRadius:8,marginBottom:6,overflow:'hidden'}}>
        <div onClick={() => toggleExpand(p.id)} style={{
          display:'grid', gridTemplateColumns:'1fr auto auto auto auto auto',
          gap:8, alignItems:'center', padding:'10px 14px',
          background: isExpanded?'#f0f9ff': p.isDuplicate?'#fff5f5':'#fff',
          cursor:'pointer',
        }}>
          <div style={{minWidth:0}}>
            <div style={{fontWeight:600,fontSize:13,color:'var(--navy)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
              {p.isDuplicate && <span style={{fontSize:11,marginRight:5}}>⚠️</span>}
              {p.subject}
            </div>
            <div style={{fontSize:11,color:'#6b7280',marginTop:1}}>{p.supplier||p.fromName||'—'} · {fmtDate(p.emailDate||p.processedAt)}</div>
          </div>
          <Badge cat={p.category}>{fmtCatLabel(p.category)}</Badge>
          {p.webLink?.startsWith('msg://') && (
            <span style={{fontSize:10,fontWeight:700,padding:'2px 7px',borderRadius:10,background:'#0d9488',color:'#fff',letterSpacing:'0.04em',whiteSpace:'nowrap'}}>REAL</span>
          )}
          <ConfPill value={p.confidence}/>
          <span style={{fontSize:11,color:'#6b7280',whiteSpace:'nowrap'}}>{fmtAmt(p.invoiceAmount)}</span>
          <span style={{fontSize:11,color:'#9ca3af'}}>{isExpanded?'▲':'▼'}</span>
        </div>

        {isExpanded && (
          <div style={{padding:'14px 16px',borderTop:'1px solid #e5e7eb',background:'#f9fafb'}}>
            {p.isDuplicate && (
              <div style={{background:'#fef2f2',border:'1px solid #fca5a5',borderRadius:6,padding:'6px 10px',marginBottom:12,fontSize:12,color:'#991b1b'}}>
                ⚠️ <strong>Duplicate:</strong> {p.duplicateReason}
              </div>
            )}
            {/* Actions checklist */}
            {(() => {
              const acts = ef.actions !== undefined ? ef.actions : parseActs(p);
              if (!acts || acts.length === 0) return null;
              const setActs = (next) => setEditFields(f=>({...f,[p.id]:{...(f[p.id]||{}),actions:next}}));
              return (
                <div style={{marginBottom:14}}>
                  <div style={{fontSize:11,fontWeight:700,textTransform:'uppercase',letterSpacing:'0.06em',color:'#6b7280',marginBottom:8}}>Actions</div>
                  {acts.map((act,i) => {
                    const m = PROC_META[act.type]||PROC_META.flag;
                    const irrev = IRREV.includes(act.type);
                    const isDone = !!act.done;
                    return (
                      <div key={i} style={{display:'flex',alignItems:'center',gap:0,marginBottom:5,borderRadius:7,
                        border:`1px solid ${isDone?'#bbf7d0':'#e2e8f0'}`,background:isDone?'#f0fdf4':'#fff',overflow:'hidden'}}>
                        <div style={{padding:'7px 10px',borderRight:`1px solid ${isDone?'#bbf7d0':'#e2e8f0'}`,background:isDone?'#dcfce7':'#f8fafc',display:'flex',alignItems:'center'}}>
                          <input type="checkbox" checked={isDone}
                            onChange={e=>{
                              const next=acts.map((a,idx)=>idx===i?{...a,done:e.target.checked,doneAt:e.target.checked?new Date().toISOString():null}:a);
                              setActs(next);
                            }} style={{cursor:'pointer',width:14,height:14,accentColor:'#16a34a'}}/>
                        </div>
                        <div style={{padding:'7px 10px',borderRight:`1px solid ${isDone?'#bbf7d0':'#e2e8f0'}`,background:isDone?'#f0fdf4':'#f1f5f9',
                          fontSize:12,fontWeight:600,color:isDone?'#15803d':'#334155',whiteSpace:'nowrap',display:'flex',alignItems:'center',gap:5,flexShrink:0}}>
                          {m.icon} {m.label}
                        </div>
                        <div style={{flex:1,padding:'7px 10px',fontSize:12,color:isDone?'#16a34a':'#374151',textDecoration:isDone?'line-through':'none',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                          {act.target||act.label||'—'}
                        </div>
                        {irrev && <span title="Cannot be undone" style={{fontSize:10,color:'#f59e0b',padding:'0 8px',flexShrink:0,cursor:'help'}}>⚠ irreversible</span>}
                        {act.doneAt && <span style={{fontSize:10,color:'#94a3b8',padding:'0 8px',flexShrink:0,whiteSpace:'nowrap'}}>✓ {new Date(act.doneAt).toLocaleTimeString('en-AU',{hour:'2-digit',minute:'2-digit'})}</span>}
                      </div>
                    );
                  })}
                </div>
              );
            })()}
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:10}}>
              <div>
                <label style={{fontSize:11,fontWeight:600,color:'#6b7280',display:'block',marginBottom:3}}>CATEGORY</label>
                <select value={ef.category||''} onChange={e=>setEditFields(f=>({...f,[p.id]:{...(f[p.id]||{}),category:e.target.value}}))}
                  style={{width:'100%',fontSize:12,padding:'5px 8px',borderRadius:6,border:'1px solid #d1d5db'}}>
                  {ALL_CATS.map(c=><option key={c} value={c}>{fmtCatLabel(c)}</option>)}
                </select>
              </div>
              <div>
                <label style={{fontSize:11,fontWeight:600,color:'#6b7280',display:'block',marginBottom:3}}>FOLDER</label>
                <input list="proc-folders" value={ef.suggestedFolder||''} onChange={e=>setEditFields(f=>({...f,[p.id]:{...(f[p.id]||{}),suggestedFolder:e.target.value}}))}
                  style={{width:'100%',fontSize:12,padding:'5px 8px',borderRadius:6,border:'1px solid #d1d5db',boxSizing:'border-box'}}/>
                <datalist id="proc-folders">
                  {['Invoices','Invoices/Boral','Invoices/Hanson','Invoices/Fulton Hogan','Invoices/Coates Hire','Statements','Dockets','Urgent','Fleet','Tenders','HR','HR/Superannuation','Queries','Noise'].map(f=><option key={f} value={f}/>)}
                </datalist>
              </div>
            </div>
            <div style={{marginBottom:10}}>
              <label style={{fontSize:11,fontWeight:600,color:'#6b7280',display:'block',marginBottom:3}}>ACTION / NOTES</label>
              <textarea value={ef.action||''} onChange={e=>setEditFields(f=>({...f,[p.id]:{...(f[p.id]||{}),action:e.target.value}}))}
                rows={2} style={{width:'100%',fontSize:12,padding:'5px 8px',borderRadius:6,border:'1px solid #d1d5db',resize:'vertical',boxSizing:'border-box'}}/>
            </div>
            {p.webLink && (
              <div style={{marginBottom:10}}>
                <a href={p.webLink} target="_blank" rel="noreferrer" style={{fontSize:12,color:'#1d4ed8',fontWeight:600,textDecoration:'none'}}>📧 Open in Outlook ↗</a>
              </div>
            )}
            <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
              <button className="btn-approve" onClick={()=>handleSave(p)} disabled={saving===p.id}>
                <Icons.check style={{width:13,height:13}}/> {saving===p.id?'Saving…':'Save changes'}
              </button>
              <button className="btn-override" onClick={()=>handleRequeue(p)} disabled={saving===p.id}>↩ Move back to Queue</button>
              <button className="btn-ghost" onClick={()=>setExpandedId(null)}>Cancel</button>
            </div>
          </div>
        )}
      </div>
    );
  };

  const renderLogTab = () => (
    <div>
      {/* Print-only header */}
      <div style={{display:'none'}} className="print-only">
        <h2 style={{margin:'0 0 4px',fontSize:14}}>Elite Roads Accounts — Daily Action Log</h2>
        <p style={{margin:'0 0 12px',fontSize:11,color:'#666'}}>Printed: {new Date().toLocaleString('en-AU')} · Mindy (Accountant)</p>
      </div>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16,flexWrap:'wrap',gap:8}} className="no-print">
        <div style={{fontSize:13,color:'#6b7280'}}>{logEntries.length} total actions · includes auto + manual</div>
        <button className="btn-ghost" onClick={()=>window.print()}>🖨 Print Daily Summary</button>
      </div>
      {Object.keys(logByDate).length === 0 ? (
        <div className="empty-state"><div style={{fontSize:13,color:'#6b7280'}}>No logged actions yet — tick off actions on processed items to see them here</div></div>
      ) : Object.entries(logByDate).map(([day, entries]) => (
        <div key={day} style={{marginBottom:24}}>
          <div style={{fontSize:12,fontWeight:700,color:'#6b7280',textTransform:'uppercase',letterSpacing:'0.06em',
            marginBottom:8,paddingBottom:4,borderBottom:'1px solid #e5e7eb',display:'flex',alignItems:'center',gap:8}}>
            {day} — {entries.length} action{entries.length!==1?'s':''}
            <span style={{fontWeight:400,fontSize:11,color:'#94a3b8'}}>
              {entries.filter(e=>!e.manual).length} auto · {entries.filter(e=>e.manual).length} manual
            </span>
          </div>
          <table style={{width:'100%',borderCollapse:'collapse',fontSize:12}}>
            <thead>
              <tr style={{background:'#f9fafb'}}>
                {['Action Time','Action','Email / Subject','Email Date','Supplier','Amount','✓'].map((h,i) => (
                  <th key={h} style={{padding:'6px 10px',textAlign:i===4?'right':i===5?'center':'left',
                    fontWeight:600,color:'#6b7280',fontSize:11,borderBottom:'1px solid #e5e7eb',whiteSpace:'nowrap'}}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {entries.map((e,i) => {
                const m = PROC_META[e.type]||PROC_META.processed;
                return (
                  <tr key={i} style={{borderBottom:'1px solid #f3f4f6',background:i%2===0?'#fff':'#fafafa'}}>
                    <td style={{padding:'7px 10px',fontFamily:'var(--mono)',fontSize:11,color:'#6b7280',whiteSpace:'nowrap'}}>
                      {new Date(e.doneAt).toLocaleTimeString('en-AU',{hour:'2-digit',minute:'2-digit'})}
                    </td>
                    <td style={{padding:'7px 10px'}}>
                      <span style={{display:'inline-flex',alignItems:'center',gap:4,fontSize:12}}>
                        <span>{m.icon}</span>
                        <span style={{fontWeight:600,color:'#334155'}}>{m.label}</span>
                        {e.target&&e.target!=='—'&&<span style={{color:'#6b7280',fontSize:11}}>→ {e.target}</span>}
                        <span style={{fontSize:9,padding:'1px 5px',borderRadius:4,marginLeft:2,
                          background:e.manual?'#fef9ee':'#eff6ff',
                          color:e.manual?'#92400e':'#1d4ed8',fontWeight:700}}>
                          {e.manual?'manual':'auto'}
                        </span>
                      </span>
                    </td>
                    <td style={{padding:'7px 10px',fontSize:12,color:'#1f2937',maxWidth:220,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{e.subject}</td>
                    <td style={{padding:'7px 10px',fontSize:12,color:'#374151',fontWeight:500,whiteSpace:'nowrap'}}>{e.supplier}</td>
                    <td style={{padding:'7px 10px',fontFamily:'var(--mono)',fontSize:11,color:'#94a3b8',whiteSpace:'nowrap'}}>{e.emailDate?fmtDate(e.emailDate):'—'}</td>
                    <td style={{padding:'7px 10px',fontFamily:'var(--mono)',fontSize:12,textAlign:'right',color:'#1f2937',whiteSpace:'nowrap'}}>{e.amount!=null?fmtAmt(e.amount):'—'}</td>
                    <td style={{padding:'7px 10px',textAlign:'center'}}>
                      <span style={{display:'inline-block',width:14,height:14,border:'1px solid #d1d5db',borderRadius:3}}/>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {/* Print signature */}
          <div style={{display:'none',marginTop:12,paddingTop:8,borderTop:'1px solid #e5e7eb'}} className="print-only">
            <p style={{fontSize:10,color:'#666',margin:0}}>Reviewed: _________________________ &nbsp; Sign: _________________________ &nbsp; Date: _______________</p>
          </div>
        </div>
      ))}
    </div>
  );

  const renderListTab = (items, emptyMsg) => (
    items.length === 0
      ? <div className="empty-state"><div style={{fontSize:13,color:'#6b7280'}}>{emptyMsg}</div></div>
      : items.map(renderItem)
  );

  return (
    <div className="main-inner">
      {/* Print header */}
      <div style={{display:'none'}} className="print-only">
        <h1 style={{margin:0}}>Elite Roads Accounts — Processed Email Report</h1>
        <p style={{margin:'4px 0 0',color:'#666'}}>Generated: {new Date().toLocaleString('en-AU')}</p>
      </div>

      {/* Page header */}
      <div className="page-head no-print">
        <div>
          <h1 className="page-title">Processed</h1>
          <p className="page-sub">{allItems.length} of {processed?.length||0} emails{folderFilter ? ` · folder: ${folderFilter}` : ''}</p>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn-ghost" onClick={()=>exportCSV(allItems)}>↧ Export CSV</button>
        </div>
      </div>

      {/* Filters — always visible */}
      <div className="no-print" style={{background:'#f9fafb',borderRadius:8,border:'1px solid #e5e7eb',marginBottom:0}}>
        {/* Row 1: Email date + search + category */}
        <div style={{display:'flex',gap:10,flexWrap:'wrap',padding:'10px 14px',borderBottom: activeTab==='log'?'1px solid #e5e7eb':'none'}}>
          <div style={{display:'flex',flexDirection:'column',gap:2}}>
            <label style={{fontSize:11,fontWeight:600,color:'#6b7280'}}>EMAIL DATE FROM</label>
            <input type="date" value={fromDate} onChange={e=>setFromDate(e.target.value)} style={{fontSize:12,padding:'4px 8px',borderRadius:6,border:'1px solid #d1d5db'}}/>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:2}}>
            <label style={{fontSize:11,fontWeight:600,color:'#6b7280'}}>TO</label>
            <input type="date" value={toDate} onChange={e=>setToDate(e.target.value)} style={{fontSize:12,padding:'4px 8px',borderRadius:6,border:'1px solid #d1d5db'}}/>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:2,flex:1,minWidth:150}}>
            <label style={{fontSize:11,fontWeight:600,color:'#6b7280'}}>SEARCH</label>
            <input className="search-input" placeholder="Supplier, subject…" value={search} onChange={e=>setSearch(e.target.value)} style={{margin:0}}/>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:2}}>
            <label style={{fontSize:11,fontWeight:600,color:'#6b7280'}}>CATEGORY</label>
            <select className="cat-select" value={catFilter} onChange={e=>setCatFilter(e.target.value)} style={{margin:0}}>
              {cats.map(c=><option key={c} value={c}>{c==='all'?'All categories':fmtCatLabel(c)}</option>)}
            </select>
          </div>
          {(fromDate||toDate||search||catFilter!=='all') && (
            <div style={{display:'flex',alignItems:'flex-end'}}>
              <button className="btn-ghost" style={{fontSize:12,padding:'4px 10px'}}
                onClick={()=>{setFromDate('');setToDate('');setSearch('');setCatFilter('all');}}>× Clear</button>
            </div>
          )}
        </div>
        {/* Row 2: Action date filter — only shown on Daily Log tab */}
        {activeTab === 'log' && (
          <div style={{display:'flex',gap:10,flexWrap:'wrap',padding:'8px 14px',alignItems:'center',background:'#f0f9ff'}}>
            <span style={{fontSize:11,fontWeight:700,color:'#0369a1',whiteSpace:'nowrap'}}>📋 ACTION DATE:</span>
            <div style={{display:'flex',flexDirection:'column',gap:2}}>
              <label style={{fontSize:10,fontWeight:600,color:'#6b7280'}}>FROM</label>
              <input type="date" value={actionFrom} onChange={e=>setActionFrom(e.target.value)} style={{fontSize:12,padding:'4px 8px',borderRadius:6,border:'1px solid #bae6fd',background:'#fff'}}/>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:2}}>
              <label style={{fontSize:10,fontWeight:600,color:'#6b7280'}}>TO</label>
              <input type="date" value={actionTo} onChange={e=>setActionTo(e.target.value)} style={{fontSize:12,padding:'4px 8px',borderRadius:6,border:'1px solid #bae6fd',background:'#fff'}}/>
            </div>
            <div style={{display:'flex',alignItems:'flex-end',gap:6}}>
              <button style={{all:'unset',cursor:'pointer',fontSize:11,padding:'4px 10px',borderRadius:6,border:'1px solid #bae6fd',background:'#fff',color:'#0369a1',fontWeight:600}}
                onClick={()=>{const t=new Date().toISOString().slice(0,10);setActionFrom(t);setActionTo(t);}}>Today</button>
              <button style={{all:'unset',cursor:'pointer',fontSize:11,padding:'4px 10px',borderRadius:6,border:'1px solid #bae6fd',background:'#fff',color:'#0369a1',fontWeight:600}}
                onClick={()=>{const t=new Date();const mon=new Date(t);mon.setDate(t.getDate()-t.getDay()+1);setActionFrom(mon.toISOString().slice(0,10));setActionTo(t.toISOString().slice(0,10));}}>This week</button>
              {(actionFrom||actionTo) && (
                <button className="btn-ghost" style={{fontSize:11,padding:'4px 8px'}} onClick={()=>{setActionFrom('');setActionTo('');}}>× Clear</button>
              )}
            </div>
            <span style={{fontSize:11,color:'#94a3b8',fontStyle:'italic'}}>Filters log by when actioned — not email date</span>
          </div>
        )}
      </div>

      {/* Summary counts */}
      <div style={{display:'flex',gap:10,margin:'12px 0',flexWrap:'wrap'}}>
        {[
          {label:'Total',        value:allItems.length,    color:'#1f2937'},
          {label:'🤖 Auto',      value:botItems.length,    color:'#1d4ed8'},
          {label:'👤 Manual',    value:manualItems.length, color:'#92400e'},
          {label:'⚠️ Duplicate', value:allItems.filter(p=>p.isDuplicate).length, color:'#dc2626'},
        ].map(s=>(
          <div key={s.label} style={{padding:'7px 14px',background:'#fff',border:'1px solid #e5e7eb',borderRadius:8,textAlign:'center',minWidth:90}}>
            <div style={{fontSize:18,fontWeight:700,color:s.color}}>{s.value}</div>
            <div style={{fontSize:11,color:'#6b7280',marginTop:1}}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="no-print" style={{display:'flex',gap:0,borderBottom:'2px solid #e5e7eb',marginBottom:16}}>
        {TABS.map(t => (
          <button key={t.key} onClick={()=>setActiveTab(t.key)} style={{
            all:'unset', cursor:'pointer', padding:'9px 18px', fontSize:13, fontWeight:activeTab===t.key?700:400,
            color: activeTab===t.key?'#00263A':'#6b7280',
            borderBottom: activeTab===t.key?'2px solid #00263A':'2px solid transparent',
            marginBottom:-2, display:'flex', alignItems:'center', gap:6, whiteSpace:'nowrap',
          }}>
            {t.label}
            <span style={{fontSize:11,fontWeight:600,padding:'1px 6px',borderRadius:10,
              background:activeTab===t.key?'#00263A':'#e5e7eb',
              color:activeTab===t.key?'#fff':'#6b7280'}}>
              {t.count}
            </span>
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === 'all'    && renderListTab(allItems,    'No processed emails — run a scan to populate')}
      {activeTab === 'auto'   && renderListTab(botItems,    'No auto-processed emails in this range')}
      {activeTab === 'manual' && renderListTab(manualItems, 'No manually approved emails in this range')}
      {activeTab === 'log'    && renderLogTab()}
    </div>
  );
}
// ── Urgent Payments View ──────────────────────────────────────────────────────
function UrgentPaymentsView({ paymentLog, onRefresh, pushToast }) {
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ supplier:'', invoiceRef:'', amount:'', dueDate:'', notes:'' });
  const [saving, setSaving] = useState(false);

  const STATUSES = ['Pending','Queried','Approved','Paid','Disputed'];

  const handleStatusChange = async (id, status) => {
    try {
      await api.post('/api/payment-log/update', { id, status });
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
  };

  const handleAdd = async () => {
    if (!form.supplier.trim()) return;
    setSaving(true);
    try {
      await api.post('/api/payment-log/add', form);
      pushToast('Entry added');
      setForm({ supplier:'', invoiceRef:'', amount:'', dueDate:'', notes:'' });
      setShowAdd(false);
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
    setSaving(false);
  };

  const handleExport = async () => {
    try {
      window.location.href = '/api/payment-log/export';
      pushToast('Downloading Excel…');
    } catch(e) { pushToast('Export failed: ' + e.message); }
  };

  const outstanding = (paymentLog||[]).filter(p=>p.status !== 'Paid');
  const overdue     = outstanding.filter(p => p.dueDate && new Date(p.dueDate) < new Date());
  const totalAmt    = outstanding.reduce((s,p)=>s+(parseFloat(p.amount)||0),0);

  return (
    <div className="main-inner">
      <div className="page-head">
        <div>
          <h1 className="page-title">Urgent Payments</h1>
          <p className="page-sub">{outstanding.length} outstanding · {fmtAmt(totalAmt)} at risk · {overdue.length} overdue</p>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn-ghost" onClick={handleExport}><Icons.download style={{width:14,height:14}}/> Export Excel</button>
          <button className="btn-primary" onClick={()=>setShowAdd(s=>!s)}><Icons.plus style={{width:14,height:14}}/> Add Entry</button>
        </div>
      </div>

      {showAdd && (
        <div className="add-form">
          <div className="form-row">
            <input placeholder="Supplier name *" value={form.supplier} onChange={e=>setForm(f=>({...f,supplier:e.target.value}))}/>
            <input placeholder="Invoice ref" value={form.invoiceRef} onChange={e=>setForm(f=>({...f,invoiceRef:e.target.value}))}/>
            <input placeholder="Amount $" type="number" value={form.amount} onChange={e=>setForm(f=>({...f,amount:e.target.value}))}/>
            <input placeholder="Due date" type="date" value={form.dueDate} onChange={e=>setForm(f=>({...f,dueDate:e.target.value}))}/>
          </div>
          <input placeholder="Notes" value={form.notes} onChange={e=>setForm(f=>({...f,notes:e.target.value}))} style={{width:'100%',marginBottom:8}}/>
          <div style={{display:'flex',gap:8}}>
            <button className="btn-primary" onClick={handleAdd} disabled={saving||!form.supplier.trim()}>{saving?'Saving…':'Add Entry'}</button>
            <button className="btn-ghost" onClick={()=>setShowAdd(false)}>Cancel</button>
          </div>
        </div>
      )}

      {(!paymentLog||paymentLog.length===0)
        ? <div className="empty-state"><div style={{fontSize:13,color:'#6b7280'}}>No urgent payment entries yet</div></div>
        : (
          <div className="table-wrap">
            <table className="data-table">
              <thead><tr>
                <th>Received</th><th>Supplier</th><th>Invoice Ref</th>
                <th>Amount</th><th>Due Date</th><th>Days Overdue</th>
                <th>Status</th><th>Notes</th>
              </tr></thead>
              <tbody>
                {(paymentLog||[]).map(p => {
                  const daysOver = p.dueDate
                    ? Math.max(0, Math.floor((Date.now()-new Date(p.dueDate))/(1000*86400)))
                    : 0;
                  const isOver = daysOver > 0 && p.status !== 'Paid';
                  return (
                    <tr key={p.id} style={{background: isOver ? '#fff7f7' : undefined}}>
                      <td style={{fontFamily:'var(--mono)',fontSize:11}}>{fmtDate(p.dateReceived)}</td>
                      <td style={{fontWeight:600}}>{p.supplier}</td>
                      <td style={{fontFamily:'var(--mono)',fontSize:12}}>{p.invoiceRef||'—'}</td>
                      <td style={{fontFamily:'var(--mono)',fontSize:12,fontWeight:600}}>{fmtAmt(p.amount)}</td>
                      <td style={{fontFamily:'var(--mono)',fontSize:11}}>{fmtDate(p.dueDate)}</td>
                      <td style={{color: isOver?'#dc2626':'#16a34a',fontWeight:700,fontFamily:'var(--mono)',fontSize:12}}>
                        {isOver ? `${daysOver}d` : '—'}
                      </td>
                      <td>
                        <select value={p.status} onChange={e=>handleStatusChange(p.id,e.target.value)}
                          style={{fontSize:12,padding:'3px 6px',borderRadius:4,border:'1px solid #d1d5db',
                            background: p.status==='Paid'?'#f0fdf4':p.status==='Disputed'?'#fef2f2':'#fff'}}>
                          {STATUSES.map(s=><option key={s}>{s}</option>)}
                        </select>
                      </td>
                      <td style={{fontSize:12,color:'#6b7280',maxWidth:160}}>{p.notes||'—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )
      }
    </div>
  );
}

// ── Summary View ──────────────────────────────────────────────────────────────
function SummaryView({ state, onScan, scanning }) {
  const stats    = state?.stats || {};
  const activity = (state?.activity || state?.recentActivity || []);
  const payments = state?.paymentLog || [];
  const processed = state?.processed || [];

  const outstanding = payments.filter(p=>p.status!=='Paid');
  const overdue     = outstanding.filter(p=>p.dueDate&&new Date(p.dueDate)<new Date());
  const totalAmt    = outstanding.reduce((s,p)=>s+(parseFloat(p.amount)||0),0);

  // Category breakdown
  const catCounts = {};
  processed.forEach(p => { catCounts[p.category] = (catCounts[p.category]||0)+1; });
  const catEntries = Object.entries(catCounts).sort((a,b)=>b[1]-a[1]);
  const maxCount = Math.max(...catEntries.map(([,v])=>v), 1);

  return (
    <div className="main-inner">
      <div className="page-head">
        <div><h1 className="page-title">Summary</h1><p className="page-sub">Accounts inbox intelligence</p></div>
        <button className="btn-primary" onClick={onScan} disabled={scanning}>
          {scanning ? <><Icons.spin style={{width:14,height:14}}/> Scanning…</> : <><Icons.refresh style={{width:14,height:14}}/> Scan Now</>}
        </button>
      </div>

      {/* KPI Cards */}
      <div className="kpi-grid">
        <div className="kpi-card">
          <div className="kpi-label">Processed</div>
          <div className="kpi-value">{processed.length || stats.processedToday || 0}</div>
          <div className="kpi-sub">{processed.length > 0 ? 'total auto-filed' : 'auto-filed today'}</div>
        </div>
        <div className="kpi-card kpi-warn">
          <div className="kpi-label">Review Queue</div>
          <div className="kpi-value">{state?.queue?.length||0}</div>
          <div className="kpi-sub">awaiting Mindy</div>
        </div>
        <div className="kpi-card kpi-danger">
          <div className="kpi-label">Urgent Payments</div>
          <div className="kpi-value">{outstanding.length}</div>
          <div className="kpi-sub">{fmtAmt(totalAmt)} outstanding</div>
        </div>
        <div className="kpi-card kpi-red">
          <div className="kpi-label">Overdue</div>
          <div className="kpi-value" style={{color:'#dc2626'}}>{overdue.length}</div>
          <div className="kpi-sub">past due date</div>
        </div>
      </div>

      <div className="summary-grid">
        {/* Category breakdown */}
        <div className="summary-card">
          <h3>Category Breakdown</h3>
          {catEntries.length === 0
            ? <div style={{color:'#9ca3af',fontSize:13}}>No data yet — run a scan</div>
            : catEntries.map(([cat, count]) => {
              const cs = catStyle(cat);
              return (
                <div key={cat} style={{marginBottom:8}}>
                  <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
                    <span style={{fontSize:12,fontWeight:600,color:cs.color}}>{fmtCatLabel(cat)}</span>
                    <span style={{fontSize:12,fontFamily:'var(--mono)',color:'#374151'}}>{count}</span>
                  </div>
                  <div style={{height:6,borderRadius:3,background:'#f3f4f6'}}>
                    <div style={{height:'100%',borderRadius:3,background:cs.color,width:`${(count/maxCount)*100}%`}}/>
                  </div>
                </div>
              );
            })
          }
        </div>

        {/* Recent Activity */}
        <div className="summary-card">
          <h3>Recent Activity</h3>
          {activity.length === 0
            ? <div style={{color:'#9ca3af',fontSize:13}}>No activity yet</div>
            : activity.slice(0,10).map((a,i) => (
              <div key={i} className="activity-item">
                <span className="activity-dot"/>
                <div>
                  <div style={{fontSize:12,fontWeight:600,color:'#1f2937'}}>{a.description || a.msg || '—'}</div>
                  <div style={{fontSize:11,color:'#9ca3af',fontFamily:'var(--mono)'}}>{fmtDate(a.createdAt || a.ts)}</div>
                </div>
              </div>
            ))
          }
        </div>
      </div>

      {/* ── What's Urgent / What Can Wait footer strip ── */}
      {(() => {
        const queue = state?.queue || [];
        const critical = queue.filter(i => i.isCritical);
        const urgent = queue.filter(i => !i.isCritical && (i.tags||[]).includes('urgent-payment'));
        const needsAction = [...critical, ...urgent];
        const canWait = queue.filter(i => !i.isCritical && !(i.tags||[]).includes('urgent-payment') && (i.urgencyScore||3) >= 3);
        const lowPriority = queue.filter(i => (i.urgencyScore||3) < 3);
        const today = new Date().toISOString().slice(0,10);
        const handledToday = (state?.processed||[]).filter(p => (p.processedAt||'').startsWith(today)).length;

        const topItems = needsAction.slice(0,3);

        return (
          <div style={{
            marginTop:20, borderRadius:10, border:'1px solid #e5e7eb',
            overflow:'hidden', background:'#fff',
          }}>
            <div style={{
              padding:'10px 16px', background:'#f8fafc',
              borderBottom:'1px solid #e5e7eb',
              display:'flex', alignItems:'center', gap:8,
            }}>
              <span style={{fontSize:13,fontWeight:700,color:'#1f2937'}}>What's Urgent / What Can Wait</span>
              <span style={{fontSize:11,color:'#9ca3af',marginLeft:'auto'}}>Updates every 20s</span>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:0}}>
              {/* Needs Action Now */}
              <div style={{padding:'14px 16px',borderRight:'1px solid #e5e7eb',background: needsAction.length>0?'#fff5f5':'#fff'}}>
                <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:8}}>
                  <span style={{fontSize:22,fontWeight:800,color:needsAction.length>0?'#dc2626':'#9ca3af'}}>{needsAction.length}</span>
                  <div>
                    <div style={{fontSize:11,fontWeight:700,color:'#dc2626'}}>NEEDS ACTION NOW</div>
                    <div style={{fontSize:10,color:'#9ca3af'}}>{critical.length} critical · {urgent.length} urgent</div>
                  </div>
                </div>
                {topItems.map(i => (
                  <div key={i.id} style={{fontSize:11,color:'#374151',padding:'3px 0',borderTop:'1px solid #fef2f2',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                    {i.isCritical?'⚡':'🔴'} {i.subject?.slice(0,45)}
                  </div>
                ))}
                {needsAction.length === 0 && <div style={{fontSize:11,color:'#9ca3af',fontStyle:'italic'}}>All clear — nothing urgent</div>}
              </div>
              {/* Can Wait */}
              <div style={{padding:'14px 16px',borderRight:'1px solid #e5e7eb'}}>
                <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:8}}>
                  <span style={{fontSize:22,fontWeight:800,color:'#d97706'}}>{canWait.length}</span>
                  <div>
                    <div style={{fontSize:11,fontWeight:700,color:'#d97706'}}>CAN WAIT</div>
                    <div style={{fontSize:10,color:'#9ca3af'}}>{lowPriority.length} low priority</div>
                  </div>
                </div>
                {canWait.slice(0,3).map(i => (
                  <div key={i.id} style={{fontSize:11,color:'#374151',padding:'3px 0',borderTop:'1px solid #fef9c3',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                    ⏳ {i.subject?.slice(0,45)}
                  </div>
                ))}
              </div>
              {/* Handled Today */}
              <div style={{padding:'14px 16px',background:'#f0fdf4'}}>
                <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:8}}>
                  <span style={{fontSize:22,fontWeight:800,color:'#16a34a'}}>{handledToday}</span>
                  <div>
                    <div style={{fontSize:11,fontWeight:700,color:'#16a34a'}}>HANDLED TODAY</div>
                    <div style={{fontSize:10,color:'#9ca3af'}}>auto-filed + approved</div>
                  </div>
                </div>
                <div style={{fontSize:11,color:'#6b7280',fontStyle:'italic'}}>
                  {handledToday === 0 ? 'Nothing processed yet today' : `${handledToday} email${handledToday!==1?'s':''} dealt with today`}
                </div>
              </div>
            </div>
          </div>
        );
      })()}
    </div>
  );
}

// ── Priority Rules ────────────────────────────────────────────────────────────
function PriorityRulesSection({ pushToast }) {
  const [rules, setRules] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ prompt: '', urgencyScore: 3 });
  const [saving, setSaving] = useState(false);

  const SCORE_LABELS = {
    1: '1 — Low / Noise',
    2: '2 — Query / Info',
    3: '3 — Action Required',
    4: '4 — Overdue / Final Notice',
    5: '5 — Critical / Urgent',
  };

  const load = useCallback(async () => {
    try { const d = await api.get('/api/priority-rules'); setRules(d); } catch {}
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleSave = async () => {
    if (!form.prompt.trim()) return;
    setSaving(true);
    try {
      await api.post('/api/priority-rules', { prompt: form.prompt, urgencyScore: form.urgencyScore });
      setForm({ prompt: '', urgencyScore: 3 });
      setShowForm(false);
      pushToast('Priority rule saved');
      load();
    } catch(e) { pushToast('Error: ' + e.message); }
    setSaving(false);
  };

  const handleToggle = async (rule) => {
    await api.patch(`/api/priority-rules/${rule.id}`, { active: !rule.active });
    load();
  };

  const handleDelete = async (rule) => {
    if (!confirm(`Delete this rule?\n"${rule.prompt}"`)) return;
    await api.delete(`/api/priority-rules/${rule.id}`);
    pushToast('Rule deleted');
    load();
  };

  const scoreColor = (s) => {
    if (s >= 5) return { bg:'#fee2e2', color:'#991b1b', border:'#fca5a5' };
    if (s >= 4) return { bg:'#fff7ed', color:'#c2410c', border:'#fed7aa' };
    if (s >= 3) return { bg:'#fefce8', color:'#854d0e', border:'#fde68a' };
    if (s >= 2) return { bg:'#f0fdf4', color:'#15803d', border:'#bbf7d0' };
    return { bg:'#f3f4f6', color:'#6b7280', border:'#e5e7eb' };
  };

  return (
    <div>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16}}>
        <div>
          <div style={{fontSize:14,fontWeight:700,color:'#1f2937'}}>Priority Rules</div>
          <div style={{fontSize:12,color:'#6b7280',marginTop:2}}>Plain-English rules that tell the AI how to score urgency. Applied on every scan.</div>
        </div>
        <button className="btn-primary" onClick={()=>setShowForm(s=>!s)}>+ Add Rule</button>
      </div>

      {/* Built-in read-only rule */}
      <div style={{
        background:'#fdf4ff', border:'1px solid #e9d5ff', borderRadius:10,
        padding:'12px 16px', marginBottom:12, borderLeft:'3px solid #7c3aed',
        display:'flex', alignItems:'flex-start', gap:12,
      }}>
        <div style={{flex:1,minWidth:0}}>
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:4}}>
            <span style={{fontSize:11,fontWeight:800,padding:'2px 8px',borderRadius:10,
              background:'#fee2e2',color:'#991b1b',border:'1px solid #fca5a5'}}>Score 5 — Critical</span>
            <span style={{fontSize:10,fontWeight:700,color:'#7c3aed',background:'#ede9fe',borderRadius:10,padding:'1px 6px'}}>BUILT-IN</span>
          </div>
          <div style={{fontSize:12,color:'#374151',lineHeight:1.5}}>
            Email from <strong>@eliteroads.com.au</strong> requesting a client invoice to be raised or issued → Always Score 5 (Critical)
          </div>
          <div style={{fontSize:11,color:'#9ca3af',marginTop:4,fontStyle:'italic'}}>This rule cannot be disabled — it is enforced in the classifier and scanner.</div>
        </div>
      </div>

      {/* Add rule form */}
      {showForm && (
        <div style={{background:'#f8fafc',border:'1px solid #e2e8f0',borderRadius:10,padding:18,marginBottom:16}}>
          <div style={{fontSize:13,fontWeight:700,color:'#1f2937',marginBottom:14}}>New Priority Rule</div>
          <div style={{marginBottom:12}}>
            <label style={{fontSize:11,fontWeight:700,color:'#6b7280',display:'block',marginBottom:4}}>RULE — plain English description of emails that match *</label>
            <textarea
              value={form.prompt}
              onChange={e=>setForm(f=>({...f,prompt:e.target.value}))}
              rows={3}
              placeholder={"Examples:\n• Emails from any supplier with 'FINAL NOTICE' or 'account on hold' in the subject\n• Monthly statements from Boral or Hanson exceeding $50,000"}
              style={{width:'100%',padding:'9px 12px',borderRadius:7,border:'1px solid #d1d5db',fontSize:13,resize:'vertical',fontFamily:'inherit',boxSizing:'border-box',lineHeight:1.5}}
            />
          </div>
          <div style={{marginBottom:16}}>
            <label style={{fontSize:11,fontWeight:700,color:'#6b7280',display:'block',marginBottom:6}}>URGENCY SCORE</label>
            <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
              {[1,2,3,4,5].map(s => {
                const sc = scoreColor(s);
                const isActive = form.urgencyScore === s;
                return (
                  <button key={s} onClick={()=>setForm(f=>({...f,urgencyScore:s}))} style={{
                    all:'unset', cursor:'pointer', padding:'7px 14px', borderRadius:7, fontSize:12, fontWeight:600,
                    border:`2px solid ${isActive ? sc.color : sc.border}`,
                    background: isActive ? sc.bg : '#fff',
                    color: isActive ? sc.color : '#6b7280',
                    transition:'all 0.12s',
                  }}>
                    {SCORE_LABELS[s]}
                  </button>
                );
              })}
            </div>
          </div>
          <div style={{display:'flex',gap:8}}>
            <button className="btn-primary" onClick={handleSave} disabled={saving||!form.prompt.trim()}>
              {saving?'Saving…':'Save Rule'}
            </button>
            <button className="btn-ghost" onClick={()=>setShowForm(false)}>Cancel</button>
          </div>
        </div>
      )}

      {/* Rules list */}
      {rules.length === 0 && !showForm ? (
        <div style={{textAlign:'center',padding:'32px 20px',color:'#9ca3af'}}>
          <div style={{fontSize:28,marginBottom:8}}>📋</div>
          <div style={{fontSize:13,fontWeight:600,marginBottom:4,color:'#6b7280'}}>No custom priority rules yet</div>
          <div style={{fontSize:12}}>Add a rule to tell the AI how to prioritise specific emails</div>
        </div>
      ) : (
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {rules.map(rule => {
            const sc = scoreColor(rule.urgencyScore);
            return (
              <div key={rule.id} style={{
                background:'#fff', border:'1px solid #e5e7eb', borderRadius:10,
                padding:'14px 16px', display:'flex', alignItems:'flex-start', gap:14,
                opacity: rule.active ? 1 : 0.55,
                borderLeft:`3px solid ${sc.color}`,
              }}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:6}}>
                    <span style={{fontSize:11,fontWeight:700,padding:'2px 8px',borderRadius:10,
                      background:sc.bg,color:sc.color,border:`1px solid ${sc.border}`}}>
                      Score {rule.urgencyScore} — {rule.urgencyScore>=5?'Critical':rule.urgencyScore>=4?'Overdue/Final':rule.urgencyScore>=3?'Action Required':rule.urgencyScore>=2?'Query':'Low/Noise'}
                    </span>
                    {!rule.active && <span style={{fontSize:10,fontWeight:700,color:'#9ca3af',background:'#f3f4f6',borderRadius:10,padding:'1px 6px'}}>PAUSED</span>}
                  </div>
                  <div style={{fontSize:12,color:'#374151',lineHeight:1.5,fontStyle:'italic'}}>
                    "{rule.prompt}"
                  </div>
                </div>
                <div style={{display:'flex',gap:6,flexShrink:0}}>
                  <button onClick={()=>handleToggle(rule)}
                    style={{all:'unset',cursor:'pointer',fontSize:11,padding:'4px 10px',borderRadius:6,
                      border:'1px solid #e5e7eb',background:rule.active?'#f9fafb':'#f0fdf4',
                      color:rule.active?'#6b7280':'#16a34a',fontWeight:600}}>
                    {rule.active?'Pause':'Enable'}
                  </button>
                  <button onClick={()=>handleDelete(rule)}
                    style={{all:'unset',cursor:'pointer',fontSize:11,padding:'4px 10px',borderRadius:6,
                      border:'1px solid #fca5a5',background:'#fff',color:'#dc2626',fontWeight:600}}
                    onMouseEnter={e=>e.currentTarget.style.background='#fee2e2'}
                    onMouseLeave={e=>e.currentTarget.style.background='#fff'}>Delete</button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── Settings View ─────────────────────────────────────────────────────────────
function SettingsView({ settings, onRefresh, pushToast, labels = [] }) {
  const [cats, setCats]           = useState(settings?.categories || []);
  const [general, setGeneral]     = useState(settings?.general || { scanInterval:30, confidenceThreshold:85 });
  const [showAddCat, setShowAddCat] = useState(false);
  const [editingCat, setEditingCat] = useState(null);
  const [newCat, setNewCat]       = useState({ key:'', displayName:'', forwardTo:'', autoForward:false });
  const [saving, setSaving]       = useState(false);

  useEffect(() => {
    setCats(settings?.categories || []);
    setGeneral(settings?.general || { scanInterval:30, confidenceThreshold:85 });
  }, [settings]);

  const handleSaveGeneral = async () => {
    setSaving(true);
    try {
      await api.post('/api/settings', { categories: cats, general });
      pushToast('Settings saved');
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
    setSaving(false);
  };

  const handleAddCat = async () => {
    if (!newCat.key.trim() || !newCat.displayName.trim()) return;
    const cat = {
      key: newCat.key.toLowerCase().replace(/\s+/g,'-'),
      displayName: newCat.displayName,
      forwardTo: newCat.forwardTo.split(',').map(e=>e.trim()).filter(Boolean),
      autoForward: newCat.autoForward,
      emailFolder: `Accounts/Routed/${newCat.displayName}`,
    };
    const updated = [...cats, cat];
    try {
      await api.post('/api/settings', { categories: updated, general });
      setCats(updated);
      setShowAddCat(false);
      setNewCat({ key:'', displayName:'', forwardTo:'', autoForward:false });
      pushToast('Category added: ' + cat.displayName);
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
  };

  const handleDeleteCat = async (key) => {
    const updated = cats.filter(c=>c.key!==key);
    try {
      await api.post('/api/settings', { categories: updated, general });
      setCats(updated);
      pushToast('Category removed');
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
  };

  const handleSaveCat = async (cat) => {
    const updated = cats.map(c => c.key===cat.key ? cat : c);
    try {
      await api.post('/api/settings', { categories: updated, general });
      setCats(updated);
      setEditingCat(null);
      pushToast('Category updated');
      onRefresh();
    } catch(e) { pushToast('Error: ' + e.message); }
  };

  return (
    <div className="main-inner">
      <div className="page-head">
        <div><h1 className="page-title">Settings</h1><p className="page-sub">Configure routing categories and scan behaviour</p></div>
      </div>

      {/* Categories */}
      <div className="settings-section">
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16}}>
          <h2 className="section-title">Routing Categories</h2>
          <button className="btn-primary" onClick={()=>setShowAddCat(s=>!s)}>
            <Icons.plus style={{width:13,height:13}}/> Add Category
          </button>
        </div>

        {showAddCat && (
          <div className="add-form" style={{marginBottom:16}}>
            <div className="form-row">
              <input placeholder="Key (e.g. route-legal)" value={newCat.key}
                onChange={e=>setNewCat(f=>({...f,key:e.target.value}))}/>
              <input placeholder="Display name (e.g. → Legal)" value={newCat.displayName}
                onChange={e=>setNewCat(f=>({...f,displayName:e.target.value}))}/>
            </div>
            <input placeholder="Forward to emails (comma-separated)" value={newCat.forwardTo}
              onChange={e=>setNewCat(f=>({...f,forwardTo:e.target.value}))}
              style={{width:'100%',marginBottom:8}}/>
            <label style={{display:'flex',alignItems:'center',gap:6,fontSize:13,marginBottom:12}}>
              <input type="checkbox" checked={newCat.autoForward}
                onChange={e=>setNewCat(f=>({...f,autoForward:e.target.checked}))}/>
              Auto-forward at ≥85% confidence
            </label>
            <div style={{display:'flex',gap:8}}>
              <button className="btn-primary" onClick={handleAddCat}>Add</button>
              <button className="btn-ghost" onClick={()=>setShowAddCat(false)}>Cancel</button>
            </div>
          </div>
        )}

        <div className="table-wrap">
          <table className="data-table">
            <thead><tr><th>Key</th><th>Display Name</th><th>Forward To</th><th>Auto-Forward</th><th>Actions</th></tr></thead>
            <tbody>
              {cats.map(cat => (
                <tr key={cat.key}>
                  {editingCat?.key === cat.key ? (
                    <>
                      <td><code style={{fontSize:11}}>{cat.key}</code></td>
                      <td><input value={editingCat.displayName} onChange={e=>setEditingCat(c=>({...c,displayName:e.target.value}))} style={{width:'100%'}}/></td>
                      <td><input value={(editingCat.forwardTo||[]).join(', ')}
                        onChange={e=>setEditingCat(c=>({...c,forwardTo:e.target.value.split(',').map(x=>x.trim()).filter(Boolean)}))}
                        style={{width:'100%'}} placeholder="email1@, email2@"/></td>
                      <td><input type="checkbox" checked={editingCat.autoForward}
                        onChange={e=>setEditingCat(c=>({...c,autoForward:e.target.checked}))}/></td>
                      <td>
                        <button className="btn-sm btn-primary" onClick={()=>handleSaveCat(editingCat)}>Save</button>
                        <button className="btn-sm btn-ghost" onClick={()=>setEditingCat(null)} style={{marginLeft:4}}>Cancel</button>
                      </td>
                    </>
                  ) : (
                    <>
                      <td><code style={{fontSize:11,color:'#6b7280'}}>{cat.key}</code></td>
                      <td style={{fontWeight:600}}>{cat.displayName}</td>
                      <td style={{fontSize:12}}>
                        {(cat.forwardTo||[]).length
                          ? (cat.forwardTo||[]).map(e=><span key={e} className="email-tag">{e}</span>)
                          : <span style={{color:'#9ca3af'}}>—</span>}
                      </td>
                      <td>{cat.autoForward ? '✅' : '—'}</td>
                      <td>
                        <button className="btn-sm btn-ghost" onClick={()=>setEditingCat({...cat})}><Icons.edit style={{width:12,height:12}}/></button>
                        <button className="btn-sm btn-ghost" style={{color:'#dc2626',marginLeft:4}}
                          onClick={()=>handleDeleteCat(cat.key)}><Icons.trash style={{width:12,height:12}}/></button>
                      </td>
                    </>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Custom Labels */}
      <div className="settings-section">
        <LabelsTab pushToast={pushToast}/>
      </div>

      {/* Priority Rules */}
      <div className="settings-section">
        <PriorityRulesSection pushToast={pushToast}/>
      </div>

      {/* General Settings */}
      <div className="settings-section">
        <h2 className="section-title">General</h2>
        <div className="general-grid">
          <div>
            <label className="field-label">Scan Interval (minutes)</label>
            <input type="number" value={general.scanInterval} min={5} max={120}
              onChange={e=>setGeneral(g=>({...g,scanInterval:parseInt(e.target.value)}))}
              style={{width:100}}/>
          </div>

          <div>
            <label className="field-label">Email Source</label>
            <div style={{display:'flex',alignItems:'center',gap:8,fontSize:13}}>
              <span style={{fontWeight:700,color:'#10b981'}}>● Live (MS Graph)</span>
              <span style={{fontSize:12,color:'#6b7280'}}>accounts@eliteroads.com.au</span>
            </div>
            <div style={{fontSize:11,color:'#9ca3af',marginTop:4}}>Connected directly via Microsoft Graph API</div>
          </div>
        </div>
        <button className="btn-primary" onClick={handleSaveGeneral} disabled={saving} style={{marginTop:16}}>
          {saving?'Saving…':'Save Settings'}
        </button>
      </div>
    </div>
  );
}

// ── Activity Log View ─────────────────────────────────────────────────────────
function ActivityLogView({ activityLog, onRefresh, pushToast }) {
  const [search,     setSearch]     = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [dateRange,  setDateRange]  = useState('7d');
  const [page,       setPage]       = useState(0);
  const PAGE_SZ = 50;

  // Auto-refresh every 30 seconds
  useEffect(() => {
    const id = setInterval(onRefresh, 30000);
    return () => clearInterval(id);
  }, [onRefresh]);

  // Reset page when filters change
  useEffect(() => { setPage(0); }, [search, typeFilter, dateRange]);

  function timeAgo(isoStr) {
    if (!isoStr) return '—';
    const diff = Date.now() - new Date(isoStr).getTime();
    const mins  = Math.floor(diff / 60000);
    const hrs   = Math.floor(diff / 3600000);
    const days  = Math.floor(diff / 86400000);
    if (mins < 1)  return 'just now';
    if (mins < 60) return `${mins} min ago`;
    if (hrs  < 24) return `${hrs} hr${hrs!==1?'s':''} ago`;
    if (days === 1) {
      const t = new Date(isoStr);
      return `Yesterday at ${t.toLocaleTimeString('en-AU', { hour:'2-digit', minute:'2-digit' })}`;
    }
    const d = new Date(isoStr);
    return d.toLocaleDateString('en-AU', { day:'2-digit', month:'short' }) + ' at ' +
           d.toLocaleTimeString('en-AU', { hour:'2-digit', minute:'2-digit' });
  }

  const TYPE_BADGES = {
    scan:     { bg:'#dbeafe', color:'#1d4ed8', border:'#bfdbfe' },
    approve:  { bg:'#dcfce7', color:'#15803d', border:'#bbf7d0' },
    approved: { bg:'#dcfce7', color:'#15803d', border:'#bbf7d0' },
    dismiss:  { bg:'#f3f4f6', color:'#6b7280', border:'#e5e7eb' },
    dismissed:{ bg:'#f3f4f6', color:'#6b7280', border:'#e5e7eb' },
    override: { bg:'#fef3c7', color:'#92400e', border:'#fde68a' },
    overridden:{ bg:'#fef3c7', color:'#92400e', border:'#fde68a' },
    move:     { bg:'#f3e8ff', color:'#6b21a8', border:'#e9d5ff' },
    reply:    { bg:'#ccfbf1', color:'#0f766e', border:'#99f6e4' },
    forward:  { bg:'#ffedd5', color:'#c2410c', border:'#fed7aa' },
    manual:   { bg:'#e2e8f0', color:'#334155', border:'#cbd5e1' },
    queued:   { bg:'#dbeafe', color:'#1d4ed8', border:'#bfdbfe' },
    processed:{ bg:'#dcfce7', color:'#15803d', border:'#bbf7d0' },
    updated:  { bg:'#fef3c7', color:'#92400e', border:'#fde68a' },
    requeued: { bg:'#f3e8ff', color:'#6b21a8', border:'#e9d5ff' },
  };

  const TYPE_OPTIONS = ['all', 'scan', 'approve', 'dismiss', 'override', 'move', 'reply', 'forward', 'manual'];

  const now = Date.now();
  const filtered = (activityLog || []).filter(row => {
    if (typeFilter !== 'all') {
      const t = (row.type || '').toLowerCase();
      if (!t.startsWith(typeFilter)) return false;
    }
    if (dateRange === 'today') {
      const today = new Date().toISOString().slice(0, 10);
      if (!(row.createdAt || '').startsWith(today)) return false;
    } else if (dateRange === '7d') {
      if (now - new Date(row.createdAt).getTime() > 7 * 86400000) return false;
    }
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      const msg = (row.description || row.message || '').toLowerCase();
      const meta = row.meta ? JSON.stringify(row.meta).toLowerCase() : '';
      if (!msg.includes(q) && !meta.includes(q)) return false;
    }
    return true;
  });

  const totalPages = Math.ceil(filtered.length / PAGE_SZ);
  const paged = filtered.slice(page * PAGE_SZ, (page + 1) * PAGE_SZ);

  const badgeStyle = (type) => {
    const t = (type || '').toLowerCase();
    const s = TYPE_BADGES[t] || { bg:'#f3f4f6', color:'#374151', border:'#e5e7eb' };
    return { display:'inline-block', fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:10,
             background:s.bg, color:s.color, border:`1px solid ${s.border}`, textTransform:'uppercase',
             letterSpacing:'0.04em', whiteSpace:'nowrap' };
  };

  return (
    <div className="main-inner">
      <div className="page-head">
        <div>
          <h1 className="page-title">Activity Log</h1>
          <p className="page-sub">All actions taken via the portal or detected from Outlook</p>
        </div>
      </div>

      {/* Filter bar */}
      <div style={{display:'flex',gap:8,flexWrap:'wrap',marginBottom:14,alignItems:'center'}}>
        <input
          value={search} onChange={e=>setSearch(e.target.value)}
          placeholder="🔍 Search by message…"
          style={{fontSize:12,padding:'6px 10px',borderRadius:8,border:'1px solid #d1d5db',minWidth:200,outline:'none'}}
        />
        <select value={typeFilter} onChange={e=>setTypeFilter(e.target.value)}
          style={{fontSize:12,padding:'6px 10px',borderRadius:8,border:'1px solid #d1d5db',background:'#fff',outline:'none'}}>
          {TYPE_OPTIONS.map(t=>(
            <option key={t} value={t}>{t === 'all' ? 'All types' : t.charAt(0).toUpperCase()+t.slice(1)}</option>
          ))}
        </select>
        <div style={{display:'flex',gap:0,borderRadius:8,overflow:'hidden',border:'1px solid #d1d5db'}}>
          {[['today','Today'],['7d','Last 7 days'],['all','All time']].map(([v,l])=>(
            <button key={v} onClick={()=>setDateRange(v)}
              style={{all:'unset',cursor:'pointer',padding:'6px 12px',fontSize:12,fontWeight:dateRange===v?700:400,
                      background:dateRange===v?'#00263A':'#fff',color:dateRange===v?'#fff':'#374151',
                      borderRight:'1px solid #d1d5db',whiteSpace:'nowrap'}}>
              {l}
            </button>
          ))}
        </div>
        {(search || typeFilter !== 'all') && (
          <button onClick={()=>{setSearch('');setTypeFilter('all');}}
            style={{all:'unset',cursor:'pointer',fontSize:12,color:'#6b7280',padding:'5px 10px',
                    borderRadius:8,border:'1px solid #e5e7eb',background:'#f9fafb'}}>
            × Clear
          </button>
        )}
        <span style={{fontSize:11,color:'#9ca3af',marginLeft:'auto'}}>{filtered.length} entries</span>
      </div>

      {/* Table */}
      {filtered.length === 0 ? (
        <div style={{padding:'48px',textAlign:'center',color:'#9ca3af',fontSize:13,background:'#fff',border:'1px solid #e5e7eb',borderRadius:10}}>
          No activity yet — actions taken in the portal or Outlook will appear here
        </div>
      ) : (
        <>
          <div style={{border:'1px solid #e5e7eb',borderRadius:10,overflow:'hidden',background:'#fff'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:12}}>
              <thead>
                <tr style={{background:'#f8fafc',borderBottom:'1px solid #e5e7eb'}}>
                  <th style={{padding:'8px 12px',textAlign:'left',fontWeight:600,color:'#374151',width:120}}>Time</th>
                  <th style={{padding:'8px 12px',textAlign:'left',fontWeight:600,color:'#374151',width:100}}>Type</th>
                  <th style={{padding:'8px 12px',textAlign:'left',fontWeight:600,color:'#374151'}}>Action / Message</th>
                  <th style={{padding:'8px 12px',textAlign:'left',fontWeight:600,color:'#374151',width:180}}>Email Subject</th>
                  <th style={{padding:'8px 12px',textAlign:'left',fontWeight:600,color:'#374151',width:140}}>Folder / Dest.</th>
                </tr>
              </thead>
              <tbody>
                {paged.map((row, i) => {
                  const meta = row.meta || {};
                  return (
                    <tr key={row.id} style={{borderBottom: i < paged.length-1 ? '1px solid #f1f5f9' : 'none',
                      background: i % 2 === 0 ? '#fff' : '#fafafa'}}
                      onMouseEnter={e=>e.currentTarget.style.background='#f0f9ff'}
                      onMouseLeave={e=>e.currentTarget.style.background=i%2===0?'#fff':'#fafafa'}>
                      <td style={{padding:'8px 12px',color:'#6b7280',whiteSpace:'nowrap',fontFamily:'var(--mono)',fontSize:11}}>
                        {timeAgo(row.createdAt)}
                      </td>
                      <td style={{padding:'8px 12px'}}>
                        <span style={badgeStyle(row.type)}>{row.type || '—'}</span>
                      </td>
                      <td style={{padding:'8px 12px',color:'#1e293b',maxWidth:300}}>
                        <span style={{overflow:'hidden',textOverflow:'ellipsis',display:'block',whiteSpace:'nowrap'}}>
                          {row.description || row.message || '—'}
                        </span>
                      </td>
                      <td style={{padding:'8px 12px',color:'#6b7280',maxWidth:180}}>
                        {meta.subject
                          ? <span style={{overflow:'hidden',textOverflow:'ellipsis',display:'block',whiteSpace:'nowrap'}}>{meta.subject}</span>
                          : <span style={{color:'#d1d5db'}}>—</span>}
                      </td>
                      <td style={{padding:'8px 12px',color:'#6b7280',maxWidth:140}}>
                        {(meta.movedTo || meta.destinationFolderId)
                          ? <span style={{overflow:'hidden',textOverflow:'ellipsis',display:'block',whiteSpace:'nowrap',
                              fontFamily:'var(--mono)',fontSize:10}}>
                              {meta.movedTo || meta.destinationFolderId}
                            </span>
                          : <span style={{color:'#d1d5db'}}>—</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div style={{display:'flex',gap:6,justifyContent:'center',marginTop:14,alignItems:'center'}}>
              <button onClick={()=>setPage(p=>Math.max(0,p-1))} disabled={page===0}
                style={{all:'unset',cursor:page===0?'default':'pointer',padding:'5px 12px',borderRadius:6,
                  border:'1px solid #e5e7eb',background:'#fff',fontSize:12,color:page===0?'#d1d5db':'#374151'}}>
                ‹ Prev
              </button>
              <span style={{fontSize:12,color:'#6b7280'}}>Page {page+1} of {totalPages}</span>
              <button onClick={()=>setPage(p=>Math.min(totalPages-1,p+1))} disabled={page===totalPages-1}
                style={{all:'unset',cursor:page===totalPages-1?'default':'pointer',padding:'5px 12px',borderRadius:6,
                  border:'1px solid #e5e7eb',background:'#fff',fontSize:12,color:page===totalPages-1?'#d1d5db':'#374151'}}>
                Next ›
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ── FolderBrowserView — shows emails from a specific Outlook folder ───────────
function FolderBrowserView({ folderId, folderName, pushToast }) {
  const [emails, setEmails] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0);
  const PAGE_SIZE = 50;

  const fetchEmails = useCallback(async (pg, bust) => {
    setLoading(true);
    try {
      const skip = pg * PAGE_SIZE;
      const qs = `folderId=${encodeURIComponent(folderId)}&top=${PAGE_SIZE}&skip=${skip}${bust ? '&t=' + Date.now() : ''}`;
      const data = await api.get(`/api/folder-emails?${qs}`);
      setEmails(data.emails || []);
      setTotal(data.total || 0);
    } catch(e) {
      pushToast('Failed to load folder: ' + e.message);
      setEmails([]);
    }
    setLoading(false);
  }, [folderId]);

  // Reset and fetch when folderId changes
  useEffect(() => {
    setPage(0);
    fetchEmails(0, false);
  }, [folderId]);

  // Auto-refresh every 60 seconds
  const pageRef = useRef(page);
  useEffect(() => { pageRef.current = page; }, [page]);
  useEffect(() => {
    const id = setInterval(() => fetchEmails(pageRef.current, false), 60000);
    return () => clearInterval(id);
  }, [folderId]);

  const handlePrev = () => {
    const np = Math.max(0, page - 1);
    setPage(np);
    fetchEmails(np, false);
  };
  const handleNext = () => {
    const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
    const np = Math.min(totalPages - 1, page + 1);
    setPage(np);
    fetchEmails(np, false);
  };

  const fmtRelDate = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    const diff = Date.now() - d;
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    const days = Math.floor(hrs / 24);
    if (days < 7) return `${days}d ago`;
    return d.toLocaleDateString('en-AU', { day: 'numeric', month: 'short' });
  };

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const displayName = folderName.replace(/^\*+|\*+$/g, '').trim();

  return (
    <div style={{padding:'20px 24px', maxWidth:900}}>
      {/* Header */}
      <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:16}}>
        <h2 style={{margin:0, fontSize:18, fontWeight:700, color:'var(--navy)', flex:1}}>
          📁 {displayName}
          {total > 0 && (
            <span style={{fontSize:13, fontWeight:400, color:'#6b7280', marginLeft:8}}>
              {total} email{total !== 1 ? 's' : ''}
            </span>
          )}
        </h2>
        <button
          onClick={() => fetchEmails(page, true)}
          disabled={loading}
          style={{
            all:'unset', cursor:loading?'wait':'pointer', fontSize:12, fontWeight:600,
            padding:'6px 14px', borderRadius:6, border:'1px solid #d1d5db',
            background:'#fff', color:'#374151', display:'flex', alignItems:'center', gap:5,
          }}
        >
          {loading ? <Icons.spin style={{width:13,height:13}}/> : '🔄'} Refresh
        </button>
      </div>

      {loading && emails.length === 0 ? (
        <div style={{display:'flex', alignItems:'center', gap:12, padding:'40px 0', color:'#9ca3af'}}>
          <Icons.spin style={{width:20, height:20}}/>
          <span>Loading emails…</span>
        </div>
      ) : emails.length === 0 ? (
        <div style={{padding:'40px 0', textAlign:'center', color:'#9ca3af', fontSize:14}}>
          No emails in this folder
        </div>
      ) : (
        <>
          <div style={{border:'1px solid #e5e7eb', borderRadius:8, overflow:'hidden', background:'#fff'}}>
            {emails.map((email, idx) => (
              <div
                key={email.id}
                onClick={() => email.webLink && window.open(email.webLink, '_blank')}
                style={{
                  display:'flex', alignItems:'flex-start', gap:10,
                  padding:'10px 14px',
                  borderBottom: idx < emails.length - 1 ? '1px solid #f3f4f6' : 'none',
                  cursor: email.webLink ? 'pointer' : 'default',
                  background:'#fff',
                }}
                onMouseEnter={e => e.currentTarget.style.background='#f9fafb'}
                onMouseLeave={e => e.currentTarget.style.background='#fff'}
              >
                {/* Read/unread dot */}
                <div style={{
                  width:8, height:8, borderRadius:'50%', flexShrink:0, marginTop:5,
                  background: email.isRead ? '#d1d5db' : '#3b82f6',
                }}/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:2}}>
                    <span style={{
                      fontWeight: email.isRead ? 400 : 700,
                      fontSize:13, color:'#111827',
                      overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', flex:1,
                    }}>
                      {email.subject}
                    </span>
                    {email.hasAttachments && (
                      <Icons.clip style={{width:12, height:12, color:'#9ca3af', flexShrink:0}}/>
                    )}
                    <span style={{fontSize:11, color:'#9ca3af', flexShrink:0, fontFamily:'var(--mono)'}}>
                      {fmtRelDate(email.date)}
                    </span>
                  </div>
                  <div style={{fontSize:11, color:'#6b7280', marginBottom:2}}>
                    <span style={{fontWeight:600}}>{email.from}</span>
                    {email.fromEmail && email.fromEmail !== email.from && (
                      <span style={{fontWeight:400, marginLeft:4, color:'#9ca3af'}}>‹{email.fromEmail}›</span>
                    )}
                  </div>
                  {email.snippet && (
                    <div style={{fontSize:11, color:'#9ca3af', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>
                      {email.snippet}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div style={{display:'flex', gap:6, justifyContent:'center', marginTop:14, alignItems:'center'}}>
              <button onClick={handlePrev} disabled={page === 0}
                style={{all:'unset', cursor:page===0?'default':'pointer', padding:'5px 12px', borderRadius:6,
                  border:'1px solid #e5e7eb', background:'#fff', fontSize:12, color:page===0?'#d1d5db':'#374151'}}>
                ‹ Prev
              </button>
              <span style={{fontSize:12, color:'#6b7280'}}>Page {page+1} of {totalPages}</span>
              <button onClick={handleNext} disabled={page === totalPages-1}
                style={{all:'unset', cursor:page===totalPages-1?'default':'pointer', padding:'5px 12px', borderRadius:6,
                  border:'1px solid #e5e7eb', background:'#fff', fontSize:12, color:page===totalPages-1?'#d1d5db':'#374151'}}>
                Next ›
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

Object.assign(window, { ReviewQueueView, ProcessedView, UrgentPaymentsView, SummaryView, SettingsView, ActivityLogView, FolderBrowserView });
