// Approvals — mirrors apps/web/src/app/(dashboard)/approvals/page.tsx.
// Lists pending BUY approvals with inline approve/reject buttons.

window.Approvals = function Approvals({ goto, session }) {
  const { useState } = React;
  const [statusFilter, setStatusFilter] = useState('pending');
  const list = window.useApi(() => window.EQ_API.getApprovals(statusFilter), [statusFilter]);
  const [busyId, setBusyId] = useState(null);
  const [error, setError] = useState(null);

  // Frontend-only authorization: only specific emails can approve/reject.
  const canApprove = window.EQ_IS_AUTHORIZED ? window.EQ_IS_AUTHORIZED(session) : true;
  const authorizedTooltip = `Only ${(window.EQ_AUTHORIZED_EMAILS || []).join(', ')} can approve or reject.`;

  const act = async (ap, verb) => {
    if (!canApprove) return;
    setBusyId(ap.id); setError(null);
    try {
      if (verb === 'approve') await window.EQ_API.approveApproval(ap.id);
      else                    await window.EQ_API.rejectApproval(ap.id);
      list.reload();
    } catch (e) { setError(e.message); }
    finally { setBusyId(null); }
  };

  const rows = list.data?.data || [];

  return (
    <div>
      <window.TopBar
        title="Approvals"
        subtitle={list.loading ? 'Loading…' : `${rows.length} ${statusFilter}`}
        right={
          <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{
            padding: '8px 12px', fontSize: 12.5,
            background: 'var(--ink-100)', border: '1px solid var(--ink-200)',
            borderRadius: 7, outline: 'none', color: 'var(--ink-900)', fontFamily: 'inherit'
          }}>
            <option value="pending">Pending</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
          </select>
        }
      />
      <div style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {error && <window.ErrorBanner error={{ message: error }}/>}
        {list.error && <window.ErrorBanner error={list.error} onRetry={list.reload}/>}
        {list.loading && <div style={{ color: 'var(--ink-500)', fontSize: 12.5 }}>Loading…</div>}
        {!list.loading && !list.error && !rows.length && (
          <window.EmptyState title="No approvals" hint={`Nothing ${statusFilter} right now.`}/>
        )}
        {rows.map(ap => (
          <div key={ap.id} style={{
            background: 'var(--paper)', border: '1px solid var(--ink-150)',
            borderRadius: 12, padding: '14px 18px',
            display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap'
          }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink-900)', fontSize: 14 }}>
                  {ap.analyses?.ticker || ap.ticker || '—'}
                </span>
                {ap.analyses?.company_name && ap.analyses.company_name !== ap.analyses.ticker && (
                  <span style={{ fontSize: 12.5, color: 'var(--ink-600)', fontWeight: 400 }}>
                    {ap.analyses.company_name}
                  </span>
                )}
                <window.DecisionBadge decision={ap.analyses?.decision || ap.decision || 'BUY'}/>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 4 }}>
                Requested {window.formatRelative(ap.created_at)}
                {(ap.analyses?.price_target ?? ap.price_target) != null && (
                  <> · target {window.formatPrice(ap.analyses?.price_target ?? ap.price_target)}</>
                )}
                {(ap.analyses?.upside_pct ?? ap.upside_pct) != null && (
                  <> · {window.formatPct(ap.analyses?.upside_pct ?? ap.upside_pct)} upside</>
                )}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {ap.analysis_id && (
                <button onClick={() => goto('analysis', { analysisId: ap.analysis_id })} style={{
                  padding: '7px 12px', fontSize: 12, background: 'transparent', color: 'var(--ink-600)',
                  border: '1px solid var(--ink-200)', borderRadius: 7, cursor: 'pointer', fontFamily: 'inherit'
                }}>Details →</button>
              )}
              {statusFilter === 'pending' && (
                <>
                  <button
                    disabled={busyId === ap.id || !canApprove}
                    title={!canApprove ? authorizedTooltip : undefined}
                    onClick={() => act(ap, 'reject')}
                    style={{
                      padding: '7px 14px', fontSize: 12,
                      background: 'var(--ink-100)', color: 'var(--ink-800)',
                      border: '1px solid var(--ink-200)', borderRadius: 7,
                      cursor: !canApprove ? 'not-allowed' : 'pointer',
                      opacity: !canApprove ? 0.45 : 1,
                      fontFamily: 'inherit',
                    }}
                  >Reject</button>
                  <button
                    disabled={busyId === ap.id || !canApprove}
                    title={!canApprove ? authorizedTooltip : undefined}
                    onClick={() => act(ap, 'approve')}
                    style={{
                      padding: '7px 14px', fontSize: 12, fontWeight: 500,
                      background: 'var(--buy)', color: 'white',
                      border: 'none', borderRadius: 7,
                      cursor: !canApprove ? 'not-allowed' : 'pointer',
                      opacity: !canApprove ? 0.45 : 1,
                      fontFamily: 'inherit',
                    }}
                  >{busyId === ap.id ? '…' : 'Approve'}</button>
                </>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
