"use client";
import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  Heart,
  MessageCircle,
  Package,
  Plus,
  Menu,
  ChevronDown,
  Store,
  User,
  ChevronLeft,
  MapPin,
} from "lucide-react";
import { useMarketplaceContext } from "@/contexts/marketplace/MarketplaceContext";
import { useWishlist } from "@/lib/WishlistContext";
import { useMessaging } from "@/lib/MessagingContext";
import { useLocation } from "@/hooks/useLocation";
import Image from "next/image";
import { IMAGES, TEXT } from "@/branding";

export function MarketplaceHeader() {
  const router = useRouter();
  const { mode, setMode, openMobileSidebar } = useMarketplaceContext();
  const { count: wishlistCount } = useWishlist();
  const { totalUnread } = useMessaging();
  const {
    location,
    isLoading: locationLoading,
    requestLocation,
  } = useLocation();
  const [modeOpen, setModeOpen] = useState(false);
  const modeRef = useRef<HTMLDivElement>(null);

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

  return (
    <header
      style={{
        height: 64,
        flexShrink: 0,
        background: "var(--card)",
        borderBottom: "1px solid var(--border)",
        position: "relative",
        zIndex: 30,
        boxShadow: "0 1px 0 var(--border), 0 2px 8px rgba(0,0,0,0.04)",
      }}
    >
      {/* ── Desktop layout ──────────────────────────────────────────────────── */}
      <div
        className="hidden md:flex h-full items-center justify-between"
        style={{ padding: "0 20px", gap: 16 }}
      >
        {/* LEFT: back + logo */}
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <button
            onClick={() => router.push("/")}
            aria-label="Back to Feed"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 3,
              padding: "4px 10px 4px 6px",
              borderRadius: 8,
              border: "1px solid var(--border)",
              background: "transparent",
              color: "var(--text-muted)",
              fontSize: 11,
              fontWeight: 600,
              cursor: "pointer",
              flexShrink: 0,
              transition: "all 0.15s",
              whiteSpace: "nowrap",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.background = "var(--bg)";
              (e.currentTarget as HTMLElement).style.color =
                "var(--text-primary)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.background = "transparent";
              (e.currentTarget as HTMLElement).style.color =
                "var(--text-muted)";
            }}
          >
            ← Back to Feed
          </button>

          <div
            style={{
              width: 1,
              height: 22,
              background: "var(--border)",
              flexShrink: 0,
            }}
          />

          <button
            onClick={() => router.push("/marketplace")}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 9,
              background: "none",
              border: "none",
              padding: 0,
              cursor: "pointer",
            }}
          >
            <Image
              src={IMAGES.appIcon}
              alt={TEXT.app.name}
              width={36}
              height={36}
              className="rounded-xl shrink-0"
              priority
            />
            <div style={{ textAlign: "left" }}>
              <div
                style={{
                  fontSize: 14,
                  fontWeight: 800,
                  color: "var(--text-primary)",
                  letterSpacing: "-0.02em",
                  lineHeight: 1.1,
                }}
              >
                Marketplace
              </div>
              <div
                style={{
                  fontSize: 9.5,
                  color: "var(--text-muted)",
                  letterSpacing: "0.06em",
                  textTransform: "uppercase",
                  lineHeight: 1,
                  marginTop: 2,
                }}
              >
                by Doliplay
              </div>
            </div>
          </button>
        </div>

        {/* CENTER: location indicator */}
        <div style={{ flex: 1, display: "flex", justifyContent: "left" }}>
          {locationLoading ? (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 5,
                fontSize: 11,
                color: "var(--text-muted)",
              }}
            >
              <MapPin size={12} style={{ color: "var(--accent)" }} />
              <span>Detecting location…</span>
            </div>
          ) : location ? (
            <button
              onClick={requestLocation}
              title="Refresh location"
              style={{
                display: "flex",
                alignItems: "center",
                gap: 5,
                padding: "4px 10px",
                borderRadius: 20,
                border: "1px solid var(--border)",
                background: "var(--bg)",
                color: "var(--text-muted)",
                fontSize: 11,
                fontWeight: 600,
                cursor: "pointer",
                transition: "all 0.15s",
                whiteSpace: "nowrap",
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--accent)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--border)";
              }}
            >
              <MapPin size={11} style={{ color: "var(--accent)" }} />
              <span style={{ color: "var(--text-primary)", fontWeight: 700 }}>
                {location.city}
              </span>
              {location.state && <span>, {location.state}</span>}
            </button>
          ) : (
            <button
              onClick={requestLocation}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 5,
                padding: "4px 10px",
                borderRadius: 20,
                border: "1px dashed var(--border)",
                background: "transparent",
                color: "var(--text-muted)",
                fontSize: 11,
                fontWeight: 600,
                cursor: "pointer",
                transition: "all 0.15s",
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--accent)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLElement).style.borderColor =
                  "var(--border)";
              }}
            >
              <MapPin size={11} style={{ color: "var(--accent)" }} />
              Set location
            </button>
          )}
        </div>

        {/* RIGHT: mode switcher + icons + sell */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            flexShrink: 0,
          }}
        >
          {/* Mode switcher */}
          <div ref={modeRef} style={{ position: "relative" }}>
            <button
              onClick={() => setModeOpen((v) => !v)}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 5,
                padding: "5px 10px",
                borderRadius: 20,
                border: `1px solid ${mode === "seller" ? "rgba(240,192,64,0.4)" : "rgba(252,0,0,0.25)"}`,
                background:
                  mode === "seller"
                    ? "rgba(240,192,64,0.08)"
                    : "rgba(252,0,0,0.06)",
                cursor: "pointer",
                fontSize: 11,
                fontWeight: 700,
                color: mode === "seller" ? "#f0c040" : "var(--accent)",
                transition: "all 0.15s",
                whiteSpace: "nowrap",
              }}
            >
              <span style={{ fontSize: 13 }}>
                {mode === "buyer" ? "🛒" : "🏪"}
              </span>
              {mode === "buyer" ? "Buyer" : "Seller"}
              <ChevronDown
                size={11}
                style={{
                  transform: modeOpen ? "rotate(180deg)" : "none",
                  transition: "transform 0.2s",
                }}
              />
            </button>

            {modeOpen && (
              <div
                style={{
                  position: "absolute",
                  top: "calc(100% + 8px)",
                  right: 0,
                  minWidth: 168,
                  borderRadius: 12,
                  background: "var(--card)",
                  border: "1px solid var(--border)",
                  boxShadow:
                    "0 8px 32px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.08)",
                  zIndex: 100,
                  overflow: "hidden",
                  padding: 4,
                }}
              >
                {(["buyer", "seller"] as const).map((m) => (
                  <button
                    key={m}
                    onClick={() => {
                      setMode(m);
                      setModeOpen(false);
                      router.push(
                        m === "seller" ? "/marketplace/seller" : "/marketplace",
                      );
                    }}
                    style={{
                      width: "100%",
                      padding: "9px 12px",
                      textAlign: "left",
                      fontSize: 12,
                      fontWeight: 700,
                      color:
                        mode === m
                          ? m === "seller"
                            ? "#f0c040"
                            : "var(--accent)"
                          : "var(--text-primary)",
                      background:
                        mode === m
                          ? m === "seller"
                            ? "rgba(240,192,64,0.08)"
                            : "rgba(252,0,0,0.06)"
                          : "transparent",
                      border: "none",
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      borderRadius: 8,
                      transition: "background 0.1s",
                    }}
                    onMouseEnter={(e) => {
                      if (mode !== m)
                        (e.currentTarget as HTMLElement).style.background =
                          "var(--bg)";
                    }}
                    onMouseLeave={(e) => {
                      if (mode !== m)
                        (e.currentTarget as HTMLElement).style.background =
                          "transparent";
                    }}
                  >
                    <span style={{ fontSize: 14 }}>
                      {m === "buyer" ? "🛒" : "🏪"}
                    </span>
                    <div>
                      <div>{m === "buyer" ? "Buyer Mode" : "Seller Mode"}</div>
                      <div
                        style={{
                          fontSize: 10,
                          fontWeight: 400,
                          color: "var(--text-muted)",
                          marginTop: 1,
                        }}
                      >
                        {m === "buyer"
                          ? "Browse & purchase"
                          : "Manage listings"}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Icon group */}
          <div style={{ display: "flex", alignItems: "center", gap: 2 }}>
            <IconBtn
              onClick={() => router.push("/marketplace/wishlist")}
              label="Wishlist"
              badge={wishlistCount}
            >
              <Heart size={18} />
            </IconBtn>
            <IconBtn
              onClick={() => router.push("/marketplace/messages")}
              label="Messages"
              badge={totalUnread}
              badgeColor="#22c55e"
            >
              <MessageCircle size={18} />
            </IconBtn>
            <IconBtn
              onClick={() => router.push("/marketplace/orders")}
              label="Orders"
            >
              <Package size={18} />
            </IconBtn>
            <IconBtn
              onClick={() => router.push("/marketplace/profile")}
              label="Profile"
            >
              <User size={18} />
            </IconBtn>
          </div>

          {/* Sell CTA */}
          <button
            onClick={() => router.push("/marketplace/create")}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              padding: "0 16px",
              height: 36,
              borderRadius: 9,
              background: "linear-gradient(135deg, #fc0000 0%, #e60000 100%)",
              color: "#fff",
              fontSize: 12,
              fontWeight: 800,
              letterSpacing: "0.02em",
              border: "none",
              cursor: "pointer",
              flexShrink: 0,
              boxShadow: "0 2px 8px rgba(252,0,0,0.35)",
              transition: "transform 0.12s, box-shadow 0.12s",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.transform =
                "translateY(-1px)";
              (e.currentTarget as HTMLElement).style.boxShadow =
                "0 4px 16px rgba(252,0,0,0.45)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.transform = "none";
              (e.currentTarget as HTMLElement).style.boxShadow =
                "0 2px 8px rgba(252,0,0,0.35)";
            }}
          >
            <Plus size={13} strokeWidth={2.5} />
            Sell
          </button>
        </div>
      </div>

      {/* ── Mobile layout ────────────────────────────────────────────────────── */}
      <div
        className="flex md:hidden h-full items-center"
        style={{ padding: "0 12px", gap: 8 }}
      >
        {/* Back to Social Network */}
        <button
          onClick={() => router.push("/")}
          aria-label="Back to Social Network"
          style={{
            display: "flex",
            alignItems: "center",
            gap: 2,
            padding: "5px 8px 5px 5px",
            borderRadius: 8,
            border: "1px solid var(--border)",
            background: "transparent",
            color: "var(--text-muted)",
            fontSize: 10,
            fontWeight: 700,
            cursor: "pointer",
            flexShrink: 0,
            whiteSpace: "nowrap",
            transition: "all 0.15s",
          }}
          onTouchStart={(e) => {
            (e.currentTarget as HTMLElement).style.background = "var(--bg)";
            (e.currentTarget as HTMLElement).style.color =
              "var(--text-primary)";
          }}
          onTouchEnd={(e) => {
            (e.currentTarget as HTMLElement).style.background = "transparent";
            (e.currentTarget as HTMLElement).style.color = "var(--text-muted)";
          }}
        >
          <ChevronLeft size={13} />
          Feed
        </button>

        <button
          onClick={openMobileSidebar}
          aria-label="Open menu"
          style={{
            color: "var(--text-muted)",
            padding: 6,
            borderRadius: 8,
            background: "none",
            border: "none",
            cursor: "pointer",
            flexShrink: 0,
          }}
        >
          <Menu size={22} />
        </button>

        <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
          <button
            onClick={() => router.push("/marketplace")}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 7,
              background: "none",
              border: "none",
              cursor: "pointer",
              padding: 0,
            }}
          >
            <div
              style={{
                width: 30,
                height: 30,
                borderRadius: 8,
                background: "linear-gradient(135deg, #fc0000 0%, #ff4d4d 100%)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                boxShadow: "0 2px 6px rgba(252,0,0,0.3)",
                flexShrink: 0,
              }}
            >
              <Store size={14} color="#fff" strokeWidth={2.2} />
            </div>
            <span
              style={{
                fontSize: 14,
                fontWeight: 800,
                color: "var(--text-primary)",
                letterSpacing: "-0.02em",
              }}
            >
              Marketplace
            </span>
          </button>
          {/* Location sub-label on mobile */}
          {location && !locationLoading && (
            <button
              onClick={requestLocation}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 3,
                background: "none",
                border: "none",
                cursor: "pointer",
                padding: 0,
                marginLeft: 37,
              }}
            >
              <MapPin size={9} style={{ color: "var(--accent)" }} />
              <span
                style={{
                  fontSize: 10,
                  color: "var(--text-muted)",
                  fontWeight: 600,
                }}
              >
                {location.city}
              </span>
            </button>
          )}
        </div>

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

        <div style={{ position: "relative" }}>
          <button
            onClick={() => router.push("/marketplace/wishlist")}
            style={{
              color: "var(--text-muted)",
              padding: 7,
              borderRadius: 8,
              background: "none",
              border: "none",
              cursor: "pointer",
            }}
          >
            <Heart size={20} />
          </button>
          {wishlistCount > 0 && (
            <span
              style={{
                position: "absolute",
                top: 4,
                right: 4,
                minWidth: 15,
                height: 15,
                padding: "0 3px",
                borderRadius: 8,
                background: "var(--accent)",
                color: "#fff",
                fontSize: 9,
                fontWeight: 800,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              {wishlistCount > 9 ? "9+" : wishlistCount}
            </span>
          )}
        </div>

        <button
          onClick={() => router.push("/marketplace/create")}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 5,
            padding: "6px 12px",
            borderRadius: 8,
            background: "linear-gradient(135deg, #fc0000 0%, #e60000 100%)",
            color: "#fff",
            fontSize: 11,
            fontWeight: 800,
            border: "none",
            cursor: "pointer",
            boxShadow: "0 2px 6px rgba(252,0,0,0.3)",
          }}
        >
          <Plus size={12} strokeWidth={2.5} />
          Sell
        </button>
      </div>
    </header>
  );
}

/* ── Icon button with optional badge ─────────────────────────────────────── */
function IconBtn({
  children,
  onClick,
  label,
  badge,
  badgeColor = "var(--accent)",
}: {
  children: React.ReactNode;
  onClick: () => void;
  label: string;
  badge?: number;
  badgeColor?: string;
}) {
  return (
    <button
      onClick={onClick}
      aria-label={label}
      title={label}
      style={{
        position: "relative",
        padding: 7,
        borderRadius: 8,
        color: "var(--text-muted)",
        background: "none",
        border: "none",
        cursor: "pointer",
        transition: "color 0.12s, background 0.12s",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLElement).style.color = "var(--text-primary)";
        (e.currentTarget as HTMLElement).style.background = "var(--bg)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLElement).style.color = "var(--text-muted)";
        (e.currentTarget as HTMLElement).style.background = "none";
      }}
    >
      {children}
      {badge != null && badge > 0 && (
        <span
          style={{
            position: "absolute",
            top: 3,
            right: 3,
            minWidth: 15,
            height: 15,
            padding: "0 3px",
            borderRadius: 8,
            background: badgeColor,
            color: "#fff",
            fontSize: 9,
            fontWeight: 800,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {badge > 9 ? "9+" : badge}
        </span>
      )}
    </button>
  );
}
