// Evolution view — primera vista cableada contra el backend FastAPI.
// Llama a /api/series con granularity=year|month y, opcionalmente, country=XX.
// Para la lista lateral de "Top destinos" reusa /api/countries.

function EvolutionView({ hs, hsCodes, metric, years }) {
  const CF = window.CF;
  const [granularity, setGranularity] = React.useState("month"); // 'year' | 'month'
  const [selected, setSelected] = React.useState(null);          // ISO-2 destino o null

  const lo = Math.min(...years), hi = Math.max(...years);
  const hsParam = (hsCodes && window.hsQ) ? window.hsQ(hsCodes) : `hs=${hs}`;
  const qs = `${hsParam}&from=${lo}&to=${hi}`;
  const depKey = hsCodes ? hsCodes.join(",") : hs;

  const series = window.useApi(`${window.API_BASE}/api/series?${qs}&granularity=${granularity}` + (selected ? `&country=${selected}` : ""), [depKey, lo, hi, granularity, selected]);
  const countries = window.useApi(`${window.API_BASE}/api/countries?${qs}`, [depKey, lo, hi]);

  if (series.status === "loading" || countries.status === "loading") {
    return <div className="cf-fade-in" style={{padding:24}}>Cargando datos…</div>;
  }
  if (series.status === "error") {
    return <div className="cf-fade-in" style={{padding:24, color:"var(--xn-danger)"}}>Error: {series.error}</div>;
  }

  const rows = series.data.rows;
  const volSeries = rows.map(r => ({ period: r.period, year: r.year, month: r.month, value: r.tonnes }));
  const valSeries = rows.map(r => ({ period: r.period, year: r.year, month: r.month, value: r.eur }));

  const v0 = volSeries[0]?.value ?? 0, v1 = volSeries[volSeries.length-1]?.value ?? 0;
  const e0 = valSeries[0]?.value ?? 0, e1 = valSeries[valSeries.length-1]?.value ?? 0;
  const volG = v0 > 0 ? (v1/v0 - 1) : 0;
  const valG = e0 > 0 ? (e1/e0 - 1) : 0;

  const top = (countries.data?.rows || []).slice(0, 10);
  const selectedRow = selected ? top.find(c => c.iso2 === selected) || (countries.data?.rows || []).find(c => c.iso2 === selected) : null;
  const targetLabel = selectedRow ? (selectedRow.name || selectedRow.iso2) : "global";

  const periodFmt = granularity === "month" ? "mensual" : "anual";

  return (
    <div className="cf-fade-in">
      <div className="cf-insight">
        <div className="icon"><I.TrendingUp size={18} /></div>
        <div className="body">
          <span className="tag">EVOLUCIÓN · {periodFmt.toUpperCase()}</span>
          Entre {volSeries[0]?.period} y {volSeries[volSeries.length-1]?.period}, las exportaciones a <strong>{targetLabel}</strong> variaron
          <strong className="cf-mono"> {CF.fmtDelta(volG)}</strong> en volumen y <strong className="cf-mono">{CF.fmtDelta(valG)}</strong> en valor.
          {" "}{rows.length} puntos de datos.
        </div>
      </div>

      <div className="cf-panel">
        <div className="cf-panel-head">
          <div>
            <h2>Serie temporal · {CF.HS[hs].label}</h2>
            <p>
              {selected ? `Destino: ${targetLabel} (${selected})` : "Todos los destinos"} ·
              Volumen (línea continua) y Valor (línea discontinua) en ejes independientes
            </p>
          </div>
          <div className="cf-panel-tools" style={{display:"flex", gap:8, alignItems:"center"}}>
            <div className="cf-seg">
              <button className={granularity === "year" ? "on" : ""} onClick={() => setGranularity("year")}>Anual</button>
              <button className={granularity === "month" ? "on" : ""} onClick={() => setGranularity("month")}>Mensual</button>
            </div>
            {selected && (
              <button className="cf-btn" onClick={() => setSelected(null)}>
                <I.X size={13} /> Quitar filtro
              </button>
            )}
          </div>
        </div>

        <div className="cf-chart-legend">
          <div className="it">
            <span className="sw" style={{background: "var(--xn-blue-500)"}} />
            <span><strong>Volumen</strong> · toneladas</span>
          </div>
          <div className="it">
            <span className="sw" style={{background: "var(--xn-blue-900)", height:3, borderStyle:"dashed"}} />
            <span><strong>Valor</strong> · euros</span>
          </div>
        </div>

        <DualLineChart vol={volSeries} val={valSeries} granularity={granularity} />
      </div>

      <div className="cf-grid-2">
        <div className="cf-panel">
          <div className="cf-panel-head">
            <div>
              <h2>Comparar destinos</h2>
              <p>Top 10 del período · selecciona uno para filtrar la serie</p>
            </div>
          </div>
          <div className="cf-clist">
            <div
              className={"cf-crow" + (!selected ? " selected" : "")}
              onClick={() => setSelected(null)}
            >
              <span className="rank">—</span>
              <span className="name">Todos los destinos</span>
              <span className="val">{CF.fmtVal(volSeries.reduce((a,p)=>a+p.value,0), "vol")}</span>
              <div className="bar"><span style={{width:"100%"}} /></div>
            </div>
            {top.map((c, i) => {
              const v = metric === "vol" ? c.tonnes : c.eur;
              const vMax = metric === "vol" ? top[0].tonnes : top[0].eur;
              return (
                <div
                  key={c.iso2}
                  className={"cf-crow" + (selected === c.iso2 ? " selected" : "")}
                  onClick={() => setSelected(c.iso2)}
                >
                  <span className="rank">{String(i+1).padStart(2,"0")}</span>
                  <span className="name">{c.name || c.iso2} {c.eu_member && <span className="eu">UE</span>}</span>
                  <span className="val">{CF.fmtVal(metric === "vol" ? v : v/1000, metric)}</span>
                  <div className="bar"><span style={{width: `${(v / vMax) * 100}%`}} /></div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="cf-panel">
          <div className="cf-panel-head">
            <div>
              <h2>Tabla {periodFmt}</h2>
              <p>Cifras período a período · variación interanual sobre valor</p>
            </div>
          </div>
          <SeriesTable vol={volSeries} val={valSeries} granularity={granularity} />
        </div>
      </div>
    </div>
  );
}


function DualLineChart({ vol, val, granularity }) {
  const CF = window.CF;
  const W = 900, H = 360, PL = 64, PR = 64, PT = 24, PB = 36;
  const innerW = W - PL - PR, innerH = H - PT - PB;

  const n = vol.length;
  if (n === 0) return <div style={{padding:24, color:"var(--xn-fg-3)"}}>Sin datos en el período.</div>;

  const volMax = Math.max(...vol.map(p => p.value)) * 1.1 || 1;
  const valMax = Math.max(...val.map(p => p.value)) * 1.1 || 1;

  const x    = (i) => PL + (i / Math.max(1, n - 1)) * innerW;
  const yVol = (v) => PT + innerH - (v / volMax) * innerH;
  const yVal = (v) => PT + innerH - (v / valMax) * innerH;

  const volPath = vol.map((p, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${yVol(p.value)}`).join(" ");
  const valPath = val.map((p, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${yVal(p.value)}`).join(" ");
  const volArea = `${volPath} L ${x(n - 1)} ${PT + innerH} L ${x(0)} ${PT + innerH} Z`;

  // Marcadores de eje X: si mensual y >24 puntos, una marca por enero (year start). Si anual, todos.
  const xTicks = [];
  if (granularity === "month") {
    vol.forEach((p, i) => { if (p.month === 1) xTicks.push({ i, label: String(p.year) }); });
  } else {
    vol.forEach((p, i) => xTicks.push({ i, label: String(p.year) }));
  }

  const [hoverIdx, setHoverIdx] = React.useState(null);
  const [tipPos, setTipPos] = React.useState({ x: 0, y: 0 });

  function onMouseMove(e) {
    const svg = e.currentTarget;
    const pt = svg.createSVGPoint();
    pt.x = e.clientX; pt.y = e.clientY;
    const m = svg.getScreenCTM().inverse();
    const lp = pt.matrixTransform(m);
    const rel = (lp.x - PL) / innerW;
    const i = Math.round(rel * (n - 1));
    if (i >= 0 && i < n) {
      setHoverIdx(i);
      setTipPos({ x: e.clientX, y: e.clientY });
    }
  }
  function onMouseLeave() { setHoverIdx(null); }

  // Solo dibujamos dots si hay <= 24 puntos para no saturar
  const showDots = n <= 24;

  return (
    <div className="cf-chart-wrap">
      <svg className="cf-chart-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" onMouseMove={onMouseMove} onMouseLeave={onMouseLeave}>
        {/* Y grid + axis labels */}
        {[0, 0.25, 0.5, 0.75, 1].map(t => {
          const y = PT + innerH * (1 - t);
          return (
            <g key={t}>
              <line className="grid" x1={PL} x2={W - PR} y1={y} y2={y} />
              <text className="axis-lbl" x={PL - 8} y={y + 4} textAnchor="end" style={{fill: "var(--xn-blue-500)"}}>
                {CF.fmtVal(volMax * t, "vol")}
              </text>
              <text className="axis-lbl" x={W - PR + 8} y={y + 4} textAnchor="start" style={{fill: "var(--xn-blue-900)"}}>
                {CF.fmtVal((valMax * t) / 1000, "val")}
              </text>
            </g>
          );
        })}

        {/* X labels (sparse) */}
        {xTicks.map(t => (
          <text key={t.i + "-" + t.label} className="axis-lbl" x={x(t.i)} y={H - 12} textAnchor="middle">{t.label}</text>
        ))}
        {/* X grid lines at year boundaries (only month mode) */}
        {granularity === "month" && xTicks.map(t => (
          <line key={"vg" + t.i} className="grid" x1={x(t.i)} x2={x(t.i)} y1={PT} y2={PT + innerH} strokeDasharray="2 4" opacity="0.5" />
        ))}

        {/* Volume area + line */}
        <path className="area" d={volArea} fill="var(--xn-blue-500)" />
        <path className="line-vol" d={volPath} />
        {showDots && vol.map((p, i) => (
          <circle key={"v"+i} className="dot" cx={x(i)} cy={yVol(p.value)} r="4" fill="var(--xn-blue-500)" />
        ))}

        {/* Value line */}
        <path className="line-val" d={valPath} />
        {showDots && val.map((p, i) => (
          <circle key={"e"+i} className="dot" cx={x(i)} cy={yVal(p.value)} r="4" fill="var(--xn-blue-900)" />
        ))}

        {/* hover crosshair */}
        {hoverIdx != null && (
          <g>
            <line x1={x(hoverIdx)} x2={x(hoverIdx)} y1={PT} y2={PT + innerH} stroke="var(--xn-blue-700)" strokeWidth="1" strokeDasharray="3 3" opacity="0.6" />
            <circle cx={x(hoverIdx)} cy={yVol(vol[hoverIdx].value)} r="6" fill="white" stroke="var(--xn-blue-500)" strokeWidth="2.5" />
            <circle cx={x(hoverIdx)} cy={yVal(val[hoverIdx].value)} r="6" fill="white" stroke="var(--xn-blue-900)" strokeWidth="2.5" />
          </g>
        )}
      </svg>

      {hoverIdx != null && (
        <div className="cf-chart-tip" style={{ left: Math.min(tipPos.x + 14, window.innerWidth - 220), top: tipPos.y - 70 }}>
          <div className="yr">{vol[hoverIdx].period}</div>
          <div className="row">
            <span className="dot" style={{background: "var(--xn-blue-500)"}} />
            <span style={{opacity:.65}}>Volumen</span>
            <span style={{fontWeight:600, marginLeft:"auto"}}>{CF.fmtVal(vol[hoverIdx].value, "vol")}</span>
          </div>
          <div className="row">
            <span className="dot" style={{background: "var(--xn-blue-900)"}} />
            <span style={{opacity:.65}}>Valor</span>
            <span style={{fontWeight:600, marginLeft:"auto"}}>{CF.fmtVal(val[hoverIdx].value / 1000, "val")}</span>
          </div>
        </div>
      )}
    </div>
  );
}

function SeriesTable({ vol, val, granularity }) {
  const CF = window.CF;
  // En mensual mostramos resumen anual agregado para evitar 60 filas
  const rows = granularity === "year" ? vol.map((p,i) => ({ period: p.period, v: p.value, e: val[i].value })) : aggregateAnnual(vol, val);

  return (
    <table style={{width:"100%", borderCollapse:"collapse", fontSize:13, fontVariantNumeric:"tabular-nums"}}>
      <thead>
        <tr style={{textAlign:"left", color:"var(--xn-fg-3)", fontSize:11, textTransform:"uppercase", letterSpacing:"0.06em"}}>
          <th style={{padding:"8px 6px", borderBottom:"1px solid var(--xn-border)"}}>{granularity === "year" ? "Año" : "Año"}</th>
          <th style={{padding:"8px 6px", borderBottom:"1px solid var(--xn-border)", textAlign:"right"}}>Volumen</th>
          <th style={{padding:"8px 6px", borderBottom:"1px solid var(--xn-border)", textAlign:"right"}}>Valor</th>
          <th style={{padding:"8px 6px", borderBottom:"1px solid var(--xn-border)", textAlign:"right"}}>Δ Valor</th>
        </tr>
      </thead>
      <tbody>
        {rows.map((p, i) => {
          const prev = i > 0 ? rows[i-1].e : null;
          const d = prev ? (p.e - prev) / prev : null;
          return (
            <tr key={p.period} style={{borderBottom:"1px solid var(--xn-border)"}}>
              <td style={{padding:"9px 6px", fontWeight:600, color:"var(--xn-fg-1)"}}>{p.period}</td>
              <td style={{padding:"9px 6px", textAlign:"right", color:"var(--xn-fg-1)"}}>{CF.fmtVal(p.v, "vol")}</td>
              <td style={{padding:"9px 6px", textAlign:"right", fontWeight:600, color:"var(--xn-fg-1)"}}>{CF.fmtVal(p.e / 1000, "val")}</td>
              <td style={{padding:"9px 6px", textAlign:"right", fontWeight:600, color: d == null ? "var(--xn-fg-4)" : d >= 0 ? "var(--xn-success)" : "var(--xn-danger)"}}>
                {d == null ? "—" : CF.fmtDelta(d)}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function aggregateAnnual(vol, val) {
  const acc = {};
  vol.forEach((p, i) => {
    if (!acc[p.year]) acc[p.year] = { period: String(p.year), v: 0, e: 0 };
    acc[p.year].v += p.value;
    acc[p.year].e += val[i].value;
  });
  return Object.values(acc);
}

window.EvolutionView = EvolutionView;
