"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from "lucide-react";
import { twMerge } from "tailwind-merge";

type SponsoredBanner = {
  id: string;
  placement: string;
  title: string | null;
  link_url: string | null;
  open_in_new_tab: boolean;
  image_url: string;
  image_alt: string | null;
};

function clampIndex(index: number, length: number) {
  if (length <= 0) return 0;
  const normalized = ((index % length) + length) % length;
  return normalized;
}

export function SponsoredBannersCarousel({
  placement,
  className,
  intervalMs = 7000,
}: {
  placement: string;
  className?: string;
  intervalMs?: number;
}) {
  const [collapsed, setCollapsed] = useState(false);
  const [loading, setLoading] = useState(true);
  const [banners, setBanners] = useState<SponsoredBanner[]>([]);
  const [activeIndex, setActiveIndex] = useState(0);
  const [hovered, setHovered] = useState(false);
  const timerRef = useRef<number | null>(null);

  const collapsedKey = useMemo(() => `ktl_sponsored_banners_collapsed__${placement}`, [placement]);

  useEffect(() => {
    try {
      setCollapsed(window.localStorage.getItem(collapsedKey) === "1");
    } catch {
      setCollapsed(false);
    }
  }, [collapsedKey]);

  useEffect(() => {
    let active = true;
    async function load() {
      setLoading(true);
      try {
        const res = await fetch(`/api/sponsored-banners?placement=${encodeURIComponent(placement)}`, {
          method: "GET",
          headers: { "content-type": "application/json" },
        });
        const json = (await res.json().catch(() => null)) as { banners?: SponsoredBanner[] } | null;
        const items = Array.isArray(json?.banners) ? json!.banners! : [];
        if (active) {
          setBanners(items.filter((b) => Boolean(b?.image_url)));
          setActiveIndex(0);
        }
      } catch {
        if (active) setBanners([]);
      } finally {
        if (active) setLoading(false);
      }
    }
    load();
    return () => {
      active = false;
    };
  }, [placement]);

  useEffect(() => {
    if (timerRef.current) window.clearInterval(timerRef.current);
    timerRef.current = null;
    if ((!collapsed && hovered) || banners.length <= 1) return;
    const safeInterval = Math.max(2500, Number.isFinite(intervalMs) ? intervalMs : 7000);
    timerRef.current = window.setInterval(() => {
      setActiveIndex((current) => clampIndex(current + 1, banners.length));
    }, safeInterval);
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current);
      timerRef.current = null;
    };
  }, [banners.length, collapsed, hovered, intervalMs]);

  const active = banners[clampIndex(activeIndex, banners.length)] || null;

  if (!loading && banners.length === 0) return null;

  const href = active?.link_url || "";
  const target = active?.open_in_new_tab ? "_blank" : undefined;
  const rel = active?.open_in_new_tab ? "noopener noreferrer" : undefined;
  const desktopControlsVisibility = hovered ? "md:opacity-100 md:pointer-events-auto" : "md:opacity-0 md:pointer-events-none";
  const titleText = active?.title || active?.image_alt || "Banner patrocinado";

  function toggleCollapsed() {
    setCollapsed((prev) => {
      const next = !prev;
      try {
        window.localStorage.setItem(collapsedKey, next ? "1" : "0");
      } catch {
        return next;
      }
      return next;
    });
    setHovered(false);
  }

  return (
    <section
      className={twMerge(
        "relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-900",
        "shadow-[0_12px_32px_rgba(15,23,42,0.04)]",
        className
      )}
      onMouseEnter={() => (!collapsed ? setHovered(true) : null)}
      onMouseLeave={() => setHovered(false)}
    >
      <div className="relative">
        {collapsed ? (
          <div className="relative h-16 w-full bg-slate-950">
            {active ? (
              href ? (
                <a href={href} target={target} rel={rel} className="group absolute inset-0">
                  <img
                    src={active.image_url}
                    alt={active.image_alt || active.title || "Banner patrocinado"}
                    className="h-full w-full object-cover"
                  />
                  <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.35)_0%,rgba(0,0,0,0.10)_55%,rgba(0,0,0,0.22)_100%)]" />
                </a>
              ) : (
                <>
                  <img
                    src={active.image_url}
                    alt={active.image_alt || active.title || "Banner patrocinado"}
                    className="h-full w-full object-cover"
                  />
                  <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.35)_0%,rgba(0,0,0,0.10)_55%,rgba(0,0,0,0.22)_100%)]" />
                </>
              )
            ) : (
              <div className="absolute inset-0 bg-[linear-gradient(135deg,rgba(79,70,229,0.14)_0%,rgba(15,23,42,0.72)_55%,rgba(15,23,42,0.88)_100%)]" />
            )}

            <div className="absolute inset-0 z-20 flex items-center justify-between gap-3 px-4">
              <div className="min-w-0">
                <div className="inline-flex items-center rounded-full border border-white/10 bg-black/10 px-2 py-0.5 text-[11px] font-semibold text-white/85">
                  Patrocinado
                </div>
                <div className="mt-1 truncate text-sm font-semibold tracking-[-0.01em] text-white/90">{titleText}</div>
              </div>
              <button
                type="button"
                onClick={toggleCollapsed}
                className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-black/10 text-white/70 backdrop-blur-sm transition hover:bg-black/20"
                aria-label="Abrir"
                title="Abrir"
              >
                <ChevronDown className="h-4 w-4" />
              </button>
            </div>
          </div>
        ) : (
          <>
            <div className="absolute left-4 top-4 z-20 flex items-center gap-2">
              <span className="inline-flex items-center rounded-full border border-white/15 bg-white/10 px-2.5 py-1 text-[11px] font-semibold text-white/90">
                Patrocinado
              </span>
            </div>
            <button
              type="button"
              onClick={toggleCollapsed}
              className="absolute right-4 top-4 z-20 inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-black/10 text-white/70 backdrop-blur-sm transition hover:bg-black/20"
              aria-label="Fechar"
              title="Fechar"
            >
              <ChevronUp className="h-4 w-4" />
            </button>

            <div className="relative aspect-[32/5] w-full bg-slate-950">
              {active ? (
                href ? (
                  <a href={href} target={target} rel={rel} className="group absolute inset-0">
                    <img
                      src={active.image_url}
                      alt={active.image_alt || active.title || "Banner patrocinado"}
                      className="h-full w-full object-cover transition duration-500 group-hover:scale-[1.01]"
                    />
                    <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_25%_25%,rgba(0,0,0,0.06)_0%,rgba(0,0,0,0.34)_58%,rgba(0,0,0,0.52)_100%)]" />
                  </a>
                ) : (
                  <>
                    <img
                      src={active.image_url}
                      alt={active.image_alt || active.title || "Banner patrocinado"}
                      className="h-full w-full object-cover"
                    />
                    <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_25%_25%,rgba(0,0,0,0.06)_0%,rgba(0,0,0,0.34)_58%,rgba(0,0,0,0.52)_100%)]" />
                  </>
                )
              ) : (
                <div className="absolute inset-0 bg-[linear-gradient(135deg,rgba(79,70,229,0.18)_0%,rgba(15,23,42,0.72)_55%,rgba(15,23,42,0.88)_100%)]" />
              )}
            </div>

            {banners.length > 1 ? (
              <>
                <button
                  type="button"
                  onClick={() => setActiveIndex((current) => clampIndex(current - 1, banners.length))}
                  className={twMerge(
                    "absolute left-3 top-1/2 z-20 hidden h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/10 text-white/70 backdrop-blur-sm transition hover:bg-black/20 md:inline-flex",
                    "opacity-100 pointer-events-auto md:transition-opacity md:duration-200",
                    desktopControlsVisibility
                  )}
                  aria-label="Anterior"
                  title="Anterior"
                >
                  <ChevronLeft className="h-4.5 w-4.5" />
                </button>
                <button
                  type="button"
                  onClick={() => setActiveIndex((current) => clampIndex(current + 1, banners.length))}
                  className={twMerge(
                    "absolute right-3 top-1/2 z-20 hidden h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/10 text-white/70 backdrop-blur-sm transition hover:bg-black/20 md:inline-flex",
                    "opacity-100 pointer-events-auto md:transition-opacity md:duration-200",
                    desktopControlsVisibility
                  )}
                  aria-label="Próximo"
                  title="Próximo"
                >
                  <ChevronRight className="h-4.5 w-4.5" />
                </button>

                <div
                  className={twMerge(
                    "absolute bottom-3 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1 rounded-full border border-white/10 bg-black/10 px-2 py-1.5 backdrop-blur-sm",
                    "opacity-100 pointer-events-auto md:transition-opacity md:duration-200",
                    desktopControlsVisibility
                  )}
                >
                  {banners.map((banner, idx) => {
                    const activeDot = idx === clampIndex(activeIndex, banners.length);
                    return (
                      <button
                        key={banner.id}
                        type="button"
                        onClick={() => setActiveIndex(idx)}
                        className={twMerge(
                          "h-1 w-4 rounded-full transition",
                          activeDot ? "bg-white/80" : "bg-white/25 hover:bg-white/45"
                        )}
                        aria-label={`Ir para o banner ${idx + 1}`}
                        title={`Banner ${idx + 1}`}
                      />
                    );
                  })}
                </div>
              </>
            ) : null}
          </>
        )}
      </div>
    </section>
  );
}
