// "use client";

// import { useState } from "react";
// import { X, Mail, Phone, Loader2, ArrowRight } from "lucide-react";
// import { useEffect } from "react";

// const baseURL = process.env.NEXT_PUBLIC_API_BASE_URL;

// export default function FunnelPopup({ open, onClose, actionType, config }) {
//   const [emailValue, setEmailValue] = useState("");
//   const [phoneValue, setPhoneValue] = useState("");
//   const [loading, setLoading] = useState(false);

//   const isEmail = actionType === 3;

//   useEffect(() => {
//     if (!open) return;

//     // Reset only the current input value when popup opens
//     if (actionType === 3) {
//       const savedEmail = localStorage.getItem("userEmail");
//       if (savedEmail) setEmailValue(savedEmail);
//       else setEmailValue("");
//     } else {
//       const savedMobile = localStorage.getItem("userMobile");
//       if (savedMobile) setPhoneValue(savedMobile);
//       else setPhoneValue("");
//     }
//   }, [open, actionType]);

//   if (!open) return null;

//   const currentValue = isEmail ? emailValue : phoneValue;
//   const setCurrentValue = isEmail ? setEmailValue : setPhoneValue;

//   const handleSubmit = async () => {
//     const isValid = isEmail
//       ? currentValue.includes("@")
//       : currentValue.length >= 10;

//     if (!isValid) return;

//     try {
//       setLoading(true);

//       const cookieUser = localStorage.getItem("userId");

//       // Save to localStorage
//       if (isEmail) {
//         localStorage.setItem("userEmail", currentValue);
//       } else {
//         localStorage.setItem("userMobile", currentValue);
//       }

//       // 1️ INSERT NUMBER (LEAD CAPTURE)
//       await fetch(`${baseURL}/insert_number`, {
//         method: "POST",
//         headers: { "Content-Type": "application/json" },
//         body: JSON.stringify({
//           cookieUser: cookieUser || null,
//           platform: navigator.platform,
//           browser: navigator.userAgent,
//           type: actionType,
//           mobile: !isEmail ? currentValue : null,
//           email: isEmail ? currentValue : null,
//         }),
//       });

//       // 2️⃣ INSERT FUNNEL (TRACKING)
//       await fetch(`${baseURL}/insert_funnel`, {
//         method: "POST",
//         headers: { "Content-Type": "application/json" },
//         body: JSON.stringify({
//           cookieUser: cookieUser || null,
//           platform: navigator.platform,
//           browser: navigator.userAgent,
//           type: actionType,
//           keyword_name:
//             window.location.pathname.split("/").filter(Boolean).pop() || "home",
//         }),
//       });

//       // 3️⃣ ACTION
//       if (actionType === 1) {
//         const number = config?.calling_number;

//         if (number) {
//           window.location.href = `tel:${number}`;
//         }
//       }
//       if (actionType === 2) {
//         const number = config?.whatsapp_number;

//         const url = `https://api.whatsapp.com/send/?phone=${number}&text=${encodeURIComponent(
//           config?.whatsapp_message || "Hi",
//         )}&type=phone_number&app_absent=0`;

//         window.open(url, "_blank");
//       }
//       if (actionType === 3) {
//         const email = config?.email;

//         if (email) {
//           window.location.href = `mailto:${email}`;
//         }
//       }

//       // Reset only the current value
//       setCurrentValue("");
//       onClose();
//     } catch (err) {
//       console.error("Funnel error:", err);
//     } finally {
//       setLoading(false);
//     }
//   };

//   const getTitle = (type) => {
//     switch (type) {
//       case 3:
//         return "Enter Email Address";
//       case 2:
//         return "Enter WhatsApp Number";
//       case 1:
//         return "Enter Mobile Number";
//       default:
//         return "Enter Details";
//     }
//   };

//   const getButtonText = (type) => {
//     switch (type) {
//       case 1:
//         return "Call Now";
//       case 2:
//         return "Continue";
//       case 3:
//         return "Continue";
//       default:
//         return "Submit";
//     }
//   };

//   return (
//     <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
//       <div className="bg-white w-[90%] max-w-sm rounded-2xl p-6 shadow-2xl relative">
//         {/* Close button */}
//         <button
//           onClick={onClose}
//           className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 transition-colors"
//         >
//           <X className="w-5 h-5" />
//         </button>

//         {/* Icon */}
//         <div className="flex justify-center mb-4">
//           <div
//             className={`w-14 h-14 rounded-full flex items-center justify-center ${
//               isEmail ? "bg-red-100" : "bg-blue-100"
//             }`}
//           >
//             {isEmail ? (
//               <Mail className="w-7 h-7 text-red-600" />
//             ) : (
//               <Phone className="w-7 h-7 text-blue-600" />
//             )}
//           </div>
//         </div>

//         <h2 className="text-xl font-bold text-center text-gray-800">
//           {getTitle(actionType)}
//         </h2>

//         <p className="text-sm text-center text-gray-500 mt-1">
//           {isEmail
//             ? "We'll send updates to this email"
//             : "We'll call you on this number"}
//         </p>

//         <input
//           type={isEmail ? "email" : "tel"}
//           value={currentValue}
//           onChange={(e) => setCurrentValue(e.target.value)}
//           placeholder={isEmail ? "you@example.com" : "9876543210"}
//           className="w-full border border-gray-200 rounded-xl px-4 py-3 mt-5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
//           autoFocus
//         />

//         <div className="flex gap-3 mt-6">
//           <button
//             onClick={onClose}
//             className="w-1/2 bg-gray-100 hover:bg-gray-200 py-3 rounded-xl font-medium text-gray-700 transition-all"
//           >
//             Cancel
//           </button>

//           <button
//             onClick={handleSubmit}
//             disabled={loading}
//             className={`w-1/2 ${
//               actionType === 3
//                 ? "bg-red-600 hover:bg-red-700"
//                 : "bg-blue-600 hover:bg-blue-700"
//             } text-white py-3 rounded-xl font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2`}
//           >
//             {loading ? (
//               <>
//                 <Loader2 className="w-4 h-4 animate-spin" />
//                 Processing...
//               </>
//             ) : (
//               <>
//                 {getButtonText(actionType)}
//                 <ArrowRight className="w-4 h-4" />
//               </>
//             )}
//           </button>
//         </div>
//       </div>
//     </div>
//   );
// }

"use client";

import { useState, useEffect } from "react";
import { X, Mail, Phone, Loader2, ArrowRight } from "lucide-react";

const baseURL = process.env.NEXT_PUBLIC_API_BASE_URL;

export default function FunnelPopup({ open, onClose, actionType, config }) {
  const [emailValue, setEmailValue] = useState("");
  const [phoneValue, setPhoneValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [userCountry, setUserCountry] = useState(null);
  const [countryDetected, setCountryDetected] = useState(false);

  // Detect user's country when popup opens
  useEffect(() => {
    if (!open) return;

    const detectCountry = async () => {
      try {
        const response = await fetch("https://ipapi.co/json/");
        const data = await response.json();
        console.log(data);

        setUserCountry(data.country_code);
        setCountryDetected(true);
      } catch (error) {
        console.error("Error detecting country:", error);
        setCountryDetected(true);
      }
    };

    detectCountry();
  }, [open]);

  // Determine if we should show email based on country and action type
  const shouldShowEmail = () => {
    if (!countryDetected) return actionType === 3;

    // For call (type 1) or whatsapp (type 2)
    if (actionType === 1 || actionType === 2) {
      // If user is NOT from India, show email
      if (userCountry && userCountry !== "IN") {
        return true;
      }
    }

    // For email action (type 3) always show email
    if (actionType === 3) {
      return true;
    }

    return false;
  };

  const isEmail = shouldShowEmail();

  useEffect(() => {
    if (!open) return;

    if (isEmail) {
      const savedEmail = localStorage.getItem("userEmail");
      if (savedEmail) setEmailValue(savedEmail);
      else setEmailValue("");
    } else {
      const savedMobile = localStorage.getItem("userMobile");
      if (savedMobile) setPhoneValue(savedMobile);
      else setPhoneValue("");
    }
  }, [open, actionType, isEmail, countryDetected]);

  if (!open) return null;

  const currentValue = isEmail ? emailValue : phoneValue;
  const setCurrentValue = isEmail ? setEmailValue : setPhoneValue;

  const handleSubmit = async () => {
    const isValid = isEmail
      ? currentValue.includes("@")
      : currentValue.length >= 10;

    if (!isValid) return;

    try {
      setLoading(true);

      const cookieUser = localStorage.getItem("userId");

      if (isEmail) {
        localStorage.setItem("userEmail", currentValue);
      } else {
        localStorage.setItem("userMobile", currentValue);
      }

      await fetch(`${baseURL}/insert_number`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          cookieUser: cookieUser || null,
          platform: navigator.platform,
          browser: navigator.userAgent,
          type: actionType,
          mobile: !isEmail ? currentValue : null,
          email: isEmail ? currentValue : null,
        }),
      });

      await fetch(`${baseURL}/insert_funnel`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          cookieUser: cookieUser || null,
          platform: navigator.platform,
          browser: navigator.userAgent,
          type: actionType,
          keyword_name:
            window.location.pathname.split("/").filter(Boolean).pop() || "home",
        }),
      });

      if (actionType === 1) {
        const number = config?.calling_number;
        if (number) {
          window.location.href = `tel:${number}`;
        }
      }
      if (actionType === 2) {
        const number = config?.whatsapp_number;
        const url = `https://api.whatsapp.com/send/?phone=${number}&text=${encodeURIComponent(
          config?.whatsapp_message || "Hi",
        )}&type=phone_number&app_absent=0`;
        window.open(url, "_blank");
      }
      if (actionType === 3) {
        const email = config?.email;
        if (email) {
          window.location.href = `mailto:${email}`;
        }
      }

      setCurrentValue("");
      onClose();
    } catch (err) {
      console.error("Funnel error:", err);
    } finally {
      setLoading(false);
    }
  };

  const getTitle = () => {
    if (isEmail && (actionType === 1 || actionType === 2)) {
      return actionType === 1 ? "Enter Email Address" : "Enter Email Address ";
    }

    switch (actionType) {
      case 3:
        return "Enter Email Address";
      case 2:
        return "Enter WhatsApp Number";
      case 1:
        return "Enter Mobile Number";
      default:
        return "Enter Details";
    }
  };

  const getButtonText = () => {
    switch (actionType) {
      case 1:
        return "Call Now";
      case 2:
        return "Continue";
      case 3:
        return "Continue";
      default:
        return "Submit";
    }
  };

  const getDescription = () => {
    if (isEmail && (actionType === 1 || actionType === 2)) {
      return "Please enter your email address to continue";
    }
    if (isEmail) {
      return "We'll send updates to this email";
    }
    return "We'll call you on this number";
  };

  const getPlaceholder = () => {
    if (isEmail) return "you@example.com";
    return "9876543210";
  };

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
      <div className="bg-white w-[90%] max-w-sm rounded-2xl p-6 shadow-2xl relative">
        <button
          onClick={onClose}
          className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 transition-colors"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex justify-center mb-4">
          <div
            className={`w-14 h-14 rounded-full flex items-center justify-center ${
              isEmail ? "bg-red-100" : "bg-blue-100"
            }`}
          >
            {isEmail ? (
              <Mail className="w-7 h-7 text-red-600" />
            ) : (
              <Phone className="w-7 h-7 text-blue-600" />
            )}
          </div>
        </div>

        <h2 className="text-xl font-bold text-center text-gray-800">
          {getTitle()}
        </h2>

        <p className="text-sm text-center text-gray-500 mt-1">
          {getDescription()}
        </p>

        <input
          type={isEmail ? "email" : "tel"}
          value={currentValue}
          onChange={(e) => setCurrentValue(e.target.value)}
          placeholder={getPlaceholder()}
          className="w-full border border-gray-200 rounded-xl px-4 py-3 mt-5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
          autoFocus
        />

        <div className="flex gap-3 mt-6">
          <button
            onClick={onClose}
            className="w-1/2 bg-gray-100 hover:bg-gray-200 py-3 rounded-xl font-medium text-gray-700 transition-all"
          >
            Cancel
          </button>

          <button
            onClick={handleSubmit}
            disabled={loading}
            className={`w-1/2 ${
              actionType === 3
                ? "bg-red-600 hover:bg-red-700"
                : "bg-blue-600 hover:bg-blue-700"
            } text-white py-3 rounded-xl font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2`}
          >
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Processing...
              </>
            ) : (
              <>
                {getButtonText()}
                <ArrowRight className="w-4 h-4" />
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
