
/**
 * TrackDetails — shown after user picks a track OR an artist from the search.
 *
 * Appears as a second "page" (section swap) on Homepage / Services / Results.
 * Displays: artwork, track/artist name, release year, album, genres,
 * audio preview (tracks only), top tracks (artists only), and CTAs.
 */

function TrackDetails({ selection, onReset, onContinue }) {
  const w = useWindowWidth();
  const mobile = w < 768;
  const [visible, setVisible] = React.useState(false);
  const [artist, setArtist] = React.useState(null);
  const [topTracks, setTopTracks] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  // Audio preview — only when a track was picked
  const [playing, setPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const audioRef = React.useRef(null);

  React.useEffect(() => {
    setVisible(false);
    setPlaying(false); setProgress(0);
    setArtist(null); setTopTracks([]);
    setLoading(true);
    const t = setTimeout(() => setVisible(true), 60);

    const artistId = selection?.artistId || selection?.id;
    if (!artistId) { setLoading(false); return () => clearTimeout(t); }

    let cancelled = false;
    (async () => {
      try {
        const [a, tt] = await Promise.all([
          SpotifyAPI.getArtist(artistId),
          selection.kind === 'artist' ? SpotifyAPI.getTopTracks(artistId) : Promise.resolve([]),
        ]);
        if (cancelled) return;
        setArtist(a);
        setTopTracks(tt);
      } catch (e) {
        // Silent fail — we still render whatever we have from the selection
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => { clearTimeout(t); cancelled = true; };
  }, [selection?.id, selection?.kind]);

  function togglePlay() {
    const audio = audioRef.current; if (!audio) return;
    if (playing) { audio.pause(); setPlaying(false); }
    else { audio.play(); setPlaying(true); }
  }
  function handleTimeUpdate() {
    const audio = audioRef.current;
    if (audio && audio.duration) setProgress(audio.currentTime / audio.duration);
  }
  function handleEnded() { setPlaying(false); setProgress(0); }

  if (!selection) return null;

  const isTrack = selection.kind === 'track';
  const artworkUrl = selection.artwork || artist?.artwork;
  const releaseYear = selection.releaseDate ? selection.releaseDate.slice(0, 4) : null;

  return (
    <section style={{
      minHeight: '100vh', padding: mobile ? '96px 20px 80px' : '128px 48px 100px',
      position: 'relative', maxWidth: '1080px', margin: '0 auto',
    }}>
      {/* Ambient */}
      <div style={{
        position: 'absolute', top: '15%', left: '50%', transform: 'translateX(-50%)',
        width: '700px', height: '500px', pointerEvents: 'none',
        background: 'radial-gradient(ellipse 50% 50% at 50% 50%, rgba(201,76,255,0.08) 0%, transparent 70%)',
      }} />

      <div style={{
        opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(24px)',
        transition: 'opacity 700ms cubic-bezier(0.16,1,0.3,1), transform 700ms cubic-bezier(0.16,1,0.3,1)',
        position: 'relative', zIndex: 1,
      }}>
        {/* Back link */}
        <button onClick={onReset} style={{
          background: 'transparent', border: 'none', color: '#7C7C90',
          fontSize: '13px', cursor: 'pointer', display: 'inline-flex',
          alignItems: 'center', gap: '8px', padding: '8px 0',
          fontFamily: 'inherit', letterSpacing: '-0.01em', marginBottom: '32px',
          transition: 'color 200ms',
        }}
        onMouseEnter={e => e.currentTarget.style.color = '#F5F2FF'}
        onMouseLeave={e => e.currentTarget.style.color = '#7C7C90'}
        >
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M8.5 3.5L5 7l3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Back to search
        </button>

        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : 'minmax(260px, 320px) 1fr',
          gap: mobile ? '32px' : '56px',
          alignItems: 'start',
        }}>
          {/* Artwork */}
          <div>
            <div style={{ position: 'relative' }}>
              {artworkUrl
                ? <img src={artworkUrl} alt="" style={{
                    width: '100%', aspectRatio: '1/1',
                    borderRadius: isTrack ? '20px' : '50%',
                    objectFit: 'cover', display: 'block',
                    boxShadow: '0 0 0 1px rgba(255,255,255,0.06), 0 0 80px rgba(201,76,255,0.18), 0 24px 60px rgba(0,0,0,0.6)',
                  }} />
                : <div style={{
                    width: '100%', aspectRatio: '1/1',
                    borderRadius: isTrack ? '20px' : '50%',
                    background: 'linear-gradient(135deg, rgba(94,43,255,0.4), rgba(201,76,255,0.2))',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    boxShadow: '0 0 60px rgba(201,76,255,0.12)',
                  }}>
                    <span style={{ color: '#E7C8FF', fontSize: '64px', fontWeight: 800, letterSpacing: '-0.04em' }}>
                      {(selection.artist || selection.name)?.slice(0, 2).toUpperCase()}
                    </span>
                  </div>
              }
            </div>

            {/* Preview player — only for tracks with preview */}
            {isTrack && selection.previewUrl && (
              <div style={{ marginTop: '20px' }}>
                <audio ref={audioRef} src={selection.previewUrl} onTimeUpdate={handleTimeUpdate} onEnded={handleEnded} style={{ display: 'none' }} />
                <div onClick={togglePlay} style={{
                  display: 'flex', alignItems: 'center', gap: '12px',
                  background: 'rgba(94,43,255,0.08)', border: '1px solid rgba(94,43,255,0.2)',
                  borderRadius: '14px', padding: '12px 16px', cursor: 'pointer',
                }}>
                  <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'linear-gradient(135deg, #5E2BFF, #C94CFF)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {playing
                      ? <svg width="10" height="12" viewBox="0 0 10 12" fill="none"><rect x="0" y="0" width="3.5" height="12" rx="1" fill="white"/><rect x="6.5" y="0" width="3.5" height="12" rx="1" fill="white"/></svg>
                      : <svg width="10" height="12" viewBox="0 0 10 12" fill="none"><path d="M1 1l8 5-8 5V1z" fill="white"/></svg>
                    }
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ height: '3px', background: 'rgba(255,255,255,0.1)', borderRadius: '2px', overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${progress * 100}%`, background: 'linear-gradient(to right, #5E2BFF, #C94CFF)', transition: 'width 0.2s linear' }} />
                    </div>
                  </div>
                  <span style={{ color: '#A1A1B3', fontSize: '11px', fontFamily: "'JetBrains Mono', monospace", flexShrink: 0 }}>30s</span>
                </div>
              </div>
            )}
          </div>

          {/* Details */}
          <div>
            <div style={{
              color: '#C94CFF', fontSize: '11px', fontWeight: 700,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              marginBottom: '16px', fontFamily: "'JetBrains Mono', monospace",
            }}>
              {isTrack ? 'Track selected' : 'Artist selected'}
            </div>

            <h1 style={{
              fontSize: mobile ? 'clamp(32px,8vw,44px)' : 'clamp(40px,5vw,64px)',
              fontWeight: 800, letterSpacing: '-0.04em',
              color: '#F5F2FF', margin: '0 0 10px', lineHeight: 1.02,
            }}>
              {selection.name}
            </h1>

            {isTrack && (
              <p style={{ color: '#A1A1B3', fontSize: mobile ? '16px' : '18px', fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 8px' }}>
                {selection.allArtists}
              </p>
            )}

            <div style={{
              display: 'flex', gap: '14px', flexWrap: 'wrap',
              marginBottom: '36px', marginTop: '12px',
              color: '#7C7C90', fontSize: '12px', fontFamily: "'JetBrains Mono', monospace",
            }}>
              {releaseYear && <span>Released {releaseYear}</span>}
              {selection.albumName && <span style={{ maxWidth: '260px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{selection.albumName}</span>}
              {artist?.genres?.slice(0, 2).map(g => (
                <span key={g} style={{ textTransform: 'capitalize' }}>{g}</span>
              ))}
            </div>

            <p style={{ color: '#A1A1B3', fontSize: '14px', lineHeight: 1.6, letterSpacing: '-0.01em', margin: '0 0 28px', maxWidth: '520px' }}>
              Let's get your music in front of real listeners. Pick a campaign below and we'll handle the rest — visual, targeting, launch, and daily optimization.
            </p>

            <div style={{ display: 'flex', gap: '12px', flexDirection: mobile ? 'column' : 'row' }}>
              <button onClick={onContinue} style={{
                background: 'linear-gradient(135deg, #5E2BFF, #C94CFF)',
                color: '#F5F2FF', padding: '16px 32px', borderRadius: '12px',
                fontSize: '14px', fontWeight: 700, border: 'none', cursor: 'pointer',
                letterSpacing: '-0.01em', fontFamily: 'inherit',
                transition: 'transform 300ms, box-shadow 300ms',
                boxShadow: '0 8px 24px rgba(94,43,255,0.25)',
                display: 'inline-flex', alignItems: 'center', gap: '10px',
                justifyContent: 'center',
              }}
              onMouseEnter={e => { e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 16px 32px rgba(94,43,255,0.35)'; }}
              onMouseLeave={e => { e.currentTarget.style.transform='translateY(0)'; e.currentTarget.style.boxShadow='0 8px 24px rgba(94,43,255,0.25)'; }}
              >
                Continue — pick a campaign
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <path d="M2.5 7h9M8 3.5l3.5 3.5L8 10.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <button onClick={onReset} style={{
                background: 'transparent', color: '#A1A1B3', padding: '16px 32px',
                borderRadius: '12px', fontSize: '14px', fontWeight: 500,
                border: '1px solid rgba(255,255,255,0.08)',
                cursor: 'pointer', letterSpacing: '-0.01em', fontFamily: 'inherit',
                transition: 'border-color 200ms, color 200ms',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor='rgba(255,255,255,0.15)'; e.currentTarget.style.color='#F5F2FF'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor='rgba(255,255,255,0.08)'; e.currentTarget.style.color='#A1A1B3'; }}
              >
                Search again
              </button>
            </div>

            {/* Top tracks, only for artist selections */}
            {!isTrack && topTracks.length > 0 && (
              <div style={{ marginTop: '44px', paddingTop: '32px', borderTop: '1px solid rgba(255,255,255,0.05)' }}>
                <div style={{ color: '#7C7C90', fontSize: '11px', fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: '16px', fontFamily: "'JetBrains Mono', monospace" }}>
                  Top tracks
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
                  {topTracks.map((t, i) => (
                    <div key={t.id} style={{
                      display: 'flex', alignItems: 'center', gap: '14px',
                      padding: '10px 12px', borderRadius: '10px',
                      background: 'rgba(255,255,255,0.02)',
                    }}>
                      <span style={{ color: '#7C7C90', fontSize: '12px', fontFamily: "'JetBrains Mono', monospace", width: '20px' }}>{String(i + 1).padStart(2, '0')}</span>
                      {t.artwork && <img src={t.artwork} alt="" style={{ width: '36px', height: '36px', borderRadius: '6px', objectFit: 'cover' }} />}
                      <span style={{ color: '#F5F2FF', fontSize: '14px', fontWeight: 600, letterSpacing: '-0.01em', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.name}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { TrackDetails });
