// History area chart + Allocation donut

function HistoryChart({ period, onPeriodChange, data, balanceHidden }) {
  const [hover, setHover] = React.useState(null);
  const fmtMoney = (n) => balanceHidden ? '••••••' : window.formatUSD(n);

  if (!data || data.length < 2) {
    return (
      <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: 20, boxShadow: 'var(--shadow)', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <PeriodToggle value={period} onChange={onPeriodChange} />
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Historia</h3>
        </div>
        <div style={{ height: 180, display: 'grid', placeItems: 'center', color: 'var(--text-faint)', fontSize: 13 }}>
          {data ? 'Sin datos suficientes para graficar.' : 'Cargando datos históricos…'}
        </div>
      </div>
    );
  }

  const W = 640, H = 240, PAD_L = 44, PAD_R = 10, PAD_T = 14, PAD_B = 28;
  const values = data.map(d => d.value);
  const min = Math.min(...values), max = Math.max(...values);
  const yMin = Math.floor((min - 10) / 50) * 50;
  const yMax = Math.ceil((max + 10) / 50) * 50;

  // Color dinámico: verde si cierra en alza vs el primer punto, rojo si cierra en baja.
  const firstValue = values[0];
  const lastValue = values[values.length - 1];
  const change = lastValue - firstValue;
  const changePct = firstValue > 0 ? (change / firstValue) * 100 : 0;
  const isPositive = change >= 0;
  const lineColor = isPositive ? 'var(--green)' : 'var(--red)';

  const x = i => PAD_L + (i / (data.length - 1)) * (W - PAD_L - PAD_R);
  const y = v => PAD_T + (1 - (v - yMin) / (yMax - yMin)) * (H - PAD_T - PAD_B);

  // Smooth path via catmull-rom-ish quadratic
  const pts = data.map((d, i) => [x(i), y(d.value)]);
  let path = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 1; i < pts.length; i++) {
    const prev = pts[i - 1], cur = pts[i];
    const cx = (prev[0] + cur[0]) / 2;
    path += ` Q ${prev[0]} ${prev[1]} ${cx} ${(prev[1] + cur[1]) / 2}`;
    path += ` T ${cur[0]} ${cur[1]}`;
  }
  const areaPath = `${path} L ${pts[pts.length - 1][0]} ${H - PAD_B} L ${pts[0][0]} ${H - PAD_B} Z`;

  // Y grid labels
  const yTicks = [];
  const step = (yMax - yMin) / 5;
  for (let i = 0; i <= 5; i++) yTicks.push(yMin + step * i);

  // X labels — pick 5 evenly spaced
  const xLabelIndices = [];
  const n = 5;
  for (let i = 0; i < n; i++) xLabelIndices.push(Math.round((data.length - 1) * i / (n - 1)));

  const fmtDate = (d) => {
    if (period === '24H') return d.getHours().toString().padStart(2, '0') + ':00';
    return `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth()+1).toString().padStart(2, '0')}/${d.getFullYear()}`;
  };

  const handleMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * W;
    const idx = Math.min(data.length - 1, Math.max(0, Math.round(((px - PAD_L) / (W - PAD_L - PAD_R)) * (data.length - 1))));
    setHover(idx);
  };

  // ID único del gradiente para que cada instancia tenga el suyo (por color)
  const gradId = `areaGrad-${isPositive ? 'up' : 'dn'}`;

  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: 20, boxShadow: 'var(--shadow)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, gap: 12 }}>
        <PeriodToggle value={period} onChange={onPeriodChange} />
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Historia</h3>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>
            <span style={{ color: lineColor, fontWeight: 600 }}>
              {isPositive ? '+' : ''}{fmtMoney(change)}
            </span>
            <span style={{ color: 'var(--text-faint)' }}>·</span>
            <span style={{ color: lineColor, fontWeight: 600 }}>
              {window.formatPct(changePct)}
            </span>
          </div>
        </div>
      </div>
      <div style={{ position: 'relative' }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block', overflow: 'visible' }}
             onMouseMove={handleMove} onMouseLeave={() => setHover(null)}>
          <defs>
            <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={lineColor} stopOpacity="0.4" />
              <stop offset="100%" stopColor={lineColor} stopOpacity="0" />
            </linearGradient>
          </defs>

          {/* horizontal grid */}
          {yTicks.map((t, i) => (
            <g key={i}>
              <line x1={PAD_L} x2={W - PAD_R} y1={y(t)} y2={y(t)} stroke="var(--border)" strokeDasharray="2 3" />
              <text x={PAD_L - 8} y={y(t) + 4} fontSize="11" fill="var(--text-faint)" textAnchor="end">
                {balanceHidden ? '•••' : `$${Math.round(t)}`}
              </text>
            </g>
          ))}

          {/* area */}
          <path d={areaPath} fill={`url(#${gradId})`} />
          {/* line */}
          <path d={path} fill="none" stroke={lineColor} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" />

          {/* x labels */}
          {xLabelIndices.map(i => (
            <text key={i} x={x(i)} y={H - 8} fontSize="10.5" fill="var(--text-faint)" textAnchor="middle">
              {fmtDate(data[i].date)}
            </text>
          ))}

          {/* hover */}
          {hover !== null && (
            <g>
              <line x1={x(hover)} x2={x(hover)} y1={PAD_T} y2={H - PAD_B} stroke="var(--text-faint)" strokeDasharray="3 3" />
              <circle cx={x(hover)} cy={y(data[hover].value)} r="5" fill={lineColor} stroke="var(--panel)" strokeWidth="2" />
            </g>
          )}
        </svg>

        {hover !== null && (() => {
          const xPos = (x(hover) / W) * 100;
          return (
            <div style={{
              position: 'absolute', left: `${xPos}%`, top: 4, transform: 'translateX(-50%)',
              background: 'var(--panel-2)', border: '1px solid var(--border-strong)', borderRadius: 8,
              padding: '6px 10px', fontSize: 11.5, pointerEvents: 'none', whiteSpace: 'nowrap',
              boxShadow: '0 4px 12px rgba(0,0,0,0.3)'
            }}>
              <div style={{ color: 'var(--text-dim)', fontSize: 10 }}>{fmtDate(data[hover].date)}</div>
              <div style={{ fontWeight: 600 }}>{balanceHidden ? '••••••' : `$${data[hover].value.toFixed(2)}`}</div>
            </div>
          );
        })()}
      </div>
    </div>
  );
}

function PeriodToggle({ value, onChange }) {
  const opts = ['24H', '7D', '30D'];
  return (
    <div style={{
      display: 'inline-flex', background: 'var(--panel-2)', borderRadius: 8, padding: 3,
      border: '1px solid var(--border)'
    }}>
      {opts.map(o => {
        const isActive = o === value;
        return (
          <button key={o} onClick={() => onChange(o)}
            style={{
              padding: '5px 12px', fontSize: 12, fontWeight: 500, borderRadius: 6,
              background: isActive ? 'var(--border-strong)' : 'transparent',
              color: isActive ? 'var(--text)' : 'var(--text-dim)',
              transition: 'all 0.15s',
            }}>
            {o}
          </button>
        );
      })}
    </div>
  );
}

// Paleta vibrante diferenciada para el donut. Cada color es un par from/to (gradiente).
// Si el portafolio tiene más activos que colores, se ciclan los colores.
const DONUT_PALETTE = [
  { from: '#26d989', to: '#00c275', solid: '#00c275' }, // verde brand (logo)
  { from: '#c4b5fd', to: '#8b5cf6', solid: '#a78bfa' }, // violeta
  { from: '#f9a8d4', to: '#db2777', solid: '#ec4899' }, // magenta
  { from: '#67e8f9', to: '#0891b2', solid: '#06b6d4' }, // cyan
  { from: '#bef264', to: '#65a30d', solid: '#a3e635' }, // lima
  { from: '#818cf8', to: '#4f46e5', solid: '#6366f1' }, // índigo
  { from: '#fb7185', to: '#e11d48', solid: '#f43f5e' }, // rosa
  { from: '#fcd34d', to: '#d97706', solid: '#f59e0b' }, // ámbar
  { from: '#7dd3fc', to: '#0284c7', solid: '#0ea5e9' }, // sky
  { from: '#f0abfc', to: '#c026d3', solid: '#d946ef' }, // fucsia
  { from: '#5eead4', to: '#14b8a6', solid: '#2dd4bf' }, // teal
];

// Tickers con color de marca propio (overridean la paleta rotativa).
// Color sólido (sin gradiente) — es el color de marca puro.
const BRAND_COLORS = {
  BTC:  { from: '#f7931a', to: '#f7931a', solid: '#f7931a' }, // bitcoin orange
  ETH:  { from: '#627eea', to: '#627eea', solid: '#627eea' }, // ethereum
  BNB:  { from: '#f3ba2f', to: '#f3ba2f', solid: '#f3ba2f' }, // binance
  MELI: { from: '#ffe600', to: '#ffe600', solid: '#ffe600' }, // mercadolibre yellow
};

function AllocationDonut({ assets, totalValue, balanceHidden }) {
  const [hover, setHover] = React.useState(null);
  const [mounted, setMounted] = React.useState(false);

  // Dispara la animación de entrada después del primer render
  React.useEffect(() => {
    const t = setTimeout(() => setMounted(true), 30);
    return () => clearTimeout(t);
  }, []);

  // Todos los activos (sin agrupar en 'Otros'), ordenados de mayor a menor peso
  const byAsset = assets
    .map(a => ({ label: a.ticker, value: a.qty * a.currentPrice }))
    .sort((a, b) => b.value - a.value);
  const total = byAsset.reduce((s, a) => s + a.value, 0);
  const baseSegments = byAsset.map(a => ({
    ...a,
    pct: total > 0 ? (a.value / total) * 100 : 0,
  }));

  const cx = 110, cy = 110, r = 78, sw = 22;
  const C = 2 * Math.PI * r;

  // Pre-calculo dash + offset por segmento. Tickers en BRAND_COLORS usan su color de marca,
  // el resto cicla por la paleta.
  let acc = 0;
  const segments = baseSegments.map((s, i) => {
    const dash = (s.pct / 100) * C;
    const color = BRAND_COLORS[s.label] || DONUT_PALETTE[i % DONUT_PALETTE.length];
    const seg = { ...s, dash, offset: acc, color };
    acc += dash;
    return seg;
  });

  const hovered = hover !== null ? segments[hover] : null;
  const fmt = (n) => balanceHidden ? '••••••' : window.formatUSD(n);

  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: 20, boxShadow: 'var(--shadow)' }}>
      <h3 style={{ margin: '0 0 12px', fontSize: 16, fontWeight: 600 }}>Asignación</h3>
      <div className="donut-grid" style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 16, alignItems: 'center' }}>
        {/* Donut + centro */}
        <div style={{ position: 'relative', width: 220, height: 220, justifySelf: 'center' }}>
          <svg viewBox="0 0 220 220" width="100%" style={{ display: 'block' }}>
            <defs>
              {segments.map((s, i) => (
                <linearGradient key={i} id={`donut-grad-${i}`} x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor={s.color.from} />
                  <stop offset="100%" stopColor={s.color.to} />
                </linearGradient>
              ))}
            </defs>
            {/* anillo de fondo */}
            <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--border)" strokeWidth={sw} opacity="0.3" />
            {segments.map((s, i) => {
              const isHovered = hover === i;
              const isDimmed = hover !== null && hover !== i;
              return (
                <circle
                  key={i}
                  cx={cx} cy={cy} r={r}
                  fill="none"
                  stroke={`url(#donut-grad-${i})`}
                  strokeWidth={isHovered ? sw + 6 : sw}
                  strokeDasharray={mounted ? `${s.dash} ${C - s.dash}` : `0 ${C}`}
                  strokeDashoffset={-s.offset}
                  transform={`rotate(-90 ${cx} ${cy})`}
                  strokeLinecap="butt"
                  opacity={isDimmed ? 0.35 : 1}
                  style={{
                    transition: 'stroke-dasharray 0.85s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s, stroke-width 0.2s',
                    cursor: 'pointer',
                  }}
                  onMouseEnter={() => setHover(i)}
                  onMouseLeave={() => setHover(null)}
                />
              );
            })}
          </svg>

          {/* Centro dinámico */}
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            pointerEvents: 'none', textAlign: 'center', padding: 30,
          }}>
            <div style={{
              fontSize: 10, fontWeight: 600, letterSpacing: 1.2,
              color: hovered ? hovered.color.solid : 'var(--text-faint)',
              textTransform: 'uppercase', marginBottom: 4,
              transition: 'color 0.2s',
            }}>
              {hovered ? hovered.label : 'Total'}
            </div>
            <div style={{
              fontFamily: 'Space Grotesk, Inter, sans-serif',
              fontSize: 22, fontWeight: 700, letterSpacing: -0.5,
              fontVariantNumeric: 'tabular-nums',
              color: hovered ? hovered.color.solid : 'var(--text)',
              lineHeight: 1.05,
              transition: 'color 0.2s',
            }}>
              {hovered ? fmt(hovered.value) : fmt(totalValue)}
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
              {hovered
                ? `${hovered.pct.toFixed(2)}% del portafolio`
                : `${assets.length} activo${assets.length === 1 ? '' : 's'}`
              }
            </div>
          </div>
        </div>

        {/* Legend con hover bidireccional */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {segments.map((s, i) => {
            const isHovered = hover === i;
            return (
              <div
                key={i}
                onMouseEnter={() => setHover(i)}
                onMouseLeave={() => setHover(null)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
                  padding: '7px 10px', borderRadius: 8,
                  background: isHovered ? 'var(--panel-2)' : 'transparent',
                  cursor: 'pointer',
                  transition: 'background 0.15s',
                }}
              >
                {s.label === 'BTC' ? (
                  <svg viewBox="0 0 64 64" width={14} height={14}
                    style={{
                      flexShrink: 0, display: 'block',
                      borderRadius: '50%',
                      boxShadow: isHovered ? `0 0 0 3px #f7931a33` : 'none',
                      transition: 'box-shadow 0.15s',
                    }}>
                    <circle cx="32" cy="32" r="32" fill="#f7931a" />
                    <path fill="#fff" d="M46.1 27.6c.6-4-2.4-6.1-6.6-7.5l1.4-5.5-3.4-.8-1.3 5.3c-.9-.2-1.8-.4-2.7-.6l1.3-5.4-3.3-.8-1.4 5.5c-.7-.2-1.5-.3-2.2-.5L23 16.5l-.9 3.6s2.5.6 2.4.6c1.4.3 1.6 1.2 1.6 2l-1.6 6.4c.1 0 .2.1.3.1l-.3-.1-2.2 8.9c-.2.4-.6 1-1.6.8.1.1-2.4-.6-2.4-.6L17 41.2l4.5 1.1c.8.2 1.7.4 2.5.6l-1.4 5.6 3.3.8 1.4-5.5c.9.3 1.8.5 2.7.7l-1.4 5.5 3.4.8 1.4-5.6c5.7 1.1 10 .6 11.8-4.6 1.4-4.2-.1-6.6-3.1-8.2 2.2-.5 3.9-2 4-5zm-7.7 11c-1.1 4.2-8.2 1.9-10.5 1.4l1.9-7.6c2.3.6 9.7 1.7 8.6 6.2zm1-11c-1 3.8-6.9 1.9-8.8 1.4l1.7-6.9c1.9.5 8.1 1.3 7.1 5.5z" />
                  </svg>
                ) : (
                  <span style={{
                    width: 11, height: 11, borderRadius: '50%',
                    background: `linear-gradient(135deg, ${s.color.from}, ${s.color.to})`,
                    boxShadow: isHovered ? `0 0 0 3px ${s.color.solid}33` : 'none',
                    flexShrink: 0,
                    transition: 'box-shadow 0.15s',
                  }} />
                )}
                <span style={{ fontWeight: 500 }}>{s.label}</span>
                <span style={{ color: 'var(--text-dim)', marginLeft: 'auto', fontVariantNumeric: 'tabular-nums' }}>
                  {s.pct.toFixed(2)}%
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HistoryChart, AllocationDonut });
