import { useEffect, useRef } from "react";
import {
  usePanoStartPosition,
  usePanoStartPov,
  useTargetPoint,
} from "../../../domain/gameStore";
import {
  savePanoPositionToLocalStorage,
  savePanoPovToLocalStorage,
} from "../../../domain/localStorageMethods";
import styles from "./GamePanel.module.css";
import usePano from "./usePano";

const PositionedStreetView = () => {
  const startPosition = usePanoStartPosition();
  const startPov = usePanoStartPov();
  const resetPosition = useTargetPoint();
  const panoDivRef = useRef(null);
  const panoRef = usePano(panoDivRef, startPosition, startPov);
  useEffect(() => {
    if (panoRef.current) {
      panoRef.current.addListener("position_changed", () => {
        const { lat, lng } = panoRef.current.getPosition();
        savePanoPositionToLocalStorage(lat(), lng());
      });
      panoRef.current.addListener("pov_changed", () => {
        const { heading, pitch } = panoRef.current.getPov();
        savePanoPovToLocalStorage(heading, pitch);
      });
    }
  }, [panoRef]);

  const reset = () => panoRef.current.setPosition(resetPosition);

  return (
    <>
      <div className={styles.fullsize} ref={panoDivRef} />
      <div
        role="button"
        tabIndex="0"
        className={styles.resetButton}
        onClick={reset}
        onKeyDown={({ key }) => {
          if (key === "Enter") {
            reset();
          }
        }}
      >
        Reset
      </div>
    </>
  );
};

export default PositionedStreetView;
