// SpainOrigin — Sección "Origen español → País" dentro de la ficha de país

const PROV_COLORS = [
  "#2A6BF7","#173FB0","#0B1F5C","#4F8BFF","#82AEFF",
  "#7C3AED","#EC4899","#F59E0B","#10B981","#EF4444",
  "#06B6D4","#F97316","#84CC16","#8B5CF6","#14B8A6",
];

const HS6_LABELS = {
  "021011":"Jamón con hueso",
  "021012":"Panceta / bacon",
  "021019":"Jamón deshuesado",
  "021020":"Vacuno curado",
  "021090":"Otros curados",
};

const CN8_LABELS = {
  // 0210 11 — Jamón/paleta con hueso, cerdo doméstico
  "02101111":"Jamón c/hueso · salado o en salmuera",
  "02101119":"Paleta c/hueso · salada o en salmuera",
  "02101131":"Jamón c/hueso · seco o ahumado (Serrano/Ibérico)",
  "02101139":"Paleta c/hueso · seca o ahumada (Serrana/Ibérica)",
  "02101190":"Jamón/paleta c/hueso · porcino no doméstico",
  // 0210 12 — Panceta/tocino
  "02101211":"Tocino entreverado · salado o en salmuera",
  "02101219":"Demás tocinos domésticos · salados o en salmuera",
  "02101290":"Tocino entreverado · seco o ahumado",
  // 0210 19 — Otros cortes de cerdo doméstico
  "02101910":"Tocino sin partes magras · salado o ahumado",
  "02101920":"Carne deshuesada doméstica · salada o en salmuera",
  "02101930":"Partes delanteras · saladas o en salmuera",
  "02101940":"Lomos y trozos · salados o en salmuera",
  "02101950":"Demás trozos c/hueso · salados o en salmuera",
  "02101960":"Partes delanteras y lomos · secos o ahumados",
  "02101970":"Lomo embuchado · seco o ahumado",
  "02101981":"Carne deshuesada doméstica · seca o ahumada",
  "02101989":"Carne c/hueso doméstica · seca o ahumada",
  "02101990":"Porcino no doméstico · salado, seco o ahumado",
  // 0210 20 — Vacuno
  "02102010":"Vacuno c/hueso · salado, seco o ahumado",
  "02102090":"Vacuno deshuesado · seco o ahumado (cecina)",
  // 0210 99 — Otros
  "02109921":"Ovino/caprino c/hueso · salado, seco o ahumado",
  "02109929":"Ovino/caprino deshuesado · salado, seco o ahumado",
  "02109931":"Aves de corral · saladas o en salmuera",
  "02109939":"Aves de corral · secas o ahumadas",
  "02109990":"Harina y polvo comestibles de carne o despojos",
  // 1601 — Embutidos
  "16010010":"Embutidos de hígado y preparaciones a base de hígado",
  "16010091":"Embutidos secos o para untar sin cocer (chorizo, salchichón, salami…)",
  "16010099":"Demás embutidos (frescos, cocidos, Frankfurt, mortadela…)",
  // 1602 — Conservas y preparaciones de carne
  "16021000":"Preparaciones homogeneizadas",
  "16022000":"Preparaciones de hígado",
  "16023100":"Preparaciones de pavo",
  "16023200":"Preparaciones de gallo o gallina",
  "16023900":"Preparaciones de otras aves",
  "16024110":"Jamones y trozos, cerdo doméstico, sin cocinar",
  "16024190":"Los demás jamones en conserva",
  "16024210":"Paletas y trozos, cerdo doméstico, sin cocinar",
  "16024290":"Las demás paletas en conserva",
  "16024910":"Preparaciones de cerdo, sin cocinar",
  "16024930":"Preparaciones de cerdo doméstico, cocidas",
  "16024990":"Las demás preparaciones de cerdo",
  "16025010":"Preparaciones de vacuno, sin cocinar",
  "16025031":"Roast beef",
  "16025095":"Las demás preparaciones de vacuno",
  "16029010":"Preparaciones de reno",
  "16029041":"Preparaciones de ovino o caprino",
  "16029051":"Preparaciones de aves (codorniz, perdiz…)",
  "16029091":"Las demás preparaciones cárnicas",
  // 1603 — Extractos y jugos de carne
  "16030010":"Extractos y jugos de bovino",
  "16030080":"Demás extractos y jugos de carne",
};

const MONTHS_ES = ["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"];

function metricVal(row, metric) {
  return metric === "vol" ? row.tonnes : row.eur / 1000;
}
function metricValArr(tonnes, eur, metric) {
  return metric === "vol" ? tonnes : eur.map(v => v / 1000);
}

// ─── Main section ────────────────────────────────────────────────────────────

function SpainOriginSection({ hs, hsCodes, metric, years, iso2, countryName }) {
  const CF = window.CF;
  const lo = Math.min(...years), hi = Math.max(...years);
  const [gran, setGran] = React.useState("annual");
  const defaultFocusYear = Math.min(hi, 2025);
  const [focusYear, setFocusYear] = React.useState(defaultFocusYear);

  const provApi = window.useApi(
    `${window.API_BASE}/api/country/${iso2}/origin-provinces?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}`,
    [iso2, hsCodes ? hsCodes.join(",") : hs, lo, hi]
  );

  const allProvs = provApi.data?.provinces || [];

  const [selected, setSelected] = React.useState(null);
  const [focused, setFocused]   = React.useState(null);

  // Reset selection when HS filter or country changes so new top-5 is picked
  const hsKey = hsCodes ? hsCodes.join(",") : hs;
  React.useEffect(() => {
    setSelected(null);
    setFocused(null);
  }, [hsKey, iso2]);

  React.useEffect(() => {
    if (allProvs.length === 0 || selected !== null) return;
    const top5 = allProvs.slice(0, 5).map(p => p.code);
    setSelected(top5);
    setFocused(allProvs[0]?.code || null);
  }, [allProvs]);

  const selectedProvs = selected || [];
  const selectedStr   = selectedProvs.join(",");

  const annualApi = window.useApi(
    selectedProvs.length > 0
      ? `${window.API_BASE}/api/country/${iso2}/origin-provinces/annual?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}&provinces=${selectedStr}`
      : null,
    [iso2, hsCodes ? hsCodes.join(",") : hs, lo, hi, selectedStr]
  );

  const monthlyApi = window.useApi(
    selectedProvs.length > 0 && gran === "monthly"
      ? `${window.API_BASE}/api/country/${iso2}/origin-provinces/monthly?${window.hsQ(hsCodes)}&provinces=${selectedStr}&year=${focusYear}`
      : null,
    [iso2, hsCodes ? hsCodes.join(",") : hs, selectedStr, focusYear, gran]
  );

  const hsApi = window.useApi(
    focused
      ? `${window.API_BASE}/api/country/${iso2}/origin-provinces/${focused}/hs-breakdown?${window.hsQ(hsCodes)}&year=${focusYear}`
      : null,
    [iso2, hsCodes ? hsCodes.join(",") : hs, focused, focusYear]
  );

  const shipmentsApi = window.useApi(
    `${window.API_BASE}/api/country/${iso2}/origin-provinces/shipments?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}&limit=15`,
    [iso2, hsCodes ? hsCodes.join(",") : hs, lo, hi]
  );

  if (provApi.status === "loading") {
    return (
      <div className="cf-panel" style={{marginTop:18}}>
        <div style={{padding:"20px 0", color:"var(--xn-fg-3)", fontSize:13}}>Cargando provincias de origen…</div>
      </div>
    );
  }
  if (provApi.status !== "ok" || allProvs.length === 0) return null;

  function toggleProv(code) {
    setSelected(prev => {
      const arr = prev || [];
      if (arr.includes(code)) {
        if (arr.length === 1) return arr;
        const next = arr.filter(c => c !== code);
        if (focused === code) setFocused(next[0]);
        return next;
      }
      return [...arr, code];
    });
  }

  function setQuick(n) {
    const codes = n === "all"
      ? allProvs.map(p => p.code)
      : allProvs.slice(0, n).map(p => p.code);
    setSelected(codes);
    setFocused(codes[0]);
  }

  function focusProv(code) {
    setFocused(code);
    setSelected(prev => prev && prev.includes(code) ? prev : [...(prev||[]), code]);
  }

  const colorMap = {};
  selectedProvs.forEach((code, i) => { colorMap[code] = PROV_COLORS[i % PROV_COLORS.length]; });

  const focusedProv  = allProvs.find(p => p.code === focused);
  const annualSeries   = annualApi.data?.series  || [];
  const annualYears    = annualApi.data?.years   || [];
  const monthlySeries  = monthlyApi.data?.series || [];
  const hsRows         = hsApi.data?.rows        || [];
  const hsBreakLevel   = hsApi.data?.level       || (hsCodes && hsCodes[0] ? `${hsCodes[0].length}d` : "6d");
  const shipments    = shipmentsApi.data?.shipments || [];

  const availableYears = annualYears.filter(y => y <= 2025);

  return (
    <div style={{marginTop:18}}>
      <div className="cf-panel">
        {/* Panel head */}
        <div className="cf-panel-head">
          <div>
            <h2>Origen español → {countryName}</h2>
            <p>
              Provincias que abastecen {countryName} · {CF.metricLabel(metric)} · {lo}–{hi}
            </p>
          </div>
          <div className="cf-seg">
            <button className={gran === "annual"  ? "on" : ""} onClick={() => setGran("annual")}>Anual</button>
            <button className={gran === "monthly" ? "on" : ""} onClick={() => setGran("monthly")}>Mensual</button>
          </div>
        </div>

        {/* Province selector */}
        <div className="cf-prov-selector">
          <div className="cf-prov-selector-head">
            <span className="cf-prov-count">{selectedProvs.length} de {allProvs.length} provincias</span>
            <div className="cf-prov-quick">
              <button onClick={() => setQuick(5)}>Top 5</button>
              <button onClick={() => setQuick(10)}>Top 10</button>
              <button onClick={() => setQuick("all")}>Todas</button>
              <button onClick={() => { setSelected([allProvs[0].code]); setFocused(allProvs[0].code); }}>Limpiar</button>
            </div>
          </div>
          <div className="cf-prov-pills">
            {allProvs.map((p, i) => {
              const on  = selectedProvs.includes(p.code);
              const isFocused = focused === p.code;
              const color = colorMap[p.code] || PROV_COLORS[i % PROV_COLORS.length];
              return (
                <div
                  key={p.code}
                  className={"cf-prov-pill" + (on ? " on" : "") + (isFocused ? " focused" : "")}
                  onClick={() => toggleProv(p.code)}
                  onDoubleClick={() => focusProv(p.code)}
                  title={`${p.name} · ${CF.fmtVal(metricVal(p, metric), metric)}\nDoble clic para enfocar`}
                >
                  {on && <span className="cf-prov-pill-dot" style={{background: color}} />}
                  <span className="cf-prov-pill-name">{p.name}</span>
                  <span className="cf-prov-pill-val">{CF.fmtVal(metricVal(p, metric), metric)}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Charts grid */}
        <div className="cf-origin-charts">
          <div className="cf-origin-chart-main">
            {gran === "annual" && (
              <AnnualProvinceChart
                years={annualYears}
                series={annualSeries}
                colorMap={colorMap}
                focused={focused}
                metric={metric}
                onFocus={focusProv}
              />
            )}
            {gran === "monthly" && (
              <MonthlyMultiChart
                series={monthlySeries}
                year={focusYear}
                availableYears={availableYears}
                metric={metric}
                colorMap={colorMap}
                focused={focused}
                onFocus={focusProv}
                loading={monthlyApi.status === "loading"}
              />
            )}

            {/* Legend */}
            {selectedProvs.length > 0 && (
              <div className="cf-chart-legend" style={{marginTop:10, flexWrap:"wrap", gap:10}}>
                {selectedProvs.map(code => {
                  const p = allProvs.find(x => x.code === code);
                  if (!p) return null;
                  return (
                    <div key={code} className="it" style={{cursor:"pointer"}} onClick={() => focusProv(code)}>
                      <span className="sw" style={{background: colorMap[code]}} />
                      <span style={{fontWeight: focused === code ? 700 : 400}}>{p.name}</span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          <div className="cf-origin-hs6">
            {gran === "monthly" && availableYears.length > 0 && (
              <div style={{marginBottom:10}}>
                <div style={{fontSize:11, fontWeight:600, color:"var(--xn-fg-3)", letterSpacing:"0.06em", textTransform:"uppercase", marginBottom:6}}>Año</div>
                <div style={{display:"flex", gap:4, flexWrap:"wrap"}}>
                  {availableYears.map(y => (
                    <button
                      key={y}
                      className={"cf-btn" + (y === focusYear ? " primary" : "")}
                      style={{padding:"2px 8px", fontSize:11}}
                      onClick={() => setFocusYear(y)}
                    >{y}</button>
                  ))}
                </div>
              </div>
            )}
            <HsBreakdownBars
              rows={hsRows}
              hs={hs}
              level={hsBreakLevel}
              province={focusedProv}
              year={focusYear}
              metric={metric}
              loading={hsApi.status === "loading"}
            />
          </div>
        </div>
      </div>

      {/* Shipments table */}
      {shipments.length > 0 && (
        <div className="cf-panel" style={{marginTop:12}}>
          <div className="cf-panel-head">
            <div>
              <h2>Exportaciones recientes · {countryName}</h2>
              <p>Registros agrupados por período · orden cronológico desc</p>
            </div>
          </div>
          <ShipmentsTable rows={shipments} metric={metric} />
        </div>
      )}
    </div>
  );
}

// ─── Annual multi-province line chart ────────────────────────────────────────

function AnnualProvinceChart({ years, series, colorMap, focused, metric, onFocus }) {
  const CF = window.CF;
  const W = 720, H = 230, PL = 62, PR = 12, PT = 14, PB = 38;
  const innerW = W - PL - PR, innerH = H - PT - PB;

  const [tipYear, setTipYear] = React.useState(null);
  const [hover, setHover]     = React.useState(null);
  const [tipPos, setTipPos]   = React.useState({x:0, y:0});

  if (!years.length || !series.length) {
    return <div style={{padding:"24px 0", color:"var(--xn-fg-3)", fontSize:13}}>Sin datos anuales.</div>;
  }

  const allVals = series.flatMap(s => metric === "vol" ? s.tonnes : s.eur.map(v => v/1000));
  const maxVal  = Math.max(...allVals) * 1.15 || 1;
  const nYears  = years.length;

  const cx = (yi) => PL + (nYears === 1 ? innerW / 2 : (yi / (nYears - 1)) * innerW);
  const cy = (v)  => PT + innerH - (v / maxVal) * innerH;

  function buildPath(s) {
    return years.map((_, yi) => {
      const v = metric === "vol" ? (s.tonnes[yi] || 0) : (s.eur[yi] || 0) / 1000;
      return `${yi === 0 ? "M" : "L"} ${cx(yi)} ${cy(v)}`;
    }).join(" ");
  }

  function onMouseMove(e) {
    const svg = e.currentTarget;
    const rect = svg.getBoundingClientRect();
    const relX = (e.clientX - rect.left) / rect.width * W;
    const yi = nYears === 1 ? 0 : Math.round((relX - PL) / innerW * (nYears - 1));
    if (yi < 0 || yi >= nYears) { setTipYear(null); return; }
    const pts = series.map(s => ({
      province: s.province,
      name: s.province_name,
      value: metric === "vol" ? (s.tonnes[yi] || 0) : (s.eur[yi] || 0) / 1000,
      color: colorMap[s.province] || PROV_COLORS[0],
    })).filter(p => p.value > 0).sort((a, b) => b.value - a.value);
    setTipYear(yi);
    setHover(pts);
    setTipPos({x: e.clientX, y: e.clientY});
  }

  return (
    <div className="cf-chart-wrap" style={{position:"relative"}}>
      <svg viewBox={`0 0 ${W} ${H}`} className="cf-chart-svg"
           onMouseMove={onMouseMove} onMouseLeave={() => setTipYear(null)}>

        {[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-6} y={y+4} textAnchor="end">{CF.fmtVal(maxVal * t, metric)}</text>
            </g>
          );
        })}

        {years.map((yr, yi) => (
          <text key={yr} className="axis-lbl" x={cx(yi)} y={H-10} textAnchor="middle">{yr}</text>
        ))}

        {tipYear !== null && (
          <line x1={cx(tipYear)} x2={cx(tipYear)} y1={PT} y2={PT+innerH}
                stroke="var(--xn-fg-3)" strokeWidth="1" strokeDasharray="3 3" opacity="0.5" />
        )}

        {series.map((s) => {
          const color = colorMap[s.province] || PROV_COLORS[0];
          const isFocused = focused === s.province;
          return (
            <g key={s.province} style={{cursor:"pointer"}} onClick={() => onFocus(s.province)}>
              <path d={buildPath(s)} fill="none" stroke={color}
                    strokeWidth={isFocused ? 2.5 : 2} strokeLinejoin="round" strokeLinecap="round"
                    opacity={focused && !isFocused ? 0.35 : 1} style={{transition:"opacity .15s"}} />
              {years.map((_, yi) => {
                const v = metric === "vol" ? (s.tonnes[yi] || 0) : (s.eur[yi] || 0) / 1000;
                if (!v) return null;
                return (
                  <circle key={yi} cx={cx(yi)} cy={cy(v)}
                          r={tipYear === yi ? 4.5 : isFocused ? 3.5 : 2.5}
                          fill={color} stroke="white" strokeWidth="1.5"
                          opacity={focused && !isFocused ? 0.35 : 1}
                          style={{transition:"opacity .15s"}} />
                );
              })}
            </g>
          );
        })}
      </svg>

      {tipYear !== null && hover && hover.length > 0 && (
        <div className="cf-chart-tip" style={{left: Math.min(tipPos.x+14, window.innerWidth-210), top: tipPos.y-80, minWidth:170}}>
          <div className="yr">{years[tipYear]}</div>
          {hover.map((p, i) => (
            <div key={i} className="row" style={{marginTop:3}}>
              <span className="dot" style={{background: p.color}} />
              <span style={{fontSize:11, marginLeft:4, flex:1, fontWeight: focused === p.province ? 700 : 400}}>{p.name}</span>
              <span style={{fontWeight:600, marginLeft:6, fontSize:11}}>{CF.fmtVal(p.value, metric)}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Monthly multi-province line chart ───────────────────────────────────────

function MonthlyMultiChart({ series, year, availableYears, metric, colorMap, focused, onFocus, loading }) {
  const CF = window.CF;
  const W = 720, H = 220, PL = 62, PR = 12, PT = 14, PB = 38;
  const innerW = W - PL - PR, innerH = H - PT - PB;

  const [hover, setHover] = React.useState(null); // {mi, series:[{name,value,color}]}
  const [tipPos, setTipPos] = React.useState({x:0, y:0});
  const [tipMonth, setTipMonth] = React.useState(null);

  if (loading) return <div style={{padding:"32px 0", color:"var(--xn-fg-3)", fontSize:13}}>Cargando…</div>;
  if (!series.length) return <div style={{padding:"24px 0", color:"var(--xn-fg-3)", fontSize:13}}>Sin datos mensuales.</div>;

  const hasData = series.some(s => s.monthly.some(d => (metric === "vol" ? d.tonnes : d.eur/1000) > 0));
  if (!hasData) return <div style={{padding:"24px 0", color:"var(--xn-fg-3)", fontSize:13}}>Sin datos mensuales para {year}.</div>;

  const allVals = series.flatMap(s => s.monthly.map(d => metric === "vol" ? d.tonnes : d.eur / 1000));
  const maxVal = Math.max(...allVals) * 1.15 || 1;

  const cx = (mi) => PL + (mi / 11) * innerW;
  const cy = (v)  => PT + innerH - (v / maxVal) * innerH;

  function buildPath(monthly) {
    return monthly.map((d, i) => {
      const v = metric === "vol" ? d.tonnes : d.eur / 1000;
      return `${i === 0 ? "M" : "L"} ${cx(i)} ${cy(v)}`;
    }).join(" ");
  }

  function onMouseMove(e) {
    const svg = e.currentTarget;
    const rect = svg.getBoundingClientRect();
    const relX = (e.clientX - rect.left) / rect.width * W;
    const mi = Math.round((relX - PL) / innerW * 11);
    if (mi < 0 || mi > 11) { setTipMonth(null); return; }
    const pts = series.map(s => ({
      name: s.province_name,
      value: metric === "vol" ? s.monthly[mi].tonnes : s.monthly[mi].eur / 1000,
      color: colorMap[s.province] || PROV_COLORS[0],
    })).filter(p => p.value > 0).sort((a, b) => b.value - a.value);
    setTipMonth(mi);
    setHover(pts);
    setTipPos({x: e.clientX, y: e.clientY});
  }

  return (
    <div className="cf-chart-wrap" style={{position:"relative"}}>
      <svg viewBox={`0 0 ${W} ${H}`} className="cf-chart-svg"
           onMouseMove={onMouseMove} onMouseLeave={() => setTipMonth(null)}>

        {[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-6} y={y+4} textAnchor="end">{CF.fmtVal(maxVal * t, metric)}</text>
            </g>
          );
        })}

        {MONTHS_ES.map((lbl, i) => (
          <text key={i} className="axis-lbl" x={cx(i)} y={H-10} textAnchor="middle">{lbl}</text>
        ))}

        {/* Hover column highlight */}
        {tipMonth !== null && (
          <line x1={cx(tipMonth)} x2={cx(tipMonth)} y1={PT} y2={PT+innerH}
                stroke="var(--xn-fg-3)" strokeWidth="1" strokeDasharray="3 3" opacity="0.5" />
        )}

        {series.map((s) => {
          const color = colorMap[s.province] || PROV_COLORS[0];
          const isFocused = focused === s.province;
          return (
            <g key={s.province} style={{cursor:"pointer"}} onClick={() => onFocus(s.province)}>
              <path d={buildPath(s.monthly)} fill="none" stroke={color}
                    strokeWidth={isFocused ? 2.5 : 2}
                    strokeLinejoin="round" strokeLinecap="round"
                    opacity={focused && !isFocused ? 0.35 : 1} style={{transition:"opacity .15s"}} />
              {s.monthly.map((d, i) => {
                const v = metric === "vol" ? d.tonnes : d.eur / 1000;
                if (!v) return null;
                return (
                  <circle key={i} cx={cx(i)} cy={cy(v)}
                          r={tipMonth === i ? 4 : isFocused ? 3.5 : 2.5}
                          fill={color} stroke="white" strokeWidth="1.5"
                          opacity={focused && !isFocused ? 0.35 : 1} style={{transition:"opacity .15s"}} />
                );
              })}
            </g>
          );
        })}
      </svg>

      {tipMonth !== null && hover && hover.length > 0 && (
        <div className="cf-chart-tip" style={{left: Math.min(tipPos.x+14, window.innerWidth-210), top: tipPos.y-80, minWidth:170}}>
          <div className="yr">{MONTHS_ES[tipMonth]} {year}</div>
          {hover.map((p, i) => (
            <div key={i} className="row" style={{marginTop:3}}>
              <span className="dot" style={{background: p.color}} />
              <span style={{fontSize:11, marginLeft:4, flex:1}}>{p.name}</span>
              <span style={{fontWeight:600, marginLeft:6, fontSize:11}}>{CF.fmtVal(p.value, metric)}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── HS6 breakdown horizontal bars ───────────────────────────────────────────

function HsBreakdownBars({ rows, hs, level, province, year, metric, loading }) {
  const CF = window.CF;
  const levelLabel = level === "8d" ? "CN8" : level === "4d" ? "HS4" : "HS6";

  function codeLabel(code) {
    if (code.length === 4) return CF.HS[code]?.label || null;
    if (code.length === 6) return HS6_LABELS[code] || null;
    return CN8_LABELS[code] || null;
  }

  return (
    <div>
      <div style={{fontSize:11, fontWeight:600, letterSpacing:"0.06em", textTransform:"uppercase", color:"var(--xn-fg-3)", marginBottom:12}}>
        Desglose {levelLabel} · {province?.name || "—"} · {year}
      </div>

      {loading ? (
        <div style={{fontSize:12, color:"var(--xn-fg-3)"}}>Cargando…</div>
      ) : rows.length === 0 ? (
        <div style={{fontSize:12, color:"var(--xn-fg-3)", lineHeight:1.5}}>Sin datos {levelLabel}<br/>para esta combinación</div>
      ) : (
        <div style={{display:"flex", flexDirection:"column", gap:10}}>
          {rows.map(r => (
            <div key={r.code}>
              <div style={{display:"flex", justifyContent:"space-between", marginBottom:3, gap:6}}>
                <span style={{fontSize:11, fontWeight:600, minWidth:0, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>
                  <span style={{
                    background:"var(--xn-blue-50,#EFF4FF)", color:"var(--xn-blue-700,#173FB0)",
                    borderRadius:4, padding:"1px 5px", fontSize:10, fontFamily:"var(--xn-font-mono)",
                    marginRight:5, flexShrink:0,
                  }}>{r.code}</span>
                  {codeLabel(r.code) ?? ""}
                </span>
                <span style={{fontSize:11, fontWeight:700, flexShrink:0}}>{CF.fmtPct(r.share)}</span>
              </div>
              <div style={{height:6, borderRadius:3, background:"var(--xn-bg-soft)", overflow:"hidden"}}>
                <div style={{height:"100%", width:`${r.share*100}%`, background:"var(--xn-blue-500)", borderRadius:3}} />
              </div>
              <div style={{fontSize:10, color:"var(--xn-fg-3)", marginTop:2}}>
                {CF.fmtVal(metric === "vol" ? r.tonnes : r.eur/1000, metric)}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Shipments table ──────────────────────────────────────────────────────────

function ShipmentsTable({ rows, metric }) {
  const CF = window.CF;
  return (
    <div style={{overflowX:"auto"}}>
      <table className="cf-table">
        <thead>
          <tr>
            <th>Período</th>
            <th>Provincia origen</th>
            <th>Código HS</th>
            <th style={{textAlign:"right"}}>Volumen</th>
            <th style={{textAlign:"right"}}>Valor</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i}>
              <td className="cf-mono" style={{fontSize:12}}>{MONTHS_ES[(r.month||1)-1]} {r.year}</td>
              <td style={{fontSize:12}}>{r.province_name || r.province}</td>
              <td>
                <span style={{fontFamily:"var(--xn-font-mono)", fontSize:10, background:"var(--xn-bg-soft)", borderRadius:4, padding:"2px 6px"}}>
                  {r.hs_code}
                </span>
                {HS6_LABELS[r.hs_code?.slice(0,6)] && (
                  <span style={{fontSize:11, color:"var(--xn-fg-3)", marginLeft:6}}>{HS6_LABELS[r.hs_code.slice(0,6)]}</span>
                )}
              </td>
              <td className="cf-mono" style={{textAlign:"right", fontSize:12}}>{CF.fmtVal(r.volume_t, "vol")}</td>
              <td className="cf-mono" style={{textAlign:"right", fontSize:12}}>{CF.fmtVal(r.value_keur, "val")}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

window.CN8_LABELS = CN8_LABELS;
window.SpainOriginSection = SpainOriginSection;
