"use client";

import * as React from "react";
import { Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useGlobalSearch } from "@/components/global-search/global-search-provider";

function useSearchShortcutLabel(): string {
  const [label, setLabel] = React.useState("Ctrl+K");

  React.useEffect(() => {
    const isMac =
      typeof navigator !== "undefined" &&
      /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
    setLabel(isMac ? "⌘K" : "Ctrl+K");
  }, []);

  return label;
}

export function GlobalSearchTrigger() {
  const { setOpen } = useGlobalSearch();
  const shortcut = useSearchShortcutLabel();

  return (
    <>
      <Button
        type="button"
        variant="outline"
        size="icon"
        className="size-9 shrink-0 border-border/80 bg-white/60 shadow-none hover:bg-white/90 md:hidden"
        onClick={() => setOpen(true)}
        aria-label="Open global search"
      >
        <Search className="size-4 opacity-70" />
      </Button>
      <Button
        type="button"
        variant="outline"
        size="sm"
        className="hidden h-9 w-full max-w-[220px] items-center justify-start gap-2 border-border/80 bg-white/60 px-3 text-muted-foreground shadow-none hover:bg-white/90 md:flex lg:max-w-[260px]"
        onClick={() => setOpen(true)}
        aria-label="Open global search"
      >
        <Search className="size-4 shrink-0 opacity-60" />
        <span className="flex-1 truncate text-left text-sm font-normal">
          Search…
        </span>
        <kbd className="pointer-events-none hidden rounded-md border border-border/70 bg-background px-1.5 py-0.5 font-mono text-[10px] font-medium text-foreground shadow-sm sm:inline">
          {shortcut}
        </kbd>
      </Button>
    </>
  );
}
