"use client";

import Image from "next/image";
import { useCallback, useEffect, useRef, useState } from "react";
import { portfolioProjects, portfolioUi } from "@/content/portfolio";
import type { Locale } from "@/content/site";

export function WorkGrid({ locale }: { locale: Locale }) {
  const [activeId, setActiveId] = useState<string | null>(null);
  const dialogRef = useRef<HTMLDialogElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const triggerRef = useRef<HTMLButtonElement | null>(null);
  const activeProject = portfolioProjects.find((project) => project.id === activeId);
  const ui = portfolioUi[locale];

  const closeProject = useCallback(() => {
    const video = videoRef.current;
    if (video) {
      video.pause();
      video.currentTime = 0;
    }
    setActiveId(null);
    if (dialogRef.current?.open) dialogRef.current.close();
    window.requestAnimationFrame(() => triggerRef.current?.focus());
  }, []);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;

    if (activeProject && !dialog.open) {
      dialog.showModal();
      window.requestAnimationFrame(() => closeRef.current?.focus());
    }
  }, [activeProject]);

  useEffect(() => {
    if (!activeProject) return;
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeProject();
      }
    };
    document.addEventListener("keydown", handleEscape, true);
    return () => document.removeEventListener("keydown", handleEscape, true);
  }, [activeProject, closeProject]);

  return (
    <>
      <div className="work-grid portfolio-grid">
        {portfolioProjects.map((project, index) => {
          const item = project.content[locale];
          return (
            <article
              className="work-card portfolio-card"
              key={project.id}
              data-video-src={project.video}
              data-thumbnail-src={project.thumbnail}
              data-reveal
            >
              <button
                className="portfolio-card-trigger"
                type="button"
                aria-label={`${ui.open}: ${item.title}`}
                onClick={(event) => {
                  triggerRef.current = event.currentTarget;
                  setActiveId(project.id);
                }}
              >
                <span className="work-media-shell portfolio-media-shell">
                  <Image
                    className="portfolio-thumbnail"
                    src={project.thumbnail}
                    alt={item.thumbnailAlt}
                    fill
                    sizes="(max-width: 47.99rem) 100vw, 65vw"
                  />
                  <span className="portfolio-index" aria-hidden="true">
                    {String(index + 1).padStart(2, "0")}
                  </span>
                  <span className="portfolio-play" aria-hidden="true">▶</span>
                </span>
                <span className="work-card-copy">
                  <span className="work-category">{item.category}</span>
                  <span className="portfolio-title">{item.title}</span>
                  <span className="portfolio-description">{item.description}</span>
                </span>
              </button>
            </article>
          );
        })}
      </div>

      <dialog
        ref={dialogRef}
        className="portfolio-dialog"
        aria-label={ui.dialog}
        aria-labelledby={activeProject ? `portfolio-dialog-${activeProject.id}` : undefined}
        onCancel={(event) => {
          event.preventDefault();
          closeProject();
        }}
        onClose={() => {
          if (activeId) setActiveId(null);
          window.requestAnimationFrame(() => triggerRef.current?.focus());
        }}
        onClick={(event) => {
          if (event.target === event.currentTarget) closeProject();
        }}
      >
        {activeProject && (
          <div className="portfolio-dialog-panel">
            <button
              ref={closeRef}
              className="portfolio-dialog-close"
              type="button"
              onClick={closeProject}
              aria-label={ui.close}
            >
              <span aria-hidden="true">×</span>
            </button>
            <video
              ref={videoRef}
              className="portfolio-dialog-video"
              controls
              playsInline
              preload="metadata"
              poster={activeProject.thumbnail}
              aria-label={activeProject.content[locale].previewLabel}
            >
              <source src={activeProject.video} type="video/mp4" />
            </video>
            <div className="portfolio-dialog-copy">
              <p className="work-category">{activeProject.content[locale].category}</p>
              <h2 id={`portfolio-dialog-${activeProject.id}`}>
                {activeProject.content[locale].title}
              </h2>
              <p>{activeProject.content[locale].description}</p>
            </div>
          </div>
        )}
      </dialog>
    </>
  );
}
