"use client";

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

interface AgeVerificationModalProps {
  children: React.ReactNode;
}

const AgeVerificationModal: React.FC<AgeVerificationModalProps> = ({ children }) => {
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    const ageVerified = localStorage.getItem("ageVerified");
    if (ageVerified !== "true") {
      setShowModal(true);
    }
  }, []);

  const handleVerify = (isAdult: boolean) => {
    if (isAdult) {
      localStorage.setItem("ageVerified", "true");
      setShowModal(false);
    } else {
      alert("Helaas, je moet 18+ zijn om deze website te bezoeken.");
      // Optionally redirect or close the tab
      window.location.href = "about:blank"; // Example: closes the tab or redirects
    }
  };

  if (!showModal) {
    return <>{children}</>;
  }

  // Render modal using createPortal to ensure it's at the top level
  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-70">
      <div className="bg-white p-8 rounded-lg shadow-xl text-center max-w-sm mx-auto">
        <h2 className="text-xl font-bold mb-4 text-black">
          OEPS, EVEN CHECKEN. PYK is een tikkeltje anders... net als onze check. Stel jezelf de vraag: ben je 18+? Eerlijk antwoord, graag! 😉
        </h2>
        <div className="flex justify-center gap-4">
          <button
            onClick={() => handleVerify(true)}
            className="px-6 py-3 bg-[var(--primary-cta)] text-[var(--primary-cta-text)] rounded-md hover:opacity-90 transition-opacity"
          >
            JA
          </button>
          <button
            onClick={() => handleVerify(false)}
            className="px-6 py-3 bg-[var(--secondary-cta)] text-[var(--secondary-cta-text)] border border-[var(--secondary-cta)] rounded-md hover:bg-[var(--secondary-cta)]/90 transition-colors"
          >
            NEE
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
};

export default AgeVerificationModal;
