"use client";
import { useState, useRef, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { useMessaging } from "@/lib/MessagingContext";
import { ConversationList } from "./ConversationList";
import { ChatWindow } from "./ChatWindow";

export function MessagingLayout() {
  const { selectedConversationId, selectConversation } = useMessaging();
  const [mobileView, setMobileView] = useState<"list" | "chat">("list");
  const prevIdRef = useRef<string | null>(null);

  // Switch to chat pane on mobile whenever a conversation is selected (including auto-select from URL param)
  useEffect(() => {
    if (selectedConversationId && selectedConversationId !== prevIdRef.current) {
      setMobileView("chat");
    } else if (!selectedConversationId) {
      setMobileView("list");
    }
    prevIdRef.current = selectedConversationId;
  }, [selectedConversationId]);

  const handleSelectMobile = () => setMobileView("chat");
  const handleBack = () => {
    setMobileView("list");
    selectConversation(null);
  };

  return (
    <div className="h-full flex overflow-hidden" style={{ background: "var(--bg)" }}>
      {/* ─── Desktop layout: always show both columns ─── */}
      <div className="hidden md:flex h-full w-full">
        {/* Sidebar: conversation list (fixed width) */}
        <div
          className="shrink-0 h-full overflow-hidden border-r border-[var(--border)]"
          style={{ width: 340 }}
        >
          <ConversationList />
        </div>

        {/* Chat area */}
        <div className="flex-1 h-full overflow-hidden">
          <ChatWindow />
        </div>
      </div>

      {/* ─── Mobile layout: conditional render ─── */}
      <div className="flex md:hidden h-full w-full relative overflow-hidden">
        <AnimatePresence initial={false}>
          {mobileView === "list" ? (
            <motion.div
              key="list"
              initial={{ x: 0 }}
              animate={{ x: 0 }}
              exit={{ x: "-100%" }}
              transition={{ type: "spring", stiffness: 380, damping: 36 }}
              className="absolute inset-0"
            >
              <ConversationList onSelectMobile={handleSelectMobile} />
            </motion.div>
          ) : (
            <motion.div
              key="chat"
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", stiffness: 380, damping: 36 }}
              className="absolute inset-0"
            >
              <ChatWindow onBack={handleBack} />
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
