/**
 * Player — Motor de reprodução visual do SpotOnFide
 *
 * ESTADOS:
 *
 * Desktop (lg+):
 *   - Barra fixa h-24 no bottom, esquerda em lg:left-64 (após sidebar)
 *   - Controles completos sempre visíveis
 *   - Sem expansão (desnecessária em desktop)
 *
 * Mobile (< lg):
 *   - MiniPlayer: barra h-[60px] fixo ACIMA da BottomNav
 *     * Capa + Título + Subtítulo + Play/Pause
 *     * Toque expande para player completo
 *     * Barra de progresso fina no topo (sem interação)
 *   - Player Expandido: tela cheia com todos os controles
 *     * Botão fechar no topo direito
 *     * Capa grande
 *     * Controles completos com botões grandes (min 48px)
 *
 * FASES FUTURAS (não alterar estrutura, apenas adicionar):
 *   Fase 1: MediaSession API (adicionar useEffect no PlayerContext)
 *   Fase 1: QueueDrawer acessível via botão na área de controles expandidos
 *   Fase 4: Marcadores de capítulo adicionados ao slider de progresso
 *
 * SAFE AREA:
 *   - MiniPlayer: bottom posicionado sobre a BottomNav com safe area
 *   - Player expandido: padding-bottom com safe area
 *   - Nunca usar valores fixos de px para bottom em mobile
 *
 * FUNDO SÓLIDO:
 *   - Sempre bg-[#2a0110] com valor hexadecimal explícito
 *   - NÃO usar apenas bg-sof-borgonha (variável CSS pode não propagar
 *     em contexto PWA instalado no iOS Safari)
 */

import { usePlayer } from "@/contexts/PlayerContext";
import { assetUrl } from "@/lib/asset";
import { trpc } from "@/lib/trpc";
import { useState } from "react";
import { Link } from "wouter";
import { Button } from "./ui/button";
import { Slider } from "./ui/slider";
import QueueDrawer from "./QueueDrawer";

function formatTime(time: number) {
  if (!time || isNaN(time)) return "0:00";
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
}

export default function Player() {
  const {
    currentItem,
    isPlaying,
    currentTime,
    duration,
    volume,
    repeat,
    shuffle,
    togglePlayPause,
    seek,
    setVolume,
    playNext,
    playPrevious,
    toggleRepeat,
    toggleShuffle,
  } = usePlayer();

  // Estado de expansão — exclusivo para mobile
  const [isExpanded, setIsExpanded] = useState(false);

  // Fase 1: estado de abertura do QueueDrawer — compartilhado entre o botão
  // do player expandido mobile e o botão do player desktop.
  const [isQueueOpen, setIsQueueOpen] = useState(false);

  const apresentadorId = currentItem?.kind === "episodio" ? currentItem.apresentadorId : null;
  const apresentadorQuery = trpc.podcast.getApresentador.useQuery(
    { id: apresentadorId ?? 0 },
    { enabled: !!apresentadorId }
  );

  const isIdle = !currentItem;

  const titulo = isIdle ? "Aguardando reprodução" : currentItem.titulo;

  const subtitulo = isIdle
    ? "SpotOnFide · ONFIDE"
    : currentItem.kind === "vinheta"
      ? "Vinheta"
      : (apresentadorQuery.data?.apresentador?.nome ?? currentItem.subtitulo ?? "SpotOnFide Podcast");

  const capa = isIdle || currentItem.kind === "vinheta" ? "/favicon.jpg" : currentItem.capa;
  const capaUrl = assetUrl(capa) ?? assetUrl("/placeholder-podcast.svg") ?? "";

  // Porcentagem de progresso para a barra fina do MiniPlayer
  const progressoPct = duration > 0 ? (currentTime / duration) * 100 : 0;

  // ─── ELEMENTO DE ÁUDIO ──────────────────────────────────────────────────
  // CORREÇÃO (jul/2026, ADR-004): não vive mais aqui. Antes era renderizado
  // em dois `return` diferentes deste componente (player expandido vs.
  // recolhido/desktop) — cada troca de isExpanded desmontava e recriava o
  // <audio> de verdade, perdendo a reprodução e a Media Session. Agora
  // vive dentro de PlayerProvider (client/src/contexts/PlayerContext.tsx),
  // que nunca desmonta, de propósito.

  // ─── CONTROLES COMPARTILHADOS ────────────────────────────────────────────
  // Reutilizados no Player Desktop e no Player Expandido Mobile
  const controles = (
    <div className="flex items-center justify-center gap-6">
      {/* Aleatório */}
      <button
        onClick={toggleShuffle}
        disabled={isIdle}
        aria-label="Modo aleatório"
        className={`w-10 h-10 flex items-center justify-center rounded-full transition-colors disabled:opacity-30
          ${shuffle ? "text-sof-gold" : "text-sof-text-3 hover:text-sof-text"}`}
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
          <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
        </svg>
      </button>

      {/* Anterior */}
      <button
        onClick={playPrevious}
        disabled={isIdle}
        aria-label="Faixa anterior"
        className="w-10 h-10 flex items-center justify-center rounded-full text-sof-text-3 hover:text-sof-text disabled:opacity-30 transition-colors"
      >
        <svg viewBox="0 0 24 24" fill="currentColor" className="w-6 h-6">
          <path d="M9.195 18.44c1.25.714 2.805-.189 2.805-1.629v-2.34l6.945 3.968c1.25.715 2.805-.188 2.805-1.628V8.69c0-1.44-1.555-2.343-2.805-1.628L12 11.029v-2.34c0-1.44-1.555-2.343-2.805-1.628l-7.108 4.061c-1.26.72-1.26 2.536 0 3.256l7.108 4.061z" />
        </svg>
      </button>

      {/* Play / Pause — botão principal, maior */}
      <button
        onClick={togglePlayPause}
        disabled={isIdle}
        aria-label={isPlaying ? "Pausar" : "Reproduzir"}
        className="w-14 h-14 flex items-center justify-center rounded-full bg-sof-gold text-[#2a0110] hover:bg-sof-gold-light disabled:opacity-30 transition-colors shadow-lg"
      >
        {isPlaying ? (
          <svg viewBox="0 0 24 24" fill="currentColor" className="w-7 h-7">
            <path fillRule="evenodd" d="M6.75 5.25a.75.75 0 01.75-.75H9a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H7.5a.75.75 0 01-.75-.75V5.25zm7.5 0A.75.75 0 0115 4.5h1.5a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H15a.75.75 0 01-.75-.75V5.25z" clipRule="evenodd" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" fill="currentColor" className="w-7 h-7 ml-0.5">
            <path fillRule="evenodd" d="M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z" clipRule="evenodd" />
          </svg>
        )}
      </button>

      {/* Próximo */}
      <button
        onClick={playNext}
        disabled={isIdle}
        aria-label="Próxima faixa"
        className="w-10 h-10 flex items-center justify-center rounded-full text-sof-text-3 hover:text-sof-text disabled:opacity-30 transition-colors"
      >
        <svg viewBox="0 0 24 24" fill="currentColor" className="w-6 h-6">
          <path d="M5.055 7.06c-1.25-.714-2.805.189-2.805 1.628v8.123c0 1.44 1.555 2.342 2.805 1.628L12 14.471v2.34c0 1.44 1.555 2.342 2.805 1.628l7.108-4.061c1.26-.72 1.26-2.536 0-3.256L14.805 7.06C13.555 6.346 12 7.25 12 8.688v2.34L5.055 7.06z" />
        </svg>
      </button>

      {/* Repetir */}
      <button
        onClick={toggleRepeat}
        disabled={isIdle}
        aria-label={`Repetir: ${repeat === "off" ? "desligado" : repeat === "all" ? "fila" : "uma vez"}`}
        className={`w-10 h-10 flex items-center justify-center rounded-full transition-colors disabled:opacity-30
          ${repeat !== "off" ? "text-sof-gold" : "text-sof-text-3 hover:text-sof-text"}`}
      >
        {repeat === "one" ? (
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
            <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 12c0-1.232-.046-2.453-.138-3.662a4.006 4.006 0 00-3.7-3.7 48.678 48.678 0 00-7.324 0 4.006 4.006 0 00-3.7 3.7c-.017.22-.032.441-.046.662M19.5 12l3-3m-3 3l-3-3m-12 3c0 1.232.046 2.453.138 3.662a4.006 4.006 0 003.7 3.7 48.656 48.656 0 007.324 0 4.006 4.006 0 003.7-3.7c.017-.22.032-.441.046-.662M4.5 12l3 3m-3-3l-3 3" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
            <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
          </svg>
        )}
      </button>
    </div>
  );

  // ─── SLIDER DE PROGRESSO COMPARTILHADO ──────────────────────────────────
  const sliderProgresso = (
    <div className="w-full flex items-center gap-3">
      <span className="text-xs text-sof-text-3 min-w-[36px] text-right tabular-nums">
        {formatTime(currentTime)}
      </span>
      <Slider
        value={[currentTime]}
        max={duration || 100}
        step={0.1}
        disabled={isIdle}
        onValueChange={value => seek(value[0])}
        className="flex-1"
        aria-label="Progresso da reprodução"
      />
      <span className="text-xs text-sof-text-3 min-w-[36px] tabular-nums">
        {formatTime(duration)}
      </span>
    </div>
  );

  // ─── MOBILE: PLAYER EXPANDIDO (tela cheia) ──────────────────────────────
  if (isExpanded) {
    return (
      <>
        <div className="fixed inset-0 z-50 flex flex-col bg-[#2a0110] lg:hidden">
          {/* Header do player expandido */}
          <div className="flex items-center justify-between px-4 pt-safe-top pt-4 pb-2">
            {/* Botão fechar (chevron down) */}
            <button
              onClick={() => setIsExpanded(false)}
              aria-label="Minimizar player"
              className="w-10 h-10 flex items-center justify-center text-sof-text-2 hover:text-sof-text"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} className="w-6 h-6">
                <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
              </svg>
            </button>

            {/* Título da seção */}
            <span className="text-xs uppercase tracking-widest text-sof-text-3 font-ui">
              {currentItem?.kind === "vinheta" ? "Vinheta" : "Reproduzindo agora"}
            </span>

            {/* Botão da fila de reprodução */}
            <button
              onClick={() => setIsQueueOpen(true)}
              aria-label="Ver fila de reprodução"
              className="w-10 h-10 flex items-center justify-center text-sof-text-2 hover:text-sof-text"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h10.5" />
              </svg>
            </button>
          </div>

          {/* Capa grande */}
          <div className="flex-1 flex items-center justify-center px-8 py-4">
            <div className="w-full max-w-xs aspect-square rounded-2xl overflow-hidden shadow-2xl">
              <img
                src={capaUrl}
                alt={titulo}
                className={`w-full h-full object-cover ${isIdle ? "opacity-50" : ""}`}
              />
            </div>
          </div>

          {/* Metadados */}
          <div className="px-6 pb-4">
            <div className="flex items-start justify-between gap-2 mb-1">
              <div className="min-w-0">
                <p className="text-lg font-bold text-sof-text truncate leading-tight">
                  {titulo}
                </p>
                <p className="text-sm text-sof-text-3 truncate mt-0.5">{subtitulo}</p>
              </div>
              {/* Espaço para botão favoritar (Fase 1: adicionar FavoritoButton aqui) */}
              {/* FASE-1-INTEGRATION-POINT: <FavoritoButton episodioId={...} /> */}
            </div>

            {/* Barra de progresso interativa */}
            <div className="mt-4 mb-6">{sliderProgresso}</div>

            {/* Controles */}
            <div className="mb-6">{controles}</div>

            {/* Volume — mobile expandido */}
            <div className="flex items-center gap-3 pb-safe">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-4 h-4 text-sof-text-3 flex-shrink-0">
                <path strokeLinecap="round" strokeLinejoin="round" d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z" />
              </svg>
              <Slider
                value={[volume]}
                max={1}
                step={0.01}
                onValueChange={value => setVolume(value[0])}
                className="flex-1"
                aria-label="Volume"
              />
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5 text-sof-text-3 flex-shrink-0">
                <path strokeLinecap="round" strokeLinejoin="round" d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z" />
              </svg>
            </div>
          </div>
        </div>

        <QueueDrawer open={isQueueOpen} onClose={() => setIsQueueOpen(false)} />
      </>
    );
  }

  // ─── MOBILE: MINI-PLAYER (colapsado, sobre a BottomNav) ─────────────────
  // ─── DESKTOP: PLAYER COMPLETO (barra fixa h-24) ─────────────────────────
  return (
    <>
      {/* ── MINI-PLAYER MOBILE ── */}
      {/*
       * Posicionamento:
       *   bottom: 56px (altura da BottomNav h-14) + env(safe-area-inset-bottom)
       *   Usamos a classe CSS customizada bottom-bottomnav definida em index.css
       *
       * Altura: 60px (h-[60px])
       * Fundo: bg-[#2a0110] hexadecimal explícito (não variável CSS)
       * Barra de progresso: fina (h-0.5) no topo, não interativa
       */}
      <div className="lg:hidden fixed left-0 right-0 bottom-bottomnav z-40">
        {/* Barra de progresso fina no topo do mini-player */}
        <div className="h-0.5 bg-white/10 w-full">
          <div
            className="h-full bg-sof-gold transition-all duration-300"
            style={{ width: `${progressoPct}%` }}
          />
        </div>

        <div
          className="h-[60px] bg-[#2a0110] border-t border-white/10 flex items-center px-3 gap-3 cursor-pointer"
          onClick={() => !isIdle && setIsExpanded(true)}
          role="button"
          aria-label="Expandir player"
          tabIndex={0}
          onKeyDown={e => e.key === "Enter" && !isIdle && setIsExpanded(true)}
        >
          {/* Capa pequena */}
          <img
            src={capaUrl}
            alt={titulo}
            className={`w-10 h-10 rounded-lg object-cover flex-shrink-0 ${isIdle ? "opacity-50" : ""}`}
          />

          {/* Título e subtítulo */}
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-sof-text truncate leading-tight">{titulo}</p>
            <p className="text-xs text-sof-text-3 truncate">{subtitulo}</p>
          </div>

          {/* Botão Play/Pause — único controle no mini-player */}
          {/* stopPropagation para não expandir ao clicar no botão */}
          <button
            onClick={e => {
              e.stopPropagation();
              togglePlayPause();
            }}
            disabled={isIdle}
            aria-label={isPlaying ? "Pausar" : "Reproduzir"}
            className="w-10 h-10 flex items-center justify-center rounded-full bg-sof-gold text-[#2a0110] hover:bg-sof-gold-light disabled:opacity-30 transition-colors flex-shrink-0"
          >
            {isPlaying ? (
              <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
                <path fillRule="evenodd" d="M6.75 5.25a.75.75 0 01.75-.75H9a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H7.5a.75.75 0 01-.75-.75V5.25zm7.5 0A.75.75 0 0115 4.5h1.5a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H15a.75.75 0 01-.75-.75V5.25z" clipRule="evenodd" />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5 ml-0.5">
                <path fillRule="evenodd" d="M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z" clipRule="evenodd" />
              </svg>
            )}
          </button>
        </div>
      </div>

      {/* ── PLAYER DESKTOP (lg+) ── */}
      {/*
       * Posicionamento: fixed bottom-0, left-64 (após sidebar), right-0
       * Altura: h-24 (96px) — inalterada
       * Fundo: bg-[#2a0110] hexadecimal explícito
       */}
      <div className="hidden lg:flex fixed bottom-0 left-64 right-0 h-24 bg-[#2a0110] border-t border-white/10 items-center justify-between px-8 gap-8 z-30">
        {/* Info da faixa */}
        <div className="flex-1 min-w-0 flex items-center gap-3">
          <img
            src={capaUrl}
            alt={titulo}
            className={`w-12 h-12 rounded-lg object-cover flex-shrink-0 ${isIdle ? "opacity-50" : ""}`}
          />
          <div className="min-w-0">
            {currentItem?.kind === "episodio" ? (
              <Link href={`/episodio/${currentItem.sourceId}`}>
                <p className="text-sm font-medium text-sof-text truncate hover:text-sof-gold cursor-pointer">
                  {titulo}
                </p>
              </Link>
            ) : (
              <p className="text-sm font-medium text-sof-text truncate">{titulo}</p>
            )}
            <p className="text-xs text-sof-text-3 truncate">{subtitulo}</p>
          </div>
        </div>

        {/* Controles centrais */}
        <div className="flex flex-col items-center gap-2 flex-1 max-w-xl">
          {controles}
          {sliderProgresso}
        </div>

        {/* Fila + Volume desktop */}
        <div className="flex items-center gap-4 w-48 justify-end">
          <button
            onClick={() => setIsQueueOpen(true)}
            aria-label="Ver fila de reprodução"
            className="w-9 h-9 flex items-center justify-center rounded-full text-sof-text-3 hover:text-sof-text transition-colors flex-shrink-0"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-5 h-5">
              <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h10.5" />
            </svg>
          </button>

          <div className="flex items-center gap-2 flex-1">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} className="w-4 h-4 text-sof-text-3 flex-shrink-0">
              <path strokeLinecap="round" strokeLinejoin="round" d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z" />
            </svg>
            <Slider
              value={[volume]}
              max={1}
              step={0.01}
              onValueChange={value => setVolume(value[0])}
              className="flex-1"
              aria-label="Volume"
            />
          </div>
        </div>
      </div>

      <QueueDrawer open={isQueueOpen} onClose={() => setIsQueueOpen(false)} />
    </>
  );
}
