import "./App.css";
import { usePostMessage } from "./hooks/usePostMessage";
import { useParentWindow } from "./hooks/useParentWindow";
import { log } from "./util/logger";
import { useEffect, useRef, useState } from "react";
import FrameCounter from "./components/FrameCounter";
import { DeviceInfo } from "./components/DeviceInfo";
import { SpinningLogo } from "./components/SpinningLogo";
import { Heading } from "./components/Heading";
import { DeviceAPIDetector } from "./components/DeviceAPIDetector";
import { useKeyboardShortcut } from "./hooks/useKeyboardShortcut";
import type { BSTicker } from "./BrightSign";
import { ServiceWorkerStatus } from "./components/ServiceWorkerStatus";

const NESTED_IFRAME_URL =
  "https://www.youtube.com/embed/jfKfPfyJRdk?si=HfFYzvJqGDKWtiUI";

export default function App() {
  const { isBrightSign, isDeviceAPIAvailable } = useParentWindow();
  const [showNestedIframe, setShowNestedIframe] = useState(false);
  const ticker = useRef<BSTicker | null>(null);

  usePostMessage();
  useKeyboardShortcut();

  useEffect(() => {
    log("App rendered. Messages from the child window will be logged in blue");
  }, []);

  const createTicker = () => {
    if (isBrightSign) {
      const tickerString = "Hello from the iframe playground";
      const tickerHeight = 30;
      ticker.current = new window.parent.BSTicker(
        0,
        window.innerHeight - tickerHeight,
        window.innerWidth,
        tickerHeight,
        0
      );
      ticker.current.AddString(tickerString);
      ticker.current.SetForegroundColor(255, 255, 255, 255);
      ticker.current.SetBackgroundColor(128, 0, 0, 0);
      ticker.current.SetPixelsPerSecond(200);
      ticker.current.SetSeparatorString(" | ");
    }
  };

  const reboot = () => {
    if (isDeviceAPIAvailable) {
      window.parent.DeviceAPI.reboot();
    }
  };

  return (
    <>
      <SpinningLogo />
      <Heading />
      <DeviceAPIDetector />
      <DeviceInfo />

      {/* Service Worker Status Component for offline functionality */}
      <ServiceWorkerStatus />

      {showNestedIframe ? (
        <iframe
          width="560"
          height="315"
          src={NESTED_IFRAME_URL}
          allow="autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          frameBorder={0}
        />
      ) : null}

      <div className="card row">
        <button onClick={createTicker}>Add BrightSign Ticker</button>
        <button onClick={() => setShowNestedIframe(!showNestedIframe)}>
          Toggle Nested iframe
        </button>
        <button onClick={reboot}>Reboot Device</button>
      </div>
      <FrameCounter />
    </>
  );
}
