/* Cobranças · helpers partilhados — formatters, badges, ícones, marcador "Validar Patrícia" */

window.FinHelpers = (() => {
  const fmtEUR = (n) => {
    if (n == null) return '—';
    const sign = n < 0 ? '-' : '';
    const abs = Math.abs(n);
    return sign + '€ ' + abs.toLocaleString('pt-PT', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  };

  const fmtEURcompact = (n) => {
    if (n == null) return '—';
    const abs = Math.abs(n);
    if (abs >= 1_000_000) return '€ ' + (n / 1_000_000).toFixed(2).replace('.', ',') + 'M';
    if (abs >= 1_000)     return '€ ' + (n / 1_000).toFixed(0) + 'k';
    return '€ ' + n;
  };

  const idadeColor = (idade) => {
    if (idade == null) return 'var(--text-dim)';
    if (idade < 0)  return 'var(--text-muted)';
    if (idade <= 30) return 'var(--success)';
    if (idade <= 60) return '#F59E0B';
    if (idade <= 90) return '#F97316';
    return 'var(--danger)';
  };

  const scoreColor = (s) => {
    if (s >= 80) return 'var(--success)';
    if (s >= 60) return '#F59E0B';
    if (s >= 40) return '#F97316';
    return 'var(--danger)';
  };

  const empresaChip = (id, options = {}) => {
    const e = window.FIN_EMPRESAS.find(x => x.id === id);
    if (!e) return null;
    const { large } = options;
    return React.createElement('span', {
      key: id,
      className: 'font-mono',
      style: {
        fontSize: large ? 10.5 : 9.5,
        fontWeight: 600,
        padding: large ? '2px 6px' : '1px 5px',
        borderRadius: 3,
        background: `color-mix(in oklch, ${e.color} 14%, transparent)`,
        color: e.color,
        border: `1px solid color-mix(in oklch, ${e.color} 30%, transparent)`,
        letterSpacing: '0.04em',
      }
    }, e.short);
  };

  const estadoBadge = (estado, options = {}) => {
    const conf = window.FIN_ESTADOS[estado];
    if (!conf) return null;
    const { value, count, large } = options;
    return React.createElement('span', {
      className: 'font-mono',
      title: conf.desc,
      style: {
        display: 'inline-flex', alignItems: 'center', gap: 6,
        fontSize: large ? 11 : 9.5,
        fontWeight: 600,
        padding: large ? '3px 7px' : '1px 5px',
        borderRadius: 3,
        background: `color-mix(in oklch, ${conf.color} 14%, transparent)`,
        color: conf.color,
        border: `1px solid color-mix(in oklch, ${conf.color} 28%, transparent)`,
      },
    }, estado, value != null && React.createElement('span', { style: { color: 'var(--text)', fontWeight: 600 } }, window.FinHelpers.fmtEURcompact(value)),
       count != null && count > 0 && React.createElement('span', { style: { color: 'var(--text-dim)', fontSize: 9 } }, '· ' + count + 'd'));
  };

  // Marcador (?) — assunção pendente de validar com Patrícia
  const ValidarPatricia = ({ children }) => {
    const [hover, setHover] = React.useState(false);
    return (
      <span style={{ position: 'relative', display: 'inline-flex' }}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}>
        <span style={{
          marginLeft: 4, fontSize: 10, fontWeight: 600,
          width: 14, height: 14, borderRadius: '50%',
          background: 'color-mix(in oklch, #A855F7 14%, transparent)',
          color: '#A855F7',
          border: '1px solid color-mix(in oklch, #A855F7 30%, transparent)',
          display: 'inline-grid', placeItems: 'center',
          cursor: 'help',
        }}>?</span>
        {hover && (
          <span style={{
            position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)',
            marginBottom: 6, padding: '8px 10px', borderRadius: 6,
            background: '#1E1B4B', color: '#fff', fontSize: 11, lineHeight: 1.45,
            width: 240, zIndex: 100, fontWeight: 400,
            boxShadow: '0 8px 24px rgba(0,0,0,0.3)',
          }}>
            <span style={{ color: '#A855F7', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.06em', display: 'block', marginBottom: 4 }}>VALIDAR COM PATRÍCIA</span>
            {children}
          </span>
        )}
      </span>
    );
  };

  const SLABadge = ({ state, label }) => {
    const colors = {
      ok:   { bg: 'color-mix(in oklch, var(--success) 14%, transparent)', fg: 'var(--success)', bd: 'color-mix(in oklch, var(--success) 30%, transparent)' },
      warn: { bg: 'color-mix(in oklch, #F59E0B 14%, transparent)',         fg: '#F59E0B',         bd: 'color-mix(in oklch, #F59E0B 30%, transparent)' },
      late: { bg: 'color-mix(in oklch, var(--danger) 14%, transparent)',  fg: 'var(--danger)',  bd: 'color-mix(in oklch, var(--danger) 30%, transparent)' },
    };
    const c = colors[state] || colors.ok;
    return (
      <span className="font-mono" style={{
        fontSize: 10, padding: '2px 6px', borderRadius: 3,
        background: c.bg, color: c.fg, border: `1px solid ${c.bd}`,
      }}>{label}</span>
    );
  };

  const Sparkline = ({ data, w = 80, h = 22, color = 'var(--text-dim)' }) => {
    const max = Math.max(...data), min = Math.min(...data), range = max - min || 1;
    const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - ((v - min) / range) * (h - 4) - 2}`).join(' ');
    return (
      <svg width={w} height={h} style={{ display: 'block' }}>
        <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" />
      </svg>
    );
  };

  const Donut = ({ segs, size = 80, thick = 12 }) => {
    const total = segs.reduce((s, x) => s + x.v, 0) || 1;
    const r = (size - thick) / 2;
    const c = 2 * Math.PI * r;
    let acc = 0;
    return (
      <svg width={size} height={size}>
        <g transform={`translate(${size / 2},${size / 2}) rotate(-90)`}>
          {segs.map((s, i) => {
            const len = (s.v / total) * c;
            const dash = `${len} ${c - len}`;
            const off = -acc;
            acc += len;
            return <circle key={i} r={r} fill="none" stroke={s.color} strokeWidth={thick} strokeDasharray={dash} strokeDashoffset={off} />;
          })}
        </g>
      </svg>
    );
  };

  return { fmtEUR, fmtEURcompact, idadeColor, scoreColor, empresaChip, estadoBadge, ValidarPatricia, SLABadge, Sparkline, Donut };
})();
