"use client";

import dynamic from "next/dynamic";
import { useCallback, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useSiteText } from "@/components/providers/site-text-provider";
import type { CartDrawerTriggerProps } from "@/components/layout/cart-drawer-trigger";

const LazyCartDrawerTrigger = dynamic(
  () => import("@/components/layout/cart-drawer-trigger").then((mod) => mod.CartDrawerTrigger),
  { ssr: false },
);

export function CartDrawerShell(props: CartDrawerTriggerProps) {
  const { t } = useSiteText();
  const searchParams = useSearchParams();
  const shouldOpenFromUrl = searchParams.get("openCart") === "1";
  const [hasLoadedInteractively, setHasLoadedInteractively] = useState(shouldOpenFromUrl);
  const isLoaded = hasLoadedInteractively || shouldOpenFromUrl;
  const markDrawerLoaded = useCallback(() => setHasLoadedInteractively(true), []);

  if (isLoaded) {
    return (
      <LazyCartDrawerTrigger
        {...props}
        defaultOpen={shouldOpenFromUrl}
        onOpenFromUrl={markDrawerLoaded}
      />
    );
  }

  return (
    <button
      type="button"
      aria-label={`${t("cart.button")}, ${props.itemCount} article${props.itemCount > 1 ? "s" : ""}`}
      onClick={() => setHasLoadedInteractively(true)}
      className="group relative inline-flex items-center gap-2 rounded-full bg-[var(--accent-3)] px-4 py-2 text-white transition-all duration-200 hover:-translate-y-[1px] hover:bg-[var(--accent-2)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2"
    >
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4 text-white">
        <path strokeLinecap="round" strokeLinejoin="round" d="M3 4h2l2.2 10.2a2 2 0 0 0 2 1.6h8.8a2 2 0 0 0 2-1.7L23 7H7.2" />
        <circle cx="10" cy="20" r="1.5" />
        <circle cx="18" cy="20" r="1.5" />
      </svg>
      <span className="hidden text-white sm:inline">{t("cart.button")}</span>
      <span className="ml-0.5 inline-flex min-w-5 items-center justify-center rounded-full bg-[var(--accent-soft)] px-1.5 py-0.5 text-[10px] font-bold text-[var(--accent-3)]">
        {props.itemCount}
      </span>
    </button>
  );
}
