// Panneau latéral gauche : recherche + filtres + liste groupée par couche
function Sidebar({ filtres, setFiltres, onPick, selected, accent, open, setOpen, extras, onAddTicker, addState, onRemoveTicker }) {
  const [addQ, setAddQ] = React.useState("");
  const submitAdd = () => { const v = addQ.trim(); if (v && !addState.loading) { onAddTicker(v); setAddQ(""); } };
  const toggleArr = (key, val) => setFiltres((f) => ({
    ...f, [key]: f[key].includes(val) ? f[key].filter((x) => x !== val) : [...f[key], val],
  }));
  const match = (s) =>
    (!filtres.tailles.length || filtres.tailles.includes(s.taille)) &&
    (!filtres.profils.length || filtres.profils.includes(s.profil)) &&
    (!filtres.q || (s.nom + " " + s.ticker + " " + s.these).toLowerCase().includes(filtres.q.toLowerCase()));

  const GEO_TAG = { AM: "AM", EU: "EU", AS: "AS" };

  if (!open) {
    return (
      <button onClick={() => setOpen(true)} style={{
        position: "absolute", top: 14, left: 14, zIndex: 30,
        fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.1em",
        padding: "9px 14px", borderRadius: 4, cursor: "pointer",
        background: "oklch(0.18 0.04 258 / 0.9)", color: "var(--ink)",
        border: "1px solid oklch(0.35 0.06 245)", backdropFilter: "blur(8px)",
      }}>☰ SOCIÉTÉS</button>
    );
  }

  return (
    <aside style={{
      position: "absolute", top: 0, left: 0, bottom: 0, width: 300, zIndex: 30,
      background: "oklch(0.15 0.035 258 / 0.93)", backdropFilter: "blur(12px)",
      borderRight: "1px solid oklch(0.32 0.06 248)",
      display: "flex", flexDirection: "column",
    }}>
      <div style={{ padding: "14px 16px 10px", borderBottom: "1px solid oklch(0.27 0.045 250)", display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.2em", color: accent }}>
            {window.MAP_SOCIETES.length} SOCIÉTÉS
          </span>
          <button onClick={() => setOpen(false)} aria-label="Replier" style={{
            background: "none", border: "none", color: "oklch(0.6 0.03 240)", cursor: "pointer",
            fontFamily: "var(--mono)", fontSize: 13, padding: 4,
          }}>◀</button>
        </div>
        <input
          value={filtres.q}
          onChange={(e) => setFiltres((f) => ({ ...f, q: e.target.value }))}
          placeholder="Rechercher — nom, ticker, mot-clé…"
          style={{
            fontFamily: "var(--mono)", fontSize: 12, padding: "9px 12px", width: "100%",
            background: "oklch(0.2 0.04 255)", border: `1px solid oklch(0.36 0.06 245)`,
            borderRadius: 4, color: "var(--ink)", outline: "none",
          }}
        />
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {SIZE_ORDER.map((sz) => (
            <button key={sz} onClick={() => toggleArr("tailles", sz)} style={chipStyle(filtres.tailles.includes(sz), accent)}>
              {sz}
            </button>
          ))}
          {Object.keys(PROFIL_LABEL).map((p) => (
            <button key={p} onClick={() => toggleArr("profils", p)} style={chipStyle(filtres.profils.includes(p), accent)}>
              {PROFIL_LABEL[p].toUpperCase()}
            </button>
          ))}
        </div>
        {/* Ajout d'un ticker via API — placé au siège réel */}
        <div style={{ display: "flex", gap: 6 }}>
          <input
            value={addQ}
            onChange={(e) => setAddQ(e.target.value.toUpperCase())}
            onKeyDown={(e) => { if (e.key === "Enter") submitAdd(); }}
            placeholder="+ Ticker (AAPL · SAP.DE · 005930.KS)"
            style={{
              fontFamily: "var(--mono)", fontSize: 11.5, padding: "8px 10px", flex: 1, minWidth: 0,
              background: "oklch(0.2 0.04 255)", border: `1px solid ${accent}55`,
              borderRadius: 4, color: "var(--ink)", outline: "none",
            }}
          />
          <button onClick={submitAdd} disabled={addState.loading} style={{
            fontFamily: "var(--mono)", fontSize: 12, padding: "0 12px", cursor: addState.loading ? "wait" : "pointer",
            background: accent + "22", border: `1px solid ${accent}`, borderRadius: 4, color: accent,
          }}>{addState.loading ? "…" : "→"}</button>
        </div>
        {addState.error ? (
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "oklch(0.7 0.14 25)", lineHeight: 1.4 }}>{addState.error}</div>
        ) : null}
      </div>

      <div style={{ overflowY: "auto", flex: 1, padding: "6px 0 20px" }}>
        {extras && extras.length ? (
          <div>
            <div style={{
              position: "sticky", top: 0, zIndex: 2,
              display: "flex", alignItems: "center", gap: 8,
              padding: "9px 16px 7px", background: "oklch(0.16 0.04 256 / 0.97)",
              fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em",
              color: accent, textTransform: "uppercase",
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: accent, flex: "none" }}></span>
              ★ RECHERCHÉES · {extras.length}
            </div>
            {extras.map(({ soc: s }) => {
              const isSel = selected && selected.id === s.id;
              return (
                <div key={s.id} style={{
                  display: "grid", gridTemplateColumns: "10px 1fr auto auto", alignItems: "center", gap: 9,
                  padding: "6px 16px",
                  background: isSel ? `oklch(0.28 0.06 240 / 0.6)` : "none",
                  borderLeft: isSel ? `2px solid ${accent}` : "2px solid transparent",
                }}>
                  <span style={{ width: 7, height: 7, borderRadius: "50%", justifySelf: "center", background: accent }}></span>
                  <button onClick={() => onPick(s)} style={{
                    background: "none", border: "none", textAlign: "left", cursor: "pointer", color: "var(--ink)",
                    fontFamily: "var(--sans)", fontSize: 12.5, fontWeight: isSel ? 600 : 440,
                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", padding: 0,
                  }}>{s.nom}</button>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 9.5, color: "oklch(0.58 0.04 240)" }}>{s.ticker}</span>
                  <button onClick={() => onRemoveTicker(s.id)} title="Retirer du globe" style={{
                    background: "none", border: "none", cursor: "pointer", color: "oklch(0.6 0.08 25)",
                    fontFamily: "var(--mono)", fontSize: 13, padding: "0 2px",
                  }}>✕</button>
                </div>
              );
            })}
          </div>
        ) : null}
        {window.MAP_LAYERS.map((layer) => {
          const socs = window.MAP_SOCIETES.filter((s) => s.couche === layer.id && match(s));
          if (!socs.length) return null;
          const hue = window.LAYER_HUES[layer.id];
          const dimLayer = filtres.couches.length && !filtres.couches.includes(layer.id);
          return (
            <div key={layer.id} style={{ opacity: dimLayer ? 0.4 : 1 }}>
              <div style={{
                position: "sticky", top: 0, zIndex: 2,
                display: "flex", alignItems: "center", gap: 8,
                padding: "9px 16px 7px", background: "oklch(0.16 0.04 256 / 0.97)",
                fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em",
                color: `oklch(0.72 0.1 ${hue})`, textTransform: "uppercase",
              }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: `oklch(0.7 0.13 ${hue})`, flex: "none" }}></span>
                {layer.id} · {layer.nom}
              </div>
              {socs.map((s) => {
                const isSel = selected && selected.id === s.id;
                return (
                  <button key={s.id} onClick={() => onPick(s)} style={{
                    display: "grid", gridTemplateColumns: "10px 1fr auto", alignItems: "center", gap: 9,
                    width: "100%", textAlign: "left", padding: "6px 16px",
                    background: isSel ? `oklch(0.28 0.07 ${hue} / 0.6)` : "none",
                    border: "none", borderLeft: isSel ? `2px solid ${accent}` : "2px solid transparent",
                    cursor: "pointer", color: "var(--ink)",
                  }}>
                    <span style={{
                      width: { MEGA: 10, LARGE: 8, MID: 6, SMALL: 4.5 }[s.taille],
                      height: { MEGA: 10, LARGE: 8, MID: 6, SMALL: 4.5 }[s.taille],
                      borderRadius: "50%", justifySelf: "center",
                      background: s.profil === "DISRUPTE" ? "oklch(0.5 0.13 25)" : `oklch(0.7 0.13 ${hue})`,
                      outline: s.profil === "SPEC" ? `1px dashed ${accent}` : "none", outlineOffset: 2,
                    }}></span>
                    <span style={{ fontFamily: "var(--sans)", fontSize: 12.5, fontWeight: isSel ? 600 : 440, lineHeight: 1.3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {s.nom}
                    </span>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 9.5, color: "oklch(0.58 0.04 240)" }}>
                      {s.ticker.length > 9 ? GEO_TAG[window.geoOf(s)] : s.ticker}
                    </span>
                  </button>
                );
              })}
            </div>
          );
        })}
      </div>
    </aside>
  );
}

function chipStyle(active, accent) {
  return {
    fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.08em",
    padding: "4px 8px", borderRadius: 999, cursor: "pointer",
    border: `1px solid ${active ? accent : "oklch(0.34 0.05 245)"}`,
    background: active ? accent + "22" : "none",
    color: active ? accent : "oklch(0.65 0.03 240)",
  };
}

Object.assign(window, { Sidebar });
