/* ============================================================================
   FSC UI — átomos do dashboard. window.FSCUI.*
   ============================================================================ */
const { fmt } = window.FSC;
const Icon = window.FSCIcon;

function Card({ title, subtitle, right, children, style, bodyStyle, pad = 20 }) {
  return (
    <div style={{
      background: 'var(--surface-card)', border: '1px solid var(--border-subtle)',
      borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', display: 'flex', flexDirection: 'column',
      minWidth: 0, ...style,
    }}>
      {(title || right) && (
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, padding: `${pad}px ${pad}px 0` }}>
          <div style={{ minWidth: 0 }}>
            {title && <h3 style={{ font: '600 15px/1.2 var(--font-display)', color: 'var(--text-primary)', letterSpacing: '-0.01em' }}>{title}</h3>}
            {subtitle && <p style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 3 }}>{subtitle}</p>}
          </div>
          {right && <div style={{ flexShrink: 0 }}>{right}</div>}
        </div>
      )}
      <div style={{ padding: pad, ...bodyStyle }}>{children}</div>
    </div>
  );
}

// delta: número (% ou pp). mode: 'higher-good' | 'lower-good' | 'neutral'. unit: '%' | 'pp'
function DeltaBadge({ value, mode = 'higher-good', unit = '%' }) {
  if (value == null || !isFinite(value)) {
    return <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>—</span>;
  }
  const up = value >= 0;
  const good = mode === 'neutral' ? null : (mode === 'higher-good' ? up : !up);
  const color = good == null ? 'var(--text-muted)' : good ? 'var(--positive)' : 'var(--negative)';
  const bg = good == null ? 'var(--sand-50)' : good ? 'var(--positive-soft)' : 'var(--negative-soft)';
  const txt = unit === 'pp'
    ? `${up ? '+' : ''}${value.toLocaleString('pt-BR', { maximumFractionDigits: 1 })} pp`
    : fmt.signedPct(value, 1);
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 7px 2px 5px', borderRadius: 999, background: bg, color, fontSize: 11.5, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>
      <Icon name={up ? 'arrowUpRight' : 'arrowDownRight'} size={12} strokeWidth={2.4} />{txt}
    </span>
  );
}

function Kpi({ label, value, delta, deltaMode = 'higher-good', deltaUnit = '%', sub, accent }) {
  return (
    <div style={{
      background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)',
      boxShadow: 'var(--shadow-sm)', padding: '15px 16px', display: 'flex', flexDirection: 'column', gap: 7, minWidth: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        {accent && <span style={{ width: 7, height: 7, borderRadius: 2, background: accent, flexShrink: 0 }} />}
        <span style={{ fontSize: 11.5, color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '.02em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
      </div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 23, fontWeight: 600, color: 'var(--text-primary)', letterSpacing: '-0.02em', lineHeight: 1 }}>{value}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minHeight: 18 }}>
        {delta !== undefined && <DeltaBadge value={delta} mode={deltaMode} unit={deltaUnit} />}
        {sub && <span style={{ fontSize: 11.5, color: 'var(--text-faint)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</span>}
      </div>
    </div>
  );
}

function Money({ value, signed = false, size, bold = true }) {
  const neg = value < 0;
  const color = signed ? (neg ? 'var(--negative)' : 'var(--positive)') : 'var(--text-primary)';
  return <span style={{ fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums', fontWeight: bold ? 600 : 500, color, fontSize: size }}>{signed && !neg ? '+' : ''}{fmt.brl(value)}</span>;
}

function Pill({ children, tone = 'neutral', onClick, active }) {
  const tones = {
    neutral: { bg: 'var(--sand-50)', fg: 'var(--text-secondary)' },
    positive: { bg: 'var(--positive-soft)', fg: 'var(--positive)' },
    negative: { bg: 'var(--negative-soft)', fg: 'var(--negative)' },
    ink: { bg: 'var(--ink-900)', fg: 'var(--text-on-dark)' },
  };
  const t = tones[active ? 'ink' : tone];
  return (
    <span onClick={onClick} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 999, background: t.bg, color: t.fg, fontSize: 12, fontWeight: 600, cursor: onClick ? 'pointer' : 'default', whiteSpace: 'nowrap' }}>{children}</span>
  );
}

function SectionTitle({ children, sub }) {
  return (
    <div style={{ marginBottom: 4 }}>
      <h2 style={{ font: '600 19px/1.2 var(--font-display)', letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>{children}</h2>
      {sub && <p style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</p>}
    </div>
  );
}

// dropdown nativo estilizado
function Select({ value, onChange, options, icon, width }) {
  return (
    <div style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', width }}>
      {icon && <span style={{ position: 'absolute', left: 10, color: 'var(--text-muted)', pointerEvents: 'none' }}><Icon name={icon} size={15} /></span>}
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{
        appearance: 'none', WebkitAppearance: 'none', font: '500 13.5px/1 var(--font-sans)', color: 'var(--text-primary)',
        background: 'var(--surface-card)', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-md)',
        padding: icon ? '8px 30px 8px 30px' : '8px 30px 8px 12px', cursor: 'pointer', width: '100%', height: 38,
      }}>
        {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <span style={{ position: 'absolute', right: 9, color: 'var(--text-muted)', pointerEvents: 'none' }}><Icon name="chevronDown" size={15} /></span>
    </div>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div style={{ display: 'inline-flex', background: 'var(--sand-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: 3, gap: 2 }}>
      {options.map((o) => {
        const on = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-sm)', padding: '6px 12px',
            font: '600 12.5px/1 var(--font-sans)', whiteSpace: 'nowrap',
            background: on ? 'var(--surface-card)' : 'transparent', color: on ? 'var(--text-primary)' : 'var(--text-muted)',
            boxShadow: on ? 'var(--shadow-xs)' : 'none', transition: 'all .15s',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function EmptyState({ children }) {
  return <div style={{ padding: '36px 16px', textAlign: 'center', color: 'var(--text-faint)', fontSize: 13.5 }}>{children}</div>;
}

window.FSCUI = { Card, Kpi, DeltaBadge, Money, Pill, SectionTitle, Select, Segmented, EmptyState };
