// Root App — drill-down architecture: World → Continent → Country

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light"
}/*EDITMODE-END*/;

const DEFAULT_HS_FILTER = { level: "4d", codes: ["0210"] };

function parseUrlState() {
  try {
    const sp = new URLSearchParams(window.location.search);
    const level = sp.get("hs_level");
    const codes = sp.get("hs_codes");
    const m     = sp.get("metric");
    const from  = sp.get("from");
    const to    = sp.get("to");
    const state = {};
    if (level && codes) {
      const validLevels = ["4d","6d","8d"];
      if (validLevels.includes(level)) state.hsFilter = { level, codes: codes.split(",").filter(Boolean) };
    }
    if (m && (m === "vol" || m === "val")) state.metric = m;
    if (from && to) {
      const f = parseInt(from), t = parseInt(to);
      if (!isNaN(f) && !isNaN(t)) state.years = [Math.min(f,t), Math.max(f,t)];
    }
    return state;
  } catch(_) { return {}; }
}

// Derive the single chapter code (backward compat for views & API)
function deriveHs(hsFilter) {
  if (hsFilter.codes.length === 0) return "0210";
  const first = hsFilter.codes[0];
  if (first === "0210" || first.startsWith("021")) return "0210";
  if (first === "1601" || first.startsWith("160")) return "1601";
  return "0210";
}

function deriveHsLevel(hsFilter) {
  return hsFilter.level;
}

function computeHsLabel(hsFilter) {
  const { level, codes } = hsFilter;
  if (codes.length === 0) return "Sin selección";
  if (level === "4d") {
    if (codes.includes("0210") && codes.includes("1601")) return "Todos los capítulos";
    if (codes.includes("0210")) return window.CF.HS["0210"].label;
    if (codes.includes("1601")) return window.CF.HS["1601"].label;
  }
  const first = codes[0];
  if (first.startsWith("021") || first === "0210") return window.CF.HS["0210"].label;
  if (first.startsWith("160") || first === "1601") return window.CF.HS["1601"].label;
  return first;
}

// ---- Empty HS state ---------------------------------------------------
function EmptyHsState() {
  return (
    <div className="cf-hs-empty">
      <div style={{fontSize:48, marginBottom:16}}>🌿</div>
      <h3 style={{margin:"0 0 10px",fontSize:20,fontWeight:700,letterSpacing:"-0.01em"}}>
        Sin códigos HS seleccionados
      </h3>
      <p style={{margin:"0 0 24px",fontSize:14,color:"var(--xn-fg-2)",maxWidth:400,lineHeight:1.6,textAlign:"center"}}>
        Para ver datos en el dashboard, selecciona al menos un código HS en el filtro superior. Puedes elegir capítulos (4d), subpartidas HS6 o códigos CN8 a 8 dígitos.
      </p>
      <button className="cf-btn primary" onClick={() => window.__openHsPicker?.()}>
        Abrir selector HS
      </button>
    </div>
  );
}

// ---- App ---------------------------------------------------------------
function App() {
  const initialUrl = parseUrlState();

  const [hsFilter, setHsFilter] = React.useState(initialUrl.hsFilter || DEFAULT_HS_FILTER);
  const [metric, setMetric]     = React.useState(initialUrl.metric   || "val");
  const [years, setYears]       = React.useState(initialUrl.years    || [2019, 2025]);
  const [drill, setDrill]       = React.useState({ level: "world", continent: null, country: null });

  // Preserve scroll position when filters are applied
  const contentRef = React.useRef(null);
  function keepScroll(setter) {
    return (value) => {
      const saved = contentRef.current?.scrollTop || 0;
      setter(value);
      requestAnimationFrame(() => {
        if (contentRef.current) contentRef.current.scrollTop = saved;
      });
    };
  }

  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  React.useEffect(() => {
    document.body.classList.toggle("dark", t.theme === "dark");
  }, [t.theme]);

  // URL sync
  React.useEffect(() => {
    const sp = new URLSearchParams();
    sp.set("hs_level", hsFilter.level);
    sp.set("hs_codes", hsFilter.codes.join(","));
    sp.set("metric", metric);
    sp.set("from", Math.min(...years));
    sp.set("to", Math.max(...years));
    history.replaceState(null, "", "?" + sp.toString());
  }, [JSON.stringify(hsFilter), metric, JSON.stringify(years)]);

  // Backward-compat derived values for views
  const hs      = React.useMemo(() => deriveHs(hsFilter), [hsFilter]);
  const hsLevel = React.useMemo(() => deriveHsLevel(hsFilter), [hsFilter]);
  const hsLabel = React.useMemo(() => computeHsLabel(hsFilter), [hsFilter]);

  // Country name resolution (reactive)
  const lo = Math.min(...years), hi = Math.max(...years);
  const countriesAppApi = window.useApi(
    `${window.API_BASE}/api/countries?${window.hsQ(hsFilter.codes)}&from=${lo}&to=${hi}`,
    [hsFilter.codes.join(","), lo, hi]
  );
  const countryNameMap = React.useMemo(() => {
    const rows = countriesAppApi.data?.rows || [];
    const map = {};
    for (const r of rows) {
      if (r.iso3) map[r.iso3] = r.name;
      window.__iso3toIso2    = window.__iso3toIso2    || {};
      window.__countryByIso3 = window.__countryByIso3 || {};
      if (r.iso3) {
        window.__iso3toIso2[r.iso3]    = r.iso2;
        window.__countryByIso3[r.iso3] = r;
      }
    }
    return map;
  }, [countriesAppApi.data]);

  function resolveCountryName(iso3) {
    return countryNameMap[iso3]
      || window.CF.COUNTRIES.find(c => c[0] === iso3)?.[1]
      || iso3;
  }

  const meta = (() => {
    if (drill.level === "world") return {
      eyebrow: "VISTA GLOBAL",
      title: "Exportaciones españolas · " + hsLabel,
      desc: "Cuadro de mando para la dirección estratégica. Pulsa un continente, un país, o un importador para profundizar.",
      src: "",
    };
    if (drill.level === "continent") return {
      eyebrow: "VISTA REGIONAL",
      title: drill.continent,
      desc: `Análisis de ${drill.continent.toLowerCase()} · ${hsLabel.toLowerCase()}. Pulsa un país para abrir su ficha de mercado.`,
      src: "",
    };
    const cfRef = window.CF.COUNTRIES.find(c => c[0] === drill.country);
    return {
      eyebrow: "FICHA DE MERCADO",
      title: resolveCountryName(drill.country),
      desc: "Detalle de mercado: desglose HS, importadores y exportadores españoles trazados por xNova.",
      src: "",
    };
  })();

  const noData = hsFilter.codes.length === 0;

  return (
    <div className="app" data-screen-label={drill.level}>
      <HeaderV2 hsLabel={hsLabel} />
      <SidebarV2 drill={drill} setDrill={setDrill} />

      <div className="cf-content" ref={contentRef}>
        <FilterBarV2
          hsFilter={hsFilter}   setHsFilter={keepScroll(setHsFilter)}
          metric={metric}       setMetric={keepScroll(setMetric)}
          years={years}         setYears={keepScroll(setYears)}
        />

        <main className="cf-main">
          {noData ? (
            <EmptyHsState />
          ) : (
            <>
              <div className="cf-view-header">
                <div className="cf-view-title">
                  <Breadcrumb drill={drill} setDrill={setDrill} resolveCountryName={resolveCountryName} />
                  <h1 style={{marginTop:14}}>{meta.title}</h1>
                  <p>{meta.desc}</p>
                </div>
              </div>

              {drill.level === "world"     && <DrillWorld     hs={hs} hsCodes={hsFilter.codes} metric={metric} years={years} drill={drill} setDrill={setDrill} />}
              {drill.level === "continent" && <DrillContinent hs={hs} hsCodes={hsFilter.codes} metric={metric} years={years} drill={drill} setDrill={setDrill} />}
              {drill.level === "country"   && <DrillCountry   hs={hs} hsCodes={hsFilter.codes} hsLevel={hsLevel} metric={metric} years={years} drill={drill} setDrill={setDrill} />}
            </>
          )}
        </main>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Apariencia">
          <TweakRadio
            label="Tema"
            value={t.theme}
            onChange={(v) => setTweak("theme", v)}
            options={[
              { value: "light", label: "Claro" },
              { value: "dark",  label: "Oscuro" },
            ]}
          />
        </TweakSection>
        <TweakSection title="Estado">
          <div style={{padding:"10px 12px",background:"var(--xn-bg-soft)",borderRadius:8,fontSize:12,lineHeight:1.6,color:"var(--xn-fg-2)"}}>
            <div><span style={{color:"var(--xn-fg-3)"}}>Nivel:</span> <strong style={{color:"var(--xn-fg-1)"}}>{drill.level}</strong></div>
            <div><span style={{color:"var(--xn-fg-3)"}}>HS nivel:</span> <strong className="cf-mono" style={{color:"var(--xn-fg-1)"}}>{hsFilter.level}</strong></div>
            <div><span style={{color:"var(--xn-fg-3)"}}>HS códigos:</span> <strong className="cf-mono" style={{color:"var(--xn-fg-1)"}}>{hsFilter.codes.join(", ") || "—"}</strong></div>
            <div><span style={{color:"var(--xn-fg-3)"}}>Métrica:</span> <strong style={{color:"var(--xn-fg-1)"}}>{window.CF.metricLabel(metric)}</strong></div>
            <div><span style={{color:"var(--xn-fg-3)"}}>Período:</span> <strong className="cf-mono" style={{color:"var(--xn-fg-1)"}}>{Math.min(...years)}–{Math.max(...years)}</strong></div>
          </div>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
