"use client";

import { Headset } from "lucide-react";
import { useState } from "react";

import { SupportPanel } from "./SupportPanel";
import { useUnreadCount } from "./useSupport";
import { useSupportSocket } from "./useSupportSocket";

const GREEN = "rgb(20 113 76)";
const GRADIENT = `linear-gradient(135deg, ${GREEN}, rgb(30 140 96))`;

/**
 * Floating support launcher for the portal. One device-scoped thread — opens
 * straight into the conversation, no login or form. Live pushes keep the badge
 * fresh via a `guest:<deviceId>` socket room.
 */
export function SupportWidget() {
  const [open, setOpen] = useState(false);
  const { data } = useUnreadCount(true);
  const unread = data?.unreadCount ?? 0;

  useSupportSocket(true);

  return (
    // Kept below every modal/drawer tier (z-90 through z-[120]) and the mobile sticky
    // bottom action bars (z-40) used on booking flow pages, so the floating launcher never
    // paints over dialog content or a page's "Continue" bar — it only sits above ordinary
    // in-page content.
    <div className="fixed bottom-6 right-6 z-40 flex flex-col items-end gap-3">
      {open && <SupportPanel onClose={() => setOpen(false)} />}
      {!open && (
        <button
          onClick={() => setOpen(true)}
          aria-label="Open support chat"
          className="group relative flex items-center gap-2.5 rounded-full p-2 pr-2 text-white transition-transform duration-150 hover:-translate-y-0.5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[3px] focus-visible:outline-primary active:translate-y-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0 sm:pr-5"
          style={{
            background: GRADIENT,
            boxShadow: "0 10px 28px rgba(20,113,76,0.4)",
          }}
        >
          {/* Faint breathing ring; the unread badge is loud enough on its own. */}
          {unread === 0 && (
            <span className="pointer-events-none absolute -inset-1 animate-pulse rounded-full ring-2 ring-primary/50 motion-reduce:animate-none" />
          )}

          <span className="relative grid h-[42px] w-[42px] shrink-0 place-items-center rounded-full bg-white/20">
            <Headset size={22} />
          </span>

          <span className="relative hidden text-left leading-tight sm:block">
            <span className="block whitespace-nowrap text-sm font-semibold">
              👋 Need help?
            </span>
            <span className="block whitespace-nowrap text-[11px] opacity-85">
              Chat with our team
            </span>
          </span>

          {unread > 0 && (
            <span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full border-2 border-white bg-red-500 px-1 text-xs font-bold text-white">
              {unread > 9 ? "9+" : unread}
            </span>
          )}
        </button>
      )}
    </div>
  );
}

export default SupportWidget;
