'use client';

import {ArrowRight, DoorOpen} from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import {useRouter, useSearchParams} from 'next/navigation';
import {useMemo} from 'react';
import {DemoFrame} from './DemoFrame';
import type {DemoContent} from '@/types/content';

type DemoBrowserProps = {
  demos: DemoContent[];
};

function isKnownDemo(slug: string | null, demos: DemoContent[]): slug is DemoContent['slug'] {
  return demos.some(demo => demo.slug === slug);
}

export function DemoBrowser({demos}: DemoBrowserProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const requestedDemo = searchParams.get('demo');
  const activeSlug = isKnownDemo(requestedDemo, demos) ? requestedDemo : demos[0].slug;

  const activeDemo = useMemo(
    () => demos.find(demo => demo.slug === activeSlug) ?? demos[0],
    [activeSlug, demos]
  );

  function selectDemo(slug: DemoContent['slug']) {
    router.replace(`/pl/dema?demo=${slug}`, {scroll: false});
  }

  return (
    <div className="demoBrowser">
      <aside className="demoBrowser__sidebar" aria-label="Lista dem">
        <p className="eyebrow">Wybierz demo</p>
        <div className="demoBrowser__list">
          {demos.map(demo => (
            <button
              className={demo.slug === activeDemo.slug ? 'demoBrowser__item isActive' : 'demoBrowser__item'}
              key={demo.slug}
              type="button"
              onClick={() => selectDemo(demo.slug)}
            >
              <span className="demoBrowser__thumb">
                {demo.imageUrl ? <Image src={demo.imageUrl} alt="" width={96} height={96} /> : <DoorOpen size={30} />}
              </span>
              <span>
                <strong>{demo.title}</strong>
                <small>{demo.eyebrow}</small>
              </span>
            </button>
          ))}
        </div>
      </aside>
      <section className="demoBrowser__preview" aria-live="polite">
        <DemoFrame title={activeDemo.title} url={activeDemo.iframeUrl} openLabel={activeDemo.openLabel} />
        <div className="demoBrowser__details">
          <div>
            <p className="eyebrow">{activeDemo.eyebrow}</p>
            <h2>{activeDemo.title}</h2>
            <p>{activeDemo.intro}</p>
          </div>
          <Link className="button button--secondary" href={`/pl/${activeDemo.slug}`}>
            Poczytaj więcej
            <ArrowRight size={18} />
          </Link>
        </div>
      </section>
    </div>
  );
}
