/* FinFlow Screens — Expenses (list, detail, new, OCR review, flagged, import) */

const EXPENSE_COLUMNS = ["ID", "Date", "Merchant / memo", "Owner", "Category", "Amount", "Status"];

const ExpenseList = () => {
  const d = FF_DATA;
  const [status, setStatus] = React.useState("all");
  const [cat, setCat] = React.useState("all");
  const [q, setQ] = React.useState("");
  const [compact, setCompact] = React.useState(false);
  const [selected, setSelected] = React.useState([]);
  const [columnsOpen, setColumnsOpen] = React.useState(false);
  const [message,setMessage] = React.useState('');
  const [confirmDelete,setConfirmDelete] = React.useState(false);
  const query = q.trim().toLowerCase();
  const filtered = d.expenses.filter(e =>
    (status === "all" || e.status === status) &&
    (cat === "all" || e.cat === cat) &&
    (query === "" || [e.merchant, e.memo, e.who, e.id].some(f => String(f||'').toLowerCase().includes(query)))
  );
  const total = filtered.reduce((s, e) => s + e.amount, 0);
  const selectedTotal = filtered.filter(e => selected.includes(e.id)).reduce((s, e) => s + e.amount, 0);
  const selectedReviewable = d.expenses.some(e=>selected.includes(e.id)&&['pending','flagged'].includes(e.status));
  const allSelected = filtered.length > 0 && filtered.every(e => selected.includes(e.id));

  const toggleRow = (id) => setSelected(sel => sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]);
  const toggleAll = () => setSelected(allSelected ? [] : filtered.map(e => e.id));

  return (
    <>
      <PageHead
        eyebrow="Expenses"
        title="All expenses"
        sub={`${filtered.length} items · total ${new Intl.NumberFormat('en-US', { style:'currency', currency:'USD' }).format(total)}`}
        actions={<>
          <DensityToggle compact={compact} onToggle={()=>setCompact(c=>!c)}/>
          <RefreshButton/>
          <button className="ff-btn" onClick={()=>ffGo('import')}><Icon name="upload-simple" size={14}/> Import CSV</button>
          <button className="ff-btn" disabled title="Expense export is not available in this prototype."><Icon name="download-simple" size={14}/> Export</button>
          <button className="ff-btn ff-btn--primary" onClick={()=>ffGo('new-expense')}><Icon name="plus" size={14}/> New expense</button>
        </>}
      />

      {FF_SESSION.toast && <div className="ff-alert ff-alert--info" role="status" style={{marginBottom:16}}>{FF_SESSION.toast}</div>}
      <ActionFeedback message={message}/>
      <div className="ff-row" style={{justifyContent:'space-between', marginBottom:14, flexWrap:'wrap', gap:12}}>
        <div className="ff-row" style={{gap:8, flexWrap:'wrap'}}>
          <ChipBar items={[
            { id: "all",     label: "All",     count: d.expenses.length },
            { id: "pending", label: "Pending", count: d.expenses.filter(e=>e.status==="pending").length },
            { id: "approved",label: "Approved",count: d.expenses.filter(e=>e.status==="approved").length },
            { id: "flagged", label: "Flagged", count: d.expenses.filter(e=>e.status==="flagged").length },
            { id: "rejected",label: "Rejected",count: d.expenses.filter(e=>e.status==="rejected").length }
          ]} value={status} onChange={setStatus}/>
        </div>
        <div className="ff-row" style={{gap:8}}>
          <div className="ff-search" style={{width:240}}>
            <Icon name="magnifying-glass" size={14}/>
            <input placeholder="Search expenses…" value={q} onChange={e=>setQ(e.target.value)}/>
          </div>
          <select className="ff-select" style={{width:140}} value={cat} onChange={e=>setCat(e.target.value)}>
            <option value="all">All categories</option>
            {d.categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <button className="ff-btn" disabled aria-label="Date range filtering unavailable in this prototype" title="Date filtering is not available in this prototype."><Icon name="calendar-blank" size={14}/> May 2026 <Icon name="caret-down" size={12}/></button>
          <div style={{position:'relative'}}>
            <button className="ff-btn" disabled title="Customizing expense columns is not available in this prototype."><Icon name="columns" size={14}/> Columns</button>
            {columnsOpen && (
              <div className="ff-card" style={{position:'absolute', top:'calc(100% + 6px)', right:0, zIndex:10, padding:10, width:180, boxShadow:'var(--ff-shadow-lg)'}}>
                {EXPENSE_COLUMNS.map(col => (
                  <label key={col} className="ff-row" style={{gap:8, padding:'5px 4px', fontSize:13}}>
                    <input type="checkbox" defaultChecked/> {col}
                  </label>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {selected.length > 0 && (
        <div className="ff-row" style={{
          justifyContent:'space-between', padding:'10px 16px', marginBottom:10,
          background:'var(--ff-card-2)', border:'1px solid var(--ff-border)', borderRadius:'var(--ff-radius-md)'
        }}>
          <div className="ff-row" style={{gap:10, fontSize:13}}>
            <input type="checkbox" aria-label="Clear selected expenses" checked onChange={()=>setSelected([])}/>
            <span>{selected.length} selected · total {new Intl.NumberFormat('en-US', { style:'currency', currency:'USD' }).format(selectedTotal)}</span>
          </div>
          <div className="ff-row" style={{gap:8}}>
            <button className="ff-btn ff-btn--primary ff-btn--sm" hidden={ffRole() === 'employee'} disabled={!selectedReviewable} title={!selectedReviewable?'Select a pending or flagged expense to approve.':undefined} onClick={()=>ffApprove(selected)}>Approve selected</button>
            <button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={()=>{d.expenses.filter(e=>selected.includes(e.id)).forEach(e=>e.status='flagged');setMessage(`${selected.length} expense${selected.length===1?'':'s'} flagged.`);setSelected([]);}}>Flag</button>
            <button className="ff-btn ff-btn--ghost ff-btn--sm" disabled title="Expense export is not available in this prototype.">Export</button>
            <button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={()=>setConfirmDelete(true)}>Delete</button>
          </div>
        </div>
      )}

      {filtered.length === 0 ? <EmptyState icon="magnifying-glass" title="No expenses found" body="Try a different search or clear the filters." actions={<button className="ff-btn" onClick={()=>{setQ('');setStatus('all');setCat('all');}}>Clear filters</button>}/> : <table className={`ff-table ${compact ? 'ff-table--compact' : ''}`}>
        <thead>
          <tr>
            <th style={{width:44}}><label className="ff-check-target"><input type="checkbox" aria-label="Select all" checked={allSelected} onChange={toggleAll}/></label></th>
            <th>ID</th>
            <th>Date</th>
            <th>Merchant / memo</th>
            <th>Owner</th>
            <th>Category</th>
            <th className="ff-num">Amount</th>
            <th>Status</th>
            <th style={{width:40}}></th>
          </tr>
        </thead>
        <tbody>
          {filtered.map(e => {
            const cat = d.categories.find(c => c.id === e.cat);
            return (
              <tr key={e.id} data-row-focus tabIndex="0" onClick={()=>ffGo('expense-detail', {expenseId:e.id})} onKeyDown={ffRowKeyDown} aria-label={`${e.id} ${e.merchant}`} style={{cursor:'pointer'}}>
                <td onClick={ev=>ev.stopPropagation()}><label className="ff-check-target"><input aria-label={`Select ${e.id}`} type="checkbox" checked={selected.includes(e.id)} onChange={()=>toggleRow(e.id)}/></label></td>
                <td><span className="ff-mono" style={{fontSize:12, color:'var(--ff-fg-muted)'}}>{e.id}</span></td>
                <td className="ff-tnum" style={{color:'var(--ff-fg-muted)', fontSize:12}}>{fmtDate(e.date)}</td>
                <td>
                  <div className="ff-row" style={{gap:8, fontWeight:500}}><MerchantIcon name={e.merchant} size={15}/> {e.merchant}</div>
                  <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>{e.memo}</div>
                </td>
                <td><span className="ff-row" style={{gap:6}}><Avatar initials={e.who.split(' ').map(x=>x[0]).join('').slice(0,2)} name={e.who}/>{e.who}</span></td>
                <td><CategoryTag color={cat.color} name={cat.name}/></td>
                <td className="ff-num"><Money value={e.amount}/></td>
                <td><StatusBadge status={e.status}/></td>
              <td><button className="ff-btn ff-btn--ghost ff-btn--sm ff-btn--icon" disabled title="Additional row actions are not available in this prototype." aria-label={`More actions for ${e.merchant}, ${e.id}`}><Icon name="dots-three" size={16}/></button></td>
              </tr>
            );
          })}
        </tbody>
      </table>}
      {confirmDelete && <ConfirmDialog title="Delete selected expenses?" body={`This will remove ${selected.length} selected expense${selected.length===1?'':'s'} from this prototype.`} onCancel={()=>setConfirmDelete(false)} onConfirm={()=>{const count=selected.length; d.expenses=d.expenses.filter(e=>!selected.includes(e.id));setConfirmDelete(false);setMessage(`${count} expense${count===1?'':'s'} deleted.`);setSelected([]);}}/>}
    </>
  );
};

const ExpenseDetail = () => {
  const d = FF_DATA;
  const e = d.expenses.find(x => x.id === FF_SESSION.expenseId) || d.expenses[0];
  const [commented, setCommented] = React.useState(false);
  if(!e)return <EmptyState icon="receipt" title="No expense selected" body="Create an expense to review its details." actions={<button className="ff-btn" onClick={()=>ffGo('new-expense')}>New expense</button>}/>;
  return (
    <>
      <div className="ff-row" style={{gap:8, marginBottom:12, color:'var(--ff-fg-muted)', fontSize:13, whiteSpace:'nowrap'}}>
        <a href="#" style={{color:'inherit'}} onClick={(ev)=>{ev.preventDefault(); ffGo('expenses');}}>Expenses</a>
        <Icon name="caret-right" size={12}/>
        <span style={{color:'var(--ff-fg)'}} className="ff-mono">{e.id}</span>
      </div>
      <PageHead
        title={<span className="ff-row" style={{gap:10, alignItems:'center'}}><MerchantIcon name={e.merchant} size={26}/> {e.merchant}</span>}
        sub={`${e.id} · Submitted by ${e.who} on ${fmtDate(e.date)}`}
        actions={<>
          <button className="ff-btn" disabled title="Expense comments are not available in this prototype."><Icon name="chat-text" size={14}/> Comment</button>
          <button className="ff-btn" hidden={ffRole() === 'employee' || !['pending','flagged'].includes(e.status)} onClick={()=>ffReject([e.id])}><Icon name="x" size={14}/> Reject</button>
          <button className="ff-btn ff-btn--primary" hidden={ffRole() === 'employee' || !['pending','flagged'].includes(e.status)} onClick={()=>ffApprove([e.id])}><Icon name="check" size={14}/> Approve</button>
        </>}
      />
      {commented && <div role="status" className="ff-alert ff-alert--info" style={{marginBottom:16}}>Comment added to {e.id} in this prototype.</div>}

      <div className="ff-grid" style={{gridTemplateColumns:'1.6fr 1fr'}}>
        <div className="ff-stack" style={{'--ff-stack-gap':'16px'}}>
          <Card title="Summary">
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px 28px'}}>
              <DetailRow label="Amount"><span style={{fontFamily:'var(--ff-font-sans)', fontWeight:700, fontSize:28, letterSpacing:'-0.025em'}} className="ff-tnum"><Money value={e.amount}/></span></DetailRow>
              <DetailRow label="Status"><StatusBadge status={e.status}/></DetailRow>
              <DetailRow label="Category">{d.categories.find(c=>c.id===e.cat).name}</DetailRow>
              <DetailRow label="Date"><span className="ff-tnum">{fmtDate(e.date)}</span></DetailRow>
              <DetailRow label="Payment"><span className="ff-mono">•••• {e.cardLast4}</span></DetailRow>
              <DetailRow label="Memo">{e.memo}</DetailRow>
            </div>
          </Card>

          <Card title="Receipt" action={<button className="ff-btn ff-btn--sm ff-btn--ghost" disabled title="Receipt downloads are not available in this prototype."><Icon name="download-simple" size={12}/> Download</button>}>
            <div style={{
              background:'var(--ff-card-2)', border:'1px dashed var(--ff-border)', borderRadius:10,
              padding:32, display:'flex', flexDirection:'column', alignItems:'center', gap:12
            }}>
              <div style={{
                width:200, height:280,
                background:`repeating-linear-gradient(0deg, var(--ff-border) 0 1px, transparent 1px 12px), var(--ff-card)`,
                border:'1px solid var(--ff-border)', borderRadius:6, position:'relative'
              }}>
                <div style={{position:'absolute', top:14, left:0, right:0, textAlign:'center', fontFamily:'var(--ff-font-mono)', fontSize:10, color:'var(--ff-fg-muted)'}}>{e.merchant} · sample receipt</div>
                <div style={{position:'absolute', bottom:14, left:0, right:0, textAlign:'center', fontFamily:'var(--ff-font-display)', fontSize:22, fontStyle:'italic'}} className="ff-tnum"><Money value={e.amount}/></div>
              </div>
              <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>Sample receipt for {e.id}</div>
            </div>
          </Card>

          <Card title="Activity" padded={false}>
            <div className="ff-stack" style={{'--ff-stack-gap':'0'}}>
              {[
                { who: e.who,       act: "Submitted expense",  ts: "May 22, 9:12 AM" },
                { who: "System",          act: "Policy check passed", ts: "May 22, 9:12 AM" },
                { who: ffRole() === 'manager' ? FF_DATA.me.manager.name : "Taylor Brooks", act: e.status === 'approved' ? "Manager approved" : "Routed for approval", ts: "May 22, 9:15 AM" },
                { who: FF_DATA.me[ffRole()].name, act: "Viewing now", ts: "Just now" }
              ].map((a, i, arr) => (
                <div key={i} style={{padding:'14px 20px', borderBottom: i < arr.length - 1 ? '1px solid var(--ff-border)' : '0', display:'flex', gap:12, alignItems:'center'}}>
                  <Avatar initials={a.who.split(' ').map(x=>x[0]).join('').slice(0,2)} name={a.who}/>
                  <div style={{flex:1}}>
                    <div style={{fontSize:13}}><strong>{a.who}</strong> · {a.act}</div>
                    <div style={{fontSize:11, color:'var(--ff-fg-muted)'}} className="ff-tnum">{a.ts}</div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <div className="ff-stack" style={{'--ff-stack-gap':'16px'}}>
          <Card title="Approval chain">
            <div className="ff-stack" style={{'--ff-stack-gap':'12px'}}>
              {[
                { name:"Taylor Brooks", title:"Head of Sales", status:"approved" },
                { name:"Morgan Ellis", title:"Finance",       status:"pending" }
              ].map((s, i) => (
                <div key={i} className="ff-row" style={{justifyContent:'space-between', gap:8}}>
                  <div className="ff-row" style={{gap:10, minWidth:0, flex:1}}>
                    <Avatar initials={s.name.split(' ').map(x=>x[0]).join('').slice(0,2)} name={s.name}/>
                    <div style={{minWidth:0}}>
                      <div style={{fontSize:13, fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{s.name}</div>
                      <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>{s.title}</div>
                    </div>
                  </div>
                  <StatusBadge status={s.status}/>
                </div>
              ))}
            </div>
          </Card>

          <div className="ff-alert ff-alert--info">
            <Icon name="info" size={18} weight="fill" style={{color:'inherit'}}/>
            <div className="ff-alert__body">
              <div className="ff-alert__title">{e.policy === "ok" ? "Within policy" : "Policy exception"}</div>
              <div>{e.policy === "ok" ? "No policy exception in this sample record." : "This record has a policy exception requiring review."}</div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

const DetailRow = ({ label, children }) => (
  <div>
    <div className="ff-eyebrow" style={{marginBottom:4}}>{label}</div>
    <div style={{fontSize:14}}>{children}</div>
  </div>
);

const NewExpense = () => {
  const d = FF_DATA;
  const [form,setForm] = React.useState({merchant:'',date:'',amount:'',cat:'',memo:'',project:'',payment:''});
  const [errors,setErrors] = React.useState({});
  const change = (key,value) => {setForm({...form,[key]:value}); if(key === 'amount') setErrors({...errors,amount:ffAmountError(value)});};
  const blur = key => { const messages={merchant:'Enter a merchant.',date:'Enter a valid date (YYYY-MM-DD).',cat:'Choose a category.',project:'Choose a project / cost center.',payment:'Choose a payment method.'}; const invalid=key==='merchant'?!form[key].trim():key==='date'?!/^\d{4}-\d{2}-\d{2}$/.test(form.date):!form[key]; setErrors({...errors,[key]:invalid?messages[key]:''}); };
  const submit = () => {
    const problems = {};
    if(!form.merchant.trim()) problems.merchant = 'Enter a merchant.';
    if(!/^\d{4}-\d{2}-\d{2}$/.test(form.date) || Number.isNaN(Date.parse(form.date)) || new Date(form.date).toISOString().slice(0,10) !== form.date) problems.date = 'Enter a valid date (YYYY-MM-DD).';
    const amountError = ffAmountError(form.amount); if(amountError) problems.amount = amountError;
    if(!form.cat) problems.cat = 'Choose a category.';
    if(!form.project) problems.project = 'Choose a project / cost center.';
    if(!form.payment) problems.payment = 'Choose a payment method.';
    setErrors(problems); if(Object.keys(problems).length) return;
    const id = 'EXP-' + (Math.max(2841,...d.expenses.map(e => Number(e.id.split('-')[1])))+1);
    d.expenses.unshift({id,merchant:form.merchant.trim(),date:form.date,amount:Number(form.amount),cat:form.cat,memo:form.memo,who:d.me[ffRole()].name,status:'pending',policy:'ok',cardLast4:form.payment.startsWith('FinFlow')?'4112':'Personal',project:form.project});
    ffToast(id + ' submitted for approval. Status: Pending.','expenses');
    ffGo('expenses');
  };
  const fieldError = key => errors[key] && <div role="alert" style={{fontSize:12,color:'var(--ff-rejected)',marginTop:4}}>{errors[key]}</div>;
  return (
    <>
      <PageHead
        eyebrow="Expenses"
        title="New expense"
        sub="Submit a business expense for approval"
        actions={<>
          <button className="ff-btn" disabled title="Draft saving is not available in this prototype.">Save draft</button>
          <button className="ff-btn ff-btn--primary" onClick={submit}>Submit for approval</button>
        </>}
      />

      {Object.values(errors).some(Boolean) && <div className="ff-alert ff-alert--error" role="alert" style={{marginBottom:16}}><div><strong>Check your expense</strong><ul>{Object.entries(errors).filter(([,value])=>value).map(([key,value])=><li key={key}>{value}</li>)}</ul></div></div>}
      <div className="ff-grid" style={{gridTemplateColumns:'1.5fr 1fr', gap:24}}>
        <Card>
          <div className="ff-stack" style={{'--ff-stack-gap':'18px'}}>
            <div className="ff-grid ff-grid--2">
              <div className="ff-field"><label className="ff-label">Merchant</label><input aria-label="Merchant" className="ff-input" value={form.merchant} onChange={e=>change("merchant",e.target.value)} onBlur={()=>blur('merchant')} placeholder="e.g. United Airlines"/>{fieldError("merchant")}</div>
              <div className="ff-field"><label className="ff-label">Date</label><input aria-label="Date" className="ff-input" type="text" value={form.date} onChange={e=>change("date",e.target.value)} onBlur={()=>blur('date')} placeholder="YYYY-MM-DD"/>{fieldError("date")}</div>
            </div>
            <div className="ff-grid ff-grid--2">
              <div className="ff-field"><label className="ff-label">Amount (USD)</label><input aria-label="Amount (USD)" aria-invalid={Boolean(errors.amount)} className="ff-input ff-tnum" inputMode="decimal" value={form.amount} onChange={e=>change("amount",e.target.value)} placeholder="0.00"/>{fieldError("amount")}</div>
              <div className="ff-field"><label className="ff-label">Category</label>
                <select aria-label="Category" className="ff-select" value={form.cat} onChange={e=>change("cat",e.target.value)} onBlur={()=>blur('cat')}>
                  <option value="" disabled>Select a category</option>
                  {d.categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>{fieldError("cat")}
              </div>
            </div>
            <div className="ff-field"><label className="ff-label">Memo</label><textarea className="ff-textarea" value={form.memo} onChange={e=>change("memo",e.target.value)} placeholder="What was this for?"/></div>
            <div className="ff-grid ff-grid--2">
              <div className="ff-field"><label className="ff-label">Project / cost center</label>
                <select aria-label="Project / cost center" className="ff-select" value={form.project} onChange={e=>change("project",e.target.value)} onBlur={()=>blur('project')}>
                  <option value="" disabled>Select a project</option>
                  <option>Sales — FY26</option><option>Marketing</option><option>R&amp;D</option>
                </select>{fieldError("project")}
              </div>
              <div className="ff-field"><label className="ff-label">Payment</label>
                <select aria-label="Payment" className="ff-select" value={form.payment} onChange={e=>change("payment",e.target.value)} onBlur={()=>blur('payment')}>
                  <option value="" disabled>Select a payment method</option>
                  <option>FinFlow Card · •••• 4112</option><option>Personal — request reimbursement</option>
                </select>{fieldError("payment")}
              </div>
            </div>
          </div>
        </Card>

        <div className="ff-stack" style={{'--ff-stack-gap':'16px'}}>
          <Card title="Receipt">
            <div style={{
              border:'1.5px dashed var(--ff-border-strong)', borderRadius:10, padding:'24px 20px',
              display:'flex', flexDirection:'column', alignItems:'center', gap:8, textAlign:'center'
            }}>
              <div className="ff-empty__icon"><Icon name="upload-simple" size={22}/></div>
              <div style={{fontSize:14, fontWeight:500}}>Drop a receipt</div>
              <div style={{fontSize:12, color:'var(--ff-fg-muted)'}}>PDF or image · OCR fills the form automatically</div>
              <button className="ff-btn ff-btn--sm" style={{marginTop:6}} onClick={()=>ffGo('ocr')}>Choose file</button>
            </div>
          </Card>
          <Card title="Approval preview">
            <div style={{fontSize:13, color:'var(--ff-fg-muted)', marginBottom:10}}>This expense will be routed to:</div>
            <div className="ff-stack" style={{'--ff-stack-gap':'8px'}}>
              <div className="ff-row" style={{gap:8}}><Avatar initials="TB" name="Taylor Brooks"/><span>Taylor Brooks · Head of Sales</span></div>
              <div className="ff-row" style={{gap:8}}><Avatar initials="ME" name="Morgan Ellis"/><span>Morgan Ellis · Finance</span></div>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const OcrReview = () => {
  const [message,setMessage]=React.useState('');
  const [values,setValues]=React.useState({Merchant:'Marriott Austin',Date:'2026-05-21',Amount:'1240.00',Tax:'55.00',Card:'VISA •••• 4112','Category (predicted)':'Travel · Lodging'});
  const [errors,setErrors]=React.useState({});
  const validate=(key,value)=>key==='Amount'?ffAmountError(value):key==='Tax'?(!/^\d+(\.\d{1,2})?$/.test(value)?'Enter a non-negative tax amount.':''):key==='Date'?(!value||Number.isNaN(Date.parse(value))?'Enter a valid date.':''):!value.trim()?`Enter ${key.toLowerCase()}.`:'';
  const save=()=>{const next={};Object.entries(values).forEach(([k,v])=>{next[k]=validate(k,v);});setErrors(next);if(Object.values(next).some(Boolean))return;const id='EXP-'+(Math.max(2841,...FF_DATA.expenses.map(e=>Number(e.id.split('-')[1])))+1);const person=FF_DATA.me[ffRole()];FF_DATA.expenses.unshift({id,merchant:values.Merchant,amount:Number(values.Amount),date:values.Date,cat:'tr',who:person.name,initials:person.initials,status:'flagged',receipt:true});ffToast(`${id} saved from receipt and flagged for review.`,'expenses');ffGo('expenses');};
  return (
    <>
      <PageHead
        eyebrow="Receipt OCR"
        title="Review extracted data"
        sub="We've parsed the receipt — confirm the fields below."
        actions={<>
          <button className="ff-btn" disabled title="Receipt re-scanning is not available in this prototype.">Re-scan</button>
          <button className="ff-btn ff-btn--primary" onClick={save}>Save expense</button>
        </>}
      />
      <ActionFeedback message={message}/><FormSummary errors={errors}/><div className="ff-grid" style={{gridTemplateColumns:'1fr 1fr', gap:24}}>
        <Card padded={false}>
          <div style={{padding:20}}>
            <div style={{
              background:'var(--ff-card-2)', border:'1px solid var(--ff-border)', borderRadius:8,
              width:'min(100%, 320px)', aspectRatio:'0.8 / 1', margin:'0 auto', position:'relative', overflow:'hidden'
            }}>
              <div style={{position:'absolute', inset:16, borderRadius:4, boxShadow:'var(--ff-shadow-md)', overflow:'hidden'}}>
                <img src="assets/marriott-austin.jpg" alt="Marriott Austin hotel receipt" style={{width:'100%', height:'100%', objectFit:'contain', background:'#fff'}}/>
              </div>
              <div style={{position:'absolute', top:10, right:10, background:'var(--ff-card)', border:'1px solid var(--ff-border)', borderRadius:6, padding:'4px 8px', fontSize:11, color:'var(--ff-fg-muted)', display:'flex', gap:8, alignItems:'center'}}>
                <Icon name="sparkle" size={12}/> OCR confidence · 94%
              </div>
            </div>
          </div>
        </Card>

        <Card>
          <div className="ff-stack" style={{'--ff-stack-gap':'14px'}}>
            {Object.entries(values).map(([key,value],i)=><OcrField key={key} label={key} value={value} confidence={[98,99,97,88,96,91][i]} highlight={key==='Amount'} onChange={v=>setValues({...values,[key]:v})} onBlur={()=>setErrors({...errors,[key]:validate(key,value)})} error={errors[key]}/>)}
          </div>
          <div className="ff-alert ff-alert--warn" style={{marginTop:18}}>
            <Icon name="warning" size={18} weight="fill"/>
            <div className="ff-alert__body">
              <div className="ff-alert__title">Policy: over hotel cap</div>
              <div>3 nights at $413/night exceeds the $300/night domestic cap. This expense will be flagged.</div>
            </div>
          </div>
        </Card>
      </div>
    </>
  );
};

const OcrField = ({ label, value, confidence, highlight, onChange, onBlur, error }) => (
  <div className="ff-field">
    <div className="ff-row" style={{justifyContent:'space-between'}}>
      <label className="ff-label">{label}</label>
      <span style={{fontSize:11, color: confidence > 90 ? 'var(--ff-approved)' : 'var(--ff-pending)'}}>{confidence}% confidence</span>
    </div>
    <input aria-label={label} required className={"ff-input " + (highlight ? "ff-tnum" : "")} value={value} onChange={e=>onChange(e.target.value)} onBlur={onBlur} style={highlight ? {fontWeight:600} : {}}/><FieldError error={error}/>
  </div>
);

const FlaggedExpense = () => {
  const [note,setNote] = React.useState('Customer offsite, only room block available. Approving as one-time exception.');
  const [error,setError]=React.useState('');
  const available=ffQueue().some(e=>e.id==='EXP-2839');
  return (
    <>
      <PageHead
        eyebrow="Expense · Policy violation"
        title={<span className="ff-row" style={{gap:10, alignItems:'center'}}><MerchantIcon name="Marriott Austin" size={26}/> Marriott Austin — flagged</span>}
        sub="EXP-2839 · Jordan Lee · May 21, 2026"
        actions={<>
          <button className="ff-btn" disabled title="Requesting more information is not available in this prototype."><Icon name="chat-text" size={14}/> Ask for info</button>
          <button className="ff-btn ff-btn--danger" hidden={ffRole() === 'employee'} disabled={!available} title={!available?'This expense already has a decision.':undefined} onClick={()=>ffReject(['EXP-2839'])}><Icon name="x" size={14}/> Reject</button>
          <button className="ff-btn ff-btn--primary" hidden={ffRole() === 'employee'} disabled={!available} title={!available?'This expense already has a decision.':undefined} onClick={()=>{if(!note.trim()){setError('Enter an override reason.');return;}ffApprove(['EXP-2839'], note);}}><Icon name="check" size={14}/> Approve override</button>
        </>}
      />
      <div className="ff-alert ff-alert--error" style={{marginBottom:16}}>
        <Icon name="warning-octagon" size={20} weight="fill"/>
        <div className="ff-alert__body">
          <div className="ff-alert__title">3 policy violations detected</div>
          <div>Hotel rate $413/night (cap $300) · Stay extended past sanctioned trip window · Missing project code</div>
        </div>
      </div>

      <div className="ff-grid" style={{gridTemplateColumns:'1.6fr 1fr', gap:16}}>
        <Card title="Receipt + transcription">
          <div className="ff-grid ff-grid--2">
            <div style={{aspectRatio:'0.8 / 1', maxHeight:300, margin:'0 auto', background:'var(--ff-card-2)', border:'1px solid var(--ff-border)', borderRadius:8, overflow:'hidden'}}>
              <img src="assets/marriott-austin.jpg" alt="Marriott Austin hotel receipt" style={{width:'100%', height:'100%', objectFit:'contain'}}/>
            </div>
            <div style={{fontSize:13, lineHeight:1.6}}>
              <DetailRow label="Total"><span style={{fontFamily:'var(--ff-font-sans)', fontWeight:700, fontSize:24, letterSpacing:'-0.025em'}} className="ff-tnum">$1,240.00</span></DetailRow>
              <div style={{height:12}}/>
              <DetailRow label="Nights">3 × $413.33</DetailRow>
              <div style={{height:12}}/>
              <DetailRow label="Policy cap">$300/night</DetailRow>
              <div style={{height:12}}/>
              <DetailRow label="Overage"><span style={{color:'var(--ff-rejected)'}} className="ff-tnum">+$340.00</span></DetailRow>
            </div>
          </div>
        </Card>
        <Card title="Override note">
          <FormSummary errors={{note:error}}/><textarea aria-label="Override reason" required className="ff-textarea" value={note} onChange={e=>setNote(e.target.value)} onBlur={()=>setError(note.trim()?'':'Enter an override reason.')}/><FieldError error={error}/>
          <div style={{fontSize:12, color:'var(--ff-fg-muted)', marginTop:10}}>Override reason will be saved with the expense in this prototype.</div>
        </Card>
      </div>
    </>
  );
};

const BulkImport = () => (
  <>
    <PageHead eyebrow="Expenses" title="Bulk import" sub="Upload a CSV of expenses to import in one batch."/>
    <div className="ff-grid" style={{gridTemplateColumns:'1.5fr 1fr', gap:24}}>
      <Card>
        <div style={{border:'1.5px dashed var(--ff-border-strong)', borderRadius:12, padding:48, textAlign:'center'}}>
          <div className="ff-empty__icon" style={{margin:'0 auto'}}><Icon name="file-csv" size={26}/></div>
          <div style={{fontSize:16, fontWeight:600, marginTop:12}}>Drop your CSV here</div>
          <div style={{fontSize:13, color:'var(--ff-fg-muted)', marginTop:4}}>Up to 5,000 rows · UTF-8 · max 10 MB</div>
          <button className="ff-btn ff-btn--primary" style={{marginTop:18}} disabled title="Bulk file import is not available in this prototype."><Icon name="upload-simple" size={14}/> Choose file</button>
          <div style={{marginTop:12, fontSize:12}}><button className="ff-btn ff-btn--ghost ff-btn--sm" disabled title="CSV template downloads are not available in this prototype.">Download CSV template</button></div>
        </div>
      </Card>
      <Card title="Expected columns">
        <table className="ff-table ff-table--compact">
          <thead><tr><th>Column</th><th>Required</th></tr></thead>
          <tbody>
            {[
              ["date", "Yes"], ["merchant", "Yes"], ["amount", "Yes"],
              ["category", "Yes"], ["memo", "No"], ["card_last4", "No"],
              ["owner_email", "No"], ["project_code", "No"]
            ].map(([k, r], i) => (
              <tr key={i}><td className="ff-mono" style={{fontSize:12}}>{k}</td><td>{r}</td></tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  </>
);

Object.assign(window, { ExpenseList, ExpenseDetail, NewExpense, OcrReview, FlaggedExpense, BulkImport });
