"use client";
import { useState, useRef } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Plus, Camera, Package, X } from "lucide-react";

// Static (non-profile) routes under /marketplace/seller/ — everything else
// under that prefix is a public seller profile ([slug]).
const STATIC_SELLER_ROUTES = ["dashboard", "earnings", "listings", "orders"];

// Pages that already have their own fixed bottom action bar, or where a
// "Sell Item" shortcut doesn't make sense — the FAB would visually collide
// with content there, so it's hidden entirely.
function isFabHiddenRoute(pathname: string): boolean {
  if (pathname.startsWith("/marketplace/listing/")) return true; // sticky Buy Now / Chat bar
  if (pathname.startsWith("/marketplace/checkout")) return true; // sticky mobile pay bar
  if (pathname.startsWith("/marketplace/create")) return true; // already creating a listing
  if (pathname.startsWith("/marketplace/seller/")) {
    const segment = pathname.split("/")[3] ?? "";
    return !STATIC_SELLER_ROUTES.includes(segment); // public seller profile's sticky CTA
  }
  return false;
}

const ACTIONS = [
  {
    label: "Sell Item",
    icon: Package,
    href: "/marketplace/create",
    color: "var(--accent)",
  },
  {
    label: "Add Photos",
    icon: Camera,
    href: "/marketplace/create?step=photos",
    color: "#a78bfa",
  },
];

export function MarketplaceFAB() {
  const router = useRouter();
  const pathname = usePathname();
  const [expanded, setExpanded] = useState(false);
  const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  if (isFabHiddenRoute(pathname)) return null;

  const handlePress = () => {
    if (!expanded) {
      router.push("/marketplace/create");
    } else {
      setExpanded(false);
    }
  };

  const handleLongPressStart = () => {
    pressTimer.current = setTimeout(() => setExpanded(true), 400);
  };

  const handleLongPressEnd = () => {
    if (pressTimer.current) clearTimeout(pressTimer.current);
  };

  return (
    <div
      className="md:hidden flex flex-col items-center gap-2"
      style={{
        position: "fixed",
        bottom: "calc(30px + env(safe-area-inset-bottom, 0px))",
        left: "50%",
        transform: "translateX(-50%)",
        zIndex: 50,
      }}
    >
      {/* Quick actions (shown when expanded) */}
      {expanded &&
        ACTIONS.map((action, i) => (
          <button
            key={action.label}
            onClick={() => {
              setExpanded(false);
              router.push(action.href);
            }}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              padding: "7px 14px",
              borderRadius: 20,
              background: action.color,
              color: "#fff",
              fontSize: 11,
              fontWeight: 700,
              border: "none",
              cursor: "pointer",
              boxShadow: `0 4px 14px ${action.color}60`,
              animation: `fab-action-in 0.22s ${i * 0.06}s both`,
            }}
          >
            <action.icon size={13} />
            {action.label}
          </button>
        ))}

      {/* Main FAB button */}
      <button
        onClick={handlePress}
        onMouseDown={handleLongPressStart}
        onMouseUp={handleLongPressEnd}
        onTouchStart={handleLongPressStart}
        onTouchEnd={handleLongPressEnd}
        onContextMenu={(e) => {
          e.preventDefault();
          setExpanded(true);
        }}
        aria-label="Create listing"
        className="flex items-center justify-center"
        style={{
          width: 52,
          height: 52,
          borderRadius: "50%",
          background: "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)",
          border: "none",
          cursor: "pointer",
          boxShadow: "0 4px 20px rgba(252,0,0,0.45), 0 1px 6px rgba(0,0,0,0.3)",
          transition: "transform 0.15s, box-shadow 0.15s",
        }}
        onMouseEnter={(e) => {
          (e.currentTarget as HTMLElement).style.transform = "scale(1.06)";
        }}
        onMouseLeave={(e) => {
          (e.currentTarget as HTMLElement).style.transform = "scale(1)";
        }}
      >
        <div
          style={{
            transition: "transform 0.2s",
            transform: expanded ? "rotate(45deg)" : "none",
          }}
        >
          <Plus size={22} color="#fff" strokeWidth={2.5} />
        </div>
      </button>

      <style>{`
        @keyframes fab-action-in {
          from { opacity: 0; transform: translateY(12px) scale(0.85); }
          to   { opacity: 1; transform: translateY(0)   scale(1); }
        }
      `}</style>
    </div>
  );
}
