// Inbox — approvals queue (checkpoint pattern). Agent actions awaiting human OK.
// Wired to POST /api/approvals/{id}/decide for real persistence.

function InboxScreen({ go }) {
  const d = LifeData;
  const [decisions, setDecisions] = React.useState({});

  const handle = async (id, action) => {
    setDecisions(s => ({ ...s, [id]: action }));
    const approval = d.approvals.find(a => a.id === id);
    try {
      await fetch(`/api/approvals/${id}/decide`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, kind: approval?.kind || 'bill' }),
      });
    } catch (err) {
      console.error('Approval decision failed:', err);
    }
  };

  const grouped = {
    now: d.approvals.filter(a => a.urgency === 'now'),
    today: d.approvals.filter(a => a.urgency === 'today'),
    soon: d.approvals.filter(a => a.urgency === 'soon'),
    later: d.approvals.filter(a => a.urgency === 'later'),
  };
  const headings = {
    now: 'Now · go to laptop',
    today: 'Today',
    soon: 'This week',
    later: 'Later',
  };
  const pending = d.approvals.filter(a => !decisions[a.id]).length;

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Header */}
      <div style={{ padding: '64px 20px 8px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>
          Approvals · Checkpoint
        </div>
        <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>
          {pending === 0 ? 'All caught up.' : `${pending} need a yes.`}
        </div>
        <div style={{ fontSize: 14, color: T.label2, marginTop: 4, lineHeight: '19px' }}>
          Life OS won't take irreversible actions without you. Approve once and it'll handle the rest.
        </div>
      </div>

      {/* Spend pulse */}
      <div style={{ padding: '14px 16px 0' }}>
        <Card style={{ padding: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>API spend · this month</div>
          <div style={{ display: 'flex', gap: 14 }}>
            <SpendBar label="Gemini" used={d.apiSpend.gemini} budget={d.apiSpend.gemini_budget} color={T.blue} />
            <SpendBar label="Claude" used={d.apiSpend.claude} budget={d.apiSpend.claude_budget} color={T.purple} />
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
              <div style={{ fontSize: 10, fontWeight: 600, color: T.label2, letterSpacing: 0.3, textTransform: 'uppercase' }}>Ollama</div>
              <div style={{ fontSize: 13, fontWeight: 700, color: T.green }}>free</div>
            </div>
          </div>
        </Card>
      </div>

      {/* Groups */}
      {d.approvals.length === 0 ? (
        <div style={{ padding: '30px 16px' }}>
          <Card style={{ padding: 24, textAlign: 'center' }}>
            <IconCheck size={40} color={T.green} />
            <div style={{ fontSize: 17, fontWeight: 600, marginTop: 12 }}>Nothing pending</div>
            <div style={{ fontSize: 14, color: T.label2, marginTop: 6 }}>
              Life OS will surface actions here when bills are due, groceries are low, or it needs your OK.
            </div>
          </Card>
        </div>
      ) : (
        Object.entries(grouped).filter(([, arr]) => arr.length > 0).map(([key, arr]) => (
          <Section key={key} title={headings[key]} style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {arr.map(a => (
                <ApprovalCard key={a.id} a={a} decision={decisions[a.id]} onAction={handle} />
              ))}
            </div>
          </Section>
        ))
      )}

      <div style={{ padding: '24px 16px 0', fontSize: 11, color: T.label3, textAlign: 'center', lineHeight: '17px' }}>
        Payments, deletions and submissions always pause here.
        <br />Browser sessions live on your Thinkpad only.
      </div>
    </div>
  );
}

function ApprovalCard({ a, decision, onAction }) {
  const iconMap = {
    bill:     <IconBill size={20} color="#fff" />,
    grocery:  <IconCart size={20} color="#fff" />,
    reply:    <IconReply size={20} color="#fff" />,
    cart:     <IconCart size={20} color="#fff" />,
    memory:   <IconBookmark size={20} color="#fff" />,
  };
  const kindLabel = {
    bill: 'BILL AUTOPILOT',
    grocery: 'GROCERY ORACLE',
    reply: 'REPLY DRAFT',
    cart: 'CART READY',
    memory: 'NEW MEMORY',
  };

  const handled = decision === 'approve' || decision === 'reject';

  return (
    <Card style={{
      padding: 0, overflow: 'hidden',
      opacity: handled ? 0.5 : 1,
      transition: 'opacity 0.25s',
    }}>
      <div style={{ display: 'flex', padding: 14, gap: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 12,
          background: a.accent,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>{iconMap[a.kind] || <IconBill size={20} color="#fff" />}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: a.accent, letterSpacing: 0.5 }}>{kindLabel[a.kind] || 'ACTION'}</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginTop: 3, lineHeight: '20px' }}><Bi>{a.title}</Bi></div>
          <div style={{ fontSize: 12, color: T.label2, marginTop: 2, lineHeight: '17px' }}><Bi>{a.subtitle}</Bi></div>
        </div>
      </div>
      {a.detail && (
        <div style={{
          borderTop: `0.5px solid ${T.sep}`, padding: '10px 14px', background: T.bg3,
          fontSize: 12, color: T.label2, lineHeight: '17px',
        }}>
          <Bi>{a.detail}</Bi>
        </div>
      )}
      {/* actions */}
      <div style={{ display: 'flex', borderTop: `0.5px solid ${T.sep}` }}>
        <button onClick={() => onAction(a.id, 'reject')} disabled={handled} style={{
          flex: 1, height: 44, border: 'none', background: 'transparent', cursor: handled ? 'default' : 'pointer',
          fontSize: 14, fontWeight: 500, color: T.label2,
          borderRight: `0.5px solid ${T.sep}`,
        }}>
          {decision === 'reject' ? 'Rejected ✓' : 'Not now'}
        </button>
        {a.kind === 'cart' ? (
          <button disabled={handled} style={{
            flex: 1, height: 44, border: 'none', background: 'transparent', cursor: 'pointer',
            fontSize: 14, fontWeight: 600, color: a.accent,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
          }}>
            <IconLink size={14} color={a.accent} /> Open laptop
          </button>
        ) : (
          <button onClick={() => onAction(a.id, 'approve')} disabled={handled} style={{
            flex: 1, height: 44, border: 'none', background: 'transparent', cursor: handled ? 'default' : 'pointer',
            fontSize: 14, fontWeight: 600, color: a.accent,
          }}>
            {decision === 'approve' ? 'Approved ✓' : 'Approve'}
          </button>
        )}
      </div>
    </Card>
  );
}

function SpendBar({ label, used, budget, color }) {
  const pct = budget > 0 ? Math.min(used / budget, 1) : 0;
  const overBudget = used >= budget * 0.9;
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 10, fontWeight: 600, color: T.label2, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 13, fontWeight: 700, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
        ${used.toFixed(2)} <span style={{ color: T.label3, fontWeight: 500 }}>/ ${budget.toFixed(2)}</span>
      </div>
      <div style={{ height: 4, borderRadius: 999, background: T.bg, marginTop: 5, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct*100}%`, background: overBudget ? T.red : color, borderRadius: 999 }} />
      </div>
    </div>
  );
}

window.InboxScreen = InboxScreen;
