// Contracts — simplified, human. Amounts and rates hidden unless revealed.
function ContractsScreen({ onBell, setTab, openContract, tweaks }) {
  const [filter, setFilter] = React.useState('all');
  const effectiveStatus = c => c.awaitingDecision ? 'pending' : c.status;
  const filtered = CONTRACTS
    .filter(c => filter === 'all' || effectiveStatus(c) === filter)
    .sort((a, b) => new Date(a.maturity) - new Date(b.maturity));
  const counts = {
    all: CONTRACTS.length,
    active: CONTRACTS.filter(c => effectiveStatus(c) === 'active').length,
    pending: CONTRACTS.filter(c => effectiveStatus(c) === 'pending').length,
    closed: CONTRACTS.filter(c => effectiveStatus(c) === 'closed').length,
  };
  const filters = [
    { id: 'all',     label: 'Todos' },
    { id: 'active',  label: 'Activos' },
    { id: 'pending', label: 'Pendientes' },
    { id: 'closed',  label: 'Cerrados' },
  ];
  const hide = !tweaks.showNumbersDefault;

  return (
    <div style={{ background: FA.bgSoft, minHeight: '100%', paddingBottom: 120, fontFamily: FA.sans }}>
      <AppHeader onBell={onBell} unread={2}/>
      <div style={{ padding: '4px 20px 16px' }}>
        <div style={{ fontSize: 26, fontWeight: 700, color: FA.ink, letterSpacing: -0.6 }}>Mis contratos</div>
        <div style={{ fontSize: 13, color: FA.muted, marginTop: 4 }}>
          {counts.active} trabajando · 2 por firmar · 1 en vencimiento
        </div>
      </div>

      <div style={{ padding: '0 16px 14px', display: 'flex', gap: 8, overflowX: 'auto', scrollbarWidth: 'none' }}>
        {filters.map(f => {
          const on = filter === f.id;
          return (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              flexShrink: 0, background: on ? FA.ink : '#fff',
              color: on ? '#fff' : FA.inkSoft,
              padding: '8px 14px', borderRadius: 999,
              fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
              fontFamily: FA.sans, border: on ? 'none' : '1px solid rgba(10,22,40,.06)',
              boxShadow: on ? 'none' : '0 1px 2px rgba(10,22,40,.03)',
            }}>{f.label}</button>
          );
        })}
      </div>

      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map(c => (
          <ContractCard key={c.id} contract={c} onOpen={() => openContract && openContract(c)} hide={hide}/>
        ))}
      </div>
    </div>
  );
}

function ContractCard({ contract, onOpen, hide }) {
  const c = contract;
  const badgeKind = c.awaitingDecision ? 'decide' : c.status;
  const statusLabel = c.awaitingDecision ? 'Pendiente' : { active: 'Activo', pending: 'Pendiente', closed: 'Completado' }[c.status];
  return (
    <button onClick={onOpen} style={{
      border: 'none', textAlign: 'left', padding: 0, cursor: 'pointer',
      background: 'transparent', width: '100%', fontFamily: FA.sans,
    }}>
      <Card pad={16}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 42, height: 42, borderRadius: 12,
            background: c.status === 'pending' ? '#fef3c7' : c.status === 'closed' ? FA.bgSoft : FA.skySoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            fontSize: 15, fontWeight: 700, color: c.status === 'pending' ? '#92400e' : c.status === 'closed' ? FA.muted : FA.blue,
          }}>{c.counterparty.split(' ').map(w => w[0]).slice(0, 2).join('')}</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{
              fontSize: 14.5, fontWeight: 650, color: FA.ink, letterSpacing: -0.2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{c.counterparty}</div>
            <div style={{ marginTop: 4 }}>
              <Badge kind={badgeKind}>{statusLabel}</Badge>
            </div>
          </div>
          {!hide && (
            <div style={{ textAlign: 'right' }}>
              <div style={{
                fontSize: 15, fontWeight: 650, color: FA.ink,
                fontFamily: FA.mono, letterSpacing: -0.3,
              }}>{fmtUSD(c.amount)}</div>
            </div>
          )}
          {hide && <Icon name="chev" size={14} color={FA.muted} strokeWidth={2}/>}
        </div>

        {c.status === 'active' && (
          <div style={{ marginTop: 14 }}>
            <div style={{ height: 5, background: FA.hairline, borderRadius: 3, overflow: 'hidden' }}>
              <div style={{
                width: `${c.progress}%`, height: '100%',
                background: 'linear-gradient(90deg, #38bdf8 0%, #2563eb 100%)',
              }}/>
            </div>
            <div style={{
              display: 'flex', justifyContent: 'space-between', marginTop: 8,
              fontSize: 11.5, color: FA.muted,
            }}>
              <span>{c.progress < 50 ? 'Avanzando bien' : c.progress < 90 ? 'Casi en la meta' : 'Por vencer'}</span>
              <span>Vence <span style={{ color: FA.inkSoft, fontWeight: 600 }}>{fmtDateES(new Date(c.maturity))}</span></span>
            </div>
          </div>
        )}
        {c.status === 'pending' && (
          <div style={{
            marginTop: 12, padding: '10px 12px',
            background: '#fef3c7', borderRadius: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontSize: 12, color: '#92400e', fontWeight: 600,
          }}>
            <span>Listo para firmar</span>
            <Icon name="pen" size={14} color="#92400e" strokeWidth={2}/>
          </div>
        )}
      </Card>
    </button>
  );
}

Object.assign(window, { ContractsScreen, ContractCard });
