"use client";

import { useEffect, useRef, useState } from "react";

type FloatingVideoAdProps = {
  videoSrc?: string;
  label?: string;
  reopenAfterMs?: number;
};

export default function FloatingVideoAd({
  videoSrc = "/ads/sample-ad.mp4",
  label = "Advertisement",
  reopenAfterMs = 180000, // 3 minutes
}: FloatingVideoAdProps) {
  const [showAd, setShowAd] = useState(false);
  const [canClose, setCanClose] = useState(false);
  const [closeClickUnlocked, setCloseClickUnlocked] = useState(false);

  const reopenTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const smartLinkUrl = process.env.NEXT_PUBLIC_SMARTLINK_URL;

  const openAd = () => {
    setShowAd(true);
    setCanClose(false);
    setCloseClickUnlocked(false); // har reopen par reset

    if (closeTimerRef.current) {
      clearTimeout(closeTimerRef.current);
    }

    closeTimerRef.current = setTimeout(() => {
      setCanClose(true);
    }, 6000);
  };

  const scheduleReopen = () => {
    if (reopenTimerRef.current) {
      clearTimeout(reopenTimerRef.current);
    }

    reopenTimerRef.current = setTimeout(() => {
      openAd();
    }, reopenAfterMs);
  };

  const closeAdNow = () => {
    setShowAd(false);
    setCanClose(false);
    setCloseClickUnlocked(false);
    scheduleReopen();
  };

  const handleCloseClick = () => {
    if (!canClose) return;

    // First close click = open Monetag ad
    if (!closeClickUnlocked && smartLinkUrl) {
      window.open(smartLinkUrl, "_blank", "noopener,noreferrer");
      setCloseClickUnlocked(true);
      return;
    }

    // Second close click = actually close
    closeAdNow();
  };

  const handleContinueClick = () => {
    if (!smartLinkUrl) return;
    window.open(smartLinkUrl, "_blank", "noopener,noreferrer");
  };

  useEffect(() => {
    const firstShowTimer = setTimeout(() => {
      openAd();
    }, 1500);

    return () => {
      clearTimeout(firstShowTimer);

      if (reopenTimerRef.current) {
        clearTimeout(reopenTimerRef.current);
      }

      if (closeTimerRef.current) {
        clearTimeout(closeTimerRef.current);
      }
    };
  }, []);

  if (!showAd) {
    return null;
  }

  return (
    <div
      style={{
        position: "fixed",
        right: "18px",
        bottom: "18px",
        width: "320px",
        maxWidth: "calc(100vw - 36px)",
        background: "#111",
        border: "1px solid rgba(255,255,255,0.18)",
        borderRadius: "16px",
        overflow: "hidden",
        zIndex: 99999,
        boxShadow: "0 15px 45px rgba(0,0,0,0.45)",
      }}
    >
      <div
        style={{
          height: "38px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "0 10px",
          background: "rgba(255,255,255,0.08)",
          color: "#fff",
          fontSize: "13px",
          fontWeight: 700,
        }}
      >
        <span>{label}</span>

        {canClose ? (
          <button
            type="button"
            onClick={handleCloseClick}
            aria-label="Close ad"
            title={
              closeClickUnlocked
                ? "Close ad"
                : "Ad may open once before closing"
            }
            style={{
              width: "26px",
              height: "26px",
              borderRadius: "50%",
              border: "none",
              background: closeClickUnlocked
                ? "rgba(255,255,255,0.22)"
                : "rgba(220,53,69,0.85)",
              color: "#fff",
              cursor: "pointer",
              fontWeight: 900,
              lineHeight: "26px",
            }}
          >
            ×
          </button>
        ) : (
          <span style={{ color: "rgba(255,255,255,0.55)", fontSize: "12px" }}>
            Ad
          </span>
        )}
      </div>

      <video
        autoPlay
        muted
        loop
        playsInline
        controls={false}
        onClick={handleContinueClick}
        style={{
          width: "100%",
          height: "180px",
          objectFit: "cover",
          background: "#000",
          display: "block",
          cursor: smartLinkUrl ? "pointer" : "default",
        }}
      >
        <source src={videoSrc} type="video/mp4" />
      </video>

      <div
        style={{
          padding: "10px",
          display: "flex",
          gap: "8px",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <span style={{ color: "rgba(255,255,255,0.75)", fontSize: "12px" }}>
          {closeClickUnlocked
            ? "Click × again to close"
            : "Advertisement"}
        </span>

        <button
          type="button"
          onClick={handleContinueClick}
          disabled={!smartLinkUrl}
          style={{
            background: "#dc3545",
            color: "#fff",
            padding: "7px 12px",
            borderRadius: "10px",
            fontSize: "13px",
            fontWeight: 700,
            textDecoration: "none",
            border: "none",
            cursor: smartLinkUrl ? "pointer" : "not-allowed",
            opacity: smartLinkUrl ? 1 : 0.55,
          }}
        >
          Continue
        </button>
      </div>
    </div>
  );
}