"use client";

import dynamic from "next/dynamic";
import { usePathname } from "next/navigation";
import BackToTop from "@/components/ui/BackToTop";

/**
 * The chatbot carries copy tables for six languages (much of it non-Latin, so
 * heavier than its line count suggests) plus its block renderers. A static
 * import would ship all of it with the root layout — including on seller,
 * transporter and staff routes, where the guard below renders nothing at all.
 */
const BiznieAiChatbot = dynamic(() => import("@/components/chat/BiznieAiChatbot"), {
  ssr: false,
});

/**
 * Route prefixes that make up the signed-in operational area.
 *
 * These all live under the `(dashboard)` route group, and route groups are
 * stripped from the URL, so the pathname carries no shared marker to test —
 * the prefixes have to be listed explicitly. Keep in sync with the nav in
 * `components/dashboard/DashboardLayout.tsx`.
 */
const DASHBOARD_PREFIXES = [
  "/dashboard",
  "/orders",
  "/rfq",
  "/enquiry",
  "/watchlist",
  "/wallet",
  "/credit-request",
  "/notifications",
  "/seller",
  "/transporter",
  "/staff",
  "/profile",
];

/**
 * Areas the assistant stays out of. It only serves buyers (orders, enquiries,
 * RFQs), so seller, transporter and staff consoles don't get it.
 */
const CHATBOT_HIDDEN_PREFIXES = ["/seller", "/transporter", "/staff"];

function matchesPrefix(pathname: string, prefixes: readonly string[]) {
  return prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
}

/**
 * Floating chat + back-to-top affordances.
 *
 * - The chatbot shows on marketing pages and the buyer dashboard, and is
 *   hidden in the seller / transporter / staff consoles.
 * - Back-to-top stays marketing-only: inside the dashboard it competes with the
 *   bottom tab bar for the same corner and covers table rows.
 */
export default function FloatingWidgets() {
  const pathname = usePathname() ?? "/";

  const inDashboard = matchesPrefix(pathname, DASHBOARD_PREFIXES);
  const showChatbot = !matchesPrefix(pathname, CHATBOT_HIDDEN_PREFIXES);
  const showBackToTop = !inDashboard;

  return (
    <>
      {showChatbot ? <BiznieAiChatbot aboveTabBar={inDashboard} /> : null}
      {showBackToTop ? <BackToTop /> : null}
    </>
  );
}
