// Chart interactivo: línea + área con glow, crosshair en hover, tooltip,
// botones de rango, etiquetas adaptativas.
function Chart({ symbol, accent, intensity }) {
  const ranges = ['1H', '4H', '1D', '1S', '1M', '3M', '1A'];
  const [range, setRange] = React.useState('1D');
  const [hover, setHover] = React.useState(null); // {x, idx}
  const wrapRef = React.useRef(null);

  const POINTS = range === '1H' || range === '4H' ? 60 : range === '1D' ? 78 : range === '1S' ? 60 : range === '1M' ? 64 : range === '3M' ? 72 : 96;
  const W = 900, H = 320;
  const padL = 8, padR = 56, padT = 14, padB = 28;
  const plotW = W - padL - padR;
  const plotH = H - padT - padB;

  const series = React.useMemo(() => window.genSeries(symbol, range, POINTS), [symbol, range, POINTS]);
  const labels = React.useMemo(() => window.timeLabels(range, POINTS), [range, POINTS]);

  const min = Math.min(...series);
  const max = Math.max(...series);
  const pad = (max - min) * 0.15 || max * 0.005;
  const yMin = min - pad;
  const yMax = max + pad;
  const yRange = yMax - yMin;

  const xFor = (i) => padL + (i / (POINTS - 1)) * plotW;
  const yFor = (v) => padT + (1 - (v - yMin) / yRange) * plotH;

  // Si serie sube o baja en el rango
  const isUp = series[series.length - 1] >= series[0];
  const lineColor = isUp ? accent : 'var(--neg)';
  const glowOpacity = intensity === 'atrevida' ? 0.55 : intensity === 'media' ? 0.35 : 0.2;
  const areaOpacity = intensity === 'atrevida' ? 0.30 : intensity === 'media' ? 0.18 : 0.10;

  const linePath = series.map((v, i) => `${i === 0 ? 'M' : 'L'} ${xFor(i).toFixed(2)} ${yFor(v).toFixed(2)}`).join(' ');
  const areaPath = linePath + ` L ${xFor(POINTS - 1).toFixed(2)} ${padT + plotH} L ${padL} ${padT + plotH} Z`;

  // Eje Y: 4 ticks
  const yTicks = [];
  for (let i = 0; i <= 4; i++) {
    const v = yMin + (yRange * i) / 4;
    yTicks.push({ v, y: padT + plotH - (i / 4) * plotH });
  }
  // Eje X: 5 etiquetas espaciadas
  const xLabelCount = 5;
  const xTicks = [];
  for (let i = 0; i < xLabelCount; i++) {
    const idx = Math.floor((i / (xLabelCount - 1)) * (POINTS - 1));
    xTicks.push({ idx, label: labels[idx] });
  }

  const onMouseMove = (e) => {
    const rect = wrapRef.current.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * W;
    const i = Math.round(((px - padL) / plotW) * (POINTS - 1));
    if (i < 0 || i > POINTS - 1) return setHover(null);
    setHover({ idx: i, x: xFor(i), y: yFor(series[i]), value: series[i] });
  };
  const onMouseLeave = () => setHover(null);

  const lastV = series[POINTS - 1];
  const lastY = yFor(lastV);

  return (
    <div className="chart-box">
      <div className="chart-top">
        <div className="chart-title-block">
          <span className="chart-title">Precio · {{
            '1H': '1 hora', '4H': '4 horas', '1D': '1 día',
            '1S': '1 semana', '1M': '1 mes', '3M': '3 meses', '1A': '1 año',
          }[range]}</span>
          {hover && (
            <span className="chart-hover-val">
              ${series[hover.idx].toFixed(2)}
              <em>{labels[hover.idx]}</em>
            </span>
          )}
        </div>
        <div className="time-sel">
          {ranges.map((r) => (
            <button key={r} className={`t-btn${r === range ? ' on' : ''}`}
                    onClick={() => setRange(r)}>{r}</button>
          ))}
        </div>
      </div>

      <div className="chart-svg-wrap" ref={wrapRef}
           onMouseMove={onMouseMove} onMouseLeave={onMouseLeave}>
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id={`area-${symbol}-${range}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"   stopColor={lineColor} stopOpacity={areaOpacity}/>
              <stop offset="70%"  stopColor={lineColor} stopOpacity={areaOpacity * 0.3}/>
              <stop offset="100%" stopColor={lineColor} stopOpacity="0"/>
            </linearGradient>
            <filter id={`glow-${symbol}-${range}`}>
              <feGaussianBlur stdDeviation={intensity === 'atrevida' ? 3 : intensity === 'media' ? 2 : 1.2} result="blur"/>
              <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
            </filter>
          </defs>

          {/* Cuadrícula horizontal */}
          {yTicks.map((t, i) => (
            <line key={`yt-${i}`} x1={padL} y1={t.y} x2={padL + plotW} y2={t.y}
                  stroke="var(--grid)" strokeWidth="1" strokeDasharray={i === 0 || i === 4 ? '0' : '3,4'}/>
          ))}

          {/* Etiquetas Y (derecha) */}
          {yTicks.map((t, i) => (
            <text key={`yl-${i}`} x={padL + plotW + 6} y={t.y + 3}
                  fill="var(--text-3)" fontSize="10.5" fontFamily="inherit">
              {t.v.toFixed(2)}
            </text>
          ))}

          {/* Línea del precio actual */}
          <line x1={padL} y1={lastY} x2={padL + plotW} y2={lastY}
                stroke={lineColor} strokeOpacity={intensity === 'atrevida' ? 0.25 : 0.14}
                strokeWidth="1" strokeDasharray="3,4"/>

          {/* Área */}
          <path d={areaPath} fill={`url(#area-${symbol}-${range})`}/>

          {/* Línea con glow */}
          <path d={linePath} fill="none" stroke={lineColor} strokeWidth="2"
                filter={intensity === 'conservadora' ? undefined : `url(#glow-${symbol}-${range})`}
                strokeLinejoin="round" strokeLinecap="round"/>

          {/* Brillo extra (highlight) */}
          {intensity === 'atrevida' && (
            <path d={linePath} fill="none" stroke="white" strokeWidth="0.5"
                  opacity="0.45" strokeLinejoin="round"/>
          )}

          {/* Punto actual */}
          <circle cx={xFor(POINTS - 1)} cy={lastY} r={intensity === 'atrevida' ? 14 : 10}
                  fill={lineColor} opacity={glowOpacity * 0.4}/>
          <circle cx={xFor(POINTS - 1)} cy={lastY} r={intensity === 'atrevida' ? 7 : 5}
                  fill={lineColor} opacity={0.55}/>
          <circle cx={xFor(POINTS - 1)} cy={lastY} r="3.5" fill={lineColor}/>

          {/* Crosshair hover */}
          {hover && (
            <>
              <line x1={hover.x} y1={padT} x2={hover.x} y2={padT + plotH}
                    stroke={lineColor} strokeOpacity="0.45" strokeWidth="1" strokeDasharray="2,3"/>
              <circle cx={hover.x} cy={hover.y} r="5" fill="var(--bg-card)"
                      stroke={lineColor} strokeWidth="2"/>
              <circle cx={hover.x} cy={hover.y} r="2" fill={lineColor}/>
            </>
          )}

          {/* Etiqueta de precio actual a la derecha */}
          <rect x={padL + plotW + 2} y={lastY - 9} width="50" height="18" rx="3"
                fill={lineColor} opacity="0.95"/>
          <text x={padL + plotW + 27} y={lastY + 4} textAnchor="middle"
                fill="var(--accent-text)" fontSize="11" fontWeight="700" fontFamily="inherit">
            {lastV.toFixed(2)}
          </text>

          {/* Etiquetas X */}
          {xTicks.map((t, i) => (
            <text key={`xl-${i}`} x={xFor(t.idx)} y={padT + plotH + 18}
                  textAnchor={i === 0 ? 'start' : i === xTicks.length - 1 ? 'end' : 'middle'}
                  fill="var(--text-3)" fontSize="10.5" fontFamily="inherit">
              {t.label}
            </text>
          ))}
        </svg>

        {/* Tooltip flotante */}
        {hover && (
          <div className="chart-tooltip" style={{
            left: `${(hover.x / W) * 100}%`,
            top: `${(hover.y / H) * 100}%`,
          }}>
            <div className="ctt-time">{labels[hover.idx]}</div>
            <div className="ctt-price">${series[hover.idx].toFixed(2)}</div>
            <div className="ctt-delta" style={{ color: series[hover.idx] >= series[0] ? lineColor : 'var(--neg)' }}>
              {series[hover.idx] >= series[0] ? '+' : ''}
              {(((series[hover.idx] - series[0]) / series[0]) * 100).toFixed(2)}%
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Chart = Chart;
