// Global header — 48px. City/run from API, search calls /entities live.
// API-mode chip replaces the DEMO badge.

// React hooks (Babel-standalone — make hooks visible per-script)
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

const headerStyles = {
  root: {
    height: 48, flex: "0 0 48px",
    background: "var(--vk-surface-1)",
    borderBottom: "1px solid var(--vk-border-subtle)",
    display: "flex", alignItems: "center",
    padding: "0 16px", gap: 12,
    position: "sticky", top: 0, zIndex: 10,
  },
  select: {
    display: "flex", alignItems: "center", gap: 6,
    height: 28, padding: "0 10px", borderRadius: 3,
    background: "var(--vk-surface-2)",
    boxShadow: "var(--vk-ring-ambient)",
    cursor: "pointer", fontSize: 13,
    color: "var(--vk-text-primary)",
    userSelect: "none", position: "relative",
  },
  selectLabel: { fontSize: 11, color: "var(--vk-text-tertiary)", marginRight: 2 },
  searchWrap: {
    display: "flex", alignItems: "center", gap: 6,
    flex: 1, maxWidth: 360,
    height: 28, padding: "0 10px",
    background: "var(--vk-surface-2)",
    boxShadow: "var(--vk-ring-ambient)",
    borderRadius: 3,
    position: "relative",
  },
  searchInput: {
    flex: 1, height: "100%",
    background: "transparent", border: 0, outline: 0,
    color: "var(--vk-text-primary)",
    fontFamily: "var(--vk-font-sans)", fontSize: 13,
  },
  dropdown: {
    position: "absolute",
    top: "calc(100% + 4px)", left: 0, minWidth: "100%",
    background: "var(--vk-surface-2)",
    boxShadow: "0 0 0 1px rgba(233,30,99,0.30)",
    borderRadius: 5, padding: 4, zIndex: 20,
    display: "flex", flexDirection: "column", gap: 1,
    maxHeight: 320, overflowY: "auto",
  },
  dropdownItem: {
    padding: "6px 10px", fontSize: 13,
    color: "var(--vk-text-primary)", cursor: "pointer",
    borderRadius: 3, whiteSpace: "nowrap",
    display: "flex", alignItems: "center", gap: 6,
  },
};

function Dropdown({ label, value, options, onChange, minWidth = 0, renderItem }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    function handler(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);
  return (
    <div ref={ref} style={{ ...headerStyles.select, minWidth }} onClick={() => setOpen((o) => !o)}>
      <span style={headerStyles.selectLabel}>{label}</span>
      <span>{value}</span>
      <Icon name="ChevronDown" size={14} color="var(--vk-text-tertiary)" />
      {open && (
        <div style={headerStyles.dropdown} onClick={(e) => e.stopPropagation()}>
          {options.map((o, i) => (
            <div
              key={(o.value ?? o.label ?? o) + "_" + i}
              style={{
                ...headerStyles.dropdownItem,
                ...(value === (o.label || o) ? { background: "var(--vk-surface-3)" } : {}),
              }}
              onClick={() => { onChange(o); setOpen(false); }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--vk-surface-3)")}
              onMouseLeave={(e) =>
                (e.currentTarget.style.background = value === (o.label || o) ? "var(--vk-surface-3)" : "transparent")
              }
            >
              {renderItem ? renderItem(o) : (
                <>
                  {o.icon && <Icon name={o.icon} size={14} color="var(--vk-text-tertiary)" />}
                  {o.label || o}
                  {o.subtitle && (
                    <span style={{ marginLeft: 8, fontSize: 11, color: "var(--vk-text-tertiary)" }}>
                      {o.subtitle}
                    </span>
                  )}
                </>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// API-mode chip — replaces DEMO badge
function ApiModeChip() {
  const mode = useApiMode();
  const conf = {
    live:    { label: "Live",    color: "var(--vk-success)", bg: "rgba(93,202,165,0.12)", icon: "CircleDot" },
    preview: { label: "Preview", color: "var(--vk-warning)", bg: "rgba(240,153,61,0.14)", icon: "FlaskConical" },
    error:   { label: "Offline", color: "var(--vk-danger)",  bg: "rgba(226,75,106,0.14)", icon: "TriangleAlert" },
    loading: { label: "…",       color: "var(--vk-text-tertiary)", bg: "var(--vk-surface-2)", icon: "Loader" },
    unknown: { label: "…",       color: "var(--vk-text-tertiary)", bg: "var(--vk-surface-2)", icon: "Loader" },
  }[mode] || { label: mode, color: "var(--vk-text-secondary)", bg: "var(--vk-surface-2)", icon: "Info" };
  return (
    <span
      title={mode === "preview" ? "Backend unreachable — using local seed data" : (window.__VK_API_ERROR?.message || "")}
      style={{
        display: "inline-flex", alignItems: "center", gap: 4,
        height: 22, padding: "0 8px", borderRadius: 999,
        fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase",
        fontWeight: 500, background: conf.bg, color: conf.color,
      }}
    >
      <Icon name={conf.icon} size={12} />
      {conf.label}
    </span>
  );
}

// Search results dropdown (debounced)
function SearchDropdown({ search, onPick }) {
  const [debounced, setDebounced] = useState(search);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(search), 250);
    return () => clearTimeout(t);
  }, [search]);
  const { data, loading } = useApi("/entities", { search: debounced, limit: 8 }, [debounced]);
  if (!debounced) return null;
  const rows = Array.isArray(data) ? data : [];
  return (
    <div style={{ ...headerStyles.dropdown, top: 34, left: 0, right: 0, width: "auto" }}>
      {loading && <div style={{ padding: 8, fontSize: 11, color: "var(--vk-text-tertiary)" }}>searching…</div>}
      {!loading && rows.length === 0 && (
        <div style={{ padding: 8, fontSize: 11, color: "var(--vk-text-tertiary)" }}>no matches.</div>
      )}
      {rows.map((e) => (
        <div
          key={e.entity_id}
          style={headerStyles.dropdownItem}
          onClick={() => onPick(e)}
          onMouseEnter={(ev) => (ev.currentTarget.style.background = "var(--vk-surface-3)")}
          onMouseLeave={(ev) => (ev.currentTarget.style.background = "transparent")}
        >
          <span style={{ flex: 1, fontWeight: 500 }}>{e.canonical_name}</span>
          <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)" }}>{e.entity_type}</span>
          <Score value={e.influence_score} />
        </div>
      ))}
    </div>
  );
}

function Header({ onOpenEntity }) {
  const app = useAppState();

  const citiesQ = useApi("/cities", {});
  const cities = Array.isArray(citiesQ.data) ? citiesQ.data : [];

  const runsQ = useApi("/runs", { city: app.city }, [app.city]);
  const runs = Array.isArray(runsQ.data) ? runsQ.data : [];

  // Set default run when runs load
  useEffect(() => {
    if (runs.length && !app.runId) {
      const sorted = runs.slice().sort((a, b) => new Date(b.started_at) - new Date(a.started_at));
      app.setRunId(sorted[0].run_id);
      app.setRunLabel(fmtRunLabel(sorted[0].started_at));
    }
    // eslint-disable-next-line
  }, [runs.length]);

  const cityOptions = cities.length
    ? cities.map((c) => ({ label: c.city_selector_value || c.city_name, value: c.city_name }))
    : [{ label: app.city, value: app.city }];
  const runOptions = runs.length
    ? runs.map((r) => ({
        label: fmtRunLabel(r.started_at),
        value: r.run_id,
        subtitle: r.status,
        icon: r.status === "running" ? "CircleDot" : "CircleCheck",
      }))
    : [{ label: app.runLabel, value: app.runId }];

  return (
    <header style={headerStyles.root}>
      <Dropdown
        label="City"
        value={cities.find((c) => c.city_name === app.city)?.city_selector_value || app.city}
        options={cityOptions}
        onChange={(o) => app.setCity(o.value || o.label)}
        minWidth={170}
      />
      <Dropdown
        label="Run"
        value={app.runLabel}
        options={runOptions}
        onChange={(o) => {
          app.setRunId(o.value);
          app.setRunLabel(o.label);
        }}
        minWidth={200}
      />

      <div style={{ flex: 1 }} />

      <div style={headerStyles.searchWrap}>
        <Icon name="Search" size={14} color="var(--vk-text-tertiary)" />
        <input
          style={headerStyles.searchInput}
          placeholder="Search entities…"
          value={app.search}
          onChange={(e) => app.setSearch(e.target.value)}
        />
        {app.search && (
          <Icon name="X" size={14} color="var(--vk-text-tertiary)" style={{ cursor: "pointer" }} onClick={() => app.setSearch("")} />
        )}
        {app.search && (
          <SearchDropdown
            search={app.search}
            onPick={(e) => { onOpenEntity?.(e); app.setSearch(""); }}
          />
        )}
      </div>

      <ApiModeChip />

      <button className="vk-btn vk-btn--ghost" title="Notifications" aria-label="Notifications">
        <Icon name="Bell" size={15} />
      </button>
    </header>
  );
}

Object.assign(window, { Header, Dropdown, ApiModeChip });
