"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import Icon from "@/components/ui/Icon";
import Photo from "@/components/ui/Photo";
import { youtubeId } from "@/lib/api/videos";
import { useHomeVideos } from "@/store/home";

/**
 * Home: a featured video with a short list beside it. YouTube loads only after Play (click-to-load),
 * from youtube-nocookie. The section hides itself when the API has no videos or is down.
 */
export default function Videos() {
  const reduce = useReducedMotion();
  const { items, status, load } = useHomeVideos();
  const [currentId, setCurrentId] = useState<number | null>(null);
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    if (status === "idle") void load();
  }, [status, load]);

  if (status !== "ready" || items.length === 0) return null;

  const current = items.find((v) => v.id === currentId) ?? items[0];
  const yt = youtubeId(current.video_url);
  const choose = (id: number) => {
    setCurrentId(id);
    setPlaying(false);
  };

  return (
    <section className="vids" id="videos" aria-labelledby="vids-h">
      <div className="wrap">
        <h2 id="vids-h" className="h2 vids-title">
          Watch Syria
        </h2>
        <div className="vids-grid">
          <div className="vids-main">
            <div className="vids-player">
              {playing && yt ? (
                <iframe
                  src={`https://www.youtube-nocookie.com/embed/${yt}?autoplay=1&rel=0`}
                  title={current.title}
                  allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
                  allowFullScreen
                />
              ) : (
                <AnimatePresence initial={false}>
                  <motion.div
                    key={current.id}
                    className="vids-poster"
                    initial={reduce ? false : { opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0, transition: { duration: 0.15 } }}
                    transition={{ duration: 0.25, ease: [0.2, 0.7, 0.2, 1] }}
                  >
                    <Photo src={current.cover?.url ?? null} label={current.title} alt="" />
                  </motion.div>
                </AnimatePresence>
              )}
              {!playing &&
                (yt ? (
                  <button type="button" className="vids-play" onClick={() => setPlaying(true)} aria-label={`Play ${current.title}`}>
                    <Icon name="play_arrow" className="filled" />
                  </button>
                ) : (
                  <a className="vids-play" href={current.video_url} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${current.title} (opens in a new tab)`}>
                    <Icon name="play_arrow" className="filled" />
                  </a>
                ))}
            </div>
            <h3 className="vids-name">{current.title}</h3>
            <p className="vids-desc">
              {current.city && <span>{current.city.name}</span>}
              {current.description}
            </p>
          </div>

          <ol className="vids-list" aria-label="More videos">
            {items.map((v) => (
              <li key={v.id}>
                <button type="button" className="vids-item" aria-pressed={v.id === current.id} onClick={() => choose(v.id)}>
                  <span className="vids-thumb">
                    <Photo src={v.cover?.url ?? null} label={v.title} alt="" />
                  </span>
                  <span className="vids-item-text">
                    <strong>{v.title}</strong>
                    {v.city && <small>{v.city.name}</small>}
                  </span>
                </button>
              </li>
            ))}
          </ol>
        </div>
      </div>
    </section>
  );
}
