"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 dynamic from "next/dynamic";
import { MessageCircleMore, X } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Skeleton } from "@/components/ui/skeleton";
import { ViewportPortal } from "@/components/viewport-portal";

function SohbetSkeleton() {
  return (
    <div
      aria-busy="true"
      aria-live="polite"
      className="flex h-full flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl"
    >
      <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
        <Skeleton className="h-5 w-36" />
        <Skeleton className="h-6 w-20 rounded-full" />
      </div>
      <div className="flex flex-1 flex-col items-center gap-4 px-4 py-10">
        <Skeleton className="size-7 rounded-full" />
        <Skeleton className="h-5 w-56 max-w-full" />
        <div className="w-full max-w-md space-y-2">
          <Skeleton className="mx-auto h-3.5 w-full" />
          <Skeleton className="mx-auto h-3.5 w-4/5" />
        </div>
        <div className="flex max-w-lg flex-wrap justify-center gap-2">
          {[112, 148, 96, 132].map((w, i) => (
            <Skeleton
              key={i}
              className="h-7 rounded-full"
              style={{ width: w }}
            />
          ))}
        </div>
      </div>
      <div className="border-t border-slate-100 p-3">
        <Skeleton className="h-24 w-full rounded-2xl" />
      </div>
    </div>
  );
}

// Sohbet istemcisi (markdown zinciriyle birlikte) ağır; popup ilk açıldığında
// yüklensin — /sonuc ilk yükünü şişirmesin.
const SohbetClient = dynamic(
  () => import("@/app/listem/sohbet-client").then((m) => m.SohbetClient),
  {
    ssr: false,
    loading: () => <SohbetSkeleton />,
  },
);

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>
  );
}
