import { useEffect, useState } from "react";
import { useParams, useSearchParams } from "react-router-dom";
import { useMediaSync } from "../hooks/useMediaSync";
import { fetchVideo } from "../api/videos";
import { BASE, ApiError } from "../api/client";
import type { VideoDetail } from "../api/videos";
import VideoPlayer from "../components/VideoPlayer";
import AudioWaveform from "../components/AudioWaveform";
import PlayerControls from "../components/PlayerControls";
import styles from "./EmbedPlayer.module.css";

/**
 * Minimal embed page for iframe use — renders the player
 * without app chrome (no header, nav, or footer).
 * Route: /embed/:videoId
 */
export default function EmbedPlayer() {
  const { videoId } = useParams<{ videoId: string }>();
  const [searchParams] = useSearchParams();

  // Parse ?t= start time
  const rawT = parseFloat(searchParams.get("t") ?? "");
  const startTime = Number.isFinite(rawT) && rawT > 0 ? rawT : 0;

  const [video, setVideo] = useState<VideoDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const mediaSync = useMediaSync();

  useEffect(() => {
    if (!videoId) {
      setError("No video ID provided");
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);

    fetchVideo(videoId)
      .then((v) => {
        if (!cancelled) setVideo(v);
      })
      .catch((err) => {
        if (!cancelled) {
          if (err instanceof ApiError && err.status === 404) {
            setError("Video not found");
          } else {
            setError("Failed to load video");
          }
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [videoId]);

  if (loading) {
    return <div className={styles.loadingState}>Loading…</div>;
  }

  if (error || !video) {
    return (
      <div className={styles.errorState}>
        <p className={styles.errorMessage}>{error ?? "Video not found"}</p>
      </div>
    );
  }

  const streamUrl = `${BASE}/videos/${videoId}/stream`;

  return (
    <div className={styles.page}>
      <div className={styles.playerArea}>
        {video.video_url ? (
          <VideoPlayer
            src={video.video_url}
            startTime={startTime}
            mediaSync={mediaSync}
          />
        ) : (
          <AudioWaveform src={streamUrl} mediaSync={mediaSync} />
        )}
      </div>

      <div className={styles.controls}>
        <PlayerControls mediaSync={mediaSync} />
      </div>

      <div className={styles.branding}>
        Powered by{" "}
        <a href={window.location.origin} target="_blank" rel="noopener noreferrer">
          Chrysopedia
        </a>
      </div>
    </div>
  );
}
