/* FinFlow Screens — Approvals, Reimbursements */

const ApprovalsQueue = () => {
  const d = FF_DATA;
  /* Redesign: oldest-first, not insertion-order. A queue is a triage tool —
     the item that's been sitting longest is the one most likely to be
     blocking someone, so it belongs at the top, not wherever it happened to
     land in the data. */
  const items = d.expenses.filter(e => e.status === "pending" || e.status === "flagged").sort((a, b) => a.date.localeCompare(b.date));
  const [selected, setSelected] = React.useState([]);
  const [compact, setCompact] = React.useState(false);
  const [activeRow, setActiveRow] = React.useState(0);
  const checkboxRefs = React.useRef([]);
  const selTotal = items.filter(e => selected.includes(e.id)).reduce((s, e) => s + e.amount, 0);
  const fmtUSD = (n) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(n);
  const allSelected = items.length > 0 && items.every(e => selected.includes(e.id));
  const someSelected = selected.length > 0 && !allSelected;
  const headerCbRef = React.useRef(null);
  React.useEffect(() => { if (headerCbRef.current) headerCbRef.current.indeterminate = someSelected; }, [someSelected]);
  React.useEffect(() => { if (activeRow >= items.length) setActiveRow(Math.max(0, items.length - 1)); }, [activeRow, items.length]);
  const toggleRow = (id) => setSelected(sel => sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]);
  const toggleAll = () => setSelected(allSelected ? [] : items.map(e => e.id));
  const onQueueCheckboxKeyDown = (event, index, expenseId) => {
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault();
      const direction = event.key === 'ArrowDown' ? 1 : -1;
      const next = (index + direction + items.length) % items.length;
      setActiveRow(next);
      requestAnimationFrame(() => checkboxRefs.current[next]?.focus());
      return;
    }
    if (event.key === 'Enter') {
      event.preventDefault();
      ffGo('approval-detail', {expenseId});
    }
  };
  return (
    <>
      <PageHead
        eyebrow="Approvals"
        title="Approvals queue"
        sub={`${items.length} items awaiting your review`}
        actions={<>
          <DensityToggle compact={compact} onToggle={()=>setCompact(c=>!c)}/>
          <RefreshButton/>
          <button className="ff-btn" disabled title="Approval filters are not available in this prototype."><Icon name="funnel" size={14}/> Filter</button>
          <button className="ff-btn ff-btn--accent" disabled={!items.length} title={!items.length?'There are no expenses awaiting approval.':undefined} onClick={()=>setSelected(items.map(e=>e.id))}><Icon name="lightning" size={14}/> Bulk approve ({items.length})</button>
        </>}
      />
      {FF_SESSION.toast && <div className="ff-alert ff-alert--info" role="status" style={{marginBottom:16}}>{FF_SESSION.toast}</div>}

      {/* Toolbar, not a card — a bulk-action bar is a control surface, not
          content, so it doesn't need a container competing with the queue
          for visual weight. */}
      <div style={{padding:'0 0 12px', borderBottom:'1px solid var(--ff-border-strong)', display:'flex', gap:8, alignItems:'center'}}>
        <label className="ff-check-target"><input aria-label="Select all approvals" ref={headerCbRef} type="checkbox" checked={allSelected} onChange={toggleAll}/></label> <span style={{fontSize:12, color:'var(--ff-fg-muted)'}}>{selected.length} selected · total {fmtUSD(selTotal)}</span>
        <div style={{flex:1}}/>
        <button className="ff-btn ff-btn--sm" disabled={!selected.length} title={!selected.length?'Select at least one expense.':undefined} onClick={()=>ffReject(selected)}>Reject</button>
        <button className="ff-btn ff-btn--sm ff-btn--primary" disabled={!selected.length} title={!selected.length?'Select at least one expense.':undefined} onClick={()=>ffApprove(selected)}>Approve</button>
      </div>
      {!items.length&&<EmptyState icon="check-circle" title="You are all caught up" body="New expenses will appear here when they need a decision." actions={<button className="ff-btn" onClick={()=>ffGo(ffHome())}>Back to dashboard</button>}/>}
      <div data-row-group role="list" aria-label="Approvals queue">
      {items.map((e, i) => (
        <div key={e.id} data-row-focus className="ff-approval-row" role="listitem" onClick={()=>ffGo('approval-detail',{expenseId:e.id})} aria-label={`${e.id} ${e.merchant}`} style={{padding: compact ? '12px 4px' : '18px 4px', borderBottom:'1px solid var(--ff-border)', display:'grid', gridTemplateColumns:'auto 60px 1fr auto auto', gap:16, alignItems:'center', cursor:'pointer'}}>
          <label className="ff-check-target" onClick={ev=>ev.stopPropagation()}><input ref={el=>{checkboxRefs.current[i]=el;}} aria-label={`Select ${e.id}, ${e.merchant}, ${fmtUSD(e.amount)}`} tabIndex={i === activeRow ? 0 : -1} type="checkbox" checked={selected.includes(e.id)} onFocus={()=>setActiveRow(i)} onKeyDown={event=>onQueueCheckboxKeyDown(event,i,e.id)} onChange={()=>toggleRow(e.id)}/></label>
          <div className="ff-receipt"><span style={{fontFamily:'var(--ff-font-mono)'}}>{e.cardLast4}</span></div>
          <div className="ff-approval-main">
            <div style={{display:'flex', gap:10, alignItems:'baseline'}}>
              <span className="ff-row" style={{gap:8, alignItems:'center'}}><MerchantIcon name={e.merchant} size={15}/><strong style={{fontSize:16}}>{e.merchant}</strong></span>
              <span style={{fontSize:12, color:'var(--ff-fg-muted)'}} className="ff-mono">{e.id}</span>
              <StatusBadge status={e.status}/>
              {e.policy !== 'ok' && <StatusBadge status={e.policy}/>}
            </div>
            <div style={{fontSize:12, color:'var(--ff-fg-muted)', marginTop:2}}>{e.memo} · {e.who} · {fmtDate(e.date)}</div>
          </div>
          <div className="ff-approval-amount" style={{textAlign:'right'}}>
            <div style={{fontFamily:'var(--ff-font-sans)', fontWeight:600, fontSize:22, letterSpacing:'-0.02em'}} className="ff-tnum"><Money value={e.amount}/></div>
            <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>{d.categories.find(c=>c.id===e.cat).name}</div>
          </div>
          <div className="ff-row ff-approval-actions" onClick={ev=>ev.stopPropagation()}>
            <button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={()=>ffReject([e.id])}>Reject</button>
            <button className="ff-btn ff-btn--primary ff-btn--sm" onClick={()=>ffApprove([e.id])}>Approve</button>
          </div>
        </div>
      ))}
      </div>
    </>
  );
};

const ApprovalDetail = () => <ExpenseDetail/>;  // Reuses expense detail for approval context

const ApprovalHistory = () => {
  const items = [
    { id:"EXP-2840", merchant:"Figma", who:"Avery Quinn", amount:180.00, status:"approved", decided:"May 22 14:22", by:"Morgan Ellis" },
    { id:"EXP-2837", merchant:"Google Cloud", who:"Quinn Avery", amount:3204.18, status:"approved", decided:"May 20 11:08", by:"Taylor Brooks" },
    { id:"EXP-2834", merchant:"Udemy", who:"Casey Parker", amount:995.00, status:"approved", decided:"May 19 16:42", by:"Taylor Brooks" },
    { id:"EXP-2832", merchant:"Ticketmaster", who:"Casey Parker", amount:640.00, status:"rejected", decided:"May 18 17:30", by:"Morgan Ellis" },
    { id:"EXP-2828", merchant:"Google Chat", who:"Quinn Avery", amount:149.00, status:"approved", decided:"May 16 09:14", by:"Taylor Brooks" }
  ];
  return (
    <>
      <PageHead eyebrow="Approvals" title="Approval history" sub="Decisions you've made — past 30 days"/>
      {items.length === 0 ? (
        <EmptyState icon="clock-counter-clockwise" title="No decisions yet"
          body="Expenses you approve or reject will show up here with a full audit trail."/>
      ) : (
      <table className="ff-table">
        <thead><tr><th>ID</th><th>Merchant</th><th>Owner</th><th className="ff-num">Amount</th><th>Decision</th><th>Decided at</th><th>By</th></tr></thead>
        <tbody>
          {items.map(e => (
            <tr key={e.id}>
              <td className="ff-mono" style={{fontSize:12}}>{e.id}</td>
              <td><span className="ff-row" style={{gap:8}}><MerchantIcon name={e.merchant} size={14}/> {e.merchant}</span></td>
              <td>{e.who}</td>
              <td className="ff-num"><Money value={e.amount}/></td>
              <td><StatusBadge status={e.status}/></td>
              <td className="ff-tnum" style={{color:'var(--ff-fg-muted)'}}>{e.decided}</td>
              <td>{e.by}</td>
            </tr>
          ))}
        </tbody>
      </table>
      )}
    </>
  );
};

const ReimbursementsList = () => {
  const d = FF_DATA;
  const outstanding = d.reimbursements.filter(r => !['paid','canceled'].includes(r.status));
  const owedTotal = outstanding.reduce((sum, r) => sum + r.amount, 0);
  return (
    <>
      <PageHead
        eyebrow="Reimbursements"
        title="Reimbursements"
        sub="Out-of-pocket expenses owed to employees"
        actions={<>
          <button className="ff-btn" disabled title="ACH export is not available in this prototype."><Icon name="download-simple" size={14}/> Export ACH file</button>
          <button className="ff-btn ff-btn--primary" hidden={ffRole() !== 'finance'} onClick={()=>ffGo('schedule-payout')}><Icon name="calendar-plus" size={14}/> Schedule reimbursement</button>
        </>}
      />
      {FF_SESSION.toast && <div className="ff-alert ff-alert--info" role="status" style={{marginBottom:16}}>{FF_SESSION.toast}</div>}
      <StatRow items={[
        { label: "Owed this cycle", value: <Money value={owedTotal}/>, delta: `${outstanding.length} employees` },
        { label: "Scheduled", value: "$320.40", delta: "May 30" },
        { label: "Paid YTD", value: "$48,210", delta: "142 reimbursements", trend: "up" }
      ]} style={{padding:'4px 0 20px'}}/>
      {d.reimbursements.length === 0 ? (
        <EmptyState icon="calendar-check" title="No reimbursements owed"
          body="Out-of-pocket expenses owed to employees will show up here once submitted and approved."/>
      ) : (
        <table className="ff-table">
          <thead><tr><th>ID</th><th>Employee</th><th className="ff-num">Amount</th><th>Status</th><th>Date</th><th>Method</th><th></th></tr></thead>
          <tbody>
            {d.reimbursements.map(r => (
              <tr key={r.id} data-row-focus tabIndex="0" onClick={()=>ffGo('payout-detail',{reimbursementId:r.id})} onKeyDown={ffRowKeyDown} aria-label={`${r.id} ${r.who}`} style={{cursor:'pointer'}}>
                <td className="ff-mono" style={{fontSize:12}}>{r.id}</td>
                <td><span className="ff-row" style={{gap:6}}><Avatar initials={r.who.split(' ').map(x=>x[0]).join('').slice(0,2)} name={r.who}/>{r.who}</span></td>
                <td className="ff-num"><Money value={r.amount}/></td>
                <td><StatusBadge status={r.status}/></td>
                <td className="ff-tnum" style={{color:'var(--ff-fg-muted)'}}>{fmtDate(r.date)}</td>
                <td><span className="ff-badge ff-badge--neutral ff-badge--no-dot">ACH</span></td>
                <td><button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={e=>{e.stopPropagation();ffGo('payout-detail',{reimbursementId:r.id});}}>View</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </>
  );
};

const PayoutDetail = () => {
  const r=FF_DATA.reimbursements.find(row=>row.id===FF_SESSION.reimbursementId)||FF_DATA.reimbursements[0];
  const [confirming, setConfirming] = React.useState(false);
  return (
    <>
      <PageHead
        eyebrow="Reimbursement"
        title={`${r.id} · ${r.who}`}
        sub={`${r.status} · ${r.date}`}
        actions={<>
          <button className="ff-btn ff-btn--danger" hidden={ffRole() !== 'finance'} disabled={['paid','canceled'].includes(r.status)} title={['paid','canceled'].includes(r.status)?'This reimbursement is already closed.':undefined} onClick={()=>setConfirming(true)}>Cancel reimbursement</button>
          <button className="ff-btn ff-btn--primary" hidden={ffRole() !== 'finance'} disabled={['paid','canceled'].includes(r.status)} title={['paid','canceled'].includes(r.status)?'This reimbursement is already closed.':undefined} onClick={()=>{r.status='paid';FF_SESSION.payment={rows:[{name:r.who,amount:r.amount}],date:r.date,paid:true};ffGo('state-confirm');}}>Pay now</button>
        </>}
      />
      <div className="ff-grid" style={{gridTemplateColumns:'1.4fr 1fr', gap:16}}>
        <div>
          <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Items in this reimbursement</span></div>
          <table className="ff-table">
            <thead><tr><th>Expense</th><th>Date</th><th className="ff-num">Amount</th></tr></thead>
            <tbody>
              <tr><td>{r.id} · Employee reimbursement</td><td className="ff-tnum">{fmtDate(r.date)}</td><td className="ff-num"><Money value={r.amount}/></td></tr>
            </tbody>
            <tfoot>
              <tr style={{background:'var(--ff-card-2)'}}><td colSpan="2" style={{textAlign:'right', fontWeight:600}}>Total</td><td className="ff-num" style={{fontWeight:600}}><Money value={r.amount}/></td></tr>
            </tfoot>
          </table>
        </div>
        <Card title="Reimbursement method">
          <DetailRow label="Account"><span className="ff-row" style={{gap:6}}><MerchantIcon name="Chase" size={14}/> Chase · •••• 8841</span></DetailRow>
          <div style={{height:12}}/>
          <DetailRow label="Method">ACH — same day</DetailRow>
          <div style={{height:12}}/>
          <DetailRow label="Memo">FinFlow · {r.id}</DetailRow>
          <div style={{height:18}}/>
          <div className="ff-alert ff-alert--info">
            <Icon name="info" size={18} weight="fill"/>
            <div className="ff-alert__body"><div className="ff-alert__title">{r.status} · {r.date}</div><div>Payment activity is simulated in this prototype.</div></div>
          </div>
        </Card>
      </div>
      {confirming && <ConfirmDialog title="Cancel reimbursement?" body={`This will cancel reimbursement ${r.id} before it is sent to ${r.who}.`} onCancel={()=>setConfirming(false)} onConfirm={()=>{setConfirming(false);r.status='canceled';ffToast(`${r.id} canceled.`,'reimburse');ffGo('reimburse');}}/>}
    </>
  );
};

const PAYOUT_ROWS = [
  { id: "corey", name: "Casey Parker", amount: 320.40, items: 3 },
  { id: "jordan", name: "Jordan Lee", amount: 82.00, items: 1 },
  { id: "sam", name: "Quinn Avery", amount: 218.50, items: 2 },
  { id: "jamie", name: "Devon Hayes", amount: 64.20, items: 1 },
];

const SchedulePayout = () => {
  const [selected, setSelected] = React.useState(["corey", "jordan", "sam"]);
  const [memo, setMemo] = React.useState('FinFlow · May 2026');
  const [date,setDate]=React.useState('2026-05-30');
  const [errors, setErrors] = React.useState({});
  const allSelected = selected.length === PAYOUT_ROWS.length;
  const someSelected = selected.length > 0 && !allSelected;
  const headerCbRef = React.useRef(null);
  React.useEffect(() => { if (headerCbRef.current) headerCbRef.current.indeterminate = someSelected; }, [someSelected]);
  const toggleAll = () => setSelected(allSelected ? [] : PAYOUT_ROWS.map(r => r.id));
  const toggleRow = (id) => setSelected(sel => sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]);
  const selRows = PAYOUT_ROWS.filter(r => selected.includes(r.id));
  const total = selRows.reduce((s, r) => s + r.amount, 0);
  const fmtUSD = (n) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(n);
  const submit = () => { const next={}; if(!memo.trim()) next.memo='Enter a memo.';if(!date||Number.isNaN(Date.parse(date)))next.date='Enter a valid arrival date.'; if(!selRows.length) next.items='Select at least one reimbursement.'; setErrors(next); if(!Object.keys(next).length){FF_SESSION.payment={rows:selRows.map(r=>({...r})),date,memo};selRows.forEach(row=>{const existing=FF_DATA.reimbursements.find(r=>r.who===row.name);if(existing){existing.status='scheduled';existing.date=date;}});ffToast(`${selRows.length} reimbursements scheduled.`,'state-confirm');ffGo('state-confirm');} };
  return (
    <>
      <PageHead eyebrow="Reimbursements" title="Schedule a reimbursement" sub="Choose employees and an arrival date"/>
      <FormSummary errors={errors} title="Check the reimbursement"/>
      <div className="ff-grid" style={{gridTemplateColumns:'1.5fr 1fr', gap:24}}>
        <div>
          <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Eligible items</span></div>
          <table className="ff-table">
            <thead><tr><th><input ref={headerCbRef} type="checkbox" checked={allSelected} onChange={toggleAll}/></th><th>Employee</th><th className="ff-num">Owed</th><th>Items</th></tr></thead>
            <tbody>
              {PAYOUT_ROWS.map(r => (
                <tr key={r.id}>
                  <td><input type="checkbox" checked={selected.includes(r.id)} onChange={()=>toggleRow(r.id)}/></td>
                  <td>{r.name}</td>
                  <td className="ff-num"><Money value={r.amount}/></td>
                  <td>{r.items}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Card title="Schedule">
          <div className="ff-stack" style={{'--ff-stack-gap':'14px'}}>
            <div className="ff-field"><label className="ff-label">Arrival date *</label><input aria-label="Arrival date" type="date" required className="ff-input ff-tnum" value={date} onChange={e=>setDate(e.target.value)} onBlur={()=>{if(!date)setErrors({...errors,date:'Enter a valid arrival date.'});}}/><FieldError error={errors.date}/></div>
            <div className="ff-field"><label className="ff-label">Funding source</label><select className="ff-select" disabled title="The sample funding source is fixed in this prototype."><option>Wise · Operating ·  •••• 5512</option></select></div>
            <div className="ff-field"><label className="ff-label">Memo <span aria-hidden="true" style={{color:'var(--ff-rejected)'}}>*</span></label><input aria-label="Memo" className="ff-input" value={memo} onChange={e=>setMemo(e.target.value)} onBlur={()=>{if(!memo.trim())setErrors({...errors,memo:'Enter a memo.'});}}/><FieldError error={errors.memo}/></div>
            <div className="ff-card ff-card--flat" style={{background:'var(--ff-card-2)', padding:14, marginTop:6}}>
              <div className="ff-row" style={{justifyContent:'space-between', fontSize:13}}><span>{selRows.length} reimbursements</span><span className="ff-tnum">{fmtUSD(total)}</span></div>
              <div className="ff-row" style={{justifyContent:'space-between', fontSize:13, color:'var(--ff-fg-muted)'}}><span>ACH fee</span><span className="ff-tnum">$0.00</span></div>
              <hr className="ff-divider" style={{margin:'10px 0'}}/>
              <div className="ff-row" style={{justifyContent:'space-between', fontWeight:600}}><span>Total</span><span className="ff-tnum">{fmtUSD(total)}</span></div>
            </div>
            <button className="ff-btn ff-btn--primary ff-btn--lg" onMouseDown={e=>e.preventDefault()} style={{width:'100%'}} hidden={ffRole() !== 'finance'} onClick={submit}>Schedule {selRows.length} reimbursements</button>
          </div>
        </Card>
      </div>
    </>
  );
};

Object.assign(window, { ApprovalsQueue, ApprovalDetail, ApprovalHistory, ReimbursementsList, PayoutDetail, SchedulePayout });
