"use client";

import { useEffect, useRef } from "react";
import Lenis from "lenis";
import { isSettingEnabled, type WebsiteSettings } from "@/lib/website-settings";

export function WebsiteEffects({
  settings = {},
}: {
  settings?: WebsiteSettings;
}) {
  const hideChatbot = isSettingEnabled(settings.hide_website_chatbot);
  const chatbotFrameRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    const prefersReducedMotion = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    );
    const lenis = new Lenis({
      duration: 1.2,
      lerp: 0.09,
      smoothWheel: true,
      syncTouch: false,
      touchMultiplier: 1,
      wheelMultiplier: 1,
    });
    const parallaxTargets = Array.from(
      document.querySelectorAll<HTMLElement>("[data-parallax]"),
    );
    let frame = 0;
    let lenisFrame = 0;

    const updateParallax = () => {
      frame = 0;
      const scrollY = window.scrollY;
      parallaxTargets.forEach((element) => {
        const speed = Number(element.dataset.parallax || 0.08);
        element.style.transform = `translate3d(0, ${scrollY * speed}px, 0)`;
      });
    };

    const raf = (time: number) => {
      lenis.raf(time);
      lenisFrame = window.requestAnimationFrame(raf);
    };

    const onScroll = () => {
      if (prefersReducedMotion.matches) return;
      if (!frame) frame = window.requestAnimationFrame(updateParallax);
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    lenis.on("scroll", onScroll);
    lenisFrame = window.requestAnimationFrame(raf);
    updateParallax();

    return () => {
      lenis.off("scroll", onScroll);
      lenis.destroy();
      window.removeEventListener("scroll", onScroll);
      if (frame) window.cancelAnimationFrame(frame);
      if (lenisFrame) window.cancelAnimationFrame(lenisFrame);
    };
  }, []);

  useEffect(() => {
    if (hideChatbot) {
      return;
    }

    const onMessage = (event: MessageEvent) => {
      if (
        event.origin !== "https://aichatbot.dilonline.in" ||
        event.data?.source !== "medisync-widget"
      ) {
        return;
      }

      const frame =
        chatbotFrameRef.current ||
        document.querySelector<HTMLIFrameElement>(
          "iframe[src*='/chatnexa/embed']",
        );

      if (!frame) {
        return;
      }

      if (event.data.open) {
        frame.style.width = window.innerWidth <= 480 ? "100%" : "400px";
        frame.style.height =
          window.innerWidth <= 480 ? "100%" : "min(680px,calc(100vh - 40px))";
        frame.style.right = window.innerWidth <= 480 ? "0" : "20px";
        frame.style.bottom = window.innerWidth <= 480 ? "0" : "20px";
      } else {
        frame.style.width = "76px";
        frame.style.height = "76px";
        frame.style.right = "20px";
        frame.style.bottom = "20px";
      }
    };

    window.addEventListener("message", onMessage);

    return () => {
      window.removeEventListener("message", onMessage);
    };
  }, [hideChatbot]);

  if (hideChatbot) {
    return null;
  }

  return (
    <iframe
      ref={chatbotFrameRef}
      src="https://aichatbot.dilonline.in/chatnexa/embed?tenant=uttarakhand-guides&pos=right"
      title="Uttarakhand Travel Guide Assistant"
      style={{
        position: "fixed",
        right: "20px",
        bottom: "20px",
        width: "76px",
        height: "76px",
        border: 0,
        zIndex: 2147483000,
        background: "transparent",
      }}
      allow="clipboard-write; microphone"
      data-lenis-prevent
    />
  );
}
