import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect } from 'react';

function SearchBar({ large = false }) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const debounceRef = useRef();
  useEffect(() => {
    if (query.length < 2) {
      setResults([]);
      return;
    }
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
        if (res.ok) setResults(await res.json());
      } catch {
      }
    }, 200);
    return () => clearTimeout(debounceRef.current);
  }, [query]);
  useEffect(() => {
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);
  const handleKeyDown = (e) => {
    if (e.key === "Enter" && query.trim().length >= 2) {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: "search", search_term: query.trim() });
      setOpen(false);
      window.location.href = `/zoeken?q=${encodeURIComponent(query.trim())}`;
    }
  };
  const searchUrl = `/zoeken?q=${encodeURIComponent(query.trim())}`;
  const handleViewAll = () => {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: "search", search_term: query.trim() });
  };
  return /* @__PURE__ */ jsxs("div", { ref, className: "relative z-[60] w-full", children: [
    /* @__PURE__ */ jsxs("div", { className: `relative flex items-center rounded-2xl border border-border/50 bg-bg-card transition-all focus-within:border-accent/50 focus-within:shadow-lg focus-within:shadow-accent/5 ${large ? "px-5 py-4" : "px-4 py-2.5"}`, children: [
      /* @__PURE__ */ jsx("svg", { className: "mr-3 h-5 w-5 shrink-0 text-text-muted", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" }) }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "text",
          value: query,
          onChange: (e) => {
            setQuery(e.target.value);
            setOpen(true);
          },
          onFocus: () => setOpen(true),
          onKeyDown: handleKeyDown,
          placeholder: "Zoek sneakers...",
          className: `w-full bg-transparent text-text placeholder-text-muted outline-none ${large ? "text-lg" : "text-sm"}`,
          "aria-label": "Zoek sneakers"
        }
      ),
      query && /* @__PURE__ */ jsx("button", { onClick: () => {
        setQuery("");
        setOpen(false);
      }, className: "ml-2 text-text-muted hover:text-text", "aria-label": "Zoekopdracht wissen", children: /* @__PURE__ */ jsx("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" }) }) })
    ] }),
    open && results.length > 0 && /* @__PURE__ */ jsxs("div", { className: "absolute left-0 right-0 top-full z-[100] mt-2 overflow-hidden rounded-2xl border border-border/50 bg-bg-card shadow-2xl", children: [
      results.map((s) => /* @__PURE__ */ jsxs(
        "a",
        {
          href: `/sneakers/${s.slug}`,
          className: "flex items-center gap-4 px-4 py-3 transition-colors hover:bg-bg-hover",
          onClick: () => {
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({ ecommerce: null });
            window.dataLayer.push({
              event: "select_item",
              ecommerce: {
                items: [{
                  item_id: s.id,
                  item_name: `${s.brand} ${s.name}`,
                  item_brand: s.brand,
                  price: s.lowestPrice
                }]
              }
            });
          },
          children: [
            /* @__PURE__ */ jsx("img", { src: s.image, alt: "", className: "h-12 w-12 rounded-lg bg-bg-elevated object-contain" }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
              /* @__PURE__ */ jsxs("div", { className: "truncate text-sm font-semibold text-text", children: [
                s.brand,
                " ",
                s.name
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "text-xs text-text-muted", children: [
                s.colorway,
                s.shopCount > 0 && ` · ${s.shopCount} ${s.shopCount === 1 ? "winkel" : "winkels"}`
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "text-sm font-bold text-accent", children: [
              "€",
              s.lowestPrice.toFixed(2).replace(".", ",")
            ] })
          ]
        },
        s.id
      )),
      /* @__PURE__ */ jsxs(
        "a",
        {
          href: searchUrl,
          onClick: handleViewAll,
          className: "flex items-center justify-center gap-2 border-t border-border/30 px-4 py-3 text-sm font-semibold text-accent transition-colors hover:bg-bg-hover",
          children: [
            "Bekijk alle resultaten",
            /* @__PURE__ */ jsx("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 5l7 7-7 7" }) })
          ]
        }
      )
    ] })
  ] });
}

export { SearchBar as S };
