// Invoice Approval Hub — competitor best-of (StrataMax Invoice Hub / MRI online
// approval), in Opsmera's language. Committee approves / queries / denies online;
// on majority it auto-drops into the payment run. Every action stamped.
const ST_ICON = { approved: 'check', denied: 'x', query: 'message-circle-question', pending: 'clock' };

function fmt(n) { return '$' + n.toLocaleString('en-AU'); }

function InvoiceRow({ inv, sel, onClick }) {
  const ok = inv.approvers.filter(a => a.state === 'approved').length;
  return (
    <div className={`inv-row ${sel ? 'sel' : ''}`} onClick={onClick}>
      <div>
        <div className="cr">{inv.creditor}</div>
        <div className="mb">{siteOf(inv.bldg).short} · {siteOf(inv.bldg).sp} · {inv.id}</div>
      </div>
      <div>
        <div className="amt">{fmt(inv.amount)}</div>
        <div className="prog">
          {inv.approvers.map((a, i) => (
            <span key={i} className={`pip ${a.state === 'approved' ? 'ok' : a.state === 'denied' ? 'no' : a.state === 'query' ? 'q' : ''}`} />
          ))}
        </div>
      </div>
    </div>
  );
}

function InvoiceDetail({ inv }) {
  const ok = inv.approvers.filter(a => a.state === 'approved').length;
  const denied = inv.approvers.some(a => a.state === 'denied');
  const met = ok >= inv.need && !denied;
  const pct = Math.min(100, Math.round(ok / inv.need * 100));
  return (
    <div className="inv-detail">
      <div className="inv-sum">
        <div className="top">
          <div>
            <div className="mb" style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>{inv.id} · {inv.creditor}</div>
            <div className="big" style={{ marginTop: 10 }}>{fmt(inv.amount)}<small>incl. {fmt(inv.gst)} GST · {siteOf(inv.bldg).short} · {siteOf(inv.bldg).sp}</small></div>
          </div>
          {inv.status === 'overdue'
            ? <Tag track="breached" sub="Overdue" />
            : <Tag stage={inv.status === 'approved' ? 'approved' : 'awaiting'} />}
        </div>
        <p style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.55, margin: '14px 0 0' }}>{inv.desc}</p>
      </div>
      <div className="inv-body">
        <div className="ai-card">
          <div className="hd"><Icon name="sparkles" />Opsmera AI · recommendation</div>
          <p>{met
            ? `Majority reached (${ok} of ${inv.need}). I can add this to Friday's payment run and file it against the ${inv.bldg} ${inv.cat.toLowerCase()} register. Certificate attached for the audit trail.`
            : denied
              ? `One approver denied with a query. I have held it out of the payment run and notified ${inv.creditor}. Resolve the query to re-open approval.`
              : `${ok} of ${inv.need} approvals in. This matches the approved ${inv.cat.toLowerCase()} quote for ${inv.bldg} - no duplicate found. I have nudged the pending approvers.`}</p>
          {inv.basis && <div className="ai-card-basis"><Icon name="history" /><span><b>Based on history:</b> {inv.basis}</span></div>}
        </div>
        <div>
          <h4 style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--fg-3)', margin: '0 0 12px' }}>Line items</h4>
          <table className="lines">
            <tbody>
              {inv.lines.map(([d, a], i) => (<tr key={i}><td>{d}</td><td className="r">{fmt(a)}</td></tr>))}
              <tr className="total"><td>Total incl. GST</td><td className="r">{fmt(inv.amount)}</td></tr>
            </tbody>
          </table>
        </div>
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <h4 style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--fg-3)', margin: 0 }}>Committee approval</h4>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: met ? 'var(--mint-500)' : 'var(--fg-3)' }}>{ok} of {inv.need} needed</span>
          </div>
          <div className="maj" style={{ marginBottom: 14 }}><i style={{ width: pct + '%', background: met ? 'var(--mint-500)' : 'var(--status-warning)' }} /></div>
          <div className="tally">
            {inv.approvers.map((a, i) => (
              <div className="appr" key={i}>
                <div className="av">{a.nm.split(/[. ]/).filter(Boolean).map(s => s[0]).join('').slice(0,2)}</div>
                <div className="who"><div className="nm">{a.nm}</div><div className="rl">{a.role}{a.when ? ' · ' + a.when : ''}</div></div>
                <span className={`st ${a.state}`}><Icon name={ST_ICON[a.state]} />{a.state}</span>
              </div>
            ))}
          </div>
        </div>
        {inv.thread.length > 0 && (
          <div>
            <h4 style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--fg-3)', margin: '0 0 14px' }}>Queries</h4>
            <div className="thread">
              {inv.thread.map(([nm, msg, tm], i) => (
                <div className="msg" key={i}>
                  <div className="av">{nm === 'You' ? 'JY' : nm.split(/[. ]/).filter(Boolean).map(s => s[0]).join('').slice(0,2)}</div>
                  <div className="bub"><div className="mh"><span className="nm">{nm}</span><span className="tm">{tm}</span></div><p>{msg}</p></div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      <div className="inv-actions">
        <button className="btn btn-primary" onClick={() => act('Invoice approved', { kind: 'resolved', sub: inv.id + ' added to Friday’s payment run' })}><Icon name="check" />Approve</button>
        <button className="btn btn-ghost" onClick={() => act('Query sent to committee', { kind: 'warning', icon: 'message-circle-question', sub: 'Held out of the payment run' })}><Icon name="message-circle-question" />Query</button>
        <button className="btn btn-ghost" onClick={() => act('Invoice denied', { kind: 'urgent', icon: 'x', sub: inv.creditor + ' notified' })}><Icon name="x" />Deny</button>
        <button className="btn btn-ghost" style={{ marginLeft: 'auto' }} onClick={() => act('Reassign approver', { kind: 'info', icon: 'user-round-plus' })}><Icon name="user-round-plus" />Reassign</button>
      </div>
    </div>
  );
}

function InvoiceHub() {
  const [sel, setSel] = React.useState(INVOICES[0].id);
  const [tab, setTab] = React.useState('Awaiting');
  const [showDetail, setShowDetail] = React.useState(false);
  const isMobile = useIsMobile(820);
  const tabs = ['Awaiting', 'Mine', 'Approved', 'Overdue'];
  const inv = INVOICES.find(i => i.id === sel);
  const pick = id => { setSel(id); setShowDetail(true); };
  return (
    <div className="view"><div className={`split ${showDetail ? 'show-detail' : ''}`}>
      <div className="split-list">
        <div className="in-toolbar">
          <div className="seg">{tabs.map(t => <button key={t} className={t === tab ? 'on' : ''} onClick={() => setTab(t)}>{t}</button>)}</div>
          <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }} onClick={() => act('Payment run prepared', { kind: 'resolved', icon: 'banknote', sub: '$184k across 26 approved invoices' })}><Icon name="banknote" />Payment run</button>
        </div>
        <div style={{ padding: '16px 20px 6px' }}>
          <div className="stat-strip" style={{ marginBottom: 6 }}>
            <div className="s"><div className="n alert">18</div><div className="l">Awaiting</div></div>
            <div className="s"><div className="n">26</div><div className="l">In approval</div></div>
            <div className="s"><div className="n">$184k</div><div className="l">Approved / wk</div></div>
            <div className="s"><div className="n">3</div><div className="l">Overdue</div></div>
          </div>
        </div>
        {INVOICES.map(i => <InvoiceRow key={i.id} inv={i} sel={i.id === sel} onClick={() => pick(i.id)} />)}
      </div>
      <div className="split-detail">
        {isMobile && <button className="detail-back" onClick={() => setShowDetail(false)}><Icon name="arrow-left" />All invoices</button>}
        <InvoiceDetail inv={inv} />
      </div>
    </div></div>
  );
}
Object.assign(window, { InvoiceHub });
