'use client';

import { useEffect, useState } from 'react';

import { useTranslations } from 'next-intl';

import { ChevronLeft, ChevronRight } from 'lucide-react';

import { RouteLink } from '@/components/ui/route-link';
import { cn } from '@/lib/utils';
import { isCreationPagerLink } from '@/utils/creationHelpers';

import type { CreationPager, CreationPagerLink } from '@/types/Creation';

/* ============================================================================
   CREATION PAGER — prev/next navigation through the creator's œuvre, in the
   backend's chronological order (`elozo_kovetkezo.prev` / `.next`), with the
   current position (`cntAct` / `cntMax`) shown between the two directions.

   Two placements, ONE visual language (uppercase chevron links, brand hover):
     • DESKTOP (lg+)  → CreationPagerBar: a compact inline bar in the breadcrumb
       row's rightSlot. Reads as navigation chrome, not a slideshow, so it never
       floats over the map / carousels lower on the page.
     • MOBILE (<lg)   → CreationNavButtons: the same links in a fixed bottom bar,
       within thumb reach.
   ========================================================================== */

const ITEM_BASE =
  'inline-flex items-center gap-1.5 text-[12px] font-semibold uppercase tracking-[0.15em] transition-colors';
const COUNTER_BASE = 'text-[11px] tabular-nums tracking-[0.1em] text-[#151720]/40';

function PagerLink({
  link,
  direction,
  label,
  className,
}: {
  link: CreationPagerLink | null;
  direction: 'left' | 'right';
  label: string;
  className?: string;
}) {
  const isLeft = direction === 'left';
  const chevron = isLeft ? (
    <ChevronLeft className="h-4 w-4 shrink-0" />
  ) : (
    <ChevronRight className="h-4 w-4 shrink-0" />
  );

  // No work in this direction → keep the slot, but inert and dimmed.
  if (!link) {
    return (
      <span aria-hidden="true" className={cn(ITEM_BASE, 'text-[#151720]/25', className)}>
        {isLeft && chevron}
        <span>{label}</span>
        {!isLeft && chevron}
      </span>
    );
  }

  return (
    <RouteLink
      href={{ pathname: '/alkotas/[id]', params: { id: link.alkotasAzonosito } }}
      aria-label={`${label}: ${link.nev}`}
      title={link.nev}
      className={cn(ITEM_BASE, 'text-[#151720]/70 hover:text-brand-primary', className)}
    >
      {isLeft && chevron}
      <span>{label}</span>
      {!isLeft && chevron}
    </RouteLink>
  );
}

function useLinks(pager: CreationPager | null) {
  const prev = isCreationPagerLink(pager?.prev) ? pager!.prev! : null;
  const next = isCreationPagerLink(pager?.next) ? pager!.next! : null;
  const counter = pager?.cntAct && pager?.cntMax ? `${pager.cntAct}/${pager.cntMax}` : null;
  return { prev, next, counter };
}

/* DESKTOP — inline bar for the breadcrumb rightSlot (lg+) */
export function CreationPagerBar({ pager }: { pager: CreationPager | null }) {
  const t = useTranslations('creationPage.pager');
  const { prev, next, counter } = useLinks(pager);

  if (!prev && !next) return null;

  return (
    <nav aria-label={t('label')} className="hidden h-full items-center lg:flex">
      <PagerLink link={prev} direction="left" label={t('previous')} className="h-full px-2.5" />
      {counter && <span className={cn(COUNTER_BASE, 'px-1.5')}>{counter}</span>}
      <PagerLink link={next} direction="right" label={t('next')} className="h-full px-2.5" />
    </nav>
  );
}

/* MOBILE — fixed bottom bar (<lg) */
export default function CreationNavButtons({
  pager,
  className,
}: {
  pager: CreationPager | null;
  className?: string;
}) {
  const t = useTranslations('creationPage.pager');
  // Slide the bar away once the footer scrolls into view, so it never sits on top of it.
  const [footerInView, setFooterInView] = useState(false);
  useEffect(() => {
    const footer = document.querySelector('footer');
    if (!footer) return;
    const observer = new IntersectionObserver(([entry]) => setFooterInView(entry.isIntersecting));
    observer.observe(footer);
    return () => observer.disconnect();
  }, []);

  const { prev, next, counter } = useLinks(pager);

  if (!prev && !next) return null;

  return (
    <nav
      aria-label={t('label')}
      aria-hidden={footerInView}
      className={cn(
        'fixed inset-x-0 bottom-0 z-50 border-t border-brand-primary/10 bg-surface-paper px-site pb-[env(safe-area-inset-bottom)] shadow-[0_-2px_10px_-6px_rgba(20,23,32,0.25)] transition-transform duration-300 ease-in-out lg:hidden',
        footerInView ? 'pointer-events-none translate-y-full' : 'translate-y-0',
        className
      )}
    >
      <div className="flex h-11 items-center justify-between">
        <PagerLink link={prev} direction="left" label={t('previous')} className="h-full" />
        {counter && <span className={COUNTER_BASE}>{counter}</span>}
        <PagerLink link={next} direction="right" label={t('next')} className="h-full" />
      </div>
    </nav>
  );
}
