// DrillCountry — country detail: KPIs, HS breakdown, xNova companies, evolution

function DrillCountry({ hs, hsCodes, hsLevel, metric, years, drill, setDrill }) {
  const CF = window.CF;
  const lo = Math.min(...years), hi = Math.max(...years);

  const iso3 = drill.country;
  const cfRef = CF.COUNTRIES.find(c => c[0] === iso3);
  const iso2 = window.iso3toIso2(iso3);
  const iso  = iso3;

  if (!iso2 && !cfRef) return <div className="cf-empty">País no encontrado.</div>;

  // Serie temporal del país desde la API
  const seriesApi = window.useApi(
    iso2 ? `${window.API_BASE}/api/series?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}&granularity=year&country=${iso2}` : null,
    [hsCodes ? hsCodes.join(",") : hs, lo, hi, iso2]
  );

  // Ranking global y mercados similares
  const countriesApi = window.useApi(
    `${window.API_BASE}/api/countries?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}`,
    [hsCodes ? hsCodes.join(",") : hs, lo, hi]
  );

  const seriesRows = seriesApi.data?.rows || [];
  const allCountriesRows = React.useMemo(() => {
    if (!countriesApi.data) return [];
    const rows = countriesApi.data.rows
      .map(r => window.normalizeCountryRow(r, metric))
      .sort((a, b) => b.value - a.value);
    window.populateCountryCache(countriesApi.data.rows);
    return rows;
  }, [countriesApi.data, metric]);

  // Nombre y metadatos: fuente principal = API (allCountriesRows / cache), fallback = COUNTRIES mock
  const countryFromApi = allCountriesRows.find(c => c.iso === iso3)
    || (window.__countryByIso3[iso3] ? window.normalizeCountryRow(window.__countryByIso3[iso3], metric) : null);
  const name      = countryFromApi?.name || cfRef?.[1] || iso3;
  const continent = countryFromApi?.continent || cfRef?.[2] || drill.continent;
  const eu        = countryFromApi ? !!countryFromApi.eu : !!cfRef?.[3];

  // Calcular stats a partir de la serie API (en t ó k€ según metric)
  const series = seriesRows.map(r => ({
    year: r.year,
    value: metric === "vol" ? r.tonnes : r.eur / 1000,
  }));
  const total     = series.reduce((a, p) => a + p.value, 0);
  const globalTotal = allCountriesRows.reduce((a, c) => a + c.value, 0);
  const share     = globalTotal > 0 ? total / globalTotal : 0;
  const rank      = allCountriesRows.findIndex(c => c.iso === iso3) + 1;
  const v0 = series[0]?.value || 0, v1 = series[series.length - 1]?.value || 0;
  const growth = v0 > 0 ? v1 / v0 - 1 : 0;
  const lastY  = v1;
  const prevY  = series[series.length - 2]?.value || lastY;
  const yoy    = prevY > 0 ? (lastY - prevY) / prevY : 0;

  // HS breakdown — datos reales de la API
  const hsBreakdownApi = window.useApi(
    iso2 ? `${window.API_BASE}/api/country/${iso2}/hs-breakdown?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}` : null,
    [hsCodes ? hsCodes.join(",") : hs, lo, hi, iso2]
  );
  const hsRows = React.useMemo(() => {
    const CF = window.CF;
    const apiRows = hsBreakdownApi.data?.rows;
    if (apiRows && apiRows.length > 0) {
      const hs6Map  = Object.fromEntries((CF.HS[hs].children || []).map(c => [c.code, c.label]));
      const hs4Map  = Object.fromEntries(Object.entries(CF.HS).map(([k, v]) => [k, v.label]));
      const cn8Map  = Object.fromEntries((CF.HS[hs].cn8 || []).map(c => [c.code, c.label]));
      const labelMap = { ...hs4Map, ...hs6Map, ...cn8Map, ...window.CN8_LABELS };
      const level = hsBreakdownApi.data.level;
      return apiRows.map(r => ({
        code:  r.code,
        level: level,
        label: labelMap[r.code] || r.code,
        value: metric === "vol" ? r.tonnes : r.eur / 1000,
        share: r.share,
      }));
    }
    // Fallback al mock escalado mientras carga o si no hay datos
    return window.CFHelpers.hsRows(hs, hsLevel, iso, metric, years, total);
  }, [hsBreakdownApi.data, hs, hsLevel, metric, iso, years, total]);

  const loading = seriesApi.status === "loading" || countriesApi.status === "loading";

  function backToContinent() {
    setDrill({ level: "continent", continent, country: null });
  }

  return (
    <div className="cf-fade-in">
      {/* Country hero / KPI strip */}
      <div className="cf-country-hero">
        <div className="cf-country-hero-main">
          <div className="cf-country-hero-id">
            <FlagPlaceholder iso2={iso2} />
            <div>
              <div className="cf-country-meta">
                <span>#{rank} mercado global</span>
                <span className="cf-dot"/>
                <span>{continent}</span>
                {eu && <><span className="cf-dot"/><span style={{color:"white", fontWeight:600}}>UE</span></>}
                <SourceTag label="xNova · datos granulares" kind="xnova" />
              </div>
              <h1 className="cf-country-name">{name}</h1>
              <p className="cf-country-desc">Exportaciones españolas de {CF.HS[hs].label.toLowerCase()} · {lo}–{hi}</p>
            </div>
          </div>
        </div>
        <div className="cf-country-hero-stats">
          <CountryStat label="Total período" value={CF.fmtVal(total, metric)} sub={`${CF.fmtPct(share)} cuota global`} />
          <CountryStat label={`YoY (${hi})`} value={CF.fmtDelta(yoy)} dir={yoy >= 0 ? "up" : "down"} />
          <CountryStat label={`Crecimiento ${lo}→${hi}`} value={CF.fmtDelta(growth)} dir={growth >= 0 ? "up" : "down"} sub="acumulado" />
          <CountryStat label="Último año" value={CF.fmtVal(lastY, metric)} sub={`${hi}`} />
        </div>
      </div>

      {/* Two-column: HS breakdown · Evolution */}
      <div className="cf-grid-2" style={{marginTop:18}}>
        <div className="cf-panel">
          <div className="cf-panel-head">
            <div>
              <h2>Desglose HS · {name}</h2>
              <p>{hsLevel === "8d" ? "Granularidad CN8 · 8 dígitos" : hsLevel === "6d" ? "Granularidad HS6 · 6 dígitos" : "Capítulo · 4 dígitos"}</p>
            </div>
          </div>
          <HsBreakdownTable rows={hsRows} total={total} metric={metric} hsLevel={hsLevel} />
        </div>

        <CountryEvolutionPanel
          name={name} hs={hs} hsCodes={hsCodes} metric={metric} years={years} iso2={iso2}
        />
      </div>

      {/* xNova importers */}
      {iso2 && <XnovaImporters countryName={name} />}

      {/* Origen provincial */}
      {iso2 && <window.SpainOriginSection hs={hs} hsCodes={hsCodes} metric={metric} years={years} iso2={iso2} countryName={name} />}

      {/* Footer · related markets */}
      <div className="cf-panel" style={{marginTop:18}}>
        <div className="cf-panel-head">
          <div>
            <h2>Mercados similares en {continent}</h2>
            <p>Comparativa rápida para identificar oportunidades adyacentes</p>
          </div>
          <button className="cf-btn" onClick={backToContinent}><I.ChevronRight size={14} style={{transform:"rotate(180deg)"}}/> Volver a {continent}</button>
        </div>
        <RankingList
          rows={allCountriesRows.filter(c => c.continent === continent && c.iso !== iso3).slice(0, 6)}
          max={allCountriesRows.filter(c => c.continent === continent)[0]?.value || total}
          metric={metric}
          onClick={(c) => setDrill({ level: "country", continent, country: c.iso })}
          selectedIso={iso3}
        />
      </div>
    </div>
  );
}

// ---- sub-components ----

// Panel de evolución autocontenido para la ficha de país.
// Gestiona su propia granularidad, fetch y modal de ampliación.
function CountryEvolutionPanel({ name, hs, hsCodes, metric, years, iso2 }) {
  const CF = window.CF;
  const lo = Math.min(...years), hi = Math.max(...years);
  const [gran, setGran]         = React.useState("month");
  const [expanded, setExpanded] = React.useState(false);

  const s = window.useApi(
    iso2 ? `${window.API_BASE}/api/series?${window.hsQ(hsCodes)}&from=${lo}&to=${hi}&granularity=${gran}&country=${iso2}` : null,
    [hsCodes ? hsCodes.join(",") : hs, lo, hi, gran, iso2]
  );

  const rows = s.data?.rows || [];
  const volS = rows.map(r => ({ period: r.period, year: r.year, month: r.month, value: r.tonnes }));
  const valS = rows.map(r => ({ period: r.period, year: r.year, month: r.month, value: r.eur   }));

  const lastYrRows = rows.filter(r => r.year === hi);
  const prevYrRows = rows.filter(r => r.year === hi - 1);
  const sumEur = arr => arr.reduce((a, r) => a + r.eur, 0);
  const yoy = prevYrRows.length && sumEur(prevYrRows) > 0
    ? (sumEur(lastYrRows) - sumEur(prevYrRows)) / sumEur(prevYrRows) : null;

  const loading = s.status === "loading";
  const hasData = rows.length > 0;

  React.useEffect(() => {
    if (!expanded) return;
    const onKey = e => { if (e.key === "Escape") setExpanded(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [expanded]);

  const chartContent = (height) => (
    <>
      <div className="cf-chart-legend" style={{marginBottom:6}}>
        <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> · miles €</span></div>
      </div>
      <window.DualLineChartInner vol={volS} val={valS} granularity={gran} height={height} />
    </>
  );

  return (
    <>
      <div className="cf-panel">
        <div className="cf-panel-head">
          <div>
            <h2>Evolución · {name}</h2>
            <p>{CF.metricLabel(metric)} · {lo}–{hi}</p>
          </div>
          <div className="cf-panel-tools" style={{display:"flex", gap:8, alignItems:"center"}}>
            {yoy != null && (
              <span className={"cf-tag " + (yoy >= 0 ? "pos" : "neg")}>
                {yoy >= 0 ? <I.ArrowUp size={11}/> : <I.ArrowDown size={11}/>} {CF.fmtDelta(yoy)} YoY {hi}
              </span>
            )}
            <div className="cf-seg">
              <button className={gran === "year"  ? "on" : ""} onClick={() => setGran("year")}>Anual</button>
              <button className={gran === "month" ? "on" : ""} onClick={() => setGran("month")}>Mensual</button>
            </div>
            {hasData && (
              <button className="cf-btn" onClick={() => setExpanded(true)}>
                <I.Expand size={13} /> Ampliar
              </button>
            )}
          </div>
        </div>
        {loading && <div style={{padding:"20px 0", color:"var(--xn-fg-3)", fontSize:13}}>Cargando…</div>}
        {!loading && hasData && chartContent(220)}
      </div>

      {expanded && ReactDOM.createPortal(
        <div
          onClick={() => setExpanded(false)}
          style={{
            position:"fixed", inset:0, zIndex:10000,
            background:"rgba(4,10,22,0.88)", display:"flex",
            alignItems:"center", justifyContent:"center",
            padding:32, backdropFilter:"blur(4px)",
          }}
        >
          <div
            className="cf-panel"
            onClick={e => e.stopPropagation()}
            style={{width:"100%", maxWidth:1200, margin:0, boxShadow:"0 24px 80px rgba(0,0,0,0.5)"}}
          >
            <div className="cf-panel-head">
              <div><h2>Evolución · {name}</h2><p>{CF.metricLabel(metric)} · {lo}–{hi} · {gran === "month" ? "mensual" : "anual"}</p></div>
              <button className="cf-btn" onClick={() => setExpanded(false)}>Cerrar ✕</button>
            </div>
            {chartContent(460)}
          </div>
        </div>,
        document.body
      )}
    </>
  );
}

function FlagPlaceholder({ iso2 }) {
  const src = iso2
    ? `https://flagcdn.com/w80/${iso2.toLowerCase()}.png`
    : null;
  return (
    <div className="cf-flag-emoji" aria-hidden>
      {src
        ? <img src={src} alt="" style={{width:"100%", height:"100%", objectFit:"cover", borderRadius:8}} />
        : <span style={{fontSize:28}}>🌍</span>
      }
    </div>
  );
}

function CountryStat({ label, value, sub, dir }) {
  const color = dir === "up" ? "var(--xn-success)" : dir === "down" ? "var(--xn-danger)" : "white";
  return (
    <div className="cf-country-stat">
      <div className="lbl">{label}</div>
      <div className="val" style={{color}}>{value}</div>
      {sub && <div className="sub">{sub}</div>}
    </div>
  );
}

function HsBreakdownTable({ rows, total, metric, hsLevel }) {
  const CF = window.CF;
  const palette = ["#0B1F5C", "#173FB0", "#2A6BF7", "#4F8BFF", "#82AEFF"];
  return (
    <div className="cf-tree">
      {rows.map((r, i) => (
        <div key={r.code} className={"cf-tree-row" + (r.level === "4d" ? " chapter" : "")} style={r.level === "4d" ? null : { marginLeft: 0 }}>
          <div className="lbl">
            <span className="code">{r.level === "4d" ? "HS4 · " : r.level === "8d" ? "CN8 · " : "HS6 · "}{r.code}</span>
            <span className="nm">{r.label}</span>
          </div>
          <div className="v">
            <div className="num">{CF.fmtVal(r.value, metric)}</div>
            <div className="pc">{CF.fmtPct(r.share)}</div>
          </div>
          {r.level === "6d" && (
            <div className="bar2"><span style={{width: `${r.share * 100}%`, background: palette[i % palette.length]}} /></div>
          )}
        </div>
      ))}
      {rows.length === 1 && rows[0].level === "4d" && (
        <div style={{padding:"10px 14px", marginTop:8, background:"var(--xn-bg-soft)", borderRadius:"var(--xn-radius-md)", fontSize:12, color:"var(--xn-fg-3)", lineHeight:1.5}}>
          <I.Info size={13} style={{verticalAlign:-2, marginRight:6}}/>
          Cambia la <strong style={{color:"var(--xn-fg-1)"}}>agregación a 6d</strong> arriba para ver el desglose por subcódigos HS6 (jamón con hueso, deshuesado, panceta…).
        </div>
      )}
    </div>
  );
}

function CountryEvolution({ series, metric, height }) {
  const CF = window.CF;
  const W = 900, H = height || 200, PL = 60, PR = 20, PT = 18, PB = 28;
  const innerW = W - PL - PR, innerH = H - PT - PB;
  const max = Math.max(...series.map(p => p.value)) * 1.1;
  const x = (i) => PL + (i / Math.max(1, series.length - 1)) * innerW;
  const y = (v) => PT + innerH - (v / max) * innerH;
  const linePath = series.map((p, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(p.value)}`).join(" ");
  const areaPath = linePath + ` L ${x(series.length - 1)} ${PT + innerH} L ${x(0)} ${PT + innerH} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{width:"100%", display:"block"}}>
      {[0, 0.5, 1].map(t => {
        const yy = PT + innerH * (1 - t);
        return (
          <g key={t}>
            <line x1={PL} x2={W - PR} y1={yy} y2={yy} stroke="var(--xn-border)" strokeWidth="1" strokeDasharray="2 4" />
            <text x={PL - 8} y={yy + 4} textAnchor="end" fontSize="11" fontFamily="var(--xn-font-mono)" fontWeight="600" fill="var(--xn-fg-3)">
              {CF.fmtVal(max * t, metric)}
            </text>
          </g>
        );
      })}
      {series.map((p, i) => (
        <text key={p.year} x={x(i)} y={H - 8} textAnchor="middle" fontSize="11" fontFamily="var(--xn-font-mono)" fontWeight="600" fill="var(--xn-fg-3)">{p.year}</text>
      ))}
      <path d={areaPath} fill="var(--xn-blue-500)" opacity="0.1" />
      <path d={linePath} fill="none" stroke="var(--xn-blue-500)" strokeWidth="2.5" />
      {series.map((p, i) => (
        <circle key={i} cx={x(i)} cy={y(p.value)} r="4" fill="white" stroke="var(--xn-blue-500)" strokeWidth="2" />
      ))}
    </svg>
  );
}

function XnovaImporters({ countryName }) {
  return (
    <div className="cf-xnova-section">
      <div className="cf-xnova-banner">
        <div className="cf-xnova-icon"><I.Sparkles size={18}/></div>
        <div style={{flex:1}}>
          <div className="cf-xnova-eyebrow">
            <span className="cf-xnova-tag">XNOVA</span>
            <span>Inteligencia de mercado</span>
          </div>
          <div className="cf-xnova-title">
            Importadores de cárnicos en <strong>{countryName}</strong> ·
            {" "}Accede a la plataforma xNova para ver el listado completo de operadores trazados
          </div>
        </div>
        <a
          href="https://app.xnovainternational.com/"
          target="_blank"
          rel="noopener noreferrer"
          className="cf-btn primary"
          style={{textDecoration:"none", display:"inline-flex", alignItems:"center", gap:6, flexShrink:0}}
        >
          <I.ExternalLink size={13}/> Ver en xNova
        </a>
      </div>
    </div>
  );
}

window.DrillCountry = DrillCountry;
