"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import {
  Search,
  LayoutGrid,
  List,
  Plus,
  FilterX,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ReactSelect } from "@/components/ui/react-select";
import { Spinner } from "@/components/ui/spinner";
import { Can } from "@/components/providers/ability-provider";
import { DealsPageHeaderProps } from "@/types/deals";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { DealsDateRangeFilter } from "./deals-date-range-filter";

import { useIsFetching } from "@tanstack/react-query";
import { useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import {
  setSearch,
  setView,
  setDateRange as setReduxDateRange,
  setTeamFilterDisplay,
  setLeadChannelFilterId,
  setStageFilterId,
  setServiceFilterId,
  setTimelineIntentFilterId,
  setLeadOwnerFilterId,
  setContributorFilterId,
  setAssignAeFilterId,
  setAssignBdrFilterId,
  setDivisionFilterId,
  setBusinessDealFilters,
  resetBusinessDealFilters,
  resetFilters,
} from "@/store/slices/deals-header-slice";
import { setSelectedTeam, clearTeamFilter } from "@/store/slices/team-filter-slice";
import { buildHierarchicalTeamFilterOptions } from "@/lib/team-filter";
import { useGetLeadChannelsQuery } from "@/api/rtk/lead-channels-api";
import { useGetRolesQuery, useGetServicesQuery, useGetTimelineIntentsQuery } from "@/api/rtk";
import {
  useGetProjectTypesQuery,
  useGetRegionsQuery,
} from "@/api/rtk/deal-meta-api";
import { Team, type TeamUser, useGetAllUsersQuery } from "@/api/rtk/teams-api";
import { pickRoleIdFromOrgRoles } from "@/components/deals/contributor-user-picker";
import {
  isAccountExecutiveRoleName,
  isBdrRoleName,
} from "@/lib/permissions";
import { DEFAULT_BUSINESS_DEAL_FILTERS } from "@/components/deals/types";
import {
  DEALS_FILTER_CLEAR_BUTTON_CLASS,
  DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
  DEALS_FILTER_TRIGGER_CLASS,
} from "@/components/deals/deals-filter-styles";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

/** List/table + kanban server filters read Redux `search` — only commit after idle to avoid request storms. */
const DEALS_HEADER_SEARCH_DEBOUNCE_MS = 550;

/** Fixed-width filter slots — avoid flex-1 so adjacent selects do not stretch apart. */
const FILTER_WRAP_CLASS = "shrink-0 min-w-[118px] min-[1500px]:min-w-[148px]";

function normalizeRoleLabel(name?: string | null): string {
  return (name ?? "").trim().toLowerCase().replace(/\s+/g, " ");
}

function userMatchesAeAssignmentPool(user: TeamUser, aeRoleId?: string): boolean {
  if (aeRoleId && user.role?.id === aeRoleId) return true;
  const role = normalizeRoleLabel(user.role?.name);
  if (!role) return false;
  if (isAccountExecutiveRoleName(role)) return true;
  if (role.includes("account executive")) return true;
  return role === "ae" || role.endsWith(" ae") || role.startsWith("ae ");
}

function userMatchesBdrAssignmentPool(user: TeamUser, bdrRoleId?: string): boolean {
  if (bdrRoleId && user.role?.id === bdrRoleId) return true;
  const role = normalizeRoleLabel(user.role?.name);
  if (!role) return false;
  if (isBdrRoleName(role)) return true;
  if (role.includes("business development")) return true;
  return role === "bdr" || role.includes(" bdr") || role.startsWith("bdr ");
}

function buildAssigneeFilterOptions(
  users: TeamUser[],
  allLabel: string,
  match: (user: TeamUser) => boolean,
): { value: string; label: React.ReactNode }[] {
  const matched = users.filter(match);
  const pool = matched.length > 0 ? matched : users;
  const sorted = [...pool].sort((a, b) =>
    (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
  );
  return [
    { value: "all", label: allLabel },
    ...sorted.map((u) => ({
      value: u.id,
      label: u.name || u.email || u.id,
    })),
  ];
}

/** Deal type + region (and similar pairs) stay visually grouped. */
const FILTER_PAIR_GROUP_CLASS = "flex shrink-0 items-center gap-2";

function dealsFilterTooltipLabel(
  baseLabel: string,
  value: string | undefined,
  options: { value: string; label: React.ReactNode }[],
  allValue = "all",
): string {
  if (!value || value === allValue) return baseLabel;
  const match = options.find((o) => o.value === value);
  const selected = match ? String(match.label) : value;
  return `${baseLabel}: ${selected}`;
}

function DealsFilterTooltip({
  label,
  children,
  className,
}: {
  label: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div className={cn("min-w-0", className)}>{children}</div>
      </TooltipTrigger>
      <TooltipContent side="bottom" sideOffset={6}>
        {label}
      </TooltipContent>
    </Tooltip>
  );
}

export const DealsPageHeader = React.memo(function DealsPageHeader({
  pageTitle,
  filteredDealsCount,
  pipelines,
  stages = [],
  activeBoardId,
  canSubject,
  onClearDealUrlDates,
}: DealsPageHeaderProps) {
  const dispatch = useDispatch();

  const { data: leadChannels } = useGetLeadChannelsQuery();
  const { data: services = [] } = useGetServicesQuery(undefined, {
    skip: !activeBoardId,
  });
  const { data: timelineIntents = [] } = useGetTimelineIntentsQuery(undefined, {
    skip: canSubject !== "lead",
  });
  const { data: projectTypes = [] } = useGetProjectTypesQuery(undefined, {
    skip: canSubject !== "deal",
  });
  const { data: regions = [] } = useGetRegionsQuery(undefined, {
    skip: canSubject !== "deal",
  });
  const showLeadOwnerFilter = useSelector(
    (state: RootState) => state.dealsHeader.showLeadOwnerFilter,
  );
  const { data: allUsers = [], isSuccess: allUsersLoaded } = useGetAllUsersQuery(
    undefined,
    {
      skip: !showLeadOwnerFilter,
    },
  );
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, {
    skip: !showLeadOwnerFilter,
  });
  const isFetching = useIsFetching();

  const search = useSelector((state: RootState) => state.dealsHeader.search);
  const teamFilterDisplay = useSelector((state: RootState) => state.dealsHeader.teamFilterDisplay);
  const leadChannelFilterId = useSelector((state: RootState) => state.dealsHeader.leadChannelFilterId);
  const stageFilterId = useSelector((state: RootState) => state.dealsHeader.stageFilterId ?? "all");
  const serviceFilterId = useSelector((state: RootState) => state.dealsHeader.serviceFilterId ?? "all");
  const timelineIntentFilterId = useSelector(
    (state: RootState) => state.dealsHeader.timelineIntentFilterId ?? "all",
  );
  const leadOwnerFilterId = useSelector(
    (state: RootState) => state.dealsHeader.leadOwnerFilterId ?? "all",
  );
  const contributorFilterId = useSelector(
    (state: RootState) => state.dealsHeader.contributorFilterId ?? "all",
  );
  const assignAeFilterId = useSelector(
    (state: RootState) => state.dealsHeader.assignAeFilterId ?? "all",
  );
  const assignBdrFilterId = useSelector(
    (state: RootState) => state.dealsHeader.assignBdrFilterId ?? "all",
  );
  const divisionFilterId = useSelector(
    (state: RootState) => state.dealsHeader.divisionFilterId ?? "all",
  );
  const view = useSelector((state: RootState) => state.dealsHeader.view);
  const dateRangeRaw = useSelector((state: RootState) => state.dealsHeader.dateRange);

  const dateRange = useMemo(() => {
    if (!dateRangeRaw?.from) return undefined;
    return {
      from: new Date(dateRangeRaw.from),
      to: dateRangeRaw.to ? new Date(dateRangeRaw.to) : undefined,
    };
  }, [dateRangeRaw]);

  const dateRangeTooltipLabel = useMemo(() => {
    if (!dateRange?.from) return "Filter by date range";
    const fmt = (d: Date) =>
      d.toLocaleDateString("default", {
        month: "short",
        day: "numeric",
        year: "numeric",
      });
    if (dateRange.to) {
      return `Date range: ${fmt(dateRange.from)} – ${fmt(dateRange.to)}`;
    }
    return `Date range: ${fmt(dateRange.from)}`;
  }, [dateRange]);

  const isAdmin = useSelector((state: RootState) => state.dealsHeader.isAdmin);
  const isCreatingDeal = useSelector((state: RootState) => state.dealsHeader.isCreatingDeal);
  const addDealDisabled = useSelector((state: RootState) => state.dealsHeader.addDealDisabled);
  const newRecordButtonLabel = useSelector((state: RootState) => state.dealsHeader.newRecordButtonLabel);
  const searchPlaceholder = useSelector((state: RootState) => state.dealsHeader.searchPlaceholder);
  const searchAriaLabel = useSelector((state: RootState) => state.dealsHeader.searchAriaLabel);
  const businessDealActionLabel = useSelector((state: RootState) => state.dealsHeader.businessDealActionLabel);
  const availableTeams = useSelector((state: RootState) => state.dealsHeader.availableTeams);
  const businessDealFilters = useSelector(
    (state: RootState) =>
      state.dealsHeader.businessDealFilters ?? DEFAULT_BUSINESS_DEAL_FILTERS,
  );
  /** Immediate UI; Redux `search` (and `/deals/list/page`) update after debounce or blur. */
  const [searchDraft, setSearchDraft] = React.useState(search);
  const searchDebounceTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(
    null,
  );

  const flushSearchToRedux = React.useCallback(() => {
    if (searchDebounceTimerRef.current != null) {
      clearTimeout(searchDebounceTimerRef.current);
      searchDebounceTimerRef.current = null;
    }
    if (searchDraft !== search) {
      dispatch(setSearch(searchDraft));
    }
  }, [dispatch, searchDraft, search]);

  React.useEffect(() => {
    if (searchDraft === search) return;
    if (searchDebounceTimerRef.current != null) {
      clearTimeout(searchDebounceTimerRef.current);
      searchDebounceTimerRef.current = null;
    }
    searchDebounceTimerRef.current = setTimeout(() => {
      searchDebounceTimerRef.current = null;
      dispatch(setSearch(searchDraft));
    }, DEALS_HEADER_SEARCH_DEBOUNCE_MS);
    return () => {
      if (searchDebounceTimerRef.current != null) {
        clearTimeout(searchDebounceTimerRef.current);
        searchDebounceTimerRef.current = null;
      }
    };
  }, [searchDraft, search, dispatch]);

  const hasActiveLeadFilters = useMemo(
    () =>
      canSubject === "lead" &&
      (Boolean(searchDraft.trim() || search.trim()) ||
        teamFilterDisplay !== "all" ||
        leadChannelFilterId !== "all" ||
        serviceFilterId !== "all" ||
        timelineIntentFilterId !== "all" ||
        leadOwnerFilterId !== "all" ||
        contributorFilterId !== "all" ||
        assignAeFilterId !== "all" ||
        assignBdrFilterId !== "all" ||
        divisionFilterId !== "all" ||
        stageFilterId !== "all" ||
        Boolean(dateRangeRaw?.from)),
    [
      canSubject,
      searchDraft,
      search,
      teamFilterDisplay,
      leadChannelFilterId,
      serviceFilterId,
      timelineIntentFilterId,
      leadOwnerFilterId,
      contributorFilterId,
      assignAeFilterId,
      assignBdrFilterId,
      divisionFilterId,
      stageFilterId,
      dateRangeRaw?.from,
    ],
  );

  const teamFilterOptions = useMemo(
    () =>
      buildHierarchicalTeamFilterOptions(availableTeams, {
        includeDivisionOptions: false,
      }).map((option) => ({
        value: option.value,
        label:
          option.group === "team"
            ? formatTeamLabelForUi(option.label)
            : option.label,
      })),
    [availableTeams],
  );

  const stageFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Stages" },
      ...stages
        .filter((stage) => !stage.isSubStage)
        .map((stage) => ({
          value: stage.id,
          label: stage.name,
        })),
    ],
    [stages],
  );

  const serviceFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Services" },
      ...services.map((service) => ({
        value: service.id,
        label: service.name,
      })),
    ],
    [services],
  );

  const leadChannelFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Channels" },
      ...(leadChannels?.map((channel) => ({
        value: channel.id,
        label: channel.name,
      })) ?? []),
    ],
    [leadChannels],
  );

  const timelineIntentFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Timeline Intents" },
      ...timelineIntents.map((intent) => ({
        value: intent.id,
        label: intent.name,
      })),
    ],
    [timelineIntents],
  );

  const leadOwnerFilterOptions = useMemo(() => {
    const aeUsers = (Array.isArray(allUsers) ? allUsers : []).filter((u) =>
      isAccountExecutiveRoleName(u.role?.name),
    );
    const sorted = [...aeUsers].sort((a, b) =>
      (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
    );
    return [
      { value: "all", label: "All Lead Owners" },
      ...sorted.map((u) => ({
        value: u.id,
        label: u.name || u.email || u.id,
      })),
    ];
  }, [allUsers]);

  React.useEffect(() => {
    if (leadOwnerFilterId === "all") return;
    const validIds = new Set(
      leadOwnerFilterOptions.map((o) => o.value).filter((v) => v !== "all"),
    );
    if (!validIds.has(leadOwnerFilterId)) {
      dispatch(setLeadOwnerFilterId("all"));
    }
  }, [dispatch, leadOwnerFilterId, leadOwnerFilterOptions]);

  const contributorFilterOptions = useMemo(() => {
    const aeBdrUsers = (Array.isArray(allUsers) ? allUsers : []).filter(
      (u) =>
        isAccountExecutiveRoleName(u.role?.name) ||
        isBdrRoleName(u.role?.name),
    );
    const sorted = [...aeBdrUsers].sort((a, b) =>
      (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
    );
    return [
      { value: "all", label: "All Contributors" },
      ...sorted.map((u) => ({
        value: u.id,
        label: u.name || u.email || u.id,
      })),
    ];
  }, [allUsers]);

  React.useEffect(() => {
    if (contributorFilterId === "all") return;
    const validIds = new Set(
      contributorFilterOptions.map((o) => o.value).filter((v) => v !== "all"),
    );
    if (!validIds.has(contributorFilterId)) {
      dispatch(setContributorFilterId("all"));
    }
  }, [dispatch, contributorFilterId, contributorFilterOptions]);

  const usersArray = useMemo(
    () => (Array.isArray(allUsers) ? allUsers : []),
    [allUsers],
  );

  const aeRoleId = useMemo(
    () => pickRoleIdFromOrgRoles(orgRoles, ["ae", "account executive"]),
    [orgRoles],
  );
  const bdrRoleId = useMemo(
    () =>
      pickRoleIdFromOrgRoles(orgRoles, [
        "bdr",
        "business development representative",
        "business development rep",
      ]),
    [orgRoles],
  );

  const assignAeFilterOptions = useMemo(
    () =>
      buildAssigneeFilterOptions(usersArray, "All Assign AE", (u) =>
        userMatchesAeAssignmentPool(u, aeRoleId),
      ),
    [usersArray, aeRoleId],
  );

  const assignBdrFilterOptions = useMemo(
    () =>
      buildAssigneeFilterOptions(usersArray, "All Assign BDR", (u) =>
        userMatchesBdrAssignmentPool(u, bdrRoleId),
      ),
    [usersArray, bdrRoleId],
  );

  React.useEffect(() => {
    if (!allUsersLoaded || assignAeFilterId === "all") return;
    const validIds = new Set(
      assignAeFilterOptions.map((o) => o.value).filter((v) => v !== "all"),
    );
    if (!validIds.has(assignAeFilterId)) {
      dispatch(setAssignAeFilterId("all"));
    }
  }, [dispatch, assignAeFilterId, assignAeFilterOptions, allUsersLoaded]);

  React.useEffect(() => {
    if (!allUsersLoaded || assignBdrFilterId === "all") return;
    const validIds = new Set(
      assignBdrFilterOptions.map((o) => o.value).filter((v) => v !== "all"),
    );
    if (!validIds.has(assignBdrFilterId)) {
      dispatch(setAssignBdrFilterId("all"));
    }
  }, [dispatch, assignBdrFilterId, assignBdrFilterOptions, allUsersLoaded]);

  const divisionFilterOptions = useMemo(() => {
    const byId = new Map<string, string>();
    for (const team of availableTeams) {
      const id = team.divisionId ?? team.division?.id;
      const name = team.division?.name;
      if (id && name) byId.set(id, name);
    }
    return [
      { value: "all", label: "All Divisions" },
      ...[...byId.entries()]
        .sort((a, b) => a[1].localeCompare(b[1]))
        .map(([id, name]) => ({ value: id, label: name })),
    ];
  }, [availableTeams]);

  const dealTypeFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Deal Types" },
      ...projectTypes.map((t) => ({
        value: t.name,
        label: t.name,
      })),
    ],
    [projectTypes],
  );

  const regionFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Regions" },
      ...regions.map((r) => ({
        value: r.name,
        label: r.name,
      })),
    ],
    [regions],
  );

  const hasActiveDealFilters = useMemo(() => {
    if (canSubject !== "deal") return false;
    const bf = businessDealFilters;
    return (
      Boolean(searchDraft.trim() || search.trim()) ||
      teamFilterDisplay !== "all" ||
      leadChannelFilterId !== "all" ||
      serviceFilterId !== "all" ||
      stageFilterId !== "all" ||
      Boolean(dateRangeRaw?.from) ||
      (bf.dealType !== "all" && Boolean(bf.dealType?.trim())) ||
      (bf.region !== "all" && Boolean(bf.region?.trim()))
    );
  }, [
    canSubject,
    searchDraft,
    search,
    teamFilterDisplay,
    leadChannelFilterId,
    serviceFilterId,
    stageFilterId,
    dateRangeRaw?.from,
    businessDealFilters,
  ]);

  const hasActiveFilters = hasActiveLeadFilters || hasActiveDealFilters;

  const handleClearLeadFilters = React.useCallback(() => {
    if (searchDebounceTimerRef.current != null) {
      clearTimeout(searchDebounceTimerRef.current);
      searchDebounceTimerRef.current = null;
    }
    dispatch(resetFilters());
    dispatch(clearTeamFilter());
    setSearchDraft("");
  }, [dispatch]);

  const handleClearDealFilters = React.useCallback(() => {
    if (searchDebounceTimerRef.current != null) {
      clearTimeout(searchDebounceTimerRef.current);
      searchDebounceTimerRef.current = null;
    }
    dispatch(resetBusinessDealFilters());
    dispatch(setReduxDateRange(undefined));
    dispatch(setLeadChannelFilterId("all"));
    dispatch(setStageFilterId("all"));
    dispatch(setServiceFilterId("all"));
    dispatch(setTeamFilterDisplay("all"));
    dispatch(clearTeamFilter());
    onClearDealUrlDates?.();
    setSearchDraft("");
    dispatch(setSearch(""));
  }, [dispatch, onClearDealUrlDates]);

  const handleClearFilters = React.useCallback(() => {
    if (canSubject === "deal") {
      handleClearDealFilters();
    } else {
      handleClearLeadFilters();
    }
  }, [canSubject, handleClearDealFilters, handleClearLeadFilters]);

  return (
    <div className="flex flex-col w-full gap-5  mb-2 border-b border-border/50 shrink-0">
      {/* Top Row: Title, View Switcher and Main Action */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-4 min-w-0">
          <div className="flex flex-col shrink-0 min-w-0">
            <h1 className="text-[22px] md:text-[24px] min-[1500px]:text-[30px] font-black text-gray-900 font-['Lexend'] tracking-tight leading-none truncate">
              {pageTitle}
            </h1>
          </div>
        </div>

        <div className="flex items-center gap-2.5 self-end sm:self-center">
          {isFetching > 0 && (
            <p className="text-[11px] font-bold text-accent/70 font-['Lexend_Deca'] animate-pulse flex items-center gap-1.5 pr-2">
              <span className="h-1.5 w-1.5 rounded-full bg-accent animate-ping" />
              Syncing...
            </p>
          )}
          <div className="flex bg-white/80 backdrop-blur-sm rounded-xl max-[1499px]:rounded-lg p-1 max-[1499px]:p-0.5 border border-border/40 shadow-sm">
            <Button
              variant={view === "kanban" ? "default" : "ghost"}
              size="icon-xs"
              className={cn(
                "rounded-lg max-[1499px]:rounded-md size-8 max-[1499px]:size-7 transition-all",
                view === "kanban"
                  ? "bg-accent text-white shadow-md"
                  : "text-gray-400 hover:text-accent hover:bg-accent/5",
              )}
              onClick={() => dispatch(setView("kanban"))}
              title="Board View"
            >
              <LayoutGrid className="size-4 max-[1499px]:size-3.5" />
            </Button>
            <Button
              variant={view === "list" ? "default" : "ghost"}
              size="icon-xs"
              className={cn(
                "rounded-lg max-[1499px]:rounded-md size-8 max-[1499px]:size-7 transition-all",
                view === "list"
                  ? "bg-accent text-white shadow-md"
                  : "text-gray-400 hover:text-accent hover:bg-accent/5",
              )}
              onClick={() => dispatch(setView("list"))}
              title="List View"
            >
              <List className="size-4 max-[1499px]:size-3.5" />
            </Button>
          </div>

          <Can action="create" subject={canSubject}>
            <Button
              size="sm"
              className="h-10 rounded-xl px-4 md:px-5 text-[13px] max-[1499px]:h-8 max-[1499px]:rounded-lg max-[1499px]:px-3 max-[1499px]:text-[11px] font-black font-['Lexend_Deca'] bg-accent text-white shadow-premium hover:scale-[1.02] active:scale-95 transition-all shrink-0 group gap-2"
              onClick={() => {
                window.dispatchEvent(new CustomEvent("trigger-add-deal"));
              }}
              disabled={addDealDisabled || isCreatingDeal}
            >
              {isCreatingDeal ? (
                <>
                  <Spinner className="size-4 mr-2" />
                  Adding lead...
                </>
              ) : (
                <>
                  <Plus
                    size={18}
                    className="stroke-[2px] group-hover:rotate-90 transition-transform duration-500"
                  />
                  {newRecordButtonLabel}
                </>
              )}
            </Button>
          </Can>
        </div>
      </div>

      {/* Search + filters (row 1) and scope filters (row 2) */}
      <TooltipProvider delayDuration={300}>
        <div className="flex w-full min-w-0 flex-col gap-2">
          <div className="flex w-full min-w-0 flex-col items-stretch justify-between gap-4 min-[1440px]:gap-3 lg:flex-row lg:items-center">
            <DealsFilterTooltip
              label={searchAriaLabel}
              className="relative flex-1 w-full max-[1499px]:max-w-[200px] min-[1500px]:max-w-[min(100%,24rem)] group"
            >
              <Search
                size={16}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-accent transition-colors duration-300 pointer-events-none min-[1440px]:left-3 min-[1440px]:size-3.5"
              />
              <Input
                type="search"
                enterKeyHint="search"
                className="pl-10 pr-4 h-7 max-[1499px]:text-[11px] min-[1500px]:h-9 min-[1500px]:text-[13px] font-bold bg-white border-border/80 rounded-lg min-[1500px]:rounded-xl w-full font-['Lexend_Deca'] shadow-sm focus:ring-accent/20 focus:border-accent hover:border-accent/40 transition-all placeholder:text-gray-400 [&::-webkit-search-cancel-button]:cursor-pointer"
                placeholder={searchPlaceholder}
                value={searchDraft}
                onChange={(e) => setSearchDraft(e.target.value)}
                onBlur={flushSearchToRedux}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    flushSearchToRedux();
                  }
                }}
                aria-label={searchAriaLabel}
              />
            </DealsFilterTooltip>

            {/* Row 1 — stage, timeline, date, deal meta, clear */}
            <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 min-[1500px]:gap-2 min-[1440px]:pb-0 lg:justify-end">
          <Can action="update" subject={canSubject}>
            {view === "list" && (
              <DealsFilterTooltip
                label={dealsFilterTooltipLabel(
                  "Filter by stage",
                  stageFilterId,
                  stageFilterOptions,
                )}
                className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[152px]")}
              >
                <ReactSelect
                  size="sm"
                  value={stageFilterId}
                  onValueChange={(v) =>
                    dispatch(setStageFilterId(v as string | "all"))
                  }
                  options={stageFilterOptions}
                  placeholder="All Stages"
                  aria-label="Filter by stage"
                  triggerClassName={cn(
                    DEALS_FILTER_TRIGGER_CLASS,
                    stageFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                  )}
                  position="popper"
                  align="start"
                />
              </DealsFilterTooltip>
            )}
          </Can>
          {canSubject === "lead" && (
            <DealsFilterTooltip
              label={dealsFilterTooltipLabel(
                "Filter by timeline intent",
                timelineIntentFilterId,
                timelineIntentFilterOptions,
              )}
              className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[168px]", "group")}
            >
              <ReactSelect
                size="sm"
                value={timelineIntentFilterId}
                onValueChange={(v) => dispatch(setTimelineIntentFilterId(v))}
                options={timelineIntentFilterOptions}
                placeholder="All Timeline Intents"
                aria-label="Filter by timeline intent"
                triggerClassName={cn(
                  DEALS_FILTER_TRIGGER_CLASS,
                  "group-hover:border-accent",
                  timelineIntentFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                )}
                position="popper"
                align="start"
              />
            </DealsFilterTooltip>
          )}
          {canSubject === "lead" && (
            <DealsFilterTooltip
              label={dateRangeTooltipLabel}
              className="shrink-0"
            >
              <DealsDateRangeFilter dateRange={dateRange} />
            </DealsFilterTooltip>
          )}
          {canSubject === "deal" && (
            <DealsFilterTooltip
              label={dateRangeTooltipLabel}
              className="shrink-0"
            >
              <DealsDateRangeFilter dateRange={dateRange} />
            </DealsFilterTooltip>
          )}

          {hasActiveFilters && (
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  variant="outline"
                  className={DEALS_FILTER_CLEAR_BUTTON_CLASS}
                  onClick={handleClearFilters}
                  aria-label="Clear filters"
                >
                  <FilterX className="size-4" aria-hidden />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="bottom" sideOffset={6}>
                Clear filters
              </TooltipContent>
            </Tooltip>
          )}

            </div>
          </div>

          {/* Row 2 — team, division, lead owner, service, channel */}
          {canSubject === "lead" && (
            <div className="flex min-w-0 flex-wrap items-center gap-1.5 min-[1500px]:gap-2 pb-3 min-[1440px]:pb-2 lg:justify-end">
              <Can action="update" subject={canSubject}>
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by team",
                    teamFilterDisplay,
                    teamFilterOptions,
                  )}
                  className={FILTER_WRAP_CLASS}
                >
                  <ReactSelect
                    size="sm"
                    value={teamFilterDisplay}
                    onValueChange={(v) => {
                      if (v !== teamFilterDisplay) {
                        dispatch(setTeamFilterDisplay(v));
                        dispatch(setSelectedTeam(v));
                        if (v !== "all") {
                          dispatch(setDivisionFilterId("all"));
                        }
                      }
                    }}
                    options={teamFilterOptions}
                    placeholder="All Teams"
                    aria-label="Filter by team"
                    triggerClassName={cn(DEALS_FILTER_TRIGGER_CLASS, "hover:border-accent")}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>

                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by division",
                    divisionFilterId,
                    divisionFilterOptions,
                  )}
                  className={FILTER_WRAP_CLASS}
                >
                  <ReactSelect
                    size="sm"
                    value={divisionFilterId}
                    onValueChange={(v) => {
                      const next = v as string | "all";
                      dispatch(setDivisionFilterId(next));
                      if (next !== "all") {
                        dispatch(setTeamFilterDisplay("all"));
                        dispatch(setSelectedTeam("all"));
                      }
                    }}
                    options={divisionFilterOptions}
                    placeholder="All Divisions"
                    aria-label="Filter by division"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      divisionFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              </Can>

              {showLeadOwnerFilter && (
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by lead owner",
                    leadOwnerFilterId,
                    leadOwnerFilterOptions,
                  )}
                  className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[152px]")}
                >
                  <ReactSelect
                    size="sm"
                    value={leadOwnerFilterId}
                    onValueChange={(v) =>
                      dispatch(setLeadOwnerFilterId(v as string | "all"))
                    }
                    options={leadOwnerFilterOptions}
                    placeholder="All Lead Owners"
                    aria-label="Filter by lead owner"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      leadOwnerFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              )}

              {showLeadOwnerFilter && (
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by contributor",
                    contributorFilterId,
                    contributorFilterOptions,
                  )}
                  className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[152px]")}
                >
                  <ReactSelect
                    size="sm"
                    value={contributorFilterId}
                    onValueChange={(v) =>
                      dispatch(setContributorFilterId(v as string | "all"))
                    }
                    options={contributorFilterOptions}
                    placeholder="All Contributors"
                    aria-label="Filter by contributor"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      contributorFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              )}

              {showLeadOwnerFilter && (
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by assigned AE",
                    assignAeFilterId,
                    assignAeFilterOptions,
                  )}
                  className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[152px]")}
                >
                  <ReactSelect
                    size="sm"
                    value={assignAeFilterId}
                    disabled={!allUsersLoaded}
                    onValueChange={(v) =>
                      dispatch(setAssignAeFilterId(v as string | "all"))
                    }
                    options={assignAeFilterOptions}
                    placeholder={allUsersLoaded ? "All Assign AE" : "Loading…"}
                    aria-label="Filter by assigned AE"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      assignAeFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              )}

              {showLeadOwnerFilter && (
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by assigned BDR",
                    assignBdrFilterId,
                    assignBdrFilterOptions,
                  )}
                  className={cn(FILTER_WRAP_CLASS, "min-[1500px]:min-w-[152px]")}
                >
                  <ReactSelect
                    size="sm"
                    value={assignBdrFilterId}
                    disabled={!allUsersLoaded}
                    onValueChange={(v) =>
                      dispatch(setAssignBdrFilterId(v as string | "all"))
                    }
                    options={assignBdrFilterOptions}
                    placeholder={allUsersLoaded ? "All Assign BDR" : "Loading…"}
                    aria-label="Filter by assigned BDR"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      assignBdrFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              )}

              <DealsFilterTooltip
                label={dealsFilterTooltipLabel(
                  "Filter by service",
                  serviceFilterId,
                  serviceFilterOptions,
                )}
                className={FILTER_WRAP_CLASS}
              >
                <ReactSelect
                  size="sm"
                  value={serviceFilterId}
                  onValueChange={(v) =>
                    dispatch(setServiceFilterId(v as string | "all"))
                  }
                  options={serviceFilterOptions}
                  placeholder="All Services"
                  aria-label="Filter by service"
                  triggerClassName={cn(
                    DEALS_FILTER_TRIGGER_CLASS,
                    serviceFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                  )}
                  position="popper"
                  align="start"
                />
              </DealsFilterTooltip>

              <DealsFilterTooltip
                label={dealsFilterTooltipLabel(
                  "Filter by channel",
                  leadChannelFilterId,
                  leadChannelFilterOptions,
                )}
                className={cn(FILTER_WRAP_CLASS, "group")}
              >
                <ReactSelect
                  size="sm"
                  value={leadChannelFilterId}
                  onValueChange={(v) => dispatch(setLeadChannelFilterId(v))}
                  options={leadChannelFilterOptions}
                  placeholder="Channel"
                  aria-label="Filter by channel"
                  triggerClassName={cn(
                    DEALS_FILTER_TRIGGER_CLASS,
                    "group-hover:border-accent",
                    leadChannelFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                  )}
                  position="popper"
                  align="start"
                />
              </DealsFilterTooltip>
            </div>
          )}

          {canSubject === "deal" && (
            <div className="flex min-w-0 flex-wrap items-center gap-1.5 min-[1500px]:gap-2 pb-3 min-[1440px]:pb-2 lg:justify-end">
              <Can action="read" subject="deal">
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by deal type",
                    businessDealFilters.dealType,
                    dealTypeFilterOptions,
                  )}
                  className={FILTER_WRAP_CLASS}
                >
                  <ReactSelect
                    size="sm"
                    value={businessDealFilters.dealType}
                    onValueChange={(v) =>
                      dispatch(setBusinessDealFilters({ dealType: v }))
                    }
                    options={dealTypeFilterOptions}
                    placeholder="All Deal Types"
                    aria-label="Filter by deal type"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      businessDealFilters.dealType !== "all" &&
                        DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by region",
                    businessDealFilters.region,
                    regionFilterOptions,
                  )}
                  className={FILTER_WRAP_CLASS}
                >
                  <ReactSelect
                    size="sm"
                    value={businessDealFilters.region}
                    onValueChange={(v) =>
                      dispatch(setBusinessDealFilters({ region: v }))
                    }
                    options={regionFilterOptions}
                    placeholder="All Regions"
                    aria-label="Filter by region"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      businessDealFilters.region !== "all" &&
                        DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              </Can>
              <Can action="update" subject={canSubject}>
                <DealsFilterTooltip
                  label={dealsFilterTooltipLabel(
                    "Filter by team",
                    teamFilterDisplay,
                    teamFilterOptions,
                  )}
                  className={FILTER_WRAP_CLASS}
                >
                  <ReactSelect
                    size="sm"
                    value={teamFilterDisplay}
                    onValueChange={(v) => {
                      if (v !== teamFilterDisplay) {
                        dispatch(setTeamFilterDisplay(v));
                        dispatch(setSelectedTeam(v));
                      }
                    }}
                    options={teamFilterOptions}
                    placeholder="All Teams"
                    aria-label="Filter by team"
                    triggerClassName={cn(
                      DEALS_FILTER_TRIGGER_CLASS,
                      teamFilterDisplay !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                    )}
                    position="popper"
                    align="start"
                  />
                </DealsFilterTooltip>
              </Can>
              <DealsFilterTooltip
                label={dealsFilterTooltipLabel(
                  "Filter by channel",
                  leadChannelFilterId,
                  leadChannelFilterOptions,
                )}
                className={cn(FILTER_WRAP_CLASS, "group")}
              >
                <ReactSelect
                  size="sm"
                  value={leadChannelFilterId}
                  onValueChange={(v) => dispatch(setLeadChannelFilterId(v))}
                  options={leadChannelFilterOptions}
                  placeholder="All Channels"
                  aria-label="Filter by channel"
                  triggerClassName={cn(
                    DEALS_FILTER_TRIGGER_CLASS,
                    "group-hover:border-accent",
                    leadChannelFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                  )}
                  position="popper"
                  align="start"
                />
              </DealsFilterTooltip>
              <DealsFilterTooltip
                label={dealsFilterTooltipLabel(
                  "Filter by service",
                  serviceFilterId,
                  serviceFilterOptions,
                )}
                className={FILTER_WRAP_CLASS}
              >
                <ReactSelect
                  size="sm"
                  value={serviceFilterId}
                  onValueChange={(v) =>
                    dispatch(setServiceFilterId(v as string | "all"))
                  }
                  options={serviceFilterOptions}
                  placeholder="All Services"
                  aria-label="Filter by service"
                  triggerClassName={cn(
                    DEALS_FILTER_TRIGGER_CLASS,
                    serviceFilterId !== "all" && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
                  )}
                  position="popper"
                  align="start"
                />
              </DealsFilterTooltip>
            </div>
          )}
        </div>
      </TooltipProvider>
    </div>
  );
});
