"use client";
import { useEffect, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAppSelector } from "@/store/hooks";
import { useMessaging } from "@/lib/MessagingContext";
import { MessagingLayout } from "@/components/messaging/MessagingLayout";

function AutoSelectConv() {
  const params = useSearchParams();
  const convId = params.get("conv");
  const { selectConversation, conversations, isLoading } = useMessaging();

  useEffect(() => {
    if (!convId || isLoading) return;
    selectConversation(convId);
  }, [convId, isLoading, conversations.length, selectConversation]);

  return null;
}

function MessagesContent() {
  const router = useRouter();
  const { isAuthenticated, isLoading } = useAppSelector((s) => s.auth);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.replace("/auth/login");
    }
  }, [isAuthenticated, isLoading, router]);

  if (isLoading || !isAuthenticated) return null;

  return (
    <>
      <Suspense>
        <AutoSelectConv />
      </Suspense>
      <MessagingLayout />
    </>
  );
}

export default function MarketplaceMessagesPage() {
  return <MessagesContent />;
}
