#![allow(dead_code, unused_variables)]
use leptos::{logging, prelude::*};
use leptos_meta::{Meta, Title};
use leptos_use::use_event_listener;
use ssr_safe::{MediaPlayer, MediaPlayerError};

mod ssr_safe;

#[component]
fn Controls() -> impl IntoView {
    let player: LocalResource<Result<MediaPlayer, MediaPlayerError>> = expect_context();

    Effect::new(move || {
        let audio_element = if let Some(Ok(p)) = player.get() {
            Some(p.audio_element())
        } else {
            None
        };

        use_event_listener(audio_element, ssr_safe::media_events::error, |ev| {
            logging::error!("{:?}", ev);
        });
    });

    view! {
      <div class="notification">
        <Suspense fallback=move || "Initializing audio player...">
          <ErrorBoundary fallback=|errors| { "Failed to initialize audio player" }>

            <div class="level is-mobile">
              <div class="level-left">
                // The play/pause/etc button
                <div class="level-item">
                  <button class="button" type="button">
                    <span class="icon is-medium" />
                  </button>
                </div>
              </div>

              // The title display
              <div class="level-item">
                {move || {
                  Ok::<_, MediaPlayerError>(player.get().transpose()?.map(|p| p.get_title()))
                }}
              </div>

              // The artist display
              <div class="level-right">
                <div class="level-item">Artist</div>
              </div>
            </div>

          </ErrorBoundary>
        </Suspense>
      </div>
    }
}

#[component]
pub fn MusicSample() -> impl IntoView {
    let player = LocalResource::new(MediaPlayer::new);
    provide_context(player);

    view! {
      <Meta name="description" content="tlater.net music visualizer sample" />
      <Title text="tlater.net music player" />

      <section class="hero is-fullheight-with-navbar">
        <div class="hero-body p-0">Body</div>
        <div class="hero-foot">
          <Controls />
        </div>
      </section>
    }
}
