"use client";
import { useAppSelector } from '@/core/utils/hooks/useRedux';
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { panoramaLinks } from './panoramaLinks';
import Logger from "@/core/utils/helpers/logger";

const getLinkIdByRoom = (selectedRoom: string | null): `${number}` => {
  for (const room in panoramaLinks) {
    if (panoramaLinks[room]?.fullName === selectedRoom) {
      return panoramaLinks[room].linkId;
    }
  }
  return panoramaLinks.kitchen.linkId;
};

const PanoramaPage = () => {
  const frame = useRef<HTMLIFrameElement>(null);
  const [currentLinkId, setCurrentLinkId] = useState<`${number}`>('200');
  const selectedRoom = useAppSelector(state => state.customization.selectedCurrentRoom);

  useEffect(() => {
    const linkId = getLinkIdByRoom(selectedRoom);
    setCurrentLinkId(linkId);
  }, [selectedRoom])

  useEffect(() => {
    /**
     * Well.. good try but not. The cors is blocking it.
     * Coulb be implemented by adding simple javascript code to the iFrame origin html.
     * Firstly – we'll send a post message:
     *
     *      .contentWindow?.postMessage({ .. });
     *
     * Then – this message could be listened by "message" event on the iPanaroma html page file.
     * Guess we could try
     */
    if (frame.current) {
      frame.current.onload = () => {
        const panoramaDocument = frame.current?.contentDocument;
        Logger.dev("panoramaDocument", panoramaDocument);
        if (panoramaDocument) {
          const bottomPane = panoramaDocument.querySelector<HTMLDivElement>("div.ipnrm-scene-bottom-panel");
          Logger.dev("bottomPane", bottomPane);
          bottomPane && (bottomPane.style.display = "none");
        }
      }
    }
  }, [currentLinkId, selectedRoom]);

  return (
    <div style={{ width: '100%', height: '100vh', position: "fixed", top: 0, left: 0, right: 0, bottom: 0 }}>
      <iframe
        ref={frame}
        src={`https://ipanorama.happyuser.info/${currentLinkId}`}
        style={{ width: '100%', height: '100%', border: 'none' }}
        title={"Panorama"}
      />
    </div>
  );
};

export default PanoramaPage;