"use client";

import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";

const AgeVerificationModal = ({ children }: { children: React.ReactNode }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isVerified, setIsVerified] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const ageVerified = localStorage.getItem("ageVerified");
      if (ageVerified === "true") {
        setIsVerified(true);
      } else {
        setIsModalOpen(true);
      }
    }
  }, []);

  const handleVerifyAge = (verified: boolean) => {
    if (typeof window !== "undefined") {
      localStorage.setItem("ageVerified", verified ? "true" : "false");
      setIsVerified(verified);
      setIsModalOpen(false);
      if (!verified) {
        window.location.href = "https://www.google.com"; // Redirect if not verified
      }
    }
  };

  if (isVerified) {
    return <>{children}</>;
  }

  if (typeof window === "undefined" || !isModalOpen) {
    return null;
  }

  return createPortal(
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80">
      <div className="bg-white p-8 rounded-lg shadow-xl text-center max-w-sm mx-auto">
        <h2 className="text-2xl font-bold mb-4 text-black">Leeftijdsverificatie</h2>
        <p className="text-gray-700 mb-6">U moet 18 jaar of ouder zijn om deze website te bezoeken.</p>
        <div className="flex justify-center space-x-4">
          <button
            onClick={() => handleVerifyAge(true)}
            className="bg-blue-600 text-white px-6 py-2 rounded-md hover:bg-blue-700 transition-colors"
          >
            Ja, ik ben 18+
          </button>
          <button
            onClick={() => handleVerifyAge(false)}
            className="bg-gray-300 text-gray-800 px-6 py-2 rounded-md hover:bg-gray-400 transition-colors"
          >
            Nee
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
};

export default AgeVerificationModal;
