// Charts.jsx — Lightweight SVG chart components (no external deps)
'use strict';


// Mede a largura real do container. Com o viewBox igual ao tamanho em pixels,
// o grafico preenche o card inteiro em vez de ficar centralizado com sobra.
function useLarguraDoContainer(padrao) {
  const ref = React.useRef(null);
  const [largura, setLargura] = React.useState(padrao);
  React.useEffect(function () {
    const el = ref.current;
    if (!el) return;
    const medir = function () {
      const w = Math.round(el.getBoundingClientRect().width);
      if (w > 0) setLargura(w);
    };
    medir();
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", medir);
      return function () { window.removeEventListener("resize", medir); };
    }
    const ro = new ResizeObserver(medir);
    ro.observe(el);
    return function () { ro.disconnect(); };
  }, []);
  return [ref, largura];
}
// ── Area / Line Chart ─────────────────────────────────────────────────────
function SimpleAreaChart({ data, lines, height = 200, xKey = 'month', formatY, formatTooltip }) {
  const [tooltip, setTooltip] = React.useState(null);
  const [wrapRef, W] = useLarguraDoContainer(560);
  const H = height, PAD = { top: 10, right: 14, bottom: 28, left: 52 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;

  const allVals = lines.flatMap(l => data.map(d => d[l.key] || 0));
  const maxVal = Math.max(...allVals, 1);
  const minVal = 0;
  const range = maxVal - minVal || 1;

  const scaleX = i => PAD.left + (i / (data.length - 1)) * innerW;
  const scaleY = v => PAD.top + innerH - ((v - minVal) / range) * innerH;

  const makePath = key => {
    if (data.length < 2) return '';
    const pts = data.map((d, i) => [scaleX(i), scaleY(d[key] || 0)]);
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i < pts.length; i++) {
      const cp1x = (pts[i - 1][0] + pts[i][0]) / 2;
      d += ` C ${cp1x} ${pts[i - 1][1]}, ${cp1x} ${pts[i][1]}, ${pts[i][0]} ${pts[i][1]}`;
    }
    return d;
  };

  const makeArea = key => {
    const line = makePath(key);
    if (!line) return '';
    const lastX = scaleX(data.length - 1);
    const baseY = PAD.top + innerH;
    return `${line} L ${lastX} ${baseY} L ${PAD.left} ${baseY} Z`;
  };

  const yTicks = 4;
  const yTickVals = Array.from({ length: yTicks + 1 }, (_, i) => minVal + (i / yTicks) * range);

  const handleMouseMove = (e, svgRef) => {
    if (!svgRef.current) return;
    const rect = svgRef.current.getBoundingClientRect();
    const svgX = (e.clientX - rect.left) * (W / rect.width) - PAD.left;
    const idx = Math.round((svgX / innerW) * (data.length - 1));
    const clamped = Math.max(0, Math.min(data.length - 1, idx));
    setTooltip({ idx: clamped, x: e.clientX - rect.left, y: e.clientY - rect.top });
  };

  const svgRef = React.useRef(null);

  return (
    <div ref={wrapRef} className="relative w-full" style={{ height }}>
      <svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none"
        className="w-full h-full" onMouseMove={e => handleMouseMove(e, svgRef)} onMouseLeave={() => setTooltip(null)}>
        <defs>
          {lines.map(l => (
            <linearGradient key={l.key} id={`grad-${l.key}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"   stopColor={l.color} stopOpacity={0.25}/>
              <stop offset="100%" stopColor={l.color} stopOpacity={0}/>
            </linearGradient>
          ))}
        </defs>

        {/* Grid lines */}
        {yTickVals.map((v, i) => {
          const y = scaleY(v);
          return (
            <g key={i}>
              <line x1={PAD.left} y1={y} x2={W - PAD.right} y2={y} stroke="#F1F5F9" strokeWidth={1}/>
              <text x={PAD.left - 6} y={y + 4} textAnchor="end" fontSize={10} fill="#94A3B8">
                {formatY ? formatY(v) : Math.round(v)}
              </text>
            </g>
          );
        })}

        {/* X axis labels */}
        {data.map((d, i) => (
          <text key={i} x={scaleX(i)} y={H - 4} textAnchor="middle" fontSize={10} fill="#94A3B8">
            {d[xKey]}
          </text>
        ))}

        {/* Area fills */}
        {lines.map(l => (
          <path key={`area-${l.key}`} d={makeArea(l.key)} fill={`url(#grad-${l.key})`}/>
        ))}

        {/* Lines */}
        {lines.map(l => (
          <path key={`line-${l.key}`} d={makePath(l.key)} fill="none" stroke={l.color} strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"/>
        ))}

        {/* Hover indicator */}
        {tooltip && data[tooltip.idx] && (
          <g>
            <line x1={scaleX(tooltip.idx)} y1={PAD.top} x2={scaleX(tooltip.idx)} y2={PAD.top + innerH}
              stroke="#CBD5E1" strokeWidth={1} strokeDasharray="4 2"/>
            {lines.map(l => (
              <circle key={l.key} cx={scaleX(tooltip.idx)} cy={scaleY(data[tooltip.idx][l.key] || 0)}
                r={4} fill={l.color} stroke="white" strokeWidth={2}/>
            ))}
          </g>
        )}
      </svg>

      {/* Tooltip */}
      {tooltip && data[tooltip.idx] && (
        <div className="absolute pointer-events-none bg-white rounded-xl shadow-card-lg border border-slate-100 p-3 text-xs z-10"
          style={{ left: Math.min(tooltip.x + 12, 300), top: Math.max(tooltip.y - 40, 0) }}>
          <p className="font-bold text-slate-700 mb-1.5">{data[tooltip.idx][xKey]}</p>
          {lines.map(l => (
            <div key={l.key} className="flex items-center gap-2 mb-0.5">
              <span className="w-2 h-2 rounded-full" style={{ background: l.color }}/>
              <span className="text-slate-500">{l.label}:</span>
              <span className="font-semibold text-slate-700">
                {formatTooltip ? formatTooltip(data[tooltip.idx][l.key] || 0) : data[tooltip.idx][l.key]}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Donut Chart ───────────────────────────────────────────────────────────
function SimpleDonutChart({ data, size = 180 }) {
  const [hovered, setHovered] = React.useState(null);
  const cx = size / 2, cy = size / 2;
  const R = size * 0.38, r = size * 0.24;
  const total = data.reduce((s, d) => s + (d.value || 0), 0) || 1;

  let angle = -Math.PI / 2;
  const arcs = data.map(d => {
    const sweep = (d.value / total) * 2 * Math.PI;
    const start = angle;
    const end = angle + sweep - 0.03;
    angle += sweep;
    const x1 = cx + R * Math.cos(start), y1 = cy + R * Math.sin(start);
    const x2 = cx + R * Math.cos(end),   y2 = cy + R * Math.sin(end);
    const x3 = cx + r * Math.cos(end),   y3 = cy + r * Math.sin(end);
    const x4 = cx + r * Math.cos(start), y4 = cy + r * Math.sin(start);
    const large = sweep > Math.PI ? 1 : 0;
    const path = `M ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${r} ${r} 0 ${large} 0 ${x4} ${y4} Z`;
    return { ...d, path, midAngle: start + sweep / 2 };
  });

  const hovItem = hovered !== null ? data[hovered] : null;

  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      {arcs.map((arc, i) => (
        <path key={i} d={arc.path} fill={arc.color || arc.fill}
          opacity={hovered === null || hovered === i ? 1 : 0.5}
          style={{ cursor: 'pointer', transition: 'opacity 0.15s' }}
          onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}
          transform={hovered === i ? `translate(${Math.cos(arc.midAngle) * 3}, ${Math.sin(arc.midAngle) * 3})` : ''}/>
      ))}
      {/* Center text */}
      <text x={cx} y={cy - 6} textAnchor="middle" fontSize={18} fontWeight="700" fill="#0A1F44">
        {hovItem ? hovItem.value : total}
      </text>
      <text x={cx} y={cy + 12} textAnchor="middle" fontSize={9} fill="#94A3B8">
        {hovItem ? hovItem.name : 'total'}
      </text>
    </svg>
  );
}

// ── Vertical Bar Chart ────────────────────────────────────────────────────
function SimpleBarChart({ data, xKey, bars, height = 180, formatY, formatTooltip }) {
  const [tooltip, setTooltip] = React.useState(null);
  const [wrapRef, W] = useLarguraDoContainer(560);
  const H = height, PAD = { top: 10, right: 14, bottom: 28, left: 52 };
  const innerW = W - PAD.left - PAD.right;
  const innerH = H - PAD.top - PAD.bottom;

  const allVals = bars.flatMap(b => data.map(d => d[b.key] || 0));
  const maxVal = Math.max(...allVals, 1);
  const scaleY = v => PAD.top + innerH - (v / maxVal) * innerH;
  const barWidth = (innerW / data.length) / (bars.length + 1);
  const groupWidth = barWidth * bars.length + barWidth * 0.3;

  const yTicks = 4;

  return (
    <div ref={wrapRef} className="relative w-full" style={{ height }}>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="w-full h-full">
        {/* Grid */}
        {Array.from({ length: yTicks + 1 }, (_, i) => {
          const v = (i / yTicks) * maxVal;
          const y = scaleY(v);
          return (
            <g key={i}>
              <line x1={PAD.left} y1={y} x2={W - PAD.right} y2={y} stroke="#F1F5F9" strokeWidth={1}/>
              <text x={PAD.left - 6} y={y + 4} textAnchor="end" fontSize={10} fill="#94A3B8">
                {formatY ? formatY(v) : Math.round(v)}
              </text>
            </g>
          );
        })}
        {/* Bars */}
        {data.map((d, gi) => {
          const groupX = PAD.left + (gi / data.length) * innerW + (innerW / data.length - groupWidth) / 2;
          return (
            <g key={gi} onMouseEnter={() => setTooltip(gi)} onMouseLeave={() => setTooltip(null)}>
              {bars.map((b, bi) => {
                const val = d[b.key] || 0;
                const bx = groupX + bi * (barWidth + 2);
                const bh = Math.max(((val / maxVal) * innerH), 2);
                const by = PAD.top + innerH - bh;
                return <rect key={bi} x={bx} y={by} width={barWidth} height={bh} fill={b.color} rx={3}/>;
              })}
              <text x={groupX + groupWidth / 2} y={H - 4} textAnchor="middle" fontSize={10} fill="#94A3B8">
                {d[xKey]}
              </text>
              {tooltip === gi && (
                <rect x={groupX - 4} y={PAD.top} width={groupWidth + 8} height={innerH} fill="#0A1F44" opacity={0.03} rx={4}/>
              )}
            </g>
          );
        })}
      </svg>

      {tooltip !== null && data[tooltip] && (
        <div className="absolute pointer-events-none bg-white rounded-xl shadow-card-lg border border-slate-100 p-3 text-xs z-10"
          style={{ left: `${((tooltip + 0.5) / data.length) * 100}%`, top: 0, transform: 'translateX(-50%)' }}>
          <p className="font-bold text-slate-700 mb-1.5">{data[tooltip][xKey]}</p>
          {bars.map(b => (
            <div key={b.key} className="flex items-center gap-2 mb-0.5">
              <span className="w-2 h-2 rounded-full" style={{ background: b.color }}/>
              <span className="text-slate-500">{b.label}:</span>
              <span className="font-semibold text-slate-700">
                {formatTooltip ? formatTooltip(data[tooltip][b.key] || 0) : data[tooltip][b.key]}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Horizontal Bar Chart ──────────────────────────────────────────────────
function HorizontalBarChart({ data, valueKey = 'value', labelKey = 'name', color = '#3B82F6', height = 220, formatValue }) {
  const [hovered, setHovered] = React.useState(null);
  const maxVal = Math.max(...data.map(d => d[valueKey] || 0), 1);
  const barH = Math.min(18, (height - data.length * 8) / data.length);

  return (
    <div className="w-full space-y-2" style={{ height }}>
      {data.map((d, i) => {
        const pct = ((d[valueKey] || 0) / maxVal) * 100;
        return (
          <div key={i} className="flex items-center gap-3" onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
            <div className="text-xs text-slate-600 font-medium text-right flex-shrink-0" style={{ width: 130 }}>{d[labelKey]}</div>
            <div className="flex-1 relative rounded-full overflow-hidden" style={{ height: barH, background: '#F1F5F9' }}>
              <div className="absolute inset-y-0 left-0 rounded-full transition-all duration-500"
                style={{ width: `${pct}%`, background: Array.isArray(color) ? color[i % color.length] : color, opacity: hovered === i ? 1 : 0.8 }}/>
            </div>
            <div className="text-xs font-bold text-slate-700 text-right flex-shrink-0" style={{ width: 60 }}>
              {formatValue ? formatValue(d[valueKey]) : d[valueKey]}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { SimpleAreaChart, SimpleDonutChart, SimpleBarChart, HorizontalBarChart });
