"use client";

import { useEffect, useState } from "react";
import { CalButton } from "@/components/cal-button";
import { trackEvent } from "@/lib/analytics";
import { IconBrandWhatsapp, IconPhone } from "@tabler/icons-react";

export function StickySidebarCTA() {
  const [visible, setVisible] = useState(false);
  const whatsappNumber = process.env.NEXT_PUBLIC_WHATSAPP_NUMBER;

  useEffect(() => {
    const mq = window.matchMedia("(min-width: 1280px)");
    if (!mq.matches) return;

    let scrolledPast300 = false;
    let ctaSectionVisible = false;

    // Hide when CTA section enters viewport
    const ctaSection = document.getElementById("cta-section");
    let observer: IntersectionObserver | null = null;
    if (ctaSection) {
      observer = new IntersectionObserver(
        ([entry]) => {
          ctaSectionVisible = entry.isIntersecting;
          setVisible(scrolledPast300 && !ctaSectionVisible);
        },
        { threshold: 0 }
      );
      observer.observe(ctaSection);
    }

    // Show after 300px scroll
    let ticking = false;
    const handleScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        scrolledPast300 = window.scrollY > 300;
        setVisible(scrolledPast300 && !ctaSectionVisible);
        ticking = false;
      });
    };

    window.addEventListener("scroll", handleScroll, { passive: true });

    const handleResize = () => {
      if (!mq.matches) {
        setVisible(false);
      }
    };
    mq.addEventListener("change", handleResize);

    return () => {
      window.removeEventListener("scroll", handleScroll);
      mq.removeEventListener("change", handleResize);
      observer?.disconnect();
    };
  }, []);

  if (!visible) return null;

  return (
    <div className="hidden xl:block fixed right-8 top-1/3 z-40 w-56 animate-in fade-in slide-in-from-right-4 duration-300">
      <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-lg">
        <p className="text-sm font-semibold text-gray-900">
          Audit gratuit de vos factures
        </p>
        <p className="mt-1 text-xs text-gray-500">
          Nos ingénieurs identifient vos leviers d'économies en 48h.
        </p>

        <CalButton
          location="sticky_sidebar"
          className="mt-4 w-full px-4 py-2.5 text-xs"
        >
          <IconPhone size={14} className="mr-1.5 inline" />
          Prendre RDV
        </CalButton>

        {whatsappNumber && (
          <a
            href={`https://wa.me/${whatsappNumber}`}
            target="_blank"
            rel="noopener noreferrer"
            aria-label="Poser une question rapide sur WhatsApp (nouvel onglet)"
            onClick={() =>
              trackEvent("cta_click", {
                cta_type: "whatsapp",
                cta_location: "sticky_sidebar",
              })
            }
            className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-full border border-gray-200 px-4 py-2.5 text-xs font-semibold text-gray-700 transition-colors hover:bg-gray-50"
          >
            <IconBrandWhatsapp size={14} className="text-[#25D366]" />
            Question rapide
          </a>
        )}
      </div>
    </div>
  );
}
