"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Volume2, VolumeX } from "lucide-react";
import ProfileCard from "./ProfileCard";
import ScrollProfile from "./ScrollProfile";
import Effects from "./Effects";
import ProfileAudioPlayer from "./ProfileAudioPlayer";
import ProfileLyricsBox from "./ProfileLyricsBox";
import AudioVisualizer from "./AudioVisualizer";
import { PREMIUM_AUDIO_TRACK_LIMIT, type Profile } from "@/lib/constants";

export default function ProfilePage({ profile, previewMode = false }: { profile: Profile; previewMode?: boolean }) {
  const accent = profile.accent || "#f5caca";
  const hasBackgroundVideo = /\.(mp4|webm|mov)(\?|#|$)/i.test(profile.background_url || "");
  const tracks = useMemo(() => {
    const list = Array.isArray(profile.audio_tracks) ? profile.audio_tracks.filter((t) => /^https?:\/\//.test(t.url || "")) : [];
    if (list.length) return list.slice(0, PREMIUM_AUDIO_TRACK_LIMIT);
    return /^https?:\/\//.test(profile.audio_url || "") ? [{ id: 0, url: profile.audio_url, name: "Audio" }] : [];
  }, [profile.audio_tracks, profile.audio_url]);
  const hasAudio = tracks.length > 0;
  const enterText = profile.enter_text ?? "click to enter";
  const shouldShowEnterOverlay = (hasAudio && !profile.audio_player_enabled) || hasBackgroundVideo || Boolean((enterText || "").trim());
  const [trackIndex, setTrackIndex] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [playedTrackIndexes, setPlayedTrackIndexes] = useState<number[]>([]);
  const [entered, setEntered] = useState(previewMode ? true : !shouldShowEnterOverlay);
  const isPremium = Boolean(profile.premium_until && Date.parse(profile.premium_until) > Date.now());
  const [isOverlayExiting, setIsOverlayExiting] = useState(false);
  const [isCinematicEntering, setIsCinematicEntering] = useState(false);
  const [playerAudioEl, setPlayerAudioEl] = useState<HTMLAudioElement | null>(null);
  const [muted, setMuted] = useState(false);
  const [volume, setVolume] = useState(50);
  const [showVolume, setShowVolume] = useState(false);
  useEffect(() => {
    try {
      const saved = localStorage.getItem("sinss_visitor_volume");
      if (saved !== null) {
        const parsed = parseInt(saved, 10);
        if (!isNaN(parsed) && parsed >= 0 && parsed <= 100) {
          setVolume(parsed);
        }
      }
    } catch {}
  }, []);
  const audioRef = useRef<HTMLAudioElement>(null);
  const clickSoundContextRef = useRef<AudioContext | null>(null);
  const clickSoundBufferRef = useRef<AudioBuffer | null>(null);
  const clickSoundSourceRef = useRef<AudioBufferSourceNode | null>(null);
  const playbackToken = useRef(0);
  const clickSoundUrl = useMemo(() => {
    try {
      const url = new URL(profile.click_sound_url || "");
      return url.protocol === "https:" ? url.href : "";
    } catch {
      return "";
    }
  }, [profile.click_sound_url]);
  const customCursorUrl = useMemo(() => {
    try {
      const url = new URL(profile.custom_cursor_url || "");
      return url.protocol === "https:" || url.protocol === "http:" ? url.href : "";
    } catch {
      return "";
    }
  }, [profile.custom_cursor_url]);

  useEffect(() => {
    if (previewMode) return;
    let sent = false;
    let timer: number | undefined;

    const scheduleView = () => {
      if (sent || timer !== undefined || document.visibilityState !== "visible") return;
      timer = window.setTimeout(() => {
        timer = undefined;
        if (sent || document.visibilityState !== "visible") return;
        sent = true;
        fetch(`/api/sys/v?username=${encodeURIComponent(profile.username)}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: "{}",
        }).catch(() => {});
      }, 2000);
    };

    scheduleView();
    document.addEventListener("visibilitychange", scheduleView);
    return () => {
      document.removeEventListener("visibilitychange", scheduleView);
      if (timer !== undefined) window.clearTimeout(timer);
    };
  }, [profile.username, previewMode]);

  useEffect(() => {
    if (!clickSoundUrl || previewMode) return;
    const clickSound = new Audio();
    clickSound.preload = "auto";
    clickSound.src = clickSoundUrl;
    clickSound.load();

    let disposed = false;
    let context: AudioContext | null = null;
    try {
      const audioContext = new AudioContext();
      context = audioContext;
      clickSoundContextRef.current = audioContext;
      void fetch(clickSoundUrl)
        .then((response) => {
          if (!response.ok) throw new Error(`HTTP ${response.status}`);
          return response.arrayBuffer();
        })
        .then((data) => audioContext.decodeAudioData(data))
        .then((buffer) => {
          if (!disposed) clickSoundBufferRef.current = buffer;
        })
        .catch((error: unknown) => {
          if (!disposed) console.warn("Profile click sound could not be preloaded:", error);
        });
    } catch (error) {
      console.warn("Web Audio is unavailable for this profile click sound:", error);
    }

    const playClickSound = () => {
      const audioContext = clickSoundContextRef.current;
      const buffer = clickSoundBufferRef.current;
      if (audioContext && buffer) {
        clickSoundSourceRef.current?.stop();
        const source = audioContext.createBufferSource();
        source.buffer = buffer;
        source.connect(audioContext.destination);
        clickSoundSourceRef.current = source;
        source.onended = () => {
          if (clickSoundSourceRef.current === source) clickSoundSourceRef.current = null;
          source.disconnect();
        };
        void audioContext.resume().catch((error: unknown) => {
          console.warn("Profile click sound audio context could not resume:", error);
        });
        source.start(0);
        return;
      }

      clickSound.pause();
      try {
        clickSound.currentTime = 0;
      } catch {
        clickSound.load();
      }
      void clickSound.play().catch((error: unknown) => {
        if (error instanceof DOMException && error.name === "AbortError") return;
        console.warn("Profile click sound could not be played:", error);
      });
    };

    document.addEventListener("click", playClickSound, true);
    return () => {
      disposed = true;
      document.removeEventListener("click", playClickSound, true);
      clickSound.pause();
      clickSoundSourceRef.current?.stop();
      clickSoundSourceRef.current = null;
      clickSoundBufferRef.current = null;
      clickSoundContextRef.current = null;
      if (context && context.state !== "closed") void context.close();
    };
  }, [clickSoundUrl, previewMode]);

  useEffect(() => {
    if (!customCursorUrl) return;
    const cursorStyle = document.createElement("style");
    cursorStyle.textContent = `html, body, body * { cursor: url("${customCursorUrl}") 16 16, auto !important; }`;
    document.head.appendChild(cursorStyle);
    return () => cursorStyle.remove();
  }, [customCursorUrl]);

  const playTrack = (index: number, restart = false) => {
    const audio = audioRef.current;
    const track = tracks[index];
    if (!audio || !track?.url) return;

    playbackToken.current += 1;
    const token = playbackToken.current;

    audio.volume = volume / 100;
    audio.muted = muted;

    const isVis = profile.effect === "visualizer";
    const resolvedUrl = isVis && track.url && (track.url.startsWith("http://") || track.url.startsWith("https://"))
      ? `/api/sys/audio-proxy?url=${encodeURIComponent(track.url)}`
      : track.url;

    if (audio.src !== resolvedUrl && !audio.src.endsWith(encodeURIComponent(track.url))) {
      audio.src = resolvedUrl;
      audio.load();
    } else if (restart) {
      audio.currentTime = 0;
    }

    const tryPlay = () => {
      if (playbackToken.current !== token) return;
      audio.play().catch(() => {
        // Some browsers need the file to buffer after the first click.
        // Keep the same user-requested track queued and start as soon as it can play.
        const onReady = () => {
          if (playbackToken.current === token) audio.play().catch(() => {});
        };
        audio.addEventListener("canplay", onReady, { once: true });
        audio.addEventListener("loadeddata", onReady, { once: true });
      });
    };

    tryPlay();
  };

  const enter = () => {
    const startIndex = profile.audio_shuffle && tracks.length > 1 ? Math.floor(Math.random() * tracks.length) : 0;
    setTrackIndex(startIndex);
    setPlayedTrackIndexes([startIndex]);

    const startAudio = () => {
      if (!profile.audio_player_enabled) {
        playTrack(startIndex, true);
        const targetVol = volume / 100;
        if (audioRef.current && targetVol > 0) {
          audioRef.current.volume = 0;
          let currentFade = 0;
          const fadeInterval = setInterval(() => {
            currentFade += 0.05;
            if (audioRef.current) {
              if (currentFade >= targetVol) {
                audioRef.current.volume = targetVol;
                clearInterval(fadeInterval);
              } else {
                audioRef.current.volume = currentFade;
              }
            } else {
              clearInterval(fadeInterval);
            }
          }, 20);
        }
      }
    };

    if (isPremium) {
      setIsOverlayExiting(true);
      setIsCinematicEntering(true);
      startAudio();
      setTimeout(() => {
        setEntered(true);
        setIsOverlayExiting(false);
      }, 450);
      setTimeout(() => {
        setIsCinematicEntering(false);
      }, 850);
    } else {
      setEntered(true);
      startAudio();
    }
  };


  useEffect(() => {
    if (!audioRef.current) return;
    audioRef.current.volume = volume / 100;
    audioRef.current.muted = muted;
  }, [volume, muted]);

  const toggleMute = () => {
    if (!audioRef.current) return;
    audioRef.current.muted = !audioRef.current.muted;
    setMuted(audioRef.current.muted);
  };

  const changeVolume = (next: number) => {
    setVolume(next);
    if (audioRef.current) {
      audioRef.current.volume = next / 100;
      audioRef.current.muted = next === 0;
      setMuted(audioRef.current.muted);
    }
  };

  const nextTrack = () => {
    if (!audioRef.current || tracks.length === 0) return;
    let next = (trackIndex + 1) % tracks.length;
    if (profile.audio_shuffle && tracks.length > 1) {
      const remaining = tracks.map((_, i) => i).filter((i) => i !== trackIndex && !playedTrackIndexes.includes(i));
      const pool = remaining.length ? remaining : tracks.map((_, i) => i).filter((i) => i !== trackIndex);
      next = pool[Math.floor(Math.random() * pool.length)] ?? next;
    }
    setTrackIndex(next);
    setPlayedTrackIndexes((prev) => {
      const merged = [...prev, next];
      return merged.length >= tracks.length ? [next] : merged;
    });
    playTrack(next, true);
  };

    const activeTrack = tracks[trackIndex] || null;
  const isPortfolio = profile.layout === "portfolio";
  const isCompact = profile.layout === "compact";
  const isMinimal = profile.layout === "minimal";
  const isBanner = profile.layout === "banner";
  const layoutWidth = isPortfolio || isBanner ? 760 : isCompact ? 360 : isMinimal ? 520 : 430;
  const cardWidth = Math.max(320, Math.min(900, profile.profile_card_width ?? layoutWidth));
  const cardRadius = Math.max(0, Math.min(48, profile.profile_card_radius ?? 20));

  const visualizer = entered && isPremium && profile.effect === "visualizer" ? (
    <AudioVisualizer
      accent={accent}
      isPlaying={isPlaying}
      currentTime={currentTime}
      audioElement={profile.audio_player_enabled ? playerAudioEl : audioRef.current}
      previewMode={previewMode}
    />
  ) : null;

  const lyricsBox = entered && activeTrack?.lyrics ? (
    <ProfileLyricsBox
      track={activeTrack}
      currentTime={currentTime}
      isPlaying={isPlaying}
      accent={accent}
      opacity={profile.profile_opacity ?? 70}
      blur={profile.profile_blur ?? 22}
      cardWidth={cardWidth}
      cardRadius={cardRadius}
      onSeek={(time) => {
        if (audioRef.current) {
          audioRef.current.currentTime = time;
        }
      }}
    />
  ) : null;

  return (
    <main style={{ minHeight: "100vh", position: "relative" }} suppressHydrationWarning>
      {previewMode && (
        <div role="status" style={{ position: "fixed", top: 12, left: "50%", transform: "translateX(-50%)", zIndex: 20, width: "max-content", maxWidth: "calc(100vw - 24px)", padding: "10px 15px", border: "1px solid rgba(245, 202, 202, .42)", borderRadius: 999, background: "rgba(8,13,16,.9)", color: "#ffffff", fontSize: 12, fontWeight: 750, textAlign: "center", backdropFilter: "blur(12px)" }}>
          Template preview · Nothing is saved to your profile
        </div>
      )}
      {entered && (
        <Effects accent={accent} effect={profile.effect} cursor={profile.cursor_effect} />
      )}

      <div className={isCinematicEntering ? "cinematicCardEnterWrap" : undefined} style={{ position: "relative", zIndex: 1, minHeight: "100vh" }} suppressHydrationWarning>
        {profile.layout === "scroll" ? (
          <ScrollProfile
            profile={profile}
            entered={entered}
            lyricsBox={lyricsBox}
            visualizer={visualizer}
            audioPlayer={entered && profile.audio_player_enabled && hasAudio ? (
              <ProfileAudioPlayer tracks={tracks} accent={accent} opacity={profile.profile_opacity ?? 70} blur={profile.profile_blur ?? 22} onTimeUpdate={setCurrentTime} onPlayStateChange={setIsPlaying} onTrackChange={setTrackIndex} onAudioElement={setPlayerAudioEl} isVisualizer={profile.effect === "visualizer"} />
            ) : null}
          />
        ) : (
          <ProfileCard
            profile={profile}
            entered={entered}
            lyricsBox={lyricsBox}
            visualizer={visualizer}
            audioPlayer={entered && profile.audio_player_enabled && hasAudio ? (
              <ProfileAudioPlayer tracks={tracks} accent={accent} opacity={profile.profile_opacity ?? 70} blur={profile.profile_blur ?? 22} onTimeUpdate={setCurrentTime} onPlayStateChange={setIsPlaying} onTrackChange={setTrackIndex} onAudioElement={setPlayerAudioEl} isVisualizer={profile.effect === "visualizer"} />
            ) : null}
          />
        )}
      </div>

      {hasAudio && !profile.audio_player_enabled && <audio ref={audioRef} crossOrigin="anonymous" src={profile.effect === "visualizer" && tracks[trackIndex]?.url?.startsWith("http") ? `/api/sys/audio-proxy?url=${encodeURIComponent(tracks[trackIndex]?.url || "")}` : tracks[trackIndex]?.url} loop={tracks.length === 1} preload="auto" playsInline onCanPlay={() => entered && audioRef.current?.paused && playTrack(trackIndex)} onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)} onPlay={() => setIsPlaying(true)} onPause={() => setIsPlaying(false)} onEnded={nextTrack} style={{ display: "none" }} />}

      {entered && hasAudio && !profile.audio_player_enabled && (
        <div
          onMouseEnter={() => setShowVolume(true)}
          onMouseLeave={() => setShowVolume(false)}
          style={{
            position: "fixed",
            bottom: 86,
            right: 18,
            zIndex: 6,
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: showVolume ? "8px 12px" : 0,
            borderRadius: 999,
            border: showVolume ? `1px solid ${accent}66` : "none",
            background: showVolume ? "rgba(15,15,22,0.78)" : "transparent",
            backdropFilter: "blur(8px)",
          }}
        >
          {showVolume && (
            <input
              aria-label="Audio volume"
              type="range"
              min={0}
              max={100}
              value={volume}
              onChange={(e) => changeVolume(Number(e.target.value))}
              style={{ width: 110, accentColor: accent }}
            />
          )}
          <button
            onClick={toggleMute}
            aria-label={muted ? "Unmute" : "Mute"}
            style={{
              width: 42,
              height: 42,
              borderRadius: "50%",
              border: `1px solid ${accent}66`,
              background: "rgba(15,15,22,0.7)",
              color: "#580404",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              backdropFilter: "blur(8px)",
            }}
          >
            {muted ? <VolumeX size={18} /> : <Volume2 size={18} />}
          </button>
        </div>
      )}

      {(!entered || isOverlayExiting) && shouldShowEnterOverlay && (
        <button
          onClick={enter}
          className={isOverlayExiting ? "cinematicOverlayFade" : undefined}
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 10,
            border: "none",
            cursor: "pointer",
            background: "rgba(5,5,7,0.55)",
            backdropFilter: "blur(14px)",
            WebkitBackdropFilter: "blur(14px)",
            color: "#580404",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontFamily: "Inter, system-ui, sans-serif",
            pointerEvents: isOverlayExiting ? "none" : "auto",
          }}
        >
          <span
            style={{
              display: "inline-block",
              letterSpacing: "0.18em",
              textTransform: "lowercase",
              padding: "14px 26px",
              borderRadius: 14,
              border: `1px solid ${accent}55`,
              boxShadow: `0 0 30px -8px ${accent}`,
              color: profile.enter_text_color || "#000000",
              fontSize: profile.enter_text_size ?? 22,
              filter: profile.enter_text_effect === "glow" ? `drop-shadow(0 0 12px ${profile.enter_text_color || accent})` : "none",
              animation: profile.enter_text_effect === "pulse" ? "enterTextPulse 2s ease-in-out infinite" : profile.enter_text_effect === "float" ? "enterTextFloat 3s ease-in-out infinite" : "none",
            }}
          >
            {enterText.trim() || "click to enter"}
          </span>
        </button>
      )}
      <style>{`
        @keyframes enterTextPulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }
        @keyframes enterTextFloat { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-7px); } }
        .cinematicOverlayFade {
          animation: cinematicOverlayFadeAnim 0.45s cubic-bezier(0.16, 1, 0.3, 1) forwards !important;
        }
        @keyframes cinematicOverlayFadeAnim {
          0% { opacity: 1; transform: scale(1); filter: blur(0px); }
          100% { opacity: 0; transform: scale(1.06); filter: blur(16px); }
        }
        .cinematicCardEnterWrap {
          animation: cinematicCardEnterAnim 0.75s cubic-bezier(0.16, 1, 0.3, 1) forwards;
          will-change: transform, opacity, filter;
        }
        @keyframes cinematicCardEnterAnim {
          0% {
            opacity: 0;
            transform: perspective(1000px) scale(0.92) translateY(24px) rotateX(3deg);
            filter: blur(12px) brightness(1.25);
          }
          60% {
            filter: blur(0px) brightness(1.08);
          }
          100% {
            opacity: 1;
            transform: perspective(1000px) scale(1) translateY(0) rotateX(0deg);
            filter: blur(0px) brightness(1);
          }
        }
      `}</style>
    </main>
  );
}
