"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import dynamic from "next/dynamic";
import { useRouter } from "next/navigation"; // ✅ ADD
import styles from "../../modules/commonstyle/dattabale.module.css";
import { CompanyFilters } from "./CompanyFilters";
import { Pagination } from "./Pagination";
import { EnterpriseLoader } from "./../../../../components/loader/loader";
import {
  getCompaniesPaginated,
  getAllCompanies,
  deleteCompany,
} from "@/lib/api/company.api";

import { fetchApi } from "@/lib/api/http";
import { deleteWithConfirm } from "./../../../../components/ConfirmDialog/ConfirmDialog";
import CompanyForm from "./Form/CompanyForm";
import CompanyViewModal from "./Form/CompanyViewModal";
import ScopeSummaryModal from "./Form/ScopeSummaryModal";
import CompanyAnalyticsInline from "./Filters/CompanyAnalyticsInline";
import {
  mapCompaniesApiResponse,
  mapColumnKeyToValue,
} from "@/lib/api/mappers/company.mappers";
import type { CompanyRow, PaginationMeta } from "@/lib/api/types/company.types";
import InviteClientModal from "./Form/InviteClientModal";
const CompanyRowFallback = dynamic(
  () => import("./CompanyRow").then((m) => m.CompanyRow),
  { ssr: false },
);
const DynamicCompanyRow = dynamic(
  () => import("./DynamicCompanyRow").then((m) => m.default),
  { ssr: false },
);

interface ButtonConfig {
  key: string;
  icon: string;
  color: string;
  label: string;
  order: number;
  position: "row" | "toolbar";
}
interface ColumnConfig {
  key: string;
  type: string;
  label: string;
  order: number;
  sortable: boolean;
  default_visible: boolean;
}
interface ModuleConfig {
  id: number;
  name: string;
  slug: string;
  button_config: ButtonConfig[];
  column_config: ColumnConfig[];
}
interface CompanyTableProps {
  refreshFlag?: boolean;
}

const FALLBACK_COLUMNS: ColumnConfig[] = [
  {
    key: "company_code",
    type: "text",
    label: "Code",
    order: 1,
    sortable: true,
    default_visible: true,
  },
  // ✅ MOVED — Client Group now sits directly after Code (was order 7)
  {
    key: "client_group",
    type: "custom",
    label: "Client Group",
    order: 2,
    sortable: true,
    default_visible: true,
  },
  {
    key: "name",
    type: "text",
    label: "Company",
    order: 3,
    sortable: true,
    default_visible: true,
  },
  {
    key: "city",
    type: "text",
    label: "City",
    order: 4,
    sortable: true,
    default_visible: true,
  },
  {
    key: "contact_person",
    type: "text",
    label: "Contact",
    order: 5,
    sortable: true,
    default_visible: true,
  },
  {
    key: "standards",
    type: "custom",
    label: "Standards",
    order: 6,
    sortable: false,
    default_visible: true,
  },
  {
    key: "validity",
    type: "text",
    label: "Validity",
    order: 7,
    sortable: true,
    default_visible: true,
  },
  {
    key: "actions",
    type: "actions",
    label: "Actions",
    order: 99,
    sortable: false,
    default_visible: true,
  },
];

// ✅ NEW — guarantees a "Client Group" column exists directly after "Code",
// even when the backend module config (dynamic mode) omits it or orders it last.
// This is what makes Client Group appear next to Code in production, where the
// column list usually comes from GET /modules rather than FALLBACK_COLUMNS.
function ensureClientGroupAfterCode(cols: ColumnConfig[]): ColumnConfig[] {
  const codeIdx = cols.findIndex((c) => c.key === "company_code");
  // If there's no Code column visible, don't force the group in (respects perms).
  if (codeIdx === -1) return cols;

  const existing = cols.find((c) => c.key === "client_group");
  const groupCol: ColumnConfig = existing ?? {
    key: "client_group",
    type: "custom",
    label: "Client Group",
    order: 0,
    sortable: true,
    default_visible: true,
  };

  const withoutGroup = cols.filter((c) => c.key !== "client_group");
  const insertAt = withoutGroup.findIndex((c) => c.key === "company_code") + 1;
  return [
    ...withoutGroup.slice(0, insertAt),
    groupCol,
    ...withoutGroup.slice(insertAt),
  ];
}

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

export default function CompanyTable({ refreshFlag }: CompanyTableProps) {
  const [data, setData] = useState<CompanyRow[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [allData, setAllData] = useState<CompanyRow[]>([]);
  const [allDataLoading, setAllDataLoading] = useState(false);

  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [expandedRows, setExpandedRows] = useState<number[]>([]);

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  const [searchTerm, setSearchTerm] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [cityFilter, setCityFilter] = useState("all");
  const [standardFilter, setStandardFilter] = useState("all");
  const [monthFilter, setMonthFilter] = useState("all");

  const debouncedSearch = useDebounce(searchTerm, 400);

  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [showAnalytics, setShowAnalytics] = useState(false);

  const [viewRow, setViewRow] = useState<CompanyRow | null>(null);
  const [scopeSummaryRow, setScopeSummaryRow] = useState<CompanyRow | null>(
    null,
  );
  const [inviteRow, setInviteRow] = useState<CompanyRow | null>(null);

  // ✅ NEW — track companies created during this session for visual highlight
  const [newlyCreatedIds, setNewlyCreatedIds] = useState<Set<number>>(
    new Set(),
  );

  // ✅ NEW — track previous company IDs to auto-detect new arrivals
  const [knownIds, setKnownIds] = useState<Set<number>>(new Set());

  const [allCities, setAllCities] = useState<string[]>([]);

  const [moduleConfig, setModuleConfig] = useState<ModuleConfig | null>(null);
  const [userPermissions, setUserPermissions] = useState<any[]>([]);
  const [permissionsLoading, setPermissionsLoading] = useState(true);
  const [permissionSystemReady, setPermissionSystemReady] = useState(false);
  const [showDebug, setShowDebug] = useState(true);
  const [debugLog, setDebugLog] = useState<string[]>([]);
  const [rawUserId, setRawUserId] = useState<any>(null);
  const [rawModuleResponse, setRawModuleResponse] = useState<any>(null);

  const addDebug = useCallback((msg: string) => {
    console.log(`[COMPANY-DEBUG] ${msg}`);
    setDebugLog((p) => [...p, `${new Date().toLocaleTimeString()} — ${msg}`]);
  }, []);

  const fetchModuleConfig = useCallback(async (): Promise<boolean> => {
    try {
      const response = await fetchApi<any>(`${API_BASE_URL}/modules`);
      const list = Array.isArray(response)
        ? response
        : response?.data
          ? Array.isArray(response.data)
            ? response.data
            : [response.data]
          : [response];
      setRawModuleResponse(response);
      const mod = list.find(
        (m: any) => m.slug === "companies" || m.name === "companies",
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ companies module (id:${mod.id})`);
        return true;
      }
      addDebug("⚠️ module NOT found — FALLBACK");
      return false;
    } catch (err: any) {
      addDebug(`⚠️ module fetch: ${err.message}`);
      return false;
    }
  }, [addDebug]);

  const fetchUserPermissions = useCallback(async (): Promise<boolean> => {
    try {
      let userId: any = null,
        source = "";
      if (typeof window !== "undefined") {
        try {
          const s = localStorage.getItem("user");
          if (s) {
            const p = JSON.parse(s);
            userId = p?.id || p?.userId || p?.user_id;
            source = `localStorage("user")`;
          }
        } catch { }
        if (!userId) {
          try {
            const t =
              localStorage.getItem("token") ||
              localStorage.getItem("accessToken") ||
              localStorage.getItem("access_token");
            if (t) {
              const p = JSON.parse(atob(t.split(".")[1]));
              userId = p?.id || p?.userId || p?.user_id || p?.sub;
              source = "JWT";
            }
          } catch { }
        }
        if (!userId) {
          userId =
            localStorage.getItem("userId") || localStorage.getItem("user_id");
          if (userId) source = `localStorage("userId")`;
        }
      }
      setRawUserId({ userId, source });
      if (!userId) {
        addDebug("⚠️ No userId — FALLBACK");
        setUserPermissions([]);
        return false;
      }
      const res = await fetchApi<any>(
        `${API_BASE_URL}/user-permissions/user/${userId}`,
      );
      const list = Array.isArray(res)
        ? res
        : res?.data
          ? Array.isArray(res.data)
            ? res.data
            : [res.data]
          : (res?.permissions ?? []);
      setUserPermissions(list);
      addDebug(`📦 ${list.length} permissions`);
      return true;
    } catch (err: any) {
      addDebug(`⚠️ perms: ${err.message}`);
      setUserPermissions([]);
      return false;
    }
  }, [addDebug]);

  const visibleColumns = useMemo((): ColumnConfig[] => {
    if (!moduleConfig?.column_config?.length)
      return ensureClientGroupAfterCode(FALLBACK_COLUMNS);
    const all = [...moduleConfig.column_config].sort(
      (a, b) => (a.order ?? 99) - (b.order ?? 99),
    );
    let cond: string | null = null;
    for (const up of userPermissions) {
      const mid = up.permission?.module?.id ?? up.permission?.module_id;
      if (mid && mid !== moduleConfig.id) continue;
      for (const c of up.conditions ?? []) {
        if (
          (c.condition_field || c.field) === "visible_columns" &&
          (c.condition_value || c.value)
        ) {
          cond = c.condition_value || c.value;
          break;
        }
      }
      if (cond) break;
    }
    const selected = cond
      ? all.filter((c) =>
        cond!
          .split(",")
          .map((k) => k.trim())
          .includes(c.key),
      )
      : all;
    // ✅ ensure Client Group shows next to Code even if backend config omits it
    return ensureClientGroupAfterCode(selected);
  }, [moduleConfig, userPermissions]);

  const permittedActions = useMemo((): Set<string> => {
    if (!moduleConfig)
      return new Set([
        "view",
        "edit",
        "delete",
        "create",
        "export",
        "print",
        "view_all",
      ]);
    const a = new Set<string>();
    for (const up of userPermissions) {
      if (!up.permission?.action) continue;
      const mid = up.permission.module?.id ?? up.permission.module_id;
      if (mid === moduleConfig.id) a.add(up.permission.action);
    }
    return a;
  }, [moduleConfig, userPermissions]);

  const rowButtons = useMemo(
    () =>
      !moduleConfig?.button_config
        ? []
        : moduleConfig.button_config
          .filter((b) => b.position === "row" && permittedActions.has(b.key))
          .sort((a, b) => (a.order ?? 99) - (b.order ?? 99)),
    [moduleConfig, permittedActions],
  );
  const toolbarButtons = useMemo(
    () =>
      !moduleConfig?.button_config
        ? []
        : moduleConfig.button_config
          .filter(
            (b) => b.position === "toolbar" && permittedActions.has(b.key),
          )
          .sort((a, b) => (a.order ?? 99) - (b.order ?? 99)),
    [moduleConfig, permittedActions],
  );

  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      city: string,
      standard: string,
      month: string,
      start: string,
      end: string,
    ) => {
      setLoading(true);
      setSelectedRows([]);
      setExpandedRows([]);
      getCompaniesPaginated({
        page,
        limit,
        ...(search && { search }),
        ...(city !== "all" && { city }),
        ...(standard !== "all" && { standard }),
        ...(month !== "all" && { month }),
        ...(start && { startDate: start }),
        ...(end && { endDate: end }),
      })
        .then((res) => {
          const mapped = mapCompaniesApiResponse(res.data);

          // ✅ NEW — detect newly added company IDs (compare with previously known)
          setKnownIds((prevKnown) => {
            // Skip detection on the very first load (when knownIds is empty)
            if (prevKnown.size > 0) {
              const justAddedIds = mapped
                .map((r) => r.id)
                .filter((id) => !prevKnown.has(id));

              if (justAddedIds.length > 0) {
                setNewlyCreatedIds((prev) => {
                  const next = new Set(prev);
                  justAddedIds.forEach((id) => next.add(id));
                  return next;
                });

                // Auto-clear highlight after 30 seconds
                justAddedIds.forEach((id) => {
                  setTimeout(() => {
                    setNewlyCreatedIds((prev) => {
                      const next = new Set(prev);
                      next.delete(id);
                      return next;
                    });
                  }, 30000);
                });

                addDebug(
                  `✨ Detected ${justAddedIds.length} new company(ies): ${justAddedIds.join(", ")}`,
                );
              }
            }

            // Update knownIds with all currently visible IDs
            const next = new Set<number>();
            mapped.forEach((r) => next.add(r.id));
            return next;
          });

          setData(mapped);
          setMeta(res.meta);
          addDebug(
            `✅ Page ${page}: ${res.data.length} of ${res.meta.total} total`,
          );
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    },
    [addDebug],
  );

  const fetchAllForAnalytics = useCallback(() => {
    setAllDataLoading(true);
    getAllCompanies()
      .then((companies) => {
        const rows = mapCompaniesApiResponse(companies);
        setAllData(rows);
        const cities = Array.from(
          new Set(rows.map((r) => r.city?.trim()).filter(Boolean)),
        ).sort() as string[];
        setAllCities(cities);
        addDebug(`📊 Analytics: ${rows.length} total companies loaded`);
      })
      .catch(() => addDebug("⚠️ Analytics data fetch failed"))
      .finally(() => setAllDataLoading(false));
  }, [addDebug]);

  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true);
      setDebugLog([]);
      addDebug("🚀 Companies starting...");
      const [moduleOk, permsOk] = await Promise.all([
        fetchModuleConfig(),
        fetchUserPermissions(),
      ]);
      setPermissionSystemReady(moduleOk && permsOk);
      setPermissionsLoading(false);
    };
    init();
    fetchPage(1, itemsPerPage, "", "all", "all", "all", "", "");
    fetchAllForAnalytics();
    setCurrentPage(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refreshFlag]);

  useEffect(() => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      cityFilter,
      standardFilter,
      monthFilter,
      startDate,
      endDate,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, itemsPerPage]);

  useEffect(() => {
    setCurrentPage(1);
    fetchPage(
      1,
      itemsPerPage,
      debouncedSearch,
      cityFilter,
      standardFilter,
      monthFilter,
      startDate,
      endDate,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    debouncedSearch,
    cityFilter,
    standardFilter,
    monthFilter,
    startDate,
    endDate,
  ]);

  const refresh = () => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      cityFilter,
      standardFilter,
      monthFilter,
      startDate,
      endDate,
    );
    fetchAllForAnalytics();
  };

  const clearAllFilters = () => {
    setSearchTerm("");
    setStartDate("");
    setEndDate("");
    setCityFilter("all");
    setStandardFilter("all");
    setMonthFilter("all");
  };

  const handleDelete = async (row: CompanyRow) => {
    const { confirmed, error: delErr } = await deleteWithConfirm(
      row.name,
      () => deleteCompany(row.id),
      { successMessage: "Company deleted.", errorMessage: "Failed to delete." },
    );
    if (confirmed && !delErr) refresh();
  };
 const router = useRouter();
  const handleEdit = (row: CompanyRow) => {
    router.push(`/modules/companies/edit/${row.id}`);
  };

  const handleView = (row: CompanyRow) => setViewRow(row);

  const handleAction = useCallback((row: CompanyRow, key: string) => {
    if (key === "view") handleView(row);
    else if (key === "edit") handleEdit(row);
    else if (key === "delete") handleDelete(row);
    else if (key === "print") window.print();
    else if (key === "scope_summary") setScopeSummaryRow(row);
    else if (key === "invite_client") setInviteRow(row);   // ← add

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (error)
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>⚠️</div>
        <h3 className={styles.errorTitle}>Error</h3>
        <p className={styles.errorMessage}>{error}</p>
        <button className={styles.errorButton} onClick={refresh}>
          Retry
        </button>
      </div>
    );
  if (permissionsLoading) return <EnterpriseLoader />;

  const useDynamicMode = permissionSystemReady && moduleConfig !== null;
  const hasActionsColumn = visibleColumns.some((c) => c.key === "actions");
  const headerColumns = visibleColumns.filter((c) => c.key !== "actions");

  return (
    <div className={styles.container}>
      {/* ✅ NEW — global keyframes for the green pulse animation */}
      <style jsx global>{`
        @keyframes qrsNewRowPulse {
          0%,
          100% {
            background-color: #dcfce7;
            box-shadow: inset 4px 0 0 #16a34a;
          }
          50% {
            background-color: #bbf7d0;
            box-shadow: inset 4px 0 0 #15803d, 0 0 12px rgba(34, 197, 94, 0.3);
          }
        }
        tr.qrs-new-row > td {
          animation: qrsNewRowPulse 2s ease-in-out infinite;
        }
      `}</style>

      <CompanyViewModal
        row={viewRow}
        onClose={() => setViewRow(null)}
        onEdit={handleEdit}
      />
      <ScopeSummaryModal
        isOpen={!!scopeSummaryRow}
        company={scopeSummaryRow}
        onClose={() => setScopeSummaryRow(null)}
      />
      <InviteClientModal
        isOpen={!!inviteRow}
        company={inviteRow}
        onClose={() => setInviteRow(null)}
      />

      {/* ✅ NEW — Live banner showing how many newly added companies are visible */}
      {newlyCreatedIds.size > 0 && (
        <div
          style={{
            padding: "10px 14px",
            background: "linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%)",
            border: "1.5px solid #22c55e",
            borderRadius: 8,
            marginBottom: 12,
            display: "flex",
            alignItems: "center",
            gap: 10,
            boxShadow: "0 2px 8px rgba(34, 197, 94, 0.15)",
          }}
        >
          <span
            style={{
              fontSize: 10,
              fontWeight: 800,
              color: "#fff",
              background: "#16a34a",
              padding: "3px 8px",
              borderRadius: 4,
              letterSpacing: ".08em",
            }}
          >
            ✨ NEW
          </span>
          <span
            style={{ fontSize: 13, color: "#166534", fontWeight: 600 }}
          >
            {newlyCreatedIds.size} freshly added{" "}
            {newlyCreatedIds.size === 1 ? "company" : "companies"} highlighted
            below — fades in 30 seconds.
          </span>
        </div>
      )}

      {/* ═══ DEBUG (userId=1 only) ═══ */}
      {Number(rawUserId?.userId) === 1 && (
        <div
          style={{
            margin: "0 0 16px",
            border: `2px solid ${useDynamicMode ? "#14b8a6" : "#f59e0b"}`,
            overflow: "hidden",
            background: useDynamicMode ? "#f0fdfa" : "#fffbeb",
            fontSize: "13px",
          }}
        >
          <div
            onClick={() => setShowDebug(!showDebug)}
            style={{
              padding: "10px 16px",
              background: useDynamicMode ? "#0f766e" : "#f59e0b",
              color: "#fff",
              fontWeight: 700,
              cursor: "pointer",
              display: "flex",
              justifyContent: "space-between",
            }}
          >
            <span>
              {useDynamicMode ? "✅ DYNAMIC" : "⚠️ FALLBACK"} —{" "}
              {meta?.total?.toLocaleString() ?? 0} total /{" "}
              {allData.length.toLocaleString()} analytics
            </span>
            <span>{showDebug ? "▼" : "▶"}</span>
          </div>
          {showDebug && (
            <div style={{ padding: "16px" }}>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(4,1fr)",
                  gap: "10px",
                  marginBottom: "12px",
                }}
              >
                {[
                  {
                    ok: !!moduleConfig,
                    title: moduleConfig
                      ? `Module #${moduleConfig.id}`
                      : "No Module",
                    detail: `${moduleConfig?.button_config?.length || 0}b ${moduleConfig?.column_config?.length || 0}c`,
                  },
                  {
                    ok: !!rawUserId?.userId,
                    title: rawUserId?.userId
                      ? `User #${rawUserId.userId}`
                      : "No User",
                    detail: rawUserId?.source || "",
                  },
                  {
                    ok: !!meta,
                    title: meta
                      ? `${meta.total.toLocaleString()} DB Records`
                      : "—",
                    detail: meta ? `Page ${meta.page}/${meta.totalPages}` : "",
                  },
                  {
                    ok: allData.length > 0,
                    title: `${allData.length.toLocaleString()} Analytics`,
                    detail: allDataLoading
                      ? "Loading..."
                      : "All records loaded",
                  },
                ].map((c, i) => (
                  <div
                    key={i}
                    style={{
                      padding: 10,
                      background: c.ok ? "#dcfce7" : "#fef2f2",
                      borderRadius: 8,
                      textAlign: "center",
                    }}
                  >
                    <div
                      style={{
                        fontWeight: 700,
                        color: c.ok ? "#166534" : "#991b1b",
                        fontSize: 13,
                      }}
                    >
                      {c.ok ? "✅" : "❌"} {c.title}
                    </div>
                    <div
                      style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}
                    >
                      {c.detail}
                    </div>
                  </div>
                ))}
              </div>
              <details>
                <summary
                  style={{
                    cursor: "pointer",
                    fontWeight: 600,
                    color: "#0f766e",
                  }}
                >
                  📋 Debug Log
                </summary>
                <div
                  style={{
                    background: "#0f172a",
                    borderRadius: 6,
                    padding: 10,
                    maxHeight: 150,
                    overflow: "auto",
                    marginTop: 4,
                  }}
                >
                  {debugLog.map((l, i) => (
                    <div
                      key={i}
                      style={{
                        fontSize: 11,
                        color: l.includes("✅")
                          ? "#4ade80"
                          : l.includes("⚠️")
                            ? "#fbbf24"
                            : l.includes("✨")
                              ? "#22c55e"
                              : "#94a3b8",
                        fontFamily: "monospace",
                        marginBottom: 2,
                      }}
                    >
                      {l}
                    </div>
                  ))}
                </div>
              </details>
            </div>
          )}
        </div>
      )}

      <CompanyFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        startDate={startDate}
        setStartDate={setStartDate}
        endDate={endDate}
        setEndDate={setEndDate}
        cityFilter={cityFilter}
        setCityFilter={setCityFilter}
        standardFilter={standardFilter}
        setStandardFilter={setStandardFilter}
        monthFilter={monthFilter}
        setMonthFilter={setMonthFilter}
        cities={allCities}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        onAnalyticsToggle={() => setShowAnalytics((v) => !v)}
        showAnalytics={showAnalytics}
      />

      {showAnalytics && (
        <CompanyAnalyticsInline
          companies={allData}
          cityFilter={cityFilter}
          standardFilter={standardFilter}
          monthFilter={monthFilter}
        />
      )}

      {meta && (
        <div
          style={{
            padding: "10px 16px",
            backgroundColor: "#f0fdfa",
            border: "1px solid #99f6e4",
            borderRadius: 8,
            marginBottom: 12,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 13,
            color: "#0f766e",
          }}
        >
          <span>
            📊 Showing{" "}
            <strong>
              {(currentPage - 1) * itemsPerPage + 1}–
              {Math.min(currentPage * itemsPerPage, meta.total)}
            </strong>{" "}
            of <strong>{meta.total.toLocaleString()}</strong> companies
            {(searchTerm ||
              cityFilter !== "all" ||
              standardFilter !== "all" ||
              monthFilter !== "all" ||
              startDate ||
              endDate) && (
                <span style={{ marginLeft: 8, color: "#9ca3af" }}>
                  (filtered)
                </span>
              )}
          </span>
          {(searchTerm ||
            cityFilter !== "all" ||
            standardFilter !== "all" ||
            monthFilter !== "all" ||
            startDate ||
            endDate) && (
              <button
                onClick={clearAllFilters}
                style={{
                  background: "none",
                  border: "none",
                  color: "#0f766e",
                  cursor: "pointer",
                  textDecoration: "underline",
                  fontSize: 13,
                }}
              >
                Clear filters
              </button>
            )}
        </div>
      )}

      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th className={styles.expandCol}></th>
              <th className={styles.checkboxCol}>
                <input
                  type="checkbox"
                  className={styles.checkbox}
                  checked={
                    data.length > 0 &&
                    data.every((r) => selectedRows.includes(r.sno))
                  }
                  onChange={(e) =>
                    setSelectedRows(
                      e.target.checked ? data.map((r) => r.sno) : [],
                    )
                  }
                />
              </th>
              {useDynamicMode ? (
                <>
                  {headerColumns.map((col) => (
                    <th key={col.key} className={styles.th}>
                      {col.label}
                    </th>
                  ))}
                  {hasActionsColumn && rowButtons.length > 0 && (
                    <th className={styles.actionsCol}>Actions</th>
                  )}
                </>
              ) : (
                <>
                  <th className={styles.th}>Code</th>
                  <th className={styles.th}>Client Group</th>
                  <th className={styles.th}>Company</th>
                  <th className={styles.th}>City</th>
                  <th className={styles.th}>Contact</th>
                  <th className={styles.th}>Standards</th>
                  <th className={styles.th}>Validity</th>
                  <th className={styles.actionsCol}>Actions</th>
                </>
              )}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{
                    textAlign: "center",
                    padding: "60px",
                    color: "#9ca3af",
                  }}
                >
                  <div
                    style={{
                      display: "inline-block",
                      width: 28,
                      height: 28,
                      border: "3px solid #e5e7eb",
                      borderTopColor: "#14b8a6",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                      marginBottom: 10,
                    }}
                  />
                  <p style={{ margin: 0 }}>Loading...</p>
                </td>
              </tr>
            ) : data.length > 0 ? (
              data.map((row) =>
                useDynamicMode ? (
                  <DynamicCompanyRow
                    key={row.sno}
                    row={row}
                    visibleColumns={headerColumns}
                    rowButtons={rowButtons}
                    hasActionsColumn={hasActionsColumn && rowButtons.length > 0}
                    mapColumnKeyToValue={mapColumnKeyToValue}
                    isExpanded={expandedRows.includes(row.sno)}
                    toggleRowExpand={(id) =>
                      setExpandedRows((p) =>
                        p.includes(id) ? p.filter((r) => r !== id) : [...p, id],
                      )
                    }
                    isSelected={selectedRows.includes(row.sno)}
                    handleRowSelect={(id, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, id] : p.filter((r) => r !== id),
                      )
                    }
                    onAction={handleAction}
                    /* ✅ NEW — pass the highlight flag */
                    isNew={newlyCreatedIds.has(row.id)}
                  />
                ) : (
                  <CompanyRowFallback
                    key={row.sno}
                    row={row}
                    isExpanded={expandedRows.includes(row.sno)}
                    toggleRowExpand={(id) =>
                      setExpandedRows((p) =>
                        p.includes(id) ? p.filter((r) => r !== id) : [...p, id],
                      )
                    }
                    isSelected={selectedRows.includes(row.sno)}
                    handleRowSelect={(id, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, id] : p.filter((r) => r !== id),
                      )
                    }
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onView={handleView}
                    /* ✅ NEW — pass the highlight flag */
                    isNew={newlyCreatedIds.has(row.id)}
                  />
                ),
              )
            ) : (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{ textAlign: "center", padding: "60px" }}
                >
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      gap: 12,
                    }}
                  >
                    <div style={{ fontSize: 36 }}>🏢</div>
                    <h3 style={{ margin: 0, color: "#111827" }}>
                      No Companies Found
                    </h3>
                    <p style={{ color: "#6b7280", margin: 0 }}>
                      {searchTerm ||
                        cityFilter !== "all" ||
                        standardFilter !== "all" ||
                        monthFilter !== "all"
                        ? "No companies match your filters."
                        : "Get started by adding a new company."}
                    </p>
                  </div>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {meta && (
        <Pagination
          currentPage={currentPage}
          setCurrentPage={setCurrentPage}
          totalPages={meta.totalPages}
          startIndex={(currentPage - 1) * itemsPerPage + 1}
          endIndex={Math.min(currentPage * itemsPerPage, meta.total)}
          sortedDataLength={meta.total}
          itemsPerPage={itemsPerPage}
          setItemsPerPage={(v) => {
            setCurrentPage(1);
            setItemsPerPage(v);
          }}
        />
      )}

      {/* <CompanyForm
        isOpen={isEditModalOpen}
        onClose={() => {
          setIsEditModalOpen(false);
          setEditingId(null);
        }}
        refreshData={refresh}
        editId={editingId}
      /> */}
    </div>
  );
}