// Shell V2 — Header, Sidebar, FilterBarV2 (HS picker + metric + year range)

// ---- HS taxonomy -------------------------------------------------------
const HS_TREE = {
  "1601": {
    label: "Embutidos",
    hs6: null,
    cn8: [
      { code: "16010010", label: "Embutidos que contengan hígado" },
      { code: "16010091", label: "Crudos curados (chorizo, salchichón…)" },
      { code: "16010099", label: "Otros (frescos, cocidos)" },
    ],
  },
  "0210": {
    label: "Carne curada / salada / ahumada",
    hs6: [
      { code: "021011", label: "Jamón con hueso", cn8: [
        { code: "02101111", label: "Jamón ibérico con hueso (DOP)" },
        { code: "02101119", label: "Otros jamones con hueso" },
        { code: "02101131", label: "Paleta con hueso (DOP)" },
        { code: "02101139", label: "Otras paletas con hueso" },
        { code: "02101190", label: "Otros despojos con hueso" },
      ]},
      { code: "021012", label: "Panceta / bacon", cn8: [
        { code: "02101211", label: "Panceta secada / ahumada" },
        { code: "02101219", label: "Otra panceta" },
        { code: "02101290", label: "Tocino y similares" },
      ]},
      { code: "021019", label: "Otros cortes de cerdo deshuesados", cn8: [
        { code: "02101911", label: "Jamón ibérico deshuesado (DOP)" },
        { code: "02101919", label: "Otros jamones deshuesados" },
        { code: "02101930", label: "Paleta deshuesada" },
        { code: "02101950", label: "Lomo curado" },
        { code: "02101981", label: "Otros cortes premium" },
        { code: "02101990", label: "Despojos deshuesados" },
      ]},
      { code: "021020", label: "Vacuno curado", cn8: [
        { code: "02102010", label: "Cecina con hueso" },
        { code: "02102090", label: "Cecina y vacuno curado" },
      ]},
      { code: "021090", label: "Otros (incl. despojos curados)", cn8: [
        { code: "02109010", label: "Despojos curados (caballo)" },
        { code: "02109020", label: "Aves curadas" },
        { code: "02109099", label: "Otros curados" },
      ]},
    ],
    cn8: [],
  },
  "1602": {
    label: "Conservas y preparaciones de carne",
    hs6: [
      { code: "160210", label: "Preparaciones homogeneizadas", cn8: [] },
      { code: "160220", label: "De hígado", cn8: [] },
      { code: "160231", label: "Preparaciones de pavo", cn8: [] },
      { code: "160232", label: "Preparaciones de pollo", cn8: [] },
      { code: "160239", label: "Otras aves", cn8: [] },
      { code: "160241", label: "Jamones y trozos (conserva)", cn8: [
        { code: "16024110", label: "Jamones cerdo doméstico, sin cocinar" },
        { code: "16024190", label: "Los demás jamones en conserva" },
      ]},
      { code: "160242", label: "Paletas y trozos (conserva)", cn8: [
        { code: "16024210", label: "Paletas cerdo doméstico, sin cocinar" },
        { code: "16024290", label: "Las demás paletas en conserva" },
      ]},
      { code: "160249", label: "Demás preparaciones de cerdo", cn8: [
        { code: "16024910", label: "Preparaciones cerdo, sin cocinar" },
        { code: "16024930", label: "Preparaciones cerdo doméstico, cocidas" },
        { code: "16024990", label: "Las demás preparaciones de cerdo" },
      ]},
      { code: "160250", label: "Preparaciones de vacuno", cn8: [
        { code: "16025010", label: "Vacuno, sin cocinar ni preparar" },
        { code: "16025031", label: "Roast beef" },
        { code: "16025095", label: "Las demás preparaciones de vacuno" },
      ]},
      { code: "160290", label: "Otras preparaciones cárnicas", cn8: [
        { code: "16029010", label: "De reno" },
        { code: "16029041", label: "Ovino o caprino" },
        { code: "16029051", label: "Aves (codorniz, perdiz…)" },
        { code: "16029091", label: "Las demás preparaciones cárnicas" },
      ]},
    ],
    cn8: [],
  },
  "1603": {
    label: "Extractos y jugos de carne",
    hs6: null,
    cn8: [
      { code: "16030010", label: "Extractos y jugos de bovino" },
      { code: "16030080", label: "Demás extractos y jugos de carne" },
    ],
  },
};

function getAllCodesAtLevel(level) {
  if (level === "4d") return ["1601", "1602", "1603", "0210"];
  if (level === "6d") return [
    ...HS_TREE["1602"].hs6.map(c => c.code),
    ...HS_TREE["0210"].hs6.map(c => c.code),
  ];
  if (level === "8d") return [
    ...HS_TREE["1601"].cn8.map(c => c.code),
    ...HS_TREE["1602"].hs6.flatMap(h => h.cn8),
    ...HS_TREE["1603"].cn8.map(c => c.code),
    ...HS_TREE["0210"].hs6.flatMap(h => h.cn8.map(c => c.code)),
  ];
  return [];
}

function getChapterCodesAtLevel(ch, level) {
  if (level === "4d") return [ch];
  if (level === "6d") {
    if (ch === "0210") return HS_TREE["0210"].hs6.map(c => c.code);
    if (ch === "1602") return HS_TREE["1602"].hs6.map(c => c.code);
    return [];
  }
  if (level === "8d") {
    if (ch === "1601") return HS_TREE["1601"].cn8.map(c => c.code);
    if (ch === "1602") return HS_TREE["1602"].hs6.flatMap(h => h.cn8.map(c => c.code));
    if (ch === "1603") return HS_TREE["1603"].cn8.map(c => c.code);
    return HS_TREE["0210"].hs6.flatMap(h => h.cn8.map(c => c.code));
  }
  return [];
}

function chapterOf(code) {
  if (code.startsWith("1601")) return "1601";
  if (code.startsWith("1602")) return "1602";
  if (code.startsWith("1603")) return "1603";
  if (code.startsWith("021"))  return "0210";
  return null;
}

function codesFromLevelChange(oldFilter, newLevel) {
  const { codes: oldCodes } = oldFilter;
  const chaps = new Set(oldCodes.map(chapterOf).filter(Boolean));
  if (chaps.size === 0) return getAllCodesAtLevel(newLevel);

  let newCodes = [];
  for (const ch of chaps) {
    const chs = getChapterCodesAtLevel(ch, newLevel);
    if (chs.length === 0 && newLevel === "6d" && (ch === "1601" || ch === "1603")) {
      return getAllCodesAtLevel("6d");
    }
    newCodes.push(...chs);
  }
  return newCodes.length > 0 ? [...new Set(newCodes)] : getAllCodesAtLevel(newLevel);
}

function hsTriggerLabel(hsFilter) {
  const { level, codes } = hsFilter;
  if (codes.length === 0) return "Sin selección";
  if (level === "4d") {
    if (codes.length === getAllCodesAtLevel("4d").length) return "Todos los capítulos";
    if (codes.length === 1) return HS_TREE[codes[0]]?.label || codes[0];
    return `${codes.length} capítulos`;
  }
  if (level === "6d") {
    if (codes.length === 1) {
      const all6 = [...HS_TREE["0210"].hs6, ...HS_TREE["1602"].hs6];
      const found = all6.find(c => c.code === codes[0]);
      return found ? `${codes[0]} · ${found.label}` : codes[0];
    }
    if (codes.length === getAllCodesAtLevel("6d").length) return "Todos los HS6";
    return `${codes.length} códigos seleccionados`;
  }
  if (level === "8d") {
    if (codes.length === 1) {
      const all8 = [
        ...HS_TREE["1601"].cn8,
        ...HS_TREE["1602"].hs6.flatMap(h => h.cn8),
        ...HS_TREE["1603"].cn8,
        ...HS_TREE["0210"].hs6.flatMap(h => h.cn8),
      ];
      const found = all8.find(c => c.code === codes[0]);
      return found ? `${codes[0]} · ${found.label}` : codes[0];
    }
    return `${codes.length} códigos seleccionados`;
  }
  return codes[0];
}

// ---- HsCodePicker ------------------------------------------------------
function HsCodePicker({ hsFilter, onChange }) {
  const [open, setOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(hsFilter);
  const ref = React.useRef(null);

  React.useEffect(() => { setDraft(hsFilter); }, [JSON.stringify(hsFilter)]);

  // expose opener for empty-state button
  React.useEffect(() => {
    window.__openHsPicker = () => setOpen(true);
    return () => { if (window.__openHsPicker) window.__openHsPicker = null; };
  }, []);

  // click-outside
  React.useEffect(() => {
    if (!open) return;
    function handler(e) {
      if (ref.current && !ref.current.contains(e.target)) {
        setOpen(false);
        setDraft(hsFilter);
      }
    }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open, JSON.stringify(hsFilter)]);

  function apply() {
    onChange(draft);
    setOpen(false);
  }

  function changeLevel(newLevel) {
    const newCodes = codesFromLevelChange(draft, newLevel);
    setDraft({ level: newLevel, codes: newCodes });
  }

  function toggleCode(code) {
    const has = draft.codes.includes(code);
    setDraft({ ...draft, codes: has ? draft.codes.filter(c => c !== code) : [...draft.codes, code] });
  }

  function toggleChapterAll(ch) {
    const chCodes = getChapterCodesAtLevel(ch, draft.level);
    if (chCodes.length === 0) return;
    const allOn = chCodes.every(c => draft.codes.includes(c));
    if (allOn) {
      setDraft({ ...draft, codes: draft.codes.filter(c => !chCodes.includes(c)) });
    } else {
      setDraft({ ...draft, codes: [...new Set([...draft.codes, ...chCodes])] });
    }
  }

  const triggerLabel = hsTriggerLabel(hsFilter);
  const draftCount = draft.codes.length;
  const isEmpty = hsFilter.codes.length === 0;

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className={"cf-hsp-trigger" + (open ? " open" : "") + (isEmpty ? " empty" : "")}
        onClick={() => setOpen(o => !o)}
      >
        <span className="cf-hsp-lvbadge">{hsFilter.level}</span>
        <span className="cf-hsp-tlabel">{triggerLabel}</span>
        {hsFilter.codes.length > 0 && (
          <span className="cf-hsp-count">{hsFilter.codes.length}</span>
        )}
        <I.ChevronDown size={12} style={{ flexShrink: 0 }} />
      </button>

      {open && (
        <div className="cf-hsp-popover">
          {/* Level tabs */}
          <div className="cf-hsp-sec-head">NIVEL DE GRANULARIDAD</div>
          <div className="cf-seg cf-hsp-levels">
            {["4d","6d","8d"].map(lv => (
              <button key={lv} className={draft.level === lv ? "on" : ""} onClick={() => changeLevel(lv)}>
                {lv} <span style={{opacity:.55,fontWeight:500,fontSize:11}}>
                  {lv==="4d"?"capítulo":lv==="6d"?"HS6":"CN8"}
                </span>
              </button>
            ))}
          </div>

          <div className="cf-hsp-divider" />
          <div className="cf-hsp-sec-head">
            CÓDIGOS · {draft.level==="4d"?"capítulos":draft.level==="6d"?"subpartidas HS6":"CN8"}
          </div>

          <div className="cf-hsp-list">

            {/* 4d view */}
            {draft.level === "4d" && ["1601","1602","1603","0210"].map(ch => (
              <label key={ch} className="cf-hsp-item chapter">
                <input type="checkbox" checked={draft.codes.includes(ch)} onChange={() => toggleCode(ch)} />
                <span className="cf-hsp-code">{ch}</span>
                <span className="cf-hsp-lbl">{HS_TREE[ch].label}</span>
              </label>
            ))}

            {/* 6d view */}
            {draft.level === "6d" && <>
              <div className="cf-hsp-ch-head">
                <span><span className="cf-hsp-code">1601</span> Embutidos</span>
                <span className="cf-hsp-no6d">— sin códigos a 6d —</span>
              </div>
              <div className="cf-hsp-ch-head">
                <span><span className="cf-hsp-code">1602</span> Conservas de carne</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("1602")}>
                  {getChapterCodesAtLevel("1602","6d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["1602"].hs6.map(h => (
                <label key={h.code} className="cf-hsp-item">
                  <input type="checkbox" checked={draft.codes.includes(h.code)} onChange={() => toggleCode(h.code)} />
                  <span className="cf-hsp-code">{h.code}</span>
                  <span className="cf-hsp-lbl">{h.label}</span>
                </label>
              ))}
              <div className="cf-hsp-ch-head" style={{marginTop:6}}>
                <span><span className="cf-hsp-code">1603</span> Extractos de carne</span>
                <span className="cf-hsp-no6d">— sin códigos a 6d —</span>
              </div>
              <div className="cf-hsp-ch-head" style={{marginTop:6}}>
                <span><span className="cf-hsp-code">0210</span> Carne curada</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("0210")}>
                  {getChapterCodesAtLevel("0210","6d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["0210"].hs6.map(h => (
                <label key={h.code} className="cf-hsp-item">
                  <input type="checkbox" checked={draft.codes.includes(h.code)} onChange={() => toggleCode(h.code)} />
                  <span className="cf-hsp-code">{h.code}</span>
                  <span className="cf-hsp-lbl">{h.label}</span>
                </label>
              ))}
            </>}

            {/* 8d view */}
            {draft.level === "8d" && <>
              <div className="cf-hsp-ch-head">
                <span><span className="cf-hsp-code">1601</span> Embutidos</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("1601")}>
                  {getChapterCodesAtLevel("1601","8d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["1601"].cn8.map(c => (
                <label key={c.code} className="cf-hsp-item cn8">
                  <input type="checkbox" checked={draft.codes.includes(c.code)} onChange={() => toggleCode(c.code)} />
                  <span className="cf-hsp-code">{c.code}</span>
                  <span className="cf-hsp-lbl">{c.label}</span>
                </label>
              ))}
              <div className="cf-hsp-ch-head" style={{marginTop:6}}>
                <span><span className="cf-hsp-code">1602</span> Conservas de carne</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("1602")}>
                  {getChapterCodesAtLevel("1602","8d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["1602"].hs6.map(h => (
                <React.Fragment key={h.code}>
                  {h.cn8.length > 0 && <>
                    <div className="cf-hsp-hs6-head">{h.code} · {h.label}</div>
                    {h.cn8.map(c => (
                      <label key={c.code} className="cf-hsp-item cn8">
                        <input type="checkbox" checked={draft.codes.includes(c.code)} onChange={() => toggleCode(c.code)} />
                        <span className="cf-hsp-code">{c.code}</span>
                        <span className="cf-hsp-lbl">{c.label}</span>
                        <span className="cf-hsp-parent">← {h.code}</span>
                      </label>
                    ))}
                  </>}
                </React.Fragment>
              ))}
              <div className="cf-hsp-ch-head" style={{marginTop:6}}>
                <span><span className="cf-hsp-code">1603</span> Extractos de carne</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("1603")}>
                  {getChapterCodesAtLevel("1603","8d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["1603"].cn8.map(c => (
                <label key={c.code} className="cf-hsp-item cn8">
                  <input type="checkbox" checked={draft.codes.includes(c.code)} onChange={() => toggleCode(c.code)} />
                  <span className="cf-hsp-code">{c.code}</span>
                  <span className="cf-hsp-lbl">{c.label}</span>
                </label>
              ))}
              <div className="cf-hsp-ch-head" style={{marginTop:6}}>
                <span><span className="cf-hsp-code">0210</span> Carne curada</span>
                <button className="cf-hsp-todos" onClick={() => toggleChapterAll("0210")}>
                  {getChapterCodesAtLevel("0210","8d").every(c => draft.codes.includes(c)) ? "Limpiar" : "Todos"}
                </button>
              </div>
              {HS_TREE["0210"].hs6.map(h => (
                <React.Fragment key={h.code}>
                  <div className="cf-hsp-hs6-head">{h.code} · {h.label}</div>
                  {h.cn8.map(c => (
                    <label key={c.code} className="cf-hsp-item cn8">
                      <input type="checkbox" checked={draft.codes.includes(c.code)} onChange={() => toggleCode(c.code)} />
                      <span className="cf-hsp-code">{c.code}</span>
                      <span className="cf-hsp-lbl">{c.label}</span>
                      <span className="cf-hsp-parent">← {h.code}</span>
                    </label>
                  ))}
                </React.Fragment>
              ))}
            </>}
          </div>

          <div className="cf-hsp-divider" />
          <div className="cf-hsp-footer">
            <span className="cf-hsp-fcount">
              {draftCount} {draftCount === 1 ? "código seleccionado" : "códigos seleccionados"}
            </span>
            <div style={{ display:"flex", gap:8 }}>
              {draftCount > 0 && (
                <button className="cf-btn" onClick={() => setDraft({ ...draft, codes: [] })}>
                  Limpiar todo
                </button>
              )}
              <button className="cf-btn primary" onClick={apply}>Aplicar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ---- YearRangePicker ---------------------------------------------------
function YearRangePicker({ years, onChange }) {
  const allYears = window.CF.YEARS;
  const yMin = allYears[0], yMax = allYears[allYears.length - 1];
  const [lo, hi] = [Math.min(...years), Math.max(...years)];

  const [open, setOpen] = React.useState(false);
  const [dlo, setDlo] = React.useState(lo);
  const [dhi, setDhi] = React.useState(hi);
  const ref = React.useRef(null);
  const trackRef = React.useRef(null);
  const dragging = React.useRef(null);

  // sync draft when closed or external change
  React.useEffect(() => { if (!open) { setDlo(lo); setDhi(hi); } }, [open, lo, hi]);

  // click-outside
  React.useEffect(() => {
    if (!open) return;
    function handler(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  // drag
  React.useEffect(() => {
    function snapYear(pct0) {
      const raw = yMin + pct0 * (yMax - yMin);
      return allYears.reduce((a, y) => Math.abs(y - raw) < Math.abs(a - raw) ? y : a, allYears[0]);
    }
    function onMove(e) {
      if (!dragging.current || !trackRef.current) return;
      const rect = trackRef.current.getBoundingClientRect();
      const p = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      const y = snapYear(p);
      if (dragging.current === "lo") setDlo(prev => Math.min(y, dhi));
      else setDhi(prev => Math.max(y, dlo));
    }
    function onUp() { dragging.current = null; }
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
    return () => {
      document.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseup", onUp);
    };
  }, [dlo, dhi, allYears, yMin, yMax]);

  function pct(y) { return ((y - yMin) / (yMax - yMin)) * 100; }

  const presets = [
    { label: "Último año",      v: [yMax, yMax] },
    { label: "Últimos 3 años",  v: [yMax-2, yMax] },
    { label: "Últimos 5 años",  v: [yMax-4, yMax] },
    { label: "Todo el período", v: [yMin, yMax] },
  ];

  function applyPreset([a, b]) {
    onChange([a, b]);
    setOpen(false);
  }

  function apply() {
    onChange([dlo, dhi]);
    setOpen(false);
  }

  const nYears = hi - lo + 1;

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className={"cf-yrp-trigger" + (open ? " open" : "")}
        onClick={() => setOpen(o => !o)}
      >
        <I.Calendar size={13} style={{ flexShrink:0 }} />
        <span className="cf-yrp-range">{lo === hi ? `${lo}` : `${lo} – ${hi}`}</span>
        <span className="cf-yrp-badge">{nYears} {nYears===1?"año":"años"}</span>
        <I.ChevronDown size={12} style={{ flexShrink:0 }} />
      </button>

      {open && (
        <div className="cf-yrp-popover">
          <div className="cf-hsp-sec-head">ATAJOS</div>
          <div className="cf-yrp-presets">
            {presets.map(p => {
              const active = p.v[0]===dlo && p.v[1]===dhi;
              return (
                <button key={p.label} className={"cf-yrp-preset"+(active?" active":"")} onClick={() => applyPreset(p.v)}>
                  {p.label}
                </button>
              );
            })}
          </div>

          <div className="cf-hsp-divider" />
          <div className="cf-hsp-sec-head">RANGO PERSONALIZADO</div>

          <div className="cf-yrp-selects">
            <div className="cf-yrp-sel-group">
              <span>Desde</span>
              <select value={dlo} onChange={e => setDlo(Math.min(parseInt(e.target.value), dhi))}>
                {allYears.filter(y => y <= dhi).map(y => <option key={y} value={y}>{y}</option>)}
              </select>
            </div>
            <span className="cf-yrp-arrow">→</span>
            <div className="cf-yrp-sel-group">
              <span>Hasta</span>
              <select value={dhi} onChange={e => setDhi(Math.max(parseInt(e.target.value), dlo))}>
                {allYears.filter(y => y >= dlo).map(y => <option key={y} value={y}>{y}</option>)}
              </select>
            </div>
          </div>

          {/* Slider */}
          <div className="cf-yrp-slider-wrap">
            <div ref={trackRef} className="cf-yrp-track">
              <div className="cf-yrp-fill" style={{ left:`${pct(dlo)}%`, width:`${pct(dhi)-pct(dlo)}%` }} />
              {allYears.map(y => <div key={y} className="cf-yrp-dot" style={{ left:`${pct(y)}%` }} />)}
              <div
                className="cf-yrp-handle"
                style={{ left:`${pct(dlo)}%` }}
                onMouseDown={e => { e.preventDefault(); dragging.current="lo"; }}
              >
                <span className="cf-yrp-hlabel">{dlo}</span>
              </div>
              <div
                className="cf-yrp-handle"
                style={{ left:`${pct(dhi)}%` }}
                onMouseDown={e => { e.preventDefault(); dragging.current="hi"; }}
              >
                <span className="cf-yrp-hlabel">{dhi}</span>
              </div>
            </div>
            <div className="cf-yrp-axis"><span>{yMin}</span><span>{yMax}</span></div>
          </div>

          <div className="cf-hsp-divider" />
          <div style={{ display:"flex", justifyContent:"flex-end", padding:"10px 14px 14px" }}>
            <button className="cf-btn primary" onClick={apply}>Aplicar</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ---- HeaderV2 ----------------------------------------------------------
function HeaderV2({ hsLabel }) {
  return (
    <header className="cf-header" data-screen-label="Header">
      <div className="cf-brand">
        <img src="assets/logo-campofrio.png" alt="Campofrío" className="cf-brand-logo-img" />
        <div className="cf-brand-text">
          <span className="sub">{hsLabel}</span>
        </div>
      </div>
      <div className="cf-header-actions"></div>
    </header>
  );
}

// ---- SidebarV2 ---------------------------------------------------------
function SidebarV2({ drill, setDrill }) {
  return (
    <aside className="cf-sidebar">
      <div className="cf-side-section">
        <div className="cf-side-label">Inicio</div>
        <button
          className={"cf-side-item" + (drill.level === "world" ? " active" : "")}
          onClick={() => setDrill({ level: "world", continent: null, country: null })}
        >
          <I.Globe size={18} /><span>Vista global</span>
        </button>
      </div>

      <div className="cf-side-section">
        <div className="cf-side-label">Atajos</div>
        {[
          ["FRA", "Francia"],
          ["DEU", "Alemania"],
          ["USA", "Estados Unidos"],
          ["MEX", "México"],
          ["JPN", "Japón"],
        ].map(([iso, name]) => (
          <button
            key={iso}
            className={"cf-side-item small" + (drill.country === iso ? " active" : "")}
            onClick={() => {
              const cont = window.CF.COUNTRIES.find(c => c[0] === iso)?.[2];
              setDrill({ level: "country", continent: cont, country: iso });
            }}
          >
            <span style={{width:18,display:"inline-flex",justifyContent:"center",color:"var(--xn-fg-3)",fontFamily:"var(--xn-font-mono)",fontWeight:700,fontSize:11}}>{iso}</span>
            <span>{name}</span>
          </button>
        ))}
      </div>

      <div style={{marginTop:"auto", padding:"12px 12px 16px"}}>
        <button
          className="cf-side-item small"
          style={{width:"100%", color:"var(--xn-fg-3)"}}
          onClick={() => firebase.auth().signOut()}
        >
          <I.LogOut size={15} /><span>Cerrar sesión</span>
        </button>
      </div>
    </aside>
  );
}

// ---- FilterBarV2 -------------------------------------------------------
function FilterBarV2({ hsFilter, setHsFilter, metric, setMetric, years, setYears }) {
  return (
    <div className="cf-filters" data-screen-label="Filters">
      <div className="cf-filter-group">
        <span className="cf-filter-label">HS code</span>
        <HsCodePicker hsFilter={hsFilter} onChange={setHsFilter} />
      </div>

      <div className="cf-filter-group">
        <span className="cf-filter-label">Métrica</span>
        <div className="cf-seg">
          <button className={metric === "vol" ? "on" : ""} onClick={() => setMetric("vol")}>
            <I.Weight size={14} /> Volumen
          </button>
          <button className={metric === "val" ? "on" : ""} onClick={() => setMetric("val")}>
            <I.Euro size={14} /> Valor
          </button>
        </div>
      </div>

      <div className="cf-filter-group">
        <span className="cf-filter-label">Período</span>
        <YearRangePicker years={years} onChange={setYears} />
      </div>

      <div className="cf-filters-spacer" />
    </div>
  );
}

window.HeaderV2   = HeaderV2;
window.SidebarV2  = SidebarV2;
window.FilterBarV2 = FilterBarV2;
