'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { AudioPlayer, CapacitorWindow, STREAM_URL } from './AudioPlayer';
import { RadioControls } from './components/RadioControls';
import { WebsitePanel } from './components/WebsitePanel';
import { ACTIVE_SITE } from './config/sites';

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="home-layout">
      <section className="website-zone">
        <WebsitePanel label={ACTIVE_SITE.label} url={ACTIVE_SITE.url} />
      </section>

      <div className="radio-controls-wrap">
        <RadioControls
          status={status}
          isPlaying={isPlaying}
          onPlay={() => player.play(backgroundMode)}
          onStop={() => player.stop()}
        />
      </div>

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