"use client";

// AI danışman sohbeti — sayfa altında yüzen buton + intercom tarzı popup.
// Motion dili: panel tetikleyicisinden doğar (transform-origin sağ-alt),
// spring ile açılır; çıkış girişten hızlı. Reduced motion'da cross-fade.

import { useEffect, useState } from "react";
import { MessageCircleMore, X } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { SohbetClient } from "@/app/listem/sohbet-client";
import { ViewportPortal } from "@/components/viewport-portal";

export function SohbetPopup({ kredi }: { kredi: number }) {
  const [acik, setAcik] = useState(false);
  const azMotion = useReducedMotion();

  useEffect(() => {
    if (!acik) return;
    const dinle = (e: KeyboardEvent) => {
      if (e.key === "Escape") setAcik(false);
    };
    window.addEventListener("keydown", dinle);
    return () => window.removeEventListener("keydown", dinle);
  }, [acik]);

  return (
    <ViewportPortal>
      <AnimatePresence>
        {acik ? (
          <motion.div
            key="sohbet"
            initial={
              azMotion ? { opacity: 0 } : { opacity: 0, y: 24, scale: 0.95 }
            }
            animate={azMotion ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
            exit={
              azMotion
                ? { opacity: 0, transition: { duration: 0.15 } }
                : {
                    opacity: 0,
                    y: 16,
                    scale: 0.97,
                    transition: { duration: 0.18, ease: [0.23, 1, 0.32, 1] },
                  }
            }
            transition={{ type: "spring", duration: 0.4, bounce: 0.15 }}
            style={{ transformOrigin: "bottom right" }}
            className="fixed bottom-24 right-4 z-50 h-[min(72dvh,560px)] w-[min(100vw-2rem,420px)] print:hidden"
          >
            <SohbetClient
              baslangicKredi={kredi}
              className="h-full shadow-2xl"
            />
          </motion.div>
        ) : null}
      </AnimatePresence>

      {/* Yüzen tetikleyici — basışta anında küçülür (pointer-down feedback) */}
      <button
        type="button"
        onClick={() => setAcik((v) => !v)}
        aria-expanded={acik}
        className="fixed bottom-6 right-4 z-50 flex h-13 cursor-pointer items-center gap-2 rounded-full bg-slate-900 py-3 pl-4 pr-5 font-heading text-sm font-bold text-white shadow-xl transition-[transform,background-color] duration-150 hover:bg-slate-700 active:scale-[0.95] print:hidden"
      >
        {acik ? (
          <X className="size-5" aria-hidden />
        ) : (
          <MessageCircleMore className="size-5" aria-hidden />
        )}
        {acik ? "Kapat" : "Danışmana sor"}
      </button>
    </ViewportPortal>
  );
}
