"use client";

import { useMemo, useState } from "react";

import styles from "./TutorialLibrary.module.css";

export type LibraryItem = {
  id: string;
  /** The recording's own published title. Quoted, never translated. */
  title: string;
  /** Which language that title is in, so it is not read as ours. */
  titleLang: "sq" | "mk";
  /** Pre-formatted mono line: duration · language · year. */
  meta: string;
  module: string;
  /** Mono code shown at the left: the module code, or SET / SYS. */
  code: string;
};

export type LibraryFilter = { key: string; label: string };

export type LibraryStrings = {
  filterAria: string;
  all: string;
  play: string;
  playAria: string;
  watchOn: string;
  privacy: string;
  empty: string;
  close: string;
};

/**
 * The library. Filtering is local state over a server-rendered list, and a
 * video's iframe is created only when a visitor activates that row — so no
 * request reaches YouTube until then, which is what the privacy notice says.
 */
export function TutorialLibrary({
  items,
  filters,
  strings,
  showFilters = true,
}: {
  items: LibraryItem[];
  filters: LibraryFilter[];
  strings: LibraryStrings;
  showFilters?: boolean;
}) {
  const [active, setActive] = useState<string>("all");
  const [playing, setPlaying] = useState<string | null>(null);

  const counts = useMemo(() => {
    const map = new Map<string, number>();
    for (const item of items) map.set(item.module, (map.get(item.module) ?? 0) + 1);
    return map;
  }, [items]);

  const visible = active === "all" ? items : items.filter((item) => item.module === active);

  return (
    <div>
      {showFilters && filters.length > 0 ? (
        <div className={styles.filters} role="group" aria-label={strings.filterAria}>
          <button
            type="button"
            className={styles.filter}
            aria-pressed={active === "all"}
            onClick={() => setActive("all")}
          >
            {strings.all}
            <span className={styles.count}>{items.length}</span>
          </button>
          {filters.map((filter) => {
            const count = counts.get(filter.key) ?? 0;
            if (count === 0) return null;
            return (
              <button
                key={filter.key}
                type="button"
                className={styles.filter}
                aria-pressed={active === filter.key}
                onClick={() => setActive(filter.key)}
              >
                {filter.label}
                <span className={styles.count}>{count}</span>
              </button>
            );
          })}
        </div>
      ) : null}

      {visible.length === 0 ? (
        <p className={styles.empty}>{strings.empty}</p>
      ) : (
        <ul className={styles.list}>
          {visible.map((item) => {
            const isPlaying = playing === item.id;
            return (
              <li key={item.id} className={styles.item}>
                <button
                  type="button"
                  className={styles.row}
                  aria-expanded={isPlaying}
                  aria-label={strings.playAria.replace("{title}", item.title)}
                  onClick={() => setPlaying(isPlaying ? null : item.id)}
                  data-event="tutorial_play"
                >
                  <span className={styles.code}>{item.code}</span>
                  <span>
                    <span className={styles.title} lang={item.titleLang}>
                      {item.title}
                    </span>
                    <span className={styles.meta}>{item.meta}</span>
                  </span>
                  <span className={styles.play} aria-hidden="true">
                    {isPlaying ? (
                      strings.close
                    ) : (
                      <>
                        <PlayIcon />
                        {strings.play}
                      </>
                    )}
                  </span>
                </button>

                {isPlaying ? (
                  <div className={styles.frame}>
                    <div className={styles.aspect}>
                      <iframe
                        src={`https://www.youtube-nocookie.com/embed/${item.id}?autoplay=1&rel=0&modestbranding=1`}
                        title={item.title}
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture"
                        allowFullScreen
                        referrerPolicy="strict-origin-when-cross-origin"
                      />
                    </div>
                    <p className={styles.frameFoot}>
                      <span>{item.meta}</span>
                      <a
                        href={`https://www.youtube.com/watch?v=${item.id}`}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {strings.watchOn} ↗
                      </a>
                    </p>
                  </div>
                ) : null}
              </li>
            );
          })}
        </ul>
      )}

      <p className={styles.privacy}>{strings.privacy}</p>
    </div>
  );
}

function PlayIcon() {
  return (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path d="M2.5 1.5 10 6l-7.5 4.5z" stroke="currentColor" strokeWidth="1.3" />
    </svg>
  );
}
