"use client";

import { useCallback, useEffect, useState } from "react";
import NewMatchProfilePage from "@/app/new-match/profile/page";
import SectionOverlayHost from "@/components/Componentes/section-overlay-host";
import { useHardwareBackHandler } from "@/hooks/use-hardware-back-handler";

export type MatchProfileOverlayProps = {
  open: boolean;
  onClose: () => void;
};

/**
 * Hook to manage Match Profile ("More detail") slide-in overlay state.
 * Syncs with browser history (?profile=open) and intercepts hardware back in Flutter.
 */
export function useMatchProfileOverlay() {
  const [isProfileOpen, setIsProfileOpen] = useState(false);

  useEffect(() => {
    const readProfileFromUrl = () => {
      if (typeof window === "undefined") return;
      const params = new URLSearchParams(window.location.search);
      setIsProfileOpen(params.get("profile") === "open");
    };

    readProfileFromUrl();
    window.addEventListener("popstate", readProfileFromUrl);
    return () => window.removeEventListener("popstate", readProfileFromUrl);
  }, []);

  const openProfile = useCallback(() => {
    setIsProfileOpen(true);
    if (typeof window !== "undefined") {
      const url = new URL(window.location.href);
      url.searchParams.set("profile", "open");
      window.history.replaceState({ profile: "open" }, "", url.toString());
    }
  }, []);

  const closeProfile = useCallback(() => {
    setIsProfileOpen(false);
    if (typeof window !== "undefined") {
      const params = new URLSearchParams(window.location.search);
      if (params.get("profile") === "open") {
        const url = new URL(window.location.href);
        url.searchParams.delete("profile");
        window.history.replaceState({}, "", url.toString());
      }
    }
  }, []);

  // Intercept hardware back in Flutter WebView when profile overlay is open
  useHardwareBackHandler(() => {
    closeProfile();
    return true; // handled: keep WebView screen open
  }, isProfileOpen);

  return {
    isProfileOpen,
    openProfile,
    closeProfile,
  };
}

export function MatchProfileOverlay({
  open,
  onClose,
}: MatchProfileOverlayProps) {
  return (
    <SectionOverlayHost open={open} onClose={onClose}>
      <NewMatchProfilePage onClose={onClose} />
    </SectionOverlayHost>
  );
}

export default MatchProfileOverlay;
