// ─────────────────────────────────────────────────────────────
// charts.jsx — Spending chart (bars / lines / area) + Allocation block
// ─────────────────────────────────────────────────────────────
const { LedgerIcon } = window;

function LedgerSpendingChart({ data, activeIndex, style = 'bars', onSelect, titleOverride }) {
  const T = window.LedgerStore;
  const max = Math.max(1, ...data.map(d => d.value));
  const [hover, setHover] = React.useState(null);
  const W = 100, H = 100; // viewBox units; we use percentage paths
  const eyebrow = titleOverride ? titleOverride.eyebrow : 'GASTOS AO LONGO DO TEMPO';
  const title = titleOverride ? titleOverride.title : 'Gastos Acumulados';
  const peakLabel = titleOverride ? (titleOverride.peakLabel || 'MAIOR MÊS') : 'MAIOR MÊS';

  // Build points for line / area on a 0..W × 0..H grid
  const points = data.map((d, i) => {
    const x = data.length === 1 ? W / 2 : (i / (data.length - 1)) * W;
    const y = H - (d.value / max) * (H - 6) - 2; // small top inset
    return { x, y, d, i };
  });
  const linePath = points.map((p, i) => (i === 0 ? `M${p.x},${p.y}` : `L${p.x},${p.y}`)).join(' ');
  const areaPath = `M${points[0].x},${H} ${linePath} L${points[points.length - 1].x},${H} Z`;

  return (
    <div className="ledger-chart" style={{
      flex: '1 1 480px', minWidth: 0,
      background: 'var(--bg-muted)', borderRadius: 'var(--r-4)', padding: 28,
      minHeight: 386, boxSizing: 'border-box', display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{eyebrow}</div>
          <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '28px', color: 'var(--fg-strong)' }}>{title}</h3>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{peakLabel}</div>
          <div className="num" style={{ fontSize: 18, lineHeight: '24px' }}>{T.fmtMoney(max)}</div>
        </div>
      </div>

      <div style={{ flex: 1, position: 'relative', marginTop: 16, minHeight: 220 }}>
        {/* Faint horizontal grid lines */}
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', pointerEvents: 'none' }}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{ height: 1, background: 'var(--border-soft)' }} />
          ))}
        </div>

        {style === 'bars' && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'stretch', gap: 14, padding: '0 4px' }}>
            {data.map((d, i) => {
              const h = (d.value / max) * 100;
              const active = i === activeIndex;
              const isHover = hover === i;
              const lit = active || isHover;
              const hasValue = d.value > 0;
              return (
                <div key={i}
                  onClick={() => onSelect && onSelect(i)}
                  onMouseEnter={() => setHover(i)}
                  onMouseLeave={() => setHover(null)}
                  style={{ flex: 1, height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', position: 'relative', cursor: onSelect ? 'pointer' : 'default' }}>
                  {(lit && hasValue) && (
                    <div style={{
                      position: 'absolute', left: '50%', transform: 'translateX(-50%)', bottom: `calc(max(${h}%, 4px) + 6px)`,
                      background: 'var(--bg-inverse)', color: 'var(--fg-on-inverse)',
                      fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, lineHeight: '14px',
                      padding: '4px 8px', borderRadius: 'var(--r-1)', whiteSpace: 'nowrap', zIndex: 5,
                    }}>{T.fmtMoney(d.value)}</div>
                  )}
                  <div style={{
                    width: '100%',
                    height: hasValue ? `max(${h}%, 4px)` : '0%',
                    borderRadius: '4px 4px 0 0',
                    background: active ? 'var(--bg-inverse)' : 'var(--brand-magenta)',
                    opacity: active ? 1 : (hasValue ? (isHover ? 1 : 0.82) : 0),
                    boxShadow: lit ? 'var(--shadow-lg)' : 'none',
                    transition: 'all var(--dur-base) var(--ease-out)',
                  }} />
                </div>
              );
            })}
          </div>
        )}

        {(style === 'lines' || style === 'area') && (
          <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            <defs>
              <linearGradient id="lgFill" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="var(--brand-magenta)" stopOpacity="0.32" />
                <stop offset="100%" stopColor="var(--brand-magenta)" stopOpacity="0.02" />
              </linearGradient>
            </defs>
            {style === 'area' && <path d={areaPath} fill="url(#lgFill)" />}
            <path d={linePath} fill="none" stroke="var(--brand-magenta)" strokeWidth="0.6" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
            {points.map((p, i) => {
              const active = i === activeIndex;
              return (
                <g key={i} onClick={() => onSelect && onSelect(i)} style={{ cursor: onSelect ? 'pointer' : 'default' }}>
                  <circle cx={p.x} cy={p.y} r={active ? 1.6 : 0.9} fill={active ? 'var(--bg-inverse)' : 'var(--brand-magenta)'} stroke="var(--bg-muted)" strokeWidth="0.4" />
                </g>
              );
            })}
          </svg>
        )}

        {(style === 'lines' || style === 'area') && activeIndex != null && points[activeIndex] && (
          <div style={{
            position: 'absolute',
            left: `${points[activeIndex].x}%`,
            bottom: `${100 - points[activeIndex].y}%`,
            transform: 'translate(-50%, calc(-100% - 10px))',
            background: 'var(--bg-inverse)', color: 'var(--fg-on-inverse)',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, lineHeight: '14px',
            padding: '4px 8px', borderRadius: 'var(--r-1)', whiteSpace: 'nowrap',
            pointerEvents: 'none',
          }}>{T.fmtMoneyShort(data[activeIndex].value)}</div>
        )}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 4px 0' }}>
        {data.map((d, i) => (
          <div key={d.label + i} onClick={() => onSelect && onSelect(i)} style={{
            flex: 1, textAlign: 'center', cursor: onSelect ? 'pointer' : 'default',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px',
            color: i === activeIndex ? 'var(--fg)' : 'var(--fg-3)',
          }}>{d.label}</div>
        ))}
      </div>
    </div>
  );
}

// ── ALLOCATION DONUT ─────────────────────────────────────────
function LedgerAllocationBlock({ items, total, totalLabel = 'TOTAL OUT' }) {
  let acc = 0;
  const safeTotal = Math.max(1, items.reduce((s, it) => s + it.pct, 0));
  const stops = items.map(it => {
    const start = (acc / safeTotal) * 100;
    acc += it.pct;
    const end = (acc / safeTotal) * 100;
    return `${it.color} ${start}% ${end}%`;
  }).join(', ');
  return (
    <div className="ledger-alloc" style={{ background: 'var(--bg-elevated)', borderRadius: 'var(--r-4)', padding: 28, width: 298, maxWidth: '100%', flex: '0 1 298px', boxSizing: 'border-box', minHeight: 386, border: '1px solid var(--border)', display: 'flex', flexDirection: 'column' }}>
      <div className="meta" style={{ color: 'var(--fg-3)' }}>DISTRIBUIÇÃO</div>
      <h3 style={{ marginTop: 2, marginBottom: 24, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '28px', color: 'var(--fg-strong)' }}>Alocação</h3>
      <div style={{ width: 180, height: 180, margin: '0 auto', position: 'relative', borderRadius: 'var(--r-5)', overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 'var(--r-5)',
          background: `conic-gradient(${stops})`,
        }} />
        <div style={{
          position: 'absolute', inset: 18, background: 'var(--bg-elevated)', borderRadius: 'var(--r-2)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <div className="num" style={{ fontSize: 22, lineHeight: '28px', letterSpacing: '-1px' }}>{total}</div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{totalLabel}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 24 }}>
        {items.map(it => (
          <div key={it.label} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 10, height: 10, borderRadius: 'var(--r-1)', background: it.color, flex: '0 0 10px' }} />
            <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg)' }}>{it.label}</span>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--fg-strong)' }}>{Math.round((it.pct / safeTotal) * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.LedgerSpendingChart = LedgerSpendingChart;
window.LedgerAllocationBlock = LedgerAllocationBlock;

// ── STACKED CATEGORY CHART (month × category) ────────────────
// data: [{ ymk, label, cats: {catId: value}, total }]
// categories: [{ id, name }], colors: {catId: cssColor}
function LedgerStackedCategoryChart({ data, categories, colors, activeYmk, onSelect, titleOverride }) {
  const T = window.LedgerStore;
  const max = Math.max(1, ...data.map(d => d.total));
  const [hover, setHover] = React.useState(null);
  const eyebrow = titleOverride ? titleOverride.eyebrow : 'ALOCAÇÃO MÊS A MÊS';
  const title = titleOverride ? titleOverride.title : 'Gastos por categoria';

  return (
    <div style={{ background: 'var(--bg-muted)', borderRadius: 'var(--r-4)', padding: 28, boxSizing: 'border-box', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{eyebrow}</div>
          <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '28px', color: 'var(--fg-strong)' }}>{title}</h3>
        </div>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
          {categories.map(c => (
            <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: colors[c.id] || 'var(--slate-400)', flex: '0 0 10px' }} />
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-2)' }}>{c.name}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ position: 'relative', height: 240, display: 'flex', alignItems: 'flex-end', gap: 8 }}>
        {data.map((d, i) => {
          const on = d.ymk === activeYmk;
          const isHover = hover === i;
          const colH = (d.total / max) * 100;
          return (
            <div key={d.ymk} onClick={() => onSelect && onSelect(d.ymk)}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
              style={{ flex: 1, height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', cursor: onSelect ? 'pointer' : 'default', position: 'relative' }}>
              {isHover && d.total > 0 && (
                <div style={{
                  position: 'absolute', left: '50%', transform: 'translateX(-50%)', bottom: `calc(${colH}% + 6px)`,
                  background: 'var(--bg-inverse)', color: 'var(--fg-on-inverse)', whiteSpace: 'nowrap', zIndex: 5,
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, padding: '4px 8px', borderRadius: 'var(--r-1)',
                }}>{T.fmtMoney(d.total)}</div>
              )}
              <div style={{
                height: `${colH}%`, width: '100%', borderRadius: '4px 4px 0 0', overflow: 'hidden',
                display: 'flex', flexDirection: 'column-reverse', minHeight: d.total > 0 ? 3 : 0,
                outline: on ? '2px solid var(--fg-strong)' : 'none', outlineOffset: 1,
                opacity: hover != null && !isHover ? 0.55 : 1, transition: 'opacity var(--dur-fast)',
              }}>
                {categories.map(c => {
                  const v = d.cats[c.id] || 0;
                  if (v <= 0) return null;
                  return <div key={c.id} style={{ height: `${(v / d.total) * 100}%`, background: colors[c.id] || 'var(--slate-400)' }} title={`${c.name}: ${T.fmtMoney(v)}`} />;
                })}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        {data.map((d, i) => (
          <div key={d.ymk} onClick={() => onSelect && onSelect(d.ymk)} style={{
            flex: 1, textAlign: 'center', cursor: onSelect ? 'pointer' : 'default',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '0.5px',
            color: d.ymk === activeYmk ? 'var(--fg)' : 'var(--fg-3)',
          }}>{d.label}</div>
        ))}
      </div>
    </div>
  );
}

window.LedgerStackedCategoryChart = LedgerStackedCategoryChart;

// ── TREEMAP (allocation by investment type) ──────────────────
// items: [{ type|label, value, color }]
function squarifyTreemap(items, x, y, w, h) {
  if (!items.length) return [];
  if (items.length === 1) return [{ ...items[0], x, y, w, h }];
  const total = items.reduce((s, it) => s + it.value, 0);
  // pick split index closest to half the value
  let acc = 0, idx = 0, best = Infinity;
  for (let i = 0; i < items.length - 1; i++) {
    acc += items[i].value;
    const diff = Math.abs(acc - total / 2);
    if (diff < best) { best = diff; idx = i; }
  }
  const A = items.slice(0, idx + 1), B = items.slice(idx + 1);
  const aVal = A.reduce((s, it) => s + it.value, 0);
  if (w >= h) {
    const wA = w * (aVal / total);
    return [...squarifyTreemap(A, x, y, wA, h), ...squarifyTreemap(B, x + wA, y, w - wA, h)];
  }
  const hA = h * (aVal / total);
  return [...squarifyTreemap(A, x, y, w, hA), ...squarifyTreemap(B, x, y + hA, w, h - hA)];
}

function LedgerTreemap({ items, title, eyebrow, totalLabel }) {
  const T = window.LedgerStore;
  const total = items.reduce((s, it) => s + it.value, 0);
  const rects = React.useMemo(() => squarifyTreemap(items.slice().sort((a, b) => b.value - a.value), 0, 0, 100, 100), [items]);
  return (
    <div style={{ flex: '1 1 460px', minWidth: 0, background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-4)', padding: 28, boxSizing: 'border-box', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{eyebrow}</div>
          <h3 style={{ marginTop: 2, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '28px', color: 'var(--fg-strong)' }}>{title}</h3>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="meta" style={{ color: 'var(--fg-3)' }}>{totalLabel}</div>
          <div className="num" style={{ fontSize: 18, lineHeight: '24px' }}>{T.fmtMoney(total)}</div>
        </div>
      </div>
      {items.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 13 }}>
          Sem investimentos detalhados ainda.
        </div>
      ) : (
        <div style={{ position: 'relative', width: '100%', height: 280, borderRadius: 'var(--r-2)', overflow: 'hidden' }}>
          {rects.map((r, i) => {
            const pct = total > 0 ? Math.round((r.value / total) * 100) : 0;
            const big = r.w > 18 && r.h > 16;
            return (
              <div key={r.type || r.label || i} title={`${r.type || r.label}: ${T.fmtMoney(r.value)} (${pct}%)`} style={{
                position: 'absolute', left: r.x + '%', top: r.y + '%', width: r.w + '%', height: r.h + '%',
                background: r.color, boxSizing: 'border-box', border: '2px solid var(--bg-elevated)',
                padding: 10, overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
              }}>
                {big && (
                  <>
                    <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: '#fff', textShadow: '0 1px 2px rgba(0,0,0,0.25)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.type || r.label}</div>
                    <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 11, color: 'rgba(255,255,255,0.92)', textShadow: '0 1px 2px rgba(0,0,0,0.25)' }}>{T.fmtMoney(r.value)} · {pct}%</div>
                  </>
                )}
              </div>
            );
          })}
        </div>
      )}
      {items.length > 0 && (
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {items.slice().sort((a, b) => b.value - a.value).map(it => (
            <div key={it.type || it.label} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: it.color, flex: '0 0 10px' }} />
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-2)' }}>{it.type || it.label}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.LedgerTreemap = LedgerTreemap;
