"use client";

import { useEffect, useState } from "react";

function supportsDesktopEditor(): boolean {
  if (typeof window === "undefined") {
    return false;
  }

  const userAgent = typeof navigator !== "undefined" ? navigator.userAgent.toLowerCase() : "";
  const mobileUserAgent = /android|iphone|ipad|ipod|tablet|mobile/i.test(userAgent);
  if (mobileUserAgent) {
    return false;
  }

  const coarsePointer =
    window.matchMedia("(pointer: coarse)").matches ||
    window.matchMedia("(any-pointer: coarse)").matches;
  const finePointer =
    window.matchMedia("(pointer: fine)").matches ||
    window.matchMedia("(any-pointer: fine)").matches;
  const touchPoints =
    typeof navigator !== "undefined" && Number.isFinite(navigator.maxTouchPoints)
      ? navigator.maxTouchPoints
      : 0;
  const shortestScreenSide =
    typeof window.screen !== "undefined"
      ? Math.min(window.screen.width || window.innerWidth, window.screen.height || window.innerHeight)
      : Math.min(window.innerWidth, window.innerHeight);

  if (touchPoints > 0 && coarsePointer && shortestScreenSide <= 1366 && !finePointer) {
    return false;
  }

  if (coarsePointer && !finePointer) {
    return false;
  }

  return true;
}

export function useDesktopEditorSupported(): boolean | null {
  const [supported, setSupported] = useState<boolean | null>(null);

  useEffect(() => {
    const update = () => {
      setSupported(supportsDesktopEditor());
    };

    update();
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("resize", update);
    };
  }, []);

  return supported;
}
