'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { AudioPlayer, CapacitorWindow, STREAM_URL } from './AudioPlayer';

export default function HomePage() {
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [status, setStatus] = useState('Stream is stopped.');
  const [isPlaying, setIsPlaying] = useState(false);

  const backgroundMode = useMemo(() => {
    if (typeof window === 'undefined') {
      return undefined;
    }
    return (window as CapacitorWindow).Capacitor?.Plugins?.BackgroundMode;
  }, []);

  const player = useMemo(
    () =>
      new AudioPlayer(STREAM_URL, (state, msg) => {
        setIsPlaying(state === 'playing');
        setStatus(msg);
      }),
    []
  );

  useEffect(() => {
    if (audioRef.current) {
      player.setElement(audioRef.current);
    }
  }, [player]);

  useEffect(() => {
    if (!backgroundMode) {
      console.warn('BackgroundMode plugin is not available in this runtime.');
      return;
    }
    void player.initBackgroundMode(backgroundMode);
  }, [player, backgroundMode]);

  return (
    <main className="page-shell">
      <section className="player-card" aria-label="KRYZ live stream player">
        <p className="eyebrow">KRYZ Go!</p>
        <h1>Live Radio</h1>
        <p className="status" aria-live="polite">
          {status}
        </p>

        <div className="controls">
          <button type="button" onClick={() => void player.play(backgroundMode)} disabled={isPlaying}>
            Play
          </button>
          <button type="button" onClick={() => player.stop()} disabled={!isPlaying}>
            Stop
          </button>
        </div>

        <audio ref={audioRef} preload="none" />
      </section>
    </main>
  );
}
