// SearchBar with live suggestions dropdown.

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS, useRef: useRefS, useCallback: useCallbackS } = React;

function SearchBar({ onSubmit, onSelect }) {
  const [q, setQ] = useStateS("");
  const [open, setOpen] = useStateS(false);
  const [activeIdx, setActiveIdx] = useStateS(-1);
  const wrapRef = useRefS(null);
  const inputRef = useRefS(null);
  const T = window.useT();

  const { CATEGORIES, CITIES, POPULAR_SEARCHES } = window.OSH_DATA;
  const PROFILES = window.OSH_PROFILES || [];

  // Build a unified, weighted suggestion list.
  const suggestions = useMemoS(() => {
    const term = q.trim().toLowerCase().replace(/^@/, "");
    const out = [];

    const matchCreators = (term
      ? PROFILES.filter(c =>
          (c.handle && c.handle.toLowerCase().includes(term)) ||
          (c.name && c.name.toLowerCase().includes(term)))
      : PROFILES.filter(c => c.img) // when empty, surface profiles that have a photo
    ).slice(0, 6);

    const matchCats = CATEGORIES.filter(c =>
      !term || c.fi.toLowerCase().includes(term) || c.slug.includes(term.replace(/\s/g, "-"))
    ).slice(0, 4);

    const matchCities = CITIES.filter(c =>
      !term || c.fi.toLowerCase().includes(term) || c.region.toLowerCase().includes(term)
    ).slice(0, 3);

    const matchPop = POPULAR_SEARCHES.filter(s =>
      !term || s.toLowerCase().includes(term)
    ).slice(0, 3);

    matchCreators.forEach((c) => out.push({ type: "creator", id: "cre-" + c.id, data: c }));
    matchCats.forEach((c) => out.push({ type: "category", id: "cat-" + c.slug, data: c }));
    matchCities.forEach((c) => out.push({ type: "city", id: "city-" + c.slug, data: c }));
    if (!term) matchPop.forEach((s, i) => out.push({ type: "popular", id: "pop-" + i, data: s }));

    return out;
  }, [q]);

  useEffectS(() => {
    function onDocClick(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  function handleKey(e) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setOpen(true);
      setActiveIdx(i => Math.min(suggestions.length - 1, i + 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIdx(i => Math.max(-1, i - 1));
    } else if (e.key === "Enter") {
      e.preventDefault();
      if (activeIdx >= 0 && suggestions[activeIdx]) {
        pick(suggestions[activeIdx]);
      } else {
        onSubmit && onSubmit(q);
      }
    } else if (e.key === "Escape") {
      setOpen(false);
      setActiveIdx(-1);
    }
  }

  function pick(s) {
    setOpen(false);
    setActiveIdx(-1);
    if (s.type === "creator") {
      const url = s.data.of || s.data.ig;
      if (url) window.open(url, "_blank", "noopener,noreferrer");
    }
    else if (s.type === "category") setQ(s.data.fi);
    else if (s.type === "city") setQ(s.data.fi);
    else if (s.type === "popular") setQ(s.data);
    onSelect && onSelect(s);
  }

  return (
    <div ref={wrapRef} style={{ position: "relative", width: "100%" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        background: "var(--surface)",
        border: "1.5px solid " + (open ? "var(--accent)" : "var(--line)"),
        borderRadius: 18,
        padding: "6px 6px 6px 22px",
        boxShadow: open ? "0 0 0 6px var(--halo), var(--shadow-lg)" : "var(--shadow-md)",
        transition: "border-color 160ms ease, box-shadow 200ms ease",
      }}>
        <span style={{ color: "var(--muted)", display: "inline-flex" }}><Icon.search width="22" height="22" /></span>
        <input
          ref={inputRef}
          type="text"
          value={q}
          onChange={(e) => { setQ(e.target.value); setOpen(true); setActiveIdx(-1); }}
          onFocus={() => setOpen(true)}
          onKeyDown={handleKey}
          placeholder={T("hero_placeholder")}
          aria-label={T("search_aria")}
          style={{
            flex: 1, border: "none", outline: "none", background: "transparent",
            color: "var(--ink)", fontSize: 18, fontWeight: 500, padding: "16px 0",
            fontFamily: "inherit", minWidth: 0,
          }}
        />
        {q ? (
          <button
            onClick={() => { setQ(""); inputRef.current?.focus(); }}
            aria-label={T("search_clear")}
            style={{
              background: "transparent", border: "none", color: "var(--muted)",
              cursor: "pointer", padding: 6, fontSize: 14,
            }}
          >{T("search_clear")}</button>
        ) : null}
        <button
          onClick={() => onSubmit && onSubmit(q)}
          style={{
            background: "var(--ink)", color: "var(--surface)", border: "none",
            borderRadius: 14, padding: "14px 22px", fontSize: 15, fontWeight: 600,
            cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8,
            transition: "transform 100ms ease",
          }}
          onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.97)"}
          onMouseUp={(e) => e.currentTarget.style.transform = "scale(1)"}
          onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
        >
          {T("search_submit")} <Icon.arrow />
        </button>
      </div>

      {open ? (
        <div style={{
          position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0,
          background: "var(--surface)", border: "1px solid var(--line)",
          borderRadius: 18, boxShadow: "var(--shadow-lg)",
          padding: 8, zIndex: 50, maxHeight: 460, overflowY: "auto",
        }}>
          {suggestions.length === 0 ? (
            <div style={{ padding: "24px 16px", color: "var(--muted)", fontSize: 14, textAlign: "center" }}>
              {T("sug_empty_a")} <b style={{ color: "var(--ink)" }}>"{q}"</b>. {T("sug_empty_b")} <i>Helsinki</i>{window.useLang() === "en" ? " or " : " tai "}<i>{window.useLang() === "en" ? "Goth" : "Gootti"}</i>.
            </div>
          ) : (
            <SuggestionList suggestions={suggestions} activeIdx={activeIdx} setActiveIdx={setActiveIdx} pick={pick} q={q} />
          )}
        </div>
      ) : null}
    </div>
  );
}

function SuggestionList({ suggestions, activeIdx, setActiveIdx, pick, q }) {
  const T = window.useT();
  // Group by type for visual sections.
  const grouped = {};
  suggestions.forEach((s, i) => {
    if (!grouped[s.type]) grouped[s.type] = [];
    grouped[s.type].push({ ...s, i });
  });
  const labels = {
    creator:  T("sug_creators"),
    category: T("sug_categories"),
    city:     T("sug_cities"),
    popular:  T("sug_popular"),
  };
  const order = ["creator", "category", "city", "popular"];

  return (
    <div>
      {order.filter(k => grouped[k]).map(k => (
        <div key={k} style={{ padding: "4px 0" }}>
          <div style={{
            fontSize: 10.5, fontWeight: 700, color: "var(--muted)",
            letterSpacing: "0.08em", textTransform: "uppercase",
            padding: "10px 12px 6px",
          }}>{labels[k]}</div>
          {grouped[k].map(s => (
            <SuggestionRow key={s.id} s={s} active={s.i === activeIdx}
                           onHover={() => setActiveIdx(s.i)} onClick={() => pick(s)} q={q} />
          ))}
        </div>
      ))}
    </div>
  );
}

function highlight(text, q) {
  if (!q) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx < 0) return text;
  return <>{text.slice(0, idx)}<mark style={{ background: "var(--accent-soft)", color: "var(--ink)", padding: "0 2px", borderRadius: 3 }}>{text.slice(idx, idx + q.length)}</mark>{text.slice(idx + q.length)}</>;
}

function SuggestionRow({ s, active, onHover, onClick, q }) {
  const T = window.useT();
  const lang = window.useLang();
  const term = (q || "").trim();
  const bg = active ? "var(--tag-bg-hover)" : "transparent";

  let icon, primary, secondary, meta;
  if (s.type === "creator") {
    const c = s.data;
    icon = c.img
      ? <img src={c.img} alt="" width={32} height={32} loading="lazy"
             style={{ width: 32, height: 32, borderRadius: 999, objectFit: "cover", display: "block", background: "var(--accent-soft)" }} />
      : <SilhouetteAvatar seed={(c.handle || c.name || "x").charCodeAt(0)} size={32} />;
    primary = <>{c.handle ? <>@{highlight(c.handle, term)}</> : highlight(c.name, term)} {c.verified ? <span style={{ display: "inline-flex", marginLeft: 4, color: "var(--accent)", verticalAlign: "middle" }} title={T("creators_verified")}><Icon.check /></span> : null}</>;
    secondary = <span style={{ color: "var(--muted)" }}>{highlight(c.name, term)}</span>;
    meta = <span style={{ fontSize: 11, color: "var(--accent)", fontWeight: 600 }}>{T("creators_visit")}</span>;
  } else if (s.type === "category") {
    const c = s.data;
    const name = (lang === "en" && c.en) ? c.en : c.fi;
    icon = <IconBubble><Icon.tag /></IconBubble>;
    primary = <>{highlight(name, term)}</>;
    secondary = <span style={{ color: "var(--muted)" }}>{T("sug_meta_cat")}</span>;
    meta = <span style={{ fontSize: 12, color: "var(--muted)", fontVariantNumeric: "tabular-nums" }}>{formatCount(c.count)} {T("count_creators")}</span>;
  } else if (s.type === "city") {
    const c = s.data;
    icon = <IconBubble><Icon.pin /></IconBubble>;
    primary = <>{highlight(c.fi, term)}</>;
    secondary = <span style={{ color: "var(--muted)" }}>{c.region}</span>;
    meta = <span style={{ fontSize: 12, color: "var(--muted)", fontVariantNumeric: "tabular-nums" }}>{formatCount(c.count)} {T("count_creators")}</span>;
  } else {
    icon = <IconBubble><Icon.search width="14" height="14" /></IconBubble>;
    primary = <>{highlight(s.data, term)}</>;
    secondary = <span style={{ color: "var(--muted)" }}>{T("sug_meta_pop")}</span>;
    meta = null;
  }

  return (
    <div
      onMouseEnter={onHover}
      onClick={onClick}
      style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "10px 12px", borderRadius: 12,
        cursor: "pointer", background: bg,
        transition: "background 100ms ease",
      }}
    >
      <div style={{ flexShrink: 0 }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--ink)", lineHeight: 1.3 }}>{primary}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", lineHeight: 1.3, marginTop: 1 }}>{secondary}</div>
      </div>
      {meta ? <div style={{ flexShrink: 0 }}>{meta}</div> : null}
      <span style={{ color: "var(--muted)", display: "inline-flex", opacity: active ? 1 : 0.4 }}><Icon.arrow /></span>
    </div>
  );
}

function IconBubble({ children }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      width: 32, height: 32, borderRadius: 999,
      background: "var(--accent-soft)", color: "var(--accent)",
    }}>{children}</span>
  );
}

Object.assign(window, { SearchBar });
