/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ============ ICONS ============
const Icon = ({ name, size = 18, className = "", style }) => {
  const paths = {
    play: <polygon points="6 4 20 12 6 20 6 4" fill="currentColor" />,
    pause: <g fill="currentColor"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></g>,
    prev: <g fill="currentColor"><rect x="5" y="5" width="2" height="14" rx="1"/><polygon points="20 5 9 12 20 19 20 5"/></g>,
    next: <g fill="currentColor"><rect x="17" y="5" width="2" height="14" rx="1"/><polygon points="4 5 15 12 4 19 4 5"/></g>,
    shuffle: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></g>,
    repeat: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></g>,
    heart: <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" fill="currentColor"/>,
    heartOutline: <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" fill="none" stroke="currentColor" strokeWidth="1.6"/>,
    plus: <g fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></g>,
    bell: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></g>,
    search: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.5" y2="16.5"/></g>,
    chevDown: <polyline points="6 9 12 15 18 9" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>,
    chevLeft: <polyline points="15 6 9 12 15 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>,
    chevRight: <polyline points="9 6 15 12 9 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>,
    arrowRight: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></g>,
    share: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></g>,
    verified: <g fill="currentColor"><path d="M12 1l2.6 2.4 3.5-.4.7 3.4 3 1.8-1.5 3.2 1.5 3.2-3 1.8-.7 3.4-3.5-.4L12 22l-2.6-2.4-3.5.4-.7-3.4-3-1.8L3.7 12 2.2 8.8l3-1.8.7-3.4 3.5.4L12 1z"/><path d="M10.5 14.5l-2-2 1.5-1.5 1.5 1.5 3.5-3.5L16.5 10l-5 5z" fill="#000"/></g>,
    volume: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></g>,
    settings: <g fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></g>,
    home: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"><path d="M3 12L12 4l9 8"/><path d="M5 10v10h14V10"/></g>,
    library: <g fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></g>,
    list: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></g>,
    user: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></g>,
    moreH: <g fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></g>,
    lyrics: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></g>,
    eq: <g fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></g>,
    sparkles: <g fill="currentColor"><path d="M12 2l1.5 4.5L18 8l-4.5 1.5L12 14l-1.5-4.5L6 8l4.5-1.5z"/><circle cx="19" cy="17" r="1.2"/><circle cx="5" cy="17" r="1.2"/></g>,
    clock: <g fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></g>,
    download: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></g>,
  };
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" className={className} style={style}>
      {paths[name]}
    </svg>
  );
};

// ============ BRAND LOGO ============
const Logo = ({ size = 22, color = "var(--accent)" }) => (
  <svg viewBox="0 0 64 64" width={size} height={size} style={{ display: "block" }}>
    {/* angular V/T mark */}
    <g fill="none" stroke={color} strokeWidth="6" strokeLinejoin="miter">
      <path d="M6 8 L32 56 L58 8" />
      <line x1="20" y1="8" x2="44" y2="8" stroke={color} strokeWidth="6" />
    </g>
    <line x1="32" y1="20" x2="32" y2="44" stroke={color} strokeWidth="3" />
  </svg>
);

// ============ PLACEHOLDER COVER ART ============
const Placeholder = ({ variant = "stage", label, style }) => {
  // variants render different cinematic scenes with css/svg
  const presets = {
    stage:    { bg: "linear-gradient(180deg,#1a1a20,#0a0a0c)", silhouetteIdx: 0 },
    crowd:    { bg: "linear-gradient(180deg,#1c1c22,#0c0c10)", silhouetteIdx: 1 },
    drive:    { bg: "linear-gradient(180deg,#15151a,#08080a)", silhouetteIdx: 2 },
    guitar:   { bg: "linear-gradient(180deg,#181820,#08080c)", silhouetteIdx: 3 },
    industrial:{bg: "linear-gradient(180deg,#1a1820,#0a080c)", silhouetteIdx: 4 },
    fog:      { bg: "linear-gradient(180deg,#20181a,#0c0a0c)", silhouetteIdx: 5 },
    iron:     { bg: "linear-gradient(180deg,#18181c,#0a0a0e)", silhouetteIdx: 6 },
    mic:      { bg: "linear-gradient(180deg,#1a1a1f,#08080c)", silhouetteIdx: 0 },
    chaos:    { bg: "linear-gradient(180deg,#1c1820,#0c080e)", silhouetteIdx: 1 },
  };
  const p = presets[variant] || presets.stage;
  return (
    <div className="ph" style={{ background: p.bg, ...style }}>
      <div className="ph-spots" aria-hidden="true">
        <i style={{ animationDelay: "0s" }}></i>
        <i style={{ animationDelay: ".2s" }}></i>
        <i style={{ animationDelay: ".4s" }}></i>
        <i style={{ animationDelay: ".6s" }}></i>
        <i style={{ animationDelay: ".8s" }}></i>
      </div>
      <Silhouette idx={p.silhouetteIdx} />
      {label && <div className="ph-label">{label}</div>}
    </div>
  );
};

const TrackArt = ({ track, variant = "stage" }) => {
  if (track && track.artUrl) {
    return (
      <div className="catalog-art" style={{ backgroundImage: `url("${track.artUrl}")` }}>
        <img src={track.artUrl} alt="" />
      </div>
    );
  }
  return <Placeholder variant={(track && track.variant) || variant} />;
};

const Silhouette = ({ idx = 0 }) => {
  // simple abstract silhouettes (vocalist / crowd / car / guitarist / building / fog / weights / drums)
  const silhouettes = [
    // 0 vocalist
    <svg viewBox="0 0 200 200" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="0">
      <path d="M100 60 q12 -10 16 4 q4 14 -2 22 l10 35 l-6 70 l-20 5 l-5 -50 l-10 50 l-22 -5 l-2 -50 l8 -42 q-6 -16 4 -28 q12 -14 29 -11z" fill="#000" />
      <path d="M105 92 l4 25 l28 30" stroke="#000" strokeWidth="3" fill="none" />
      <circle cx="135" cy="148" r="6" fill="#000" />
    </svg>,
    // 1 crowd
    <svg viewBox="0 0 200 100" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="1" style={{ width: "100%", height: "45%" }}>
      {[10, 30, 50, 70, 90, 110, 130, 150, 170, 190].map((x, i) => (
        <g key={i}>
          <circle cx={x} cy={70} r={9} fill="#000" />
          <rect x={x - 8} y={70} width={16} height={30} fill="#000" />
          <rect x={x - 3} y={30} width={3} height={40} fill="#000" />
          <rect x={x + 0} y={20} width={3} height={50} fill={i % 2 ? "#000" : "transparent"} />
        </g>
      ))}
    </svg>,
    // 2 car
    <svg viewBox="0 0 200 100" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="2" style={{ width: "70%", height: "35%" }}>
      <path d="M10 75 Q40 35 100 35 Q160 35 190 75 L190 90 L10 90 Z" fill="#000" />
      <circle cx="55" cy="90" r="14" fill="#000" />
      <circle cx="145" cy="90" r="14" fill="#000" />
      <rect x="40" y="40" width="120" height="20" rx="4" fill="#1a1a1a" />
    </svg>,
    // 3 guitarist
    <svg viewBox="0 0 200 220" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="3">
      <path d="M90 30 q14 -6 22 6 q6 14 -4 22 l8 30 l-10 30 l-2 90 l-22 5 l-4 -50 l-8 50 l-22 -5 l4 -65 l-6 -45 q-4 -18 6 -30 q14 -16 38 -8z" fill="#000" />
      <ellipse cx="130" cy="135" rx="26" ry="36" fill="#000" />
      <rect x="100" y="55" width="44" height="6" fill="#000" transform="rotate(-30 130 80)" />
    </svg>,
    // 4 building/industrial
    <svg viewBox="0 0 200 100" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="4" style={{ width: "100%", height: "70%" }}>
      <rect x="0" y="30" width="60" height="70" fill="#000" />
      <rect x="65" y="50" width="40" height="50" fill="#000" />
      <rect x="110" y="20" width="35" height="80" fill="#000" />
      <rect x="150" y="55" width="50" height="45" fill="#000" />
      <rect x="20" y="0" width="6" height="30" fill="#000" />
      <rect x="120" y="0" width="3" height="22" fill="#000" />
    </svg>,
    // 5 mic stand fog
    <svg viewBox="0 0 200 200" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="5">
      <rect x="98" y="100" width="4" height="90" fill="#000" />
      <ellipse cx="100" cy="95" rx="14" ry="20" fill="#000" />
      <rect x="80" y="190" width="40" height="6" fill="#000" />
    </svg>,
    // 6 weights / iron
    <svg viewBox="0 0 200 100" preserveAspectRatio="xMidYMax meet" className="ph-silhouette" key="6" style={{ width: "80%" }}>
      <rect x="10" y="40" width="14" height="40" fill="#000" />
      <rect x="24" y="50" width="6" height="20" fill="#000" />
      <rect x="30" y="56" width="140" height="6" fill="#000" />
      <rect x="170" y="50" width="6" height="20" fill="#000" />
      <rect x="176" y="40" width="14" height="40" fill="#000" />
    </svg>,
  ];
  return silhouettes[idx % silhouettes.length];
};

// ============ TOP NAV ============
const TopNav = ({ active, onNav, accentDot, accountMode = "preview", currentTrack }) => {
  const links = ["Home", "Browse", "Playlists"];
  return (
    <div className="topnav">
      <div className="brand">
        <div className="brand-name">VIRAL TENSION</div>
      </div>
      <div className="nav-links">
        {links.map(l => (
          <button
            key={l}
            className={`nav-link ${active === l ? "is-active" : ""}`}
            onClick={() => onNav(l)}
          >{l}</button>
        ))}
      </div>
      <div className="nav-right">
        <button className="plan-chip" onClick={() => onNav("Admin")}>{accountMode === "preview" ? "30s Preview" : accountMode === "trial" ? "3-Day Trial" : "Premium"}</button>
        <button className="icon-btn" onClick={() => onNav("Browse")} aria-label="Search">
          <Icon name="search" />
        </button>
        <button className="avatar-chip" onClick={() => onNav("Account")} aria-label="Account settings">
          <div className="avatar account-avatar">
            <Icon name="user" size={18} />
          </div>
          <Icon name="chevDown" size={14} />
        </button>
      </div>
    </div>
  );
};

const MobileBottomNav = ({ active, onNav }) => {
  const items = [
    { label: "Home", page: "Home", icon: "home" },
    { label: "Browse", page: "Browse", icon: "search" },
    { label: "Playlists", page: "Playlists", icon: "list" },
    { label: "Account", page: "Account", icon: "user" },
  ];
  return (
    <nav className="mobile-bottom-nav" aria-label="Mobile navigation">
      {items.map((item) => (
        <button
          key={item.page}
          className={`mobile-nav-item ${active === item.page ? "is-active" : ""}`}
          onClick={() => onNav(item.page)}
        >
          <Icon name={item.icon} size={18} />
          <span>{item.label}</span>
        </button>
      ))}
    </nav>
  );
};

// ============ BOTTOM PLAYER ============
const Player = ({ track, isPlaying, setPlaying, previewSeconds = 30, isLiked = false, onToggleLike, onNextTrack, onPrevTrack }) => {
  const audioRef = useRef(null);
  const [progress, setProgress] = useState(0);
  const [duration, setDuration] = useState(track.duration || 0);

  // animated wave
  const bars = 80;
  const waveBars = useMemo(() => {
    return Array.from({ length: bars }).map((_, i) => {
      const seed = Math.sin(i * 1.3) * 0.5 + Math.cos(i * 0.6) * 0.5;
      return 0.2 + Math.abs(seed) * 0.8;
    });
  }, []);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (isPlaying) {
      audio.play().catch(() => setPlaying(false));
    } else {
      audio.pause();
    }
  }, [isPlaying, track.audioUrl]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    audio.currentTime = 0;
    setProgress(0);
    setDuration(track.duration || 0);
    if (isPlaying) audio.play().catch(() => setPlaying(false));
  }, [track.id]);

  useEffect(() => {
    const pageTitle = `${track.title} — VIRAL TENSION`;
    document.title = pageTitle;

    if (!("mediaSession" in navigator) || !window.MediaMetadata) return;

    const brandArtwork = "assets/viral-tension-profile-square.jpg";

    navigator.mediaSession.metadata = new MediaMetadata({
      title: track.title,
      artist: "VIRAL TENSION",
      album: "VIRAL TENSION",
      artwork: [
        { src: brandArtwork, sizes: "512x512", type: "image/jpeg" },
        { src: brandArtwork, sizes: "1024x1024", type: "image/jpeg" },
      ],
    });
  }, [track.id, track.title, track.artUrl]);

  const handleTimeUpdate = () => {
    const audio = audioRef.current;
    if (!audio) return;
    const realDuration = audio.duration && Number.isFinite(audio.duration) ? audio.duration : track.duration || 0;
    setDuration(realDuration);
    setProgress(realDuration ? audio.currentTime / realDuration : 0);
    if (previewSeconds && audio.currentTime >= previewSeconds) {
      audio.pause();
      setPlaying(false);
      audio.currentTime = previewSeconds;
    }
  };

  const seekTo = (event) => {
    const audio = audioRef.current;
    if (!audio || !duration) return;
    const rect = event.currentTarget.getBoundingClientRect();
    const nextProgress = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
    audio.currentTime = nextProgress * duration;
    setProgress(nextProgress);
  };

  const playedIdx = Math.floor(progress * bars);

  return (
    <div className="player">
      <audio
        ref={audioRef}
        src={track.audioUrl}
        preload="metadata"
        onTimeUpdate={handleTimeUpdate}
        onLoadedMetadata={handleTimeUpdate}
        onEnded={() => setPlaying(false)}
      />
      <div className="np">
        <div className="np-art"><TrackArt track={track} variant="crowd" /></div>
        <div className="np-meta">
          <p className="np-title">{track.title}</p>
          <p className="np-artist">{track.artist} {track.access && <span className="access-dot">{track.access}</span>}</p>
        </div>
        <div className="np-actions">
          <button className={`icon-btn like ${isLiked ? "is-on" : ""}`} onClick={onToggleLike} aria-label={isLiked ? "Unlike song" : "Like song"}>
            <Icon name={isLiked ? "heart" : "heartOutline"} />
          </button>
        </div>
      </div>

      <div className="player-center">
        <div className="player-controls">
          <button className="icon-btn player-skip" onClick={onPrevTrack} aria-label="Previous track">
            <Icon name="prev" size={18} />
          </button>
          <button className="btn-circle is-primary" onClick={() => setPlaying(!isPlaying)} aria-label="Play/Pause">
            <Icon name={isPlaying ? "pause" : "play"} size={22} />
          </button>
          <button className="icon-btn player-skip" onClick={onNextTrack} aria-label="Next track">
            <Icon name="next" size={18} />
          </button>
        </div>
        <div className="player-progress">
          <span className="player-time">{fmtTime(progress * duration)}</span>
          <div className="waveform" onClick={seekTo} role="slider" aria-label="Seek through song" aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(progress * 100)}>
            {waveBars.map((h, i) => (
              <i
                key={i}
                className={i < playedIdx ? "played" : i === playedIdx ? "now" : ""}
                style={{ height: `${h * 100}%` }}
              ></i>
            ))}
          </div>
          <span className="player-time">{fmtTime(duration || track.duration || 0)}</span>
        </div>
      </div>

      <div className="player-right">
        <div className="vol">
          <Icon name="volume" size={18} />
          <div className="vol-track"><i style={{ width: "70%" }}></i></div>
        </div>
      </div>
    </div>
  );
};

const fmtTime = (s) => {
  const m = Math.floor(s / 60);
  const ss = Math.floor(s % 60).toString().padStart(2, "0");
  return `${m}:${ss}`;
};

Object.assign(window, { Icon, Logo, Placeholder, TrackArt, Silhouette, TopNav, MobileBottomNav, Player, fmtTime });
