import { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import {
  Search,
  Tag,
  ShoppingBag,
  X,
  Sparkles,
  SearchX,
  Coins,
  ChevronDown,
  ChevronRight,
  Menu,
  Heart,
  User,
  Scale,
  Laptop,
  Smartphone,
  Camera,
  Headphones,
  Tv,
  Gamepad2,
  Watch,
  Home as HomeIcon,
  Zap,
  LayoutGrid,
  List as ListIcon,
  Rows3,
  Columns3,
  ChevronUp,
  SlidersHorizontal,
  PanelLeftClose,
  PanelLeftOpen,
} from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import SiteLayout from "@/components/SiteLayout";
import ProductCard, { ProductCardData } from "@/components/shop/ProductCard";
import LoadingSpinner from "@/components/LoadingSpinner";
import { formatPrice } from "@/lib/currency";
import { Price } from "@/components/ui/Price";
import { useCart } from "@/context/CartContext";

const client = createClient();

interface Category {
  id: number;
  name: string;
  slug: string;
  description?: string | null;
  image_url?: string | null;
  is_active?: boolean | null;
  sort_order?: number | null;
}

type Suggestion =
  | { kind: "product"; id: number; label: string; slug: string; image?: string | null; price?: number }
  | { kind: "tag"; label: string }
  | { kind: "category"; id: number; label: string };

/**
 * Shop catalog page with a marketplace-style yellow hero header:
 * - Top yellow bar with capsule search (category selector + circular search button)
 * - Utility icon cluster (compare / wishlist / user / cart)
 * - "Shop By Department" vertical sidebar + hero banner with promo CTA
 * - Secondary 3-up promo tile grid
 */
export default function Shop() {
  const [products, setProducts] = useState<ProductCardData[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [searchFocused, setSearchFocused] = useState(false);
  const [activeSuggestion, setActiveSuggestion] = useState(-1);
  const [activeCategory, setActiveCategory] = useState<number | "all">("all");
  // Search-scope category filter used INSIDE the search capsule (header dropdown).
  // "all" means search across all categories.
  const [searchCategory, setSearchCategory] = useState<number | "all">("all");
  // View-mode used by the new marketplace-style toolbar (grid density / list).
  // "grid4" = 4 columns (default), "grid3" = 3 columns, "grid2" = 2 columns, "list" = stacked list.
  const [viewMode, setViewMode] = useState<"grid4" | "grid3" | "grid2" | "list">("grid4");
  const [sortBy, setSortBy] = useState<"featured" | "price_asc" | "price_desc" | "newest">(
    "featured",
  );
  const [priceRange, setPriceRange] = useState<[number, number] | null>(null);
  // Left-side collapsible filter sidebar state.
  // On desktop the sidebar is visible by default; users can collapse it into a narrow rail.
  // On mobile it is hidden by default and opens as a slide-over panel.
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [selectedProductTypes, setSelectedProductTypes] = useState<string[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [sidebarSections, setSidebarSections] = useState<{
    category: boolean;
    price: boolean;
    productType: boolean;
    tags: boolean;
  }>({ category: true, price: true, productType: true, tags: true });
  const searchRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const [prodRes, catRes] = await Promise.all([
          client.entities.products.queryAll({
            query: { is_active: true },
            sort: "-featured,-id",
            limit: 200,
          }),
          client.entities.product_categories.queryAll({
            query: { is_active: true },
            sort: "sort_order",
            limit: 100,
          }),
        ]);
        const items = (prodRes?.data?.items || []) as ProductCardData[];
        setProducts(items);
        setCategories((catRes?.data?.items || []) as Category[]);
      } catch (e) {
        setProducts([]);
        setCategories([]);
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const priceBounds = useMemo<[number, number]>(() => {
    if (products.length === 0) return [0, 100];
    const prices = products.map((p) => Number(p.price) || 0);
    const lo = Math.floor(Math.min(...prices));
    const hi = Math.ceil(Math.max(...prices));
    return [lo, lo === hi ? hi + 1 : hi];
  }, [products]);

  useEffect(() => {
    if (!loading && priceRange === null && products.length > 0) {
      setPriceRange([priceBounds[0], priceBounds[1]]);
    }
  }, [loading, products.length, priceBounds, priceRange]);

  const priceFilterActive = useMemo(() => {
    if (!priceRange) return false;
    return priceRange[0] > priceBounds[0] || priceRange[1] < priceBounds[1];
  }, [priceRange, priceBounds]);

  const filtered = useMemo(() => {
    let list = [...products];
    // The sidebar/chip filter takes precedence when set; otherwise fall back to the
    // header search-scope category so the two surfaces stay consistent.
    const effectiveCategory =
      activeCategory !== "all" ? activeCategory : searchCategory;
    if (effectiveCategory !== "all") {
      list = list.filter((p) => (p as any).category_id === effectiveCategory);
    }
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      list = list.filter(
        (p) =>
          p.name.toLowerCase().includes(q) ||
          (p.description || "").toLowerCase().includes(q) ||
          (((p as any).tags as string) || "").toLowerCase().includes(q),
      );
    }
    if (priceRange) {
      const [lo, hi] = priceRange;
      list = list.filter((p) => {
        const price = Number(p.price) || 0;
        return price >= lo && price <= hi;
      });
    }
    if (selectedProductTypes.length > 0) {
      list = list.filter((p) =>
        selectedProductTypes.includes(((p as any).product_type as string) || ""),
      );
    }
    if (selectedTags.length > 0) {
      const selLower = selectedTags.map((t) => t.toLowerCase());
      list = list.filter((p) => {
        const raw = (((p as any).tags as string) || "").toLowerCase();
        const parts = raw
          .split(",")
          .map((t) => t.trim())
          .filter(Boolean);
        return selLower.some((s) => parts.includes(s));
      });
    }
    switch (sortBy) {
      case "price_asc":
        list.sort((a, b) => a.price - b.price);
        break;
      case "price_desc":
        list.sort((a, b) => b.price - a.price);
        break;
      case "newest":
        list.sort((a, b) => (b.id || 0) - (a.id || 0));
        break;
      default:
        list.sort((a, b) => {
          const fa = a.featured ? 1 : 0;
          const fb = b.featured ? 1 : 0;
          if (fa !== fb) return fb - fa;
          return (b.id || 0) - (a.id || 0);
        });
    }
    return list;
  }, [
    products,
    activeCategory,
    searchCategory,
    search,
    sortBy,
    priceRange,
    selectedProductTypes,
    selectedTags,
  ]);

  // Distinct product types present in the current product set, used by the
  // sidebar "Product type" filter. We count occurrences for display.
  const allProductTypes = useMemo(() => {
    const counts = new Map<string, number>();
    products.forEach((p) => {
      const t = ((p as any).product_type as string) || "";
      if (!t) return;
      counts.set(t, (counts.get(t) || 0) + 1);
    });
    return Array.from(counts.entries())
      .sort((a, b) => b[1] - a[1])
      .map(([type, count]) => ({ type, count }));
  }, [products]);

  const allTags = useMemo(() => {
    const set = new Set<string>();
    products.forEach((p) => {
      const raw = ((p as any).tags as string) || "";
      raw
        .split(",")
        .map((t) => t.trim())
        .filter(Boolean)
        .forEach((t) => set.add(t));
    });
    return Array.from(set);
  }, [products]);

  const popularPicks = useMemo(() => {
    return [...products]
      .filter((p) => p.featured)
      .slice(0, 4)
      .map((p) => p.name);
  }, [products]);

  const suggestions = useMemo<Suggestion[]>(() => {
    const q = search.trim().toLowerCase();
    if (!q) return [];
    const out: Suggestion[] = [];
    const seenLabel = new Set<string>();
    for (const p of products) {
      if (out.filter((s) => s.kind === "product").length >= 5) break;
      const name = p.name.toLowerCase();
      const desc = (p.description || "").toLowerCase();
      const tags = (((p as any).tags as string) || "").toLowerCase();
      if (name.includes(q) || desc.includes(q) || tags.includes(q)) {
        out.push({
          kind: "product",
          id: p.id,
          label: p.name,
          slug: (p as any).slug,
          image: (p as any).image_url,
          price: p.price,
        });
        seenLabel.add(p.name.toLowerCase());
      }
    }
    const matchedTags = allTags
      .filter((t) => t.toLowerCase().includes(q) && !seenLabel.has(t.toLowerCase()))
      .slice(0, 3);
    matchedTags.forEach((t) => out.push({ kind: "tag", label: t }));
    const matchedCats = categories
      .filter((c) => c.name.toLowerCase().includes(q))
      .slice(0, 2);
    matchedCats.forEach((c) => out.push({ kind: "category", id: c.id, label: c.name }));
    return out;
  }, [search, products, allTags, categories]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (!searchRef.current) return;
      if (!searchRef.current.contains(e.target as Node)) {
        setSearchFocused(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  useEffect(() => {
    setActiveSuggestion(-1);
  }, [search]);

  const applySuggestion = (s: Suggestion) => {
    if (s.kind === "product") {
      window.location.href = `/shop/${s.slug}`;
      return;
    }
    if (s.kind === "tag") {
      setSearch(s.label);
    }
    if (s.kind === "category") {
      setActiveCategory(s.id);
      setSearch("");
    }
    setSearchFocused(false);
  };

  const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (!searchFocused || suggestions.length === 0) return;
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveSuggestion((i) => (i + 1) % suggestions.length);
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveSuggestion((i) => (i <= 0 ? suggestions.length - 1 : i - 1));
    } else if (e.key === "Enter") {
      if (activeSuggestion >= 0 && activeSuggestion < suggestions.length) {
        e.preventDefault();
        applySuggestion(suggestions[activeSuggestion]);
      }
    } else if (e.key === "Escape") {
      setSearchFocused(false);
    }
  };

  const highlight = (text: string, q: string) => {
    if (!q) return text;
    const idx = text.toLowerCase().indexOf(q.toLowerCase());
    if (idx < 0) return text;
    return (
      <>
        {text.slice(0, idx)}
        <mark className="bg-[#fff4b8] text-slate-900 rounded px-0.5">
          {text.slice(idx, idx + q.length)}
        </mark>
        {text.slice(idx + q.length)}
      </>
    );
  };

  return (
    <SiteLayout>
      <MarketplaceHeroHeader
        search={search}
        setSearch={setSearch}
        searchFocused={searchFocused}
        setSearchFocused={setSearchFocused}
        searchRef={searchRef}
        handleSearchKeyDown={handleSearchKeyDown}
        activeSuggestion={activeSuggestion}
        setActiveSuggestion={setActiveSuggestion}
        suggestions={suggestions}
        applySuggestion={applySuggestion}
        popularPicks={popularPicks}
        allTags={allTags}
        filtered={filtered}
        categories={categories}
        activeCategory={activeCategory}
        setActiveCategory={setActiveCategory}
        searchCategory={searchCategory}
        setSearchCategory={setSearchCategory}
        highlight={highlight}
      />

      {/* Content */}
      <section className="max-w-7xl mx-auto px-4 md:px-6 py-8 md:py-10">
        {/* Mobile: "Filters" trigger button */}
        <div className="md:hidden mb-4">
          <button
            type="button"
            onClick={() => setSidebarOpen(true)}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-slate-200 bg-white text-sm font-semibold text-slate-700 hover:border-[#0b6e3e] hover:text-[#0b6e3e]"
          >
            <Menu className="w-4 h-4" /> Filters
            {(selectedProductTypes.length + selectedTags.length + (activeCategory !== "all" ? 1 : 0) + (priceFilterActive ? 1 : 0)) > 0 && (
              <span className="ml-1 inline-flex items-center justify-center w-5 h-5 rounded-full bg-[#0b6e3e] text-white text-[10px] font-bold">
                {selectedProductTypes.length + selectedTags.length + (activeCategory !== "all" ? 1 : 0) + (priceFilterActive ? 1 : 0)}
              </span>
            )}
          </button>
        </div>

        <div className="flex flex-col md:flex-row gap-6">
          {/* Left-side filter sidebar (desktop: inline collapsible; mobile: slide-over) */}
          <FilterSidebar
            open={sidebarOpen}
            onClose={() => setSidebarOpen(false)}
            onToggle={() => setSidebarOpen((v) => !v)}
            sections={sidebarSections}
            setSections={setSidebarSections}
            categories={categories}
            activeCategory={activeCategory}
            setActiveCategory={setActiveCategory}
            priceBounds={priceBounds}
            priceRange={priceRange ?? priceBounds}
            setPriceRange={setPriceRange}
            priceFilterActive={priceFilterActive}
            allProductTypes={allProductTypes}
            selectedProductTypes={selectedProductTypes}
            setSelectedProductTypes={setSelectedProductTypes}
            allTags={allTags}
            selectedTags={selectedTags}
            setSelectedTags={setSelectedTags}
            onClearAll={() => {
              setActiveCategory("all");
              setPriceRange([priceBounds[0], priceBounds[1]]);
              setSelectedProductTypes([]);
              setSelectedTags([]);
            }}
          />

          {/* Main column: breadcrumb, toolbar, grid */}
          <div className="flex-1 min-w-0">
        {/* Breadcrumb + Title + Results count (marketplace concept) */}
        {(() => {
          const activeCat =
            activeCategory !== "all"
              ? categories.find((c) => c.id === activeCategory)
              : null;
          const pageTitle = activeCat ? activeCat.name : search.trim() ? `Search: "${search}"` : "Shop";
          const breadcrumb = activeCat ? activeCat.name : "All products";
          return (
            <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-3 mb-4">
              <div>
                <div className="text-xs text-slate-400 font-medium mb-1">
                  <Link to="/shop" className="hover:text-[#0b6e3e]">Shop</Link>
                  <span className="mx-1.5">/</span>
                  <span className="text-slate-500">{breadcrumb}</span>
                </div>
                <h2 className="text-2xl md:text-3xl font-extrabold text-slate-900 tracking-tight">
                  {pageTitle}
                </h2>
              </div>
              <div className="text-sm text-slate-500">
                Showing{" "}
                <span className="font-bold text-slate-900">{filtered.length}</span>{" "}
                result{filtered.length === 1 ? "" : "s"}
              </div>
            </div>
          );
        })()}

        {/* Category pill filters */}
        <div className="flex items-center gap-2 flex-wrap mb-4">
          <button
            onClick={() => setActiveCategory("all")}
            className={`px-3.5 py-1.5 text-sm rounded-full border transition font-semibold ${
              activeCategory === "all"
                ? "bg-[#0b6e3e] text-white border-[#0b6e3e]"
                : "bg-white text-slate-700 border-slate-200 hover:border-[#0b6e3e]"
            }`}
          >
            All
          </button>
          {categories.map((c) => (
            <button
              key={c.id}
              onClick={() => setActiveCategory(c.id)}
              className={`px-3.5 py-1.5 text-sm rounded-full border transition font-semibold inline-flex items-center gap-1.5 ${
                activeCategory === c.id
                  ? "bg-[#0b6e3e] text-white border-[#0b6e3e]"
                  : "bg-white text-slate-700 border-slate-200 hover:border-[#0b6e3e]"
              }`}
            >
              <Tag className="w-3.5 h-3.5" /> {c.name}
            </button>
          ))}
        </div>

        {/* Gray marketplace-style toolbar: view-mode icons on the left, sort dropdown on the right */}
        <div className="bg-slate-100 rounded-lg px-3 py-2 mb-5 flex items-center justify-between gap-3 flex-wrap">
          <div className="flex items-center gap-1">
            {([
              { mode: "grid4", label: "4 columns", Icon: LayoutGrid },
              { mode: "grid3", label: "3 columns", Icon: Columns3 },
              { mode: "grid2", label: "2 columns", Icon: Rows3 },
              { mode: "list", label: "List view", Icon: ListIcon },
            ] as const).map(({ mode, label, Icon }) => (
              <button
                key={mode}
                type="button"
                onClick={() => setViewMode(mode)}
                aria-label={label}
                aria-pressed={viewMode === mode}
                className={`w-8 h-8 rounded-md flex items-center justify-center transition ${
                  viewMode === mode
                    ? "bg-white text-slate-900 shadow-sm ring-1 ring-slate-200"
                    : "text-slate-500 hover:text-slate-800 hover:bg-white/60"
                }`}
              >
                <Icon className="w-4 h-4" />
              </button>
            ))}
          </div>
          <div className="flex items-center gap-3 flex-wrap">
            <PriceRangeSlider
              bounds={priceBounds}
              value={priceRange ?? priceBounds}
              onChange={(v) => setPriceRange(v)}
            />
            <div className="relative">
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as typeof sortBy)}
                className="text-sm border border-slate-200 rounded-md pl-3 pr-8 py-1.5 bg-white font-medium text-slate-700 appearance-none focus:outline-none focus:ring-2 focus:ring-[#FFD500]"
              >
                <option value="featured">Default sorting</option>
                <option value="newest">Sort by newest</option>
                <option value="price_asc">Sort by price: low to high</option>
                <option value="price_desc">Sort by price: high to low</option>
              </select>
              <ChevronDown className="w-4 h-4 text-slate-400 absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none" />
            </div>
          </div>
        </div>

        {(search.trim() || activeCategory !== "all" || priceFilterActive) && (
          <div className="flex flex-wrap items-center gap-2 mb-6">
            <span className="text-xs font-bold uppercase tracking-widest text-slate-400 mr-1">
              Active filters:
            </span>
            {search.trim() && (
              <span className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full bg-[#0b6e3e]/10 text-[#0b6e3e] border border-[#0b6e3e]/20 font-semibold">
                <Search className="w-3 h-3" />
                "{search}"
                <button
                  onClick={() => setSearch("")}
                  aria-label="Clear search filter"
                  className="ml-1 hover:bg-[#0b6e3e]/20 rounded-full w-4 h-4 inline-flex items-center justify-center"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {activeCategory !== "all" && (
              <span className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 font-semibold">
                <Tag className="w-3 h-3" />
                {categories.find((c) => c.id === activeCategory)?.name || "Category"}
                <button
                  onClick={() => setActiveCategory("all")}
                  aria-label="Clear category filter"
                  className="ml-1 hover:bg-emerald-100 rounded-full w-4 h-4 inline-flex items-center justify-center"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {priceFilterActive && priceRange && (
              <span className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full bg-amber-50 text-amber-700 border border-amber-200 font-semibold">
                <Coins className="w-3 h-3" />SAR {priceRange[0]} – SAR {priceRange[1]}
                <button
                  onClick={() => setPriceRange([priceBounds[0], priceBounds[1]])}
                  aria-label="Clear price range filter"
                  className="ml-1 hover:bg-amber-100 rounded-full w-4 h-4 inline-flex items-center justify-center"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            <button
              onClick={() => {
                setSearch("");
                setActiveCategory("all");
                setPriceRange([priceBounds[0], priceBounds[1]]);
              }}
              className="text-xs font-semibold text-slate-500 hover:text-[#0b6e3e] underline ml-1"
            >
              Clear all
            </button>
          </div>
        )}

        {loading ? (
          <div className="py-24 flex justify-center">
            <LoadingSpinner />
          </div>
        ) : filtered.length === 0 ? (
          <div className="py-20 md:py-24 text-center max-w-xl mx-auto">
            <div className="w-20 h-20 mx-auto rounded-full bg-gradient-to-br from-slate-100 to-slate-50 border border-slate-200 flex items-center justify-center mb-5">
              <SearchX className="w-10 h-10 text-slate-400" />
            </div>
            <h3 className="text-xl md:text-2xl font-extrabold text-slate-900">
              {search.trim()
                ? <>No products match <span className="text-[#0b6e3e]">"{search}"</span></>
                : "No products in this category yet"}
            </h3>
            <p className="mt-2 text-slate-500">
              {search.trim()
                ? "Try checking your spelling, using more general keywords, or browsing a different category."
                : "Check back soon — new products are added all the time."}
            </p>

            {(allTags.length > 0 || categories.length > 0) && (
              <div className="mt-6">
                <div className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-2">
                  Try searching for
                </div>
                <div className="flex flex-wrap gap-2 justify-center">
                  {[...allTags.slice(0, 5), ...categories.slice(0, 3).map((c) => c.name)].slice(0, 8).map((t, i) => (
                    <button
                      key={`${t}-${i}`}
                      onClick={() => {
                        setSearch(t);
                        setActiveCategory("all");
                      }}
                      className="px-3 py-1.5 text-sm rounded-full bg-white border border-slate-200 text-slate-700 hover:border-[#0b6e3e] hover:text-[#0b6e3e] transition font-semibold"
                    >
                      {t}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="mt-6 flex items-center justify-center gap-3">
              <button
                onClick={() => {
                  setSearch("");
                  setActiveCategory("all");
                  setPriceRange([priceBounds[0], priceBounds[1]]);
                }}
                className="px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-semibold hover:bg-[#0a8048] transition"
              >
                Clear search & filters
              </button>
              <Link
                to="/services"
                className="px-5 py-2.5 rounded-xl bg-white border border-slate-200 text-slate-700 font-semibold hover:border-[#0b6e3e] hover:text-[#0b6e3e] transition"
              >
                Browse services
              </Link>
            </div>
          </div>
        ) : (
          <>
            {search.trim() && (
              <div className="mb-5 text-sm text-slate-600">
                <span className="font-bold text-slate-900">{filtered.length}</span> result
                {filtered.length === 1 ? "" : "s"} for{" "}
                <span className="font-semibold text-[#0b6e3e]">"{search}"</span>
                <button
                  onClick={() => setSearch("")}
                  className="ml-3 text-xs font-semibold text-slate-500 hover:text-[#0b6e3e] underline"
                >
                  Clear
                </button>
              </div>
            )}
            <div
              className={
                viewMode === "list"
                  ? "grid grid-cols-1 gap-3"
                  : viewMode === "grid2"
                    ? "grid grid-cols-1 sm:grid-cols-2 gap-4 md:gap-6"
                    : viewMode === "grid3"
                      ? "grid grid-cols-2 md:grid-cols-3 gap-4 md:gap-6"
                      : "grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6"
              }
            >
              {filtered.map((p) => (
                <ProductCard key={p.id} product={p} />
              ))}
            </div>
            <div className="mt-8 text-sm text-slate-500">
              Showing{" "}
              <span className="font-bold text-slate-900">{filtered.length}</span>{" "}
              result{filtered.length === 1 ? "" : "s"}
            </div>
          </>
        )}
          </div>
        </div>
      </section>

      <section className="max-w-6xl mx-auto px-4 md:px-6 pb-16">
        <div className="bg-gradient-to-br from-slate-50 to-white border border-slate-200 rounded-2xl p-6 md:p-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
          <div>
            <div className="text-xs uppercase tracking-widest font-bold text-[#0b6e3e]">
              Looking for hosting plans?
            </div>
            <h3 className="text-xl md:text-2xl font-bold text-slate-900 mt-1">
              Browse our full hosting & IT services
            </h3>
            <p className="text-sm text-slate-600 mt-1">
              Shared, Cloud VPS, dedicated servers, business email and more.
            </p>
          </div>
          <Link
            to="/services"
            className="px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-semibold hover:bg-[#0a8048] transition"
          >
            View services →
          </Link>
        </div>
      </section>
    </SiteLayout>
  );
}

/* =========================================================================
 * Marketplace-style hero header
 * ---------------------------------------------------------------------- */

interface MarketplaceHeroHeaderProps {
  search: string;
  setSearch: (v: string) => void;
  searchFocused: boolean;
  setSearchFocused: (v: boolean) => void;
  searchRef: React.MutableRefObject<HTMLDivElement | null>;
  handleSearchKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  activeSuggestion: number;
  setActiveSuggestion: (n: number) => void;
  suggestions: Suggestion[];
  applySuggestion: (s: Suggestion) => void;
  popularPicks: string[];
  allTags: string[];
  filtered: ProductCardData[];
  categories: Category[];
  activeCategory: number | "all";
  setActiveCategory: (v: number | "all") => void;
  searchCategory: number | "all";
  setSearchCategory: (v: number | "all") => void;
  highlight: (text: string, q: string) => React.ReactNode;
}

/**
 * A classic marketplace header with:
 * - Bright yellow top bar housing a capsule search (category selector + circular submit)
 * - Utility icons (compare / wishlist / account / cart)
 * - "Shop By Department" sidebar paired with a hero banner
 * - Three promotional tiles beneath the banner
 */
function MarketplaceHeroHeader({
  search,
  setSearch,
  searchFocused,
  setSearchFocused,
  searchRef,
  handleSearchKeyDown,
  activeSuggestion,
  setActiveSuggestion,
  suggestions,
  applySuggestion,
  popularPicks,
  allTags,
  filtered,
  categories,
  activeCategory,
  setActiveCategory,
  searchCategory,
  setSearchCategory,
  highlight,
}: MarketplaceHeroHeaderProps) {
  const { itemCount, subtotal } = useCart();
  const [deptOpen, setDeptOpen] = useState(true);
  const [catOpen, setCatOpen] = useState(false);
  const catBtnRef = useRef<HTMLDivElement | null>(null);

  // Close the capsule category dropdown on outside click.
  useEffect(() => {
    const h = (e: MouseEvent) => {
      if (!catBtnRef.current) return;
      if (!catBtnRef.current.contains(e.target as Node)) setCatOpen(false);
    };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);

  // Static department list. Uses real categories when available and falls back
  // to a common set of department labels so the sidebar always has content.
  const departments = useMemo(() => {
    const staticPrefix = [
      { label: "Value of the Day", slug: "__value", icon: Zap, highlight: true },
      { label: "Top 100 Offers", slug: "__top100", icon: Sparkles, highlight: true },
      { label: "New Arrivals", slug: "__new", icon: ShoppingBag, highlight: true },
    ];
    const iconMap: Record<string, any> = {
      laptop: Laptop,
      computer: Laptop,
      phone: Smartphone,
      mobile: Smartphone,
      camera: Camera,
      headphone: Headphones,
      audio: Headphones,
      tv: Tv,
      video: Tv,
      game: Gamepad2,
      watch: Watch,
      home: HomeIcon,
    };
    const dynamic = categories.slice(0, 9).map((c) => {
      const key = Object.keys(iconMap).find((k) => c.name.toLowerCase().includes(k));
      return { id: c.id, label: c.name, icon: key ? iconMap[key] : Tag };
    });
    return { staticPrefix, dynamic };
  }, [categories]);

  const activeCatLabel =
    searchCategory === "all"
      ? "All Categories"
      : categories.find((c) => c.id === searchCategory)?.name || "All Categories";

  return (
    <>
      {/* Yellow top strip — capsule search + utility icons */}
      <div className="bg-[#FFD500] border-b-4 border-[#f5c400]">
        <div className="max-w-7xl mx-auto px-4 md:px-6 py-3 md:py-4">
          <div className="flex items-center gap-3 md:gap-6">
            {/* Brand lockup */}
            <Link
              to="/shop"
              className="hidden sm:flex items-center gap-2 font-black text-slate-900 whitespace-nowrap"
            >
              <div className="w-9 h-9 rounded-full bg-slate-900 text-[#FFD500] flex items-center justify-center shadow-lg shadow-amber-900/20">
                <ShoppingBag className="w-5 h-5" />
              </div>
              <div className="leading-tight">
                <div className="text-base font-black tracking-tight">DoItEasy</div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-slate-700/80">
                  Shop
                </div>
              </div>
            </Link>

            {/* Capsule search */}
            <div
              className="flex-1 min-w-0 relative"
              ref={searchRef}
            >
              <div className="flex items-stretch bg-white rounded-full shadow-md ring-1 ring-black/5 overflow-hidden h-11 md:h-12">
                <input
                  value={search}
                  onFocus={() => setSearchFocused(true)}
                  onChange={(e) => {
                    setSearch(e.target.value);
                    setSearchFocused(true);
                  }}
                  onKeyDown={handleSearchKeyDown}
                  placeholder="Search for Products"
                  aria-label="Search products"
                  aria-expanded={searchFocused && (suggestions.length > 0 || !search)}
                  aria-controls="shop-search-suggestions"
                  role="combobox"
                  className="flex-1 min-w-0 px-4 md:px-5 text-sm md:text-[15px] text-slate-900 placeholder:text-slate-400 bg-transparent focus:outline-none"
                />

                {/* Divider */}
                <div className="hidden sm:block w-px bg-slate-200 my-2" />

                {/* Category dropdown trigger */}
                <div ref={catBtnRef} className="hidden sm:block relative">
                  <button
                    type="button"
                    onClick={() => setCatOpen((v) => !v)}
                    aria-haspopup="listbox"
                    aria-expanded={catOpen}
                    className="h-full inline-flex items-center gap-1.5 px-4 text-sm font-semibold text-slate-700 hover:text-slate-900 whitespace-nowrap"
                  >
                    <span className="max-w-[160px] truncate">{activeCatLabel}</span>
                    <ChevronDown className={`w-4 h-4 transition ${catOpen ? "rotate-180" : ""}`} />
                  </button>
                  {catOpen && (
                    <div className="absolute right-0 top-full mt-2 w-64 bg-white rounded-xl shadow-2xl ring-1 ring-black/5 py-2 z-40 max-h-80 overflow-y-auto">
                      <button
                        onClick={() => {
                          setSearchCategory("all");
                          setCatOpen(false);
                        }}
                        className={`w-full text-left px-4 py-2 text-sm font-semibold ${
                          searchCategory === "all"
                            ? "bg-[#FFD500]/20 text-slate-900"
                            : "hover:bg-slate-50 text-slate-700"
                        }`}
                      >
                        All Categories
                      </button>
                      <div className="my-1 border-t border-slate-100" />
                      {categories.map((c) => (
                        <button
                          key={c.id}
                          onClick={() => {
                            setSearchCategory(c.id);
                            setCatOpen(false);
                          }}
                          className={`w-full text-left px-4 py-2 text-sm font-semibold ${
                            searchCategory === c.id
                              ? "bg-[#FFD500]/20 text-slate-900"
                              : "hover:bg-slate-50 text-slate-700"
                          }`}
                        >
                          {c.name}
                        </button>
                      ))}
                      {categories.length === 0 && (
                        <div className="px-4 py-2 text-xs text-slate-400">
                          No categories yet
                        </div>
                      )}
                    </div>
                  )}
                </div>

                {/* Circular search submit button */}
                <button
                  type="button"
                  onClick={() => setSearchFocused(true)}
                  aria-label="Search"
                  className="flex items-center justify-center w-11 h-11 md:w-12 md:h-12 bg-slate-900 text-white hover:bg-slate-800 transition"
                >
                  <Search className="w-4 h-4 md:w-5 md:h-5" />
                </button>
              </div>

              {/* Clear button */}
              {search && (
                <button
                  onClick={() => {
                    setSearch("");
                    setSearchFocused(true);
                  }}
                  aria-label="Clear search"
                  className="absolute right-[96px] sm:right-[240px] top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600 inline-flex items-center justify-center transition"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              )}

              {/* Suggestions dropdown */}
              {searchFocused && (
                <div
                  id="shop-search-suggestions"
                  role="listbox"
                  className="absolute left-0 right-0 top-full mt-2 bg-white rounded-2xl shadow-2xl ring-1 ring-black/5 overflow-hidden z-30 max-h-[420px] overflow-y-auto"
                >
                  {search.trim() === "" ? (
                    <div className="p-4">
                      <div className="text-xs font-bold uppercase tracking-widest text-slate-400 px-2 pb-2 inline-flex items-center gap-1.5">
                        <Sparkles className="w-3.5 h-3.5 text-[#f5c400]" /> Popular searches
                      </div>
                      {popularPicks.length === 0 && allTags.length === 0 ? (
                        <div className="px-2 py-3 text-sm text-slate-500">
                          Start typing to search the catalog.
                        </div>
                      ) : (
                        <div className="flex flex-wrap gap-2 px-2">
                          {[...popularPicks, ...allTags.slice(0, 6)].slice(0, 8).map((t, i) => (
                            <button
                              key={`${t}-${i}`}
                              onClick={() => {
                                setSearch(t);
                              }}
                              className="px-3 py-1.5 text-sm rounded-full bg-slate-50 hover:bg-slate-900 hover:text-[#FFD500] text-slate-700 border border-slate-200 transition font-semibold"
                            >
                              {t}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  ) : suggestions.length === 0 ? (
                    <div className="p-6 text-center text-slate-500">
                      <SearchX className="w-8 h-8 mx-auto mb-2 text-slate-300" />
                      <p className="text-sm font-medium">
                        No suggestions for <span className="text-slate-900">"{search}"</span>
                      </p>
                      <p className="text-xs text-slate-400 mt-1">Try a different keyword or browse all products below.</p>
                    </div>
                  ) : (
                    <ul className="py-2">
                      {suggestions.map((s, i) => {
                        const isActive = i === activeSuggestion;
                        return (
                          <li key={`${s.kind}-${i}`} role="option" aria-selected={isActive}>
                            <button
                              onMouseEnter={() => setActiveSuggestion(i)}
                              onClick={() => applySuggestion(s)}
                              className={`w-full text-left px-4 py-2.5 flex items-center gap-3 transition ${
                                isActive ? "bg-[#FFD500]/15" : "hover:bg-slate-50"
                              }`}
                            >
                              {s.kind === "product" ? (
                                <>
                                  <div className="w-10 h-10 rounded-lg bg-slate-100 overflow-hidden flex-shrink-0">
                                    {s.image ? (
                                      <img src={s.image} alt="" className="w-full h-full object-cover" />
                                    ) : (
                                      <div className="w-full h-full flex items-center justify-center text-slate-300">
                                        <ShoppingBag className="w-5 h-5" />
                                      </div>
                                    )}
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <div className="text-sm font-semibold text-slate-900 truncate">
                                      {highlight(s.label, search)}
                                    </div>
                                    <div className="text-xs text-slate-500 inline-flex items-center gap-1">
                                      <span>Product</span>
                                      {typeof s.price === "number" && (
                                        <>
                                          <span>·</span>
                                          <Price amount={s.price} />
                                        </>
                                      )}
                                    </div>
                                  </div>
                                </>
                              ) : s.kind === "tag" ? (
                                <>
                                  <div className="w-10 h-10 rounded-lg bg-amber-50 text-amber-600 flex items-center justify-center flex-shrink-0">
                                    <Tag className="w-4 h-4" />
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <div className="text-sm font-semibold text-slate-900 truncate">
                                      {highlight(s.label, search)}
                                    </div>
                                    <div className="text-xs text-slate-500">Tag</div>
                                  </div>
                                </>
                              ) : (
                                <>
                                  <div className="w-10 h-10 rounded-lg bg-emerald-50 text-emerald-700 flex items-center justify-center flex-shrink-0">
                                    <Filter className="w-4 h-4" />
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <div className="text-sm font-semibold text-slate-900 truncate">
                                      {highlight(s.label, search)}
                                    </div>
                                    <div className="text-xs text-slate-500">Category</div>
                                  </div>
                                </>
                              )}
                            </button>
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </div>
              )}
            </div>

            {/* Utility icons */}
            <div className="hidden md:flex items-center gap-1 lg:gap-2">
              <UtilityIcon label="Compare" icon={Scale} badge={0} />
              <UtilityIcon label="Wishlist" icon={Heart} badge={0} />
              <UtilityIcon label="Account" icon={User} to="/dashboard" />
              <Link
                to="/shop/cart"
                className="group relative flex items-center gap-2 px-2.5 py-1.5 rounded-lg hover:bg-black/5 transition"
                aria-label={`View cart — ${itemCount} items`}
              >
                <div className="relative">
                  <ShoppingBag className="w-6 h-6 text-slate-900" />
                  <span className="absolute -top-1 -right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-slate-900 text-[#FFD500] text-[10px] font-extrabold flex items-center justify-center">
                    {itemCount}
                  </span>
                </div>
                <div className="text-left hidden lg:block leading-tight">
                  <div className="text-[10px] font-bold uppercase tracking-widest text-slate-700/80">
                    My Cart
                  </div>
                  <div className="text-sm font-extrabold text-slate-900">
                    <Price amount={subtotal} />
                  </div>
                </div>
              </Link>
            </div>

            {/* Mobile cart */}
            <Link
              to="/shop/cart"
              aria-label={`View cart — ${itemCount} items`}
              className="md:hidden relative p-2 rounded-lg hover:bg-black/5"
            >
              <ShoppingBag className="w-6 h-6 text-slate-900" />
              {itemCount > 0 && (
                <span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-slate-900 text-[#FFD500] text-[10px] font-extrabold flex items-center justify-center">
                  {itemCount}
                </span>
              )}
            </Link>
          </div>
        </div>
      </div>

      {/* Department sidebar + hero banner */}
      <section className="bg-white border-b border-slate-200">
        <div className="max-w-7xl mx-auto px-4 md:px-6 py-6">
          <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-6">
            {/* Departments sidebar */}
            <aside className="bg-white rounded-2xl border border-slate-200 overflow-hidden self-start">
              <button
                onClick={() => setDeptOpen((v) => !v)}
                className="w-full flex items-center justify-between gap-2 px-4 py-3.5 bg-slate-900 text-white font-extrabold"
              >
                <span className="inline-flex items-center gap-2">
                  <Menu className="w-4 h-4 text-[#FFD500]" />
                  Shop By Department
                </span>
                <ChevronDown
                  className={`w-4 h-4 transition ${deptOpen ? "" : "-rotate-90"}`}
                />
              </button>
              {deptOpen && (
                <ul className="divide-y divide-slate-100">
                  {departments.staticPrefix.map((d) => {
                    const Icon = d.icon;
                    return (
                      <li key={d.slug}>
                        <button
                          onClick={() => {
                            setActiveCategory("all");
                            setSearchCategory("all");
                          }}
                          className="w-full px-4 py-2.5 flex items-center justify-between gap-3 text-left hover:bg-[#FFD500]/15 transition"
                        >
                          <span className="inline-flex items-center gap-2.5 text-sm font-bold text-slate-800">
                            <Icon className="w-4 h-4 text-[#c99400]" />
                            {d.label}
                          </span>
                        </button>
                      </li>
                    );
                  })}
                  {departments.dynamic.map((d) => {
                    const Icon = d.icon;
                    const selected = activeCategory === d.id;
                    return (
                      <li key={d.id}>
                        <button
                          onClick={() => setActiveCategory(d.id)}
                          className={`w-full px-4 py-2.5 flex items-center justify-between gap-3 text-left transition ${
                            selected
                              ? "bg-[#FFD500]/25 text-slate-900"
                              : "hover:bg-slate-50 text-slate-700"
                          }`}
                        >
                          <span className="inline-flex items-center gap-2.5 text-sm font-semibold">
                            <Icon className="w-4 h-4 text-slate-500" />
                            {d.label}
                          </span>
                          <ChevronRight className="w-3.5 h-3.5 text-slate-400" />
                        </button>
                      </li>
                    );
                  })}
                  {departments.dynamic.length === 0 && (
                    <li className="px-4 py-3 text-xs text-slate-400">
                      Departments will appear here as categories are added.
                    </li>
                  )}
                </ul>
              )}
            </aside>

            {/* Hero banner */}
            <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-slate-50 via-white to-slate-100 border border-slate-200 min-h-[280px] md:min-h-[340px]">
              {/* Decorative geometric shapes */}
              <div className="absolute inset-0 pointer-events-none">
                <div className="absolute -top-16 -right-20 w-80 h-80 rounded-full bg-[#FFD500]/25 blur-3xl" />
                <div className="absolute -bottom-20 -left-16 w-72 h-72 rounded-full bg-slate-200/70 blur-3xl" />
              </div>

              <div className="relative grid grid-cols-1 md:grid-cols-2 gap-4 p-6 md:p-10 h-full">
                <div className="flex flex-col justify-center">
                  <div className="inline-flex items-center gap-2 w-fit bg-slate-900 text-[#FFD500] px-3 py-1 rounded-full text-[10px] font-extrabold uppercase tracking-widest">
                    <Sparkles className="w-3.5 h-3.5" /> Trending Now
                  </div>
                  <h1 className="mt-3 text-3xl md:text-5xl font-black text-slate-900 leading-[1.05] tracking-tight">
                    THE NEW
                    <br />
                    STANDARD
                  </h1>
                  <p className="mt-3 text-sm md:text-base text-slate-600 max-w-md">
                    Gear, digital goods & hosting boosts — everything you need to run a better business online, in one shop.
                  </p>
                  <div className="mt-5 flex items-end gap-4">
                    <div>
                      <div className="text-[10px] font-bold uppercase tracking-widest text-slate-500">
                        Starting from
                      </div>
                      <div className="flex items-start gap-0.5 text-slate-900">
                        <span className="text-[11px] font-bold mt-1.5">SAR</span>
                        <span className="text-4xl md:text-5xl font-black leading-none">99</span>
                        <span className="text-sm font-bold mt-1.5">.00</span>
                      </div>
                    </div>
                    <button
                      onClick={() => {
                        const el = document.getElementById("shop-grid-top");
                        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
                      }}
                      className="ml-auto md:ml-0 px-6 py-3 rounded-full bg-[#FFD500] text-slate-900 font-extrabold text-sm hover:bg-[#f5c400] transition shadow-lg shadow-amber-900/10 inline-flex items-center gap-2"
                    >
                      Start Buying <ChevronRight className="w-4 h-4" />
                    </button>
                  </div>

                  {/* Slide pagination dots */}
                  <div className="mt-6 flex items-center gap-2">
                    <span className="w-6 h-2 rounded-full bg-[#FFD500]" aria-hidden />
                    <span className="w-2 h-2 rounded-full bg-slate-300" aria-hidden />
                    <span className="w-2 h-2 rounded-full bg-slate-300" aria-hidden />
                  </div>
                </div>

                {/* Product visual */}
                <div className="relative hidden md:flex items-center justify-center">
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="w-64 h-64 rounded-full bg-white/70 ring-1 ring-slate-200" />
                  </div>
                  <div className="relative grid grid-cols-2 gap-4">
                    <HeroProductBadge icon={Watch} label="Wearables" tint="bg-slate-900 text-[#FFD500]" />
                    <HeroProductBadge icon={Laptop} label="Laptops" tint="bg-[#FFD500] text-slate-900" />
                    <HeroProductBadge icon={Headphones} label="Audio" tint="bg-[#FFD500] text-slate-900" />
                    <HeroProductBadge icon={Smartphone} label="Mobile" tint="bg-slate-900 text-[#FFD500]" />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Promo tiles */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-6" id="shop-grid-top">
            <PromoTile
              tagline="Save on smart gear"
              title="CAMERAS & DRONES"
              subtitle="Up to 30% off featured models"
              icon={Camera}
            />
            <PromoTile
              tagline="New season"
              title="MOBILE ACCESSORIES"
              subtitle="Chargers, cases, cables & more"
              icon={Smartphone}
            />
            <PromoTile
              tagline="Boost your office"
              title="COMPUTING DEALS"
              subtitle="Laptops, desktops & peripherals"
              icon={Laptop}
            />
          </div>
        </div>
      </section>

      {/* Live result counter */}
      {search.trim() && !searchFocused && (
        <div className="max-w-7xl mx-auto px-4 md:px-6 pt-4 text-xs text-slate-500">
          {filtered.length} result{filtered.length === 1 ? "" : "s"} for{" "}
          <span className="text-slate-900 font-semibold">"{search}"</span>
        </div>
      )}
    </>
  );
}

/* =========================================================================
 * Helper atoms used by the hero header
 * ---------------------------------------------------------------------- */

interface UtilityIconProps {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  badge?: number;
  to?: string;
}
function UtilityIcon({ icon: Icon, label, badge, to }: UtilityIconProps) {
  const content = (
    <div className="relative inline-flex items-center justify-center w-10 h-10 rounded-lg hover:bg-black/10 transition">
      <Icon className="w-5 h-5 text-slate-900" />
      {typeof badge === "number" && (
        <span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-slate-900 text-[#FFD500] text-[10px] font-extrabold flex items-center justify-center">
          {badge}
        </span>
      )}
    </div>
  );
  if (to) {
    return (
      <Link to={to} aria-label={label} title={label}>
        {content}
      </Link>
    );
  }
  return (
    <button type="button" aria-label={label} title={label}>
      {content}
    </button>
  );
}

interface HeroProductBadgeProps {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  tint: string;
}
function HeroProductBadge({ icon: Icon, label, tint }: HeroProductBadgeProps) {
  return (
    <div
      className={`w-28 h-28 md:w-32 md:h-32 rounded-2xl ${tint} flex flex-col items-center justify-center shadow-xl shadow-slate-900/10 transition-transform hover:-translate-y-1`}
    >
      <Icon className="w-8 h-8 mb-2" />
      <div className="text-[11px] font-extrabold uppercase tracking-widest">{label}</div>
    </div>
  );
}

interface PromoTileProps {
  tagline: string;
  title: string;
  subtitle: string;
  icon: React.ComponentType<{ className?: string }>;
}
function PromoTile({ tagline, title, subtitle, icon: Icon }: PromoTileProps) {
  return (
    <div className="group relative overflow-hidden rounded-2xl bg-slate-50 border border-slate-200 p-5 hover:border-[#FFD500] hover:shadow-lg transition">
      <div className="flex items-start gap-4">
        <div className="w-14 h-14 rounded-xl bg-white border border-slate-200 flex items-center justify-center flex-shrink-0">
          <Icon className="w-7 h-7 text-slate-700" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-[10px] font-bold uppercase tracking-widest text-[#c99400]">
            {tagline}
          </div>
          <div className="mt-1 text-base md:text-lg font-black text-slate-900 leading-tight tracking-tight">
            {title}
          </div>
          <div className="mt-1 text-xs text-slate-500">{subtitle}</div>
          <button
            onClick={() => {
              const el = document.getElementById("shop-grid-top");
              if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
            }}
            className="mt-3 inline-flex items-center gap-2 text-xs font-extrabold text-slate-900"
          >
            Shop now
            <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-[#FFD500] text-slate-900 group-hover:translate-x-0.5 transition">
              <ChevronRight className="w-3.5 h-3.5" />
            </span>
          </button>
        </div>
      </div>
    </div>
  );
}

/* =========================================================================
 * PriceRangeSlider — unchanged from the previous shop page
 * ---------------------------------------------------------------------- */

interface PriceRangeSliderProps {
  bounds: [number, number];
  value: [number, number];
  onChange: (v: [number, number]) => void;
}

function PriceRangeSlider({ bounds, value, onChange }: PriceRangeSliderProps) {
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [min, max] = bounds;
  const [lo, hi] = value;

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (!containerRef.current) return;
      if (!containerRef.current.contains(e.target as Node)) setOpen(false);
    };
    if (open) document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const isActive = lo > min || hi < max;
  const span = Math.max(1, max - min);
  const loPct = ((lo - min) / span) * 100;
  const hiPct = ((hi - min) / span) * 100;

  const clamp = (n: number, a: number, b: number) => Math.min(b, Math.max(a, n));

  const handleLo = (next: number) => {
    const v = clamp(Math.round(next), min, hi);
    onChange([v, hi]);
  };
  const handleHi = (next: number) => {
    const v = clamp(Math.round(next), lo, max);
    onChange([lo, v]);
  };

  return (
    <div className="relative" ref={containerRef}>
      <button
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="dialog"
        className={`inline-flex items-center gap-2 text-sm rounded-lg px-3 py-2 font-semibold border transition ${
          isActive
            ? "bg-amber-50 text-amber-700 border-amber-300 hover:bg-amber-100"
            : "bg-white text-slate-700 border-slate-200 hover:border-[#0b6e3e]"
        }`}
      >
        <Coins className="w-4 h-4" />
        {isActive ? `SAR ${lo} – SAR ${hi}` : "Price"}
      </button>

      {open && (
        <div
          role="dialog"
          aria-label="Price range filter"
          className="absolute right-0 top-full mt-2 w-80 bg-white rounded-2xl shadow-2xl ring-1 ring-black/5 p-5 z-30"
        >
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm font-bold text-slate-900">Price range</div>
            <button
              onClick={() => setOpen(false)}
              aria-label="Close price filter"
              className="w-7 h-7 rounded-full hover:bg-slate-100 text-slate-500 inline-flex items-center justify-center"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          <div className="flex items-center gap-2 mb-5">
            <label className="flex-1">
              <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">
                Min
              </div>
              <div className="relative">
                <span className="absolute left-2 top-1/2 -translate-y-1/2 text-slate-400 text-[11px] font-bold">SAR</span>
                <input
                  type="number"
                  value={lo}
                  min={min}
                  max={hi}
                  onChange={(e) => handleLo(Number(e.target.value))}
                  className="w-full pl-11 pr-2 py-2 border border-slate-200 rounded-lg text-sm font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-[#0b6e3e]/30 focus:border-[#0b6e3e]"
                />
              </div>
            </label>
            <div className="pt-5 text-slate-400">—</div>
            <label className="flex-1">
              <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">
                Max
              </div>
              <div className="relative">
                <span className="absolute left-2 top-1/2 -translate-y-1/2 text-slate-400 text-[11px] font-bold">SAR</span>
                <input
                  type="number"
                  value={hi}
                  min={lo}
                  max={max}
                  onChange={(e) => handleHi(Number(e.target.value))}
                  className="w-full pl-11 pr-2 py-2 border border-slate-200 rounded-lg text-sm font-semibold text-slate-900 focus:outline-none focus:ring-2 focus:ring-[#0b6e3e]/30 focus:border-[#0b6e3e]"
                />
              </div>
            </label>
          </div>

          <div className="relative h-10 mb-2">
            <div className="absolute left-0 right-0 top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-slate-200" />
            <div
              className="absolute top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-[#0b6e3e]"
              style={{ left: `${loPct}%`, right: `${100 - hiPct}%` }}
            />
            <input
              type="range"
              aria-label="Minimum price"
              min={min}
              max={max}
              value={lo}
              onChange={(e) => handleLo(Number(e.target.value))}
              className="range-thumb absolute inset-0 w-full appearance-none bg-transparent pointer-events-none"
              style={{ zIndex: lo > max - (max - min) * 0.1 ? 5 : 3 }}
            />
            <input
              type="range"
              aria-label="Maximum price"
              min={min}
              max={max}
              value={hi}
              onChange={(e) => handleHi(Number(e.target.value))}
              className="range-thumb absolute inset-0 w-full appearance-none bg-transparent pointer-events-none"
              style={{ zIndex: 4 }}
            />
          </div>
          <div className="flex justify-between text-xs text-slate-500 font-medium">
            <span>SAR {min}</span>
            <span>SAR {max}</span>
          </div>

          <div className="mt-4 flex items-center justify-between gap-2">
            <button
              onClick={() => onChange([min, max])}
              className="text-xs font-semibold text-slate-500 hover:text-[#0b6e3e] underline"
            >
              Reset
            </button>
            <button
              onClick={() => setOpen(false)}
              className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#0a8048] transition"
            >
              Apply
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ----------------------------- Filter Sidebar ----------------------------- */

interface FilterSidebarProps {
  open: boolean;
  onClose: () => void;
  onToggle: () => void;
  sections: {
    category: boolean;
    price: boolean;
    productType: boolean;
    tags: boolean;
  };
  setSections: React.Dispatch<
    React.SetStateAction<{
      category: boolean;
      price: boolean;
      productType: boolean;
      tags: boolean;
    }>
  >;
  categories: Category[];
  activeCategory: number | "all";
  setActiveCategory: (v: number | "all") => void;
  priceBounds: [number, number];
  priceRange: [number, number];
  setPriceRange: (r: [number, number]) => void;
  priceFilterActive: boolean;
  allProductTypes: { type: string; count: number }[];
  selectedProductTypes: string[];
  setSelectedProductTypes: React.Dispatch<React.SetStateAction<string[]>>;
  allTags: string[];
  selectedTags: string[];
  setSelectedTags: React.Dispatch<React.SetStateAction<string[]>>;
  onClearAll: () => void;
}

/**
 * Collapsible left-side filter sidebar for the shop category page.
 *
 * Desktop: renders inline in the flex layout. Users can collapse it to a narrow
 * rail via the header toggle; the rail only exposes the "expand" affordance.
 *
 * Mobile: renders as an overlay slide-over panel, opened via the
 * "Filters" button in the toolbar.
 */
function FilterSidebar({
  open,
  onClose,
  onToggle,
  sections,
  setSections,
  categories,
  activeCategory,
  setActiveCategory,
  priceBounds,
  priceRange,
  setPriceRange,
  priceFilterActive,
  allProductTypes,
  selectedProductTypes,
  setSelectedProductTypes,
  allTags,
  selectedTags,
  setSelectedTags,
  onClearAll,
}: FilterSidebarProps) {
  const toggleSection = (key: keyof typeof sections) =>
    setSections((prev) => ({ ...prev, [key]: !prev[key] }));

  const toggleProductType = (t: string) =>
    setSelectedProductTypes((prev) =>
      prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t],
    );

  const toggleTag = (t: string) =>
    setSelectedTags((prev) =>
      prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t],
    );

  const activeCount =
    (activeCategory !== "all" ? 1 : 0) +
    (priceFilterActive ? 1 : 0) +
    selectedProductTypes.length +
    selectedTags.length;

  const productTypeLabel = (t: string) => {
    if (!t) return "Other";
    return t.charAt(0).toUpperCase() + t.slice(1);
  };

  const panelBody = (
    <div className="flex flex-col h-full">
      <div className="flex items-center justify-between px-4 py-4 border-b border-slate-200">
        <div className="flex items-center gap-2">
          <SlidersHorizontal className="w-4 h-4 text-[#0b6e3e]" />
          <span className="text-sm font-bold tracking-wide uppercase text-slate-900">
            Filters
          </span>
          {activeCount > 0 && (
            <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-[#0b6e3e] text-white text-[10px] font-bold">
              {activeCount}
            </span>
          )}
        </div>
        <div className="flex items-center gap-1">
          {activeCount > 0 && (
            <button
              type="button"
              onClick={onClearAll}
              className="text-xs font-semibold text-slate-500 hover:text-[#0b6e3e] px-2 py-1"
            >
              Clear all
            </button>
          )}
          {/* Desktop collapse button */}
          <button
            type="button"
            onClick={onToggle}
            className="hidden md:inline-flex items-center justify-center w-8 h-8 rounded-md text-slate-500 hover:bg-slate-100 hover:text-[#0b6e3e]"
            aria-label="Collapse filters"
          >
            <PanelLeftClose className="w-4 h-4" />
          </button>
          {/* Mobile close button */}
          <button
            type="button"
            onClick={onClose}
            className="md:hidden inline-flex items-center justify-center w-8 h-8 rounded-md text-slate-500 hover:bg-slate-100 hover:text-[#0b6e3e]"
            aria-label="Close filters"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-5">
        {/* Category section */}
        <SidebarSection
          title="Category"
          isOpen={sections.category}
          onToggle={() => toggleSection("category")}
        >
          <div className="space-y-1.5">
            <button
              type="button"
              onClick={() => setActiveCategory("all")}
              className={
                "w-full flex items-center justify-between px-2.5 py-1.5 rounded-md text-sm transition-colors " +
                (activeCategory === "all"
                  ? "bg-[#0b6e3e]/10 text-[#0b6e3e] font-semibold"
                  : "text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e]")
              }
            >
              <span>All categories</span>
            </button>
            {categories.map((c) => (
              <button
                key={c.id}
                type="button"
                onClick={() => setActiveCategory(c.id)}
                className={
                  "w-full flex items-center justify-between px-2.5 py-1.5 rounded-md text-sm transition-colors " +
                  (activeCategory === c.id
                    ? "bg-[#0b6e3e]/10 text-[#0b6e3e] font-semibold"
                    : "text-slate-700 hover:bg-slate-50 hover:text-[#0b6e3e]")
                }
              >
                <span className="truncate">{c.name}</span>
              </button>
            ))}
            {categories.length === 0 && (
              <div className="text-xs text-slate-400 px-2.5 py-1">
                No categories available
              </div>
            )}
          </div>
        </SidebarSection>

        {/* Price range section */}
        <SidebarSection
          title="Price range"
          isOpen={sections.price}
          onToggle={() => toggleSection("price")}
        >
          {priceBounds[1] > priceBounds[0] ? (
            <div className="pt-1">
              <PriceRangeSlider
                bounds={priceBounds}
                value={priceRange}
                onChange={setPriceRange}
              />
            </div>
          ) : (
            <div className="text-xs text-slate-400">Not enough products</div>
          )}
        </SidebarSection>

        {/* Product type section */}
        <SidebarSection
          title="Product type"
          isOpen={sections.productType}
          onToggle={() => toggleSection("productType")}
        >
          {allProductTypes.length > 0 ? (
            <div className="space-y-2">
              {allProductTypes.map(({ type, count }) => {
                const checked = selectedProductTypes.includes(type);
                return (
                  <label
                    key={type}
                    className="flex items-center justify-between gap-2 cursor-pointer group"
                  >
                    <span className="flex items-center gap-2 min-w-0">
                      <input
                        type="checkbox"
                        checked={checked}
                        onChange={() => toggleProductType(type)}
                        className="w-4 h-4 rounded border-slate-300 text-[#0b6e3e] focus:ring-[#0b6e3e]"
                      />
                      <span
                        className={
                          "text-sm truncate " +
                          (checked
                            ? "text-[#0b6e3e] font-semibold"
                            : "text-slate-700 group-hover:text-[#0b6e3e]")
                        }
                      >
                        {productTypeLabel(type)}
                      </span>
                    </span>
                    <span className="text-xs text-slate-400">{count}</span>
                  </label>
                );
              })}
            </div>
          ) : (
            <div className="text-xs text-slate-400">No product types</div>
          )}
        </SidebarSection>

        {/* Tags section */}
        <SidebarSection
          title="Tags"
          isOpen={sections.tags}
          onToggle={() => toggleSection("tags")}
        >
          {allTags.length > 0 ? (
            <div className="flex flex-wrap gap-2">
              {allTags.slice(0, 30).map((t) => {
                const checked = selectedTags.includes(t);
                return (
                  <button
                    key={t}
                    type="button"
                    onClick={() => toggleTag(t)}
                    className={
                      "px-2.5 py-1 rounded-full text-xs font-semibold border transition-colors " +
                      (checked
                        ? "bg-[#0b6e3e] border-[#0b6e3e] text-white"
                        : "bg-white border-slate-200 text-slate-600 hover:border-[#0b6e3e] hover:text-[#0b6e3e]")
                    }
                  >
                    {t}
                  </button>
                );
              })}
            </div>
          ) : (
            <div className="text-xs text-slate-400">No tags available</div>
          )}
        </SidebarSection>
      </div>
    </div>
  );

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={
          "hidden md:block shrink-0 transition-[width] duration-200 " +
          (open ? "w-64" : "w-12")
        }
      >
        {open ? (
          <div className="sticky top-24 bg-white border border-slate-200 rounded-xl overflow-hidden max-h-[calc(100vh-7rem)]">
            {panelBody}
          </div>
        ) : (
          <div className="sticky top-24">
            <button
              type="button"
              onClick={onToggle}
              className="w-10 h-10 inline-flex items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-600 hover:border-[#0b6e3e] hover:text-[#0b6e3e] shadow-sm"
              aria-label="Expand filters"
              title="Expand filters"
            >
              <PanelLeftOpen className="w-4 h-4" />
            </button>
            {activeCount > 0 && (
              <div className="mt-2 text-[10px] font-bold text-center text-[#0b6e3e]">
                {activeCount}
              </div>
            )}
          </div>
        )}
      </aside>

      {/* Mobile slide-over */}
      {open && (
        <div className="md:hidden fixed inset-0 z-50 flex">
          <div
            className="absolute inset-0 bg-slate-900/50"
            onClick={onClose}
            aria-hidden
          />
          <div className="relative w-[85%] max-w-sm h-full bg-white shadow-2xl">
            {panelBody}
          </div>
        </div>
      )}
    </>
  );
}

/* Small collapsible section used inside the FilterSidebar. */
interface SidebarSectionProps {
  title: string;
  isOpen: boolean;
  onToggle: () => void;
  children: React.ReactNode;
}

function SidebarSection({ title, isOpen, onToggle, children }: SidebarSectionProps) {
  return (
    <div className="pb-4 border-b border-slate-100 last:border-b-0">
      <button
        type="button"
        onClick={onToggle}
        className="w-full flex items-center justify-between py-1.5 text-left"
      >
        <span className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
          {title}
        </span>
        {isOpen ? (
          <ChevronUp className="w-4 h-4 text-slate-400" />
        ) : (
          <ChevronDown className="w-4 h-4 text-slate-400" />
        )}
      </button>
      {isOpen && <div className="mt-3">{children}</div>}
    </div>
  );
}