"use client";

import React, { useEffect, useState, useMemo } from "react";
import {
  Users, Megaphone, Star, Globe,
  UserCog, Building2, LayoutTemplate,
  FileText, Briefcase, Award, FileCheck, Archive,
  ClipboardList, Send, CheckCircle2, AlertCircle,
  // 🔹 NEW icons for Auditor dashboard
  Calendar, ClipboardCheck, ShieldAlert, TrendingUp, Activity,
  Layers, AlertTriangle, CircleDot, Check,
} from "lucide-react";
import { useRouter } from "next/navigation";
import styles from "./dashboard.module.css";
import "./dashboard-polish.css";
import { fetchApi } from "@/lib/api/http";
import DashboardAnalytics from "./DashboardAnalytics";
const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

// ─── Tunable endpoints (change here if yours differ) ───────────────────
const AUDIT_LIST_ENDPOINT = `${API_BASE_URL}/company-audits?limit=9999`;
const PREVIOUS_NC_PAGED_ENDPOINT = `${API_BASE_URL}/previous-nc/paged`;

// ✅ NEW — Helper to safely fetch a count from a paginated endpoint
async function safeFetchCount(url: string): Promise<number | null> {
  try {
    const res = await fetchApi<any>(url);
    if (typeof res === "number") return res;
    if (res?.meta?.total !== undefined) return Number(res.meta.total);
    if (res?.total !== undefined) return Number(res.total);
    if (res?.count !== undefined) return Number(res.count);
    if (Array.isArray(res)) return res.length;
    if (Array.isArray(res?.data)) return res.data.length;
    return null;
  } catch (err) {
    console.warn(`[Dashboard] Failed to fetch ${url}:`, err);
    return null;
  }
}

function formatCount(n: number | null): string {
  if (n === null) return "N/A";
  return n.toLocaleString();
}

const INQUIRY_STATUS_CONFIG = {
  PENDING: { label: "Pending", color: "#d97706", bg: "rgba(217,119,6,0.15)" },
  IN_REVIEW: { label: "In Review", color: "#2563eb", bg: "rgba(37,99,235,0.15)" },
  DRAFT_READY: { label: "Draft Ready", color: "#7c3aed", bg: "rgba(124,58,237,0.15)" },
  CHANGES_REQUESTED: { label: "Changes", color: "#dc2626", bg: "rgba(220,38,38,0.15)" },
  CLIENT_CONFIRMED: { label: "Confirmed", color: "#059669", bg: "rgba(5,150,105,0.15)" },
  FINAL_ISSUED: { label: "Issued", color: "#0f766e", bg: "rgba(15,118,110,0.15)" },
} as const;

const FULL_KPI_CARDS_CONFIG = [
  { label: "Auditors/Users", icon: <Users size={26} />, endpoint: `${API_BASE_URL}/users?limit=1`, route: "/modules/users", color: "#2563eb" },
  { label: "Audit Compliance", icon: <Megaphone size={26} />, endpoint: `${API_BASE_URL}/audit-schedules?limit=1`, route: "/modules/audit-schedules", color: "#7c3aed" },
  { label: "Standards", icon: <Star size={26} />, endpoint: `${API_BASE_URL}/standards`, route: "/modules/standards", color: "#f59e0b" },
  { label: "Countries", icon: <Globe size={26} />, endpoint: `${API_BASE_URL}/countries`, route: "/modules/countries", color: "#0891b2" },
  { label: "Inquiries", icon: <ClipboardList size={26} />, endpoint: `${API_BASE_URL}/inquiries?limit=1`, route: "/modules/inquiries", color: "#0f766e" },
  { label: "Clients", icon: <Building2 size={26} />, endpoint: `${API_BASE_URL}/companies?limit=1`, route: "/modules/companies", color: "#dc2626" },
  { label: "Draft & Digital Certificates", icon: <Award size={26} />, endpoint: `${API_BASE_URL}/certificates?limit=1`, route: "/modules/certificates", color: "#059669" },
  { label: "Templates", icon: <LayoutTemplate size={26} />, endpoint: `${API_BASE_URL}/templates`, route: "/modules/templates", color: "#9333ea" },
  { label: "Audit Documents", icon: <FileText size={26} />, endpoint: `${API_BASE_URL}/company-audits?limit=1`, route: "/modules/company-audits", color: "#14b8a6" }, { label: "My Audits", icon: <Briefcase size={26} />, endpoint: `${API_BASE_URL}/my-audits?limit=1`, route: "/modules/my-audits", color: "#8b5cf6" },
  { label: "Audit Requests", icon: <ClipboardCheck size={26} />, endpoint: `${API_BASE_URL}/audit-requests?limit=1`, route: "/modules/audit-requests", color: "#0ea5e9" },
  { label: "Audit Report", icon: <FileText size={26} />, endpoint: `${API_BASE_URL}/audit-report/detail?limit=1`, route: "/modules/audit-report", color: "#7904c2" },
  { label: "NCs", icon: <ShieldAlert size={26} />, endpoint: `${API_BASE_URL}/previous-nc/paged?limit=1`, route: "/modules/previous-nc", color: "#ef4444" },
  { label: "Job Registrar", icon: <UserCog size={26} />, endpoint: `${API_BASE_URL}/jobs`, route: "/modules/jobs", color: "#ea580c" },
  { label: "Notifications", icon: <FileCheck size={26} />, endpoint: `${API_BASE_URL}/notifications`, route: "/modules/notifications", color: "#be185d" },
  { label: "Previous Certificates", icon: <Archive size={26} />, endpoint: `${API_BASE_URL}/excel`, route: "/modules/excel", color: "#6b7280" },
];

const ACTIVITY = [
  { text: "New certificate issued for Al Fara'a Group", time: "2 min ago", dot: "#c084fc", status: "Issued", statusBg: "rgba(192,132,252,0.2)", statusColor: "#e9d5ff" },
  { text: "Job #JR-4821 assigned to auditor", time: "18 min ago", dot: "#60a5fa", status: "Assigned", statusBg: "rgba(96,165,250,0.2)", statusColor: "#bfdbfe" },
  { text: "Certificate expiring — Gulf Contracting", time: "1 hr ago", dot: "#fbbf24", status: "Warning", statusBg: "rgba(251,191,36,0.2)", statusColor: "#fef08a" },
  { text: "New client registered — Vision Tech LLC", time: "3 hr ago", dot: "#34d399", status: "New", statusBg: "rgba(52,211,153,0.2)", statusColor: "#a7f3d0" },
  { text: "ISO 9001 audit completed successfully", time: "5 hr ago", dot: "#34d399", status: "Done", statusBg: "rgba(52,211,153,0.2)", statusColor: "#a7f3d0" },
];

const CHART_DATA = [
  { label: "Jan", height: 40 }, { label: "Feb", height: 60 }, { label: "Mar", height: 45 },
  { label: "Apr", height: 80 }, { label: "May", height: 65 }, { label: "Jun", height: 90 },
  { label: "Jul", height: 75, active: true }, { label: "Aug", height: 55 },
];

function getUserFromToken(): {
  id: number | null;
  email: string;
  roleNames: string[];
  firstName: string;
} {
  if (typeof window === "undefined") {
    return { id: null, email: "", roleNames: [], firstName: "" };
  }
  try {
    const token =
      localStorage.getItem("access_token") || localStorage.getItem("token");
    if (!token) return { id: null, email: "", roleNames: [], firstName: "" };
    const payload = JSON.parse(atob(token.split(".")[1]));
    return {
      id: payload?.sub ?? payload?.id ?? null,
      email: payload?.email ?? "",
      roleNames: payload?.roleNames ?? [],
      firstName: payload?.firstName ?? payload?.email?.split("@")[0] ?? "User",
    };
  } catch {
    return { id: null, email: "", roleNames: [], firstName: "" };
  }
}

function hasFullAccess(roleNames: string[]): boolean {
  const lc = roleNames.map((r) => r.toLowerCase());
  return lc.includes("super-admin") || lc.includes("scheme");
}

function isMarketing(roleNames: string[]): boolean {
  return roleNames.map((r) => r.toLowerCase()).includes("marketing");
}

// 🔹 NEW — detect auditor role
function isAuditor(roleNames: string[]): boolean {
  return roleNames.map((r) => r.toLowerCase()).some((r) => r.includes("auditor"));
}

export default function DashboardPage() {
  const router = useRouter();
  const hour = new Date().getHours();
  const greeting =
    hour < 12 ? "Good Morning" : hour < 17 ? "Good Afternoon" : "Good Evening";

  const [user, setUser] = useState({
    id: null as number | null,
    email: "",
    roleNames: [] as string[],
    firstName: "",
  });

  const [myInquiries, setMyInquiries] = useState<any[]>([]);
  const [myInquiriesLoading, setMyInquiriesLoading] = useState(false);

  const [kpiCounts, setKpiCounts] = useState<(number | null)[]>(
    () => new Array(FULL_KPI_CARDS_CONFIG.length).fill(null),
  );
  const [kpiLoading, setKpiLoading] = useState(true);

  // 🔹 NEW — Auditor state
  const [myAudits, setMyAudits] = useState<any[]>([]);
  const [myNcs, setMyNcs] = useState<any[]>([]);
  const [auditorFullName, setAuditorFullName] = useState<string>("");
  const [auditorLoading, setAuditorLoading] = useState(false);

  useEffect(() => {
    setUser(getUserFromToken());
  }, []);

  const fullAccess = useMemo(() => hasFullAccess(user.roleNames), [user.roleNames]);
  const marketingUser = useMemo(() => isMarketing(user.roleNames), [user.roleNames]);
  const auditorUser = useMemo(() => isAuditor(user.roleNames), [user.roleNames]); // 🔹 NEW

  // Marketing inquiries fetch (unchanged)
  useEffect(() => {
    if (!user.id || fullAccess) return;
    setMyInquiriesLoading(true);
    fetchApi<any>(`${API_BASE_URL}/inquiries?limit=9999`)
      .then((res) => {
        const all = res?.data ?? [];
        const mine = all.filter((inq: any) => inq.submitted_by?.id === user.id);
        setMyInquiries(mine);
      })
      .catch(() => setMyInquiries([]))
      .finally(() => setMyInquiriesLoading(false));
  }, [user.id, fullAccess]);

  // Full-dashboard KPI fetch (unchanged)
  useEffect(() => {
    if (!fullAccess) return;
    setKpiLoading(true);
    Promise.all(FULL_KPI_CARDS_CONFIG.map((card) => safeFetchCount(card.endpoint)))
      .then((results) => setKpiCounts(results))
      .catch((err) => console.error("[DASHBOARD] KPI fetch error:", err))
      .finally(() => setKpiLoading(false));
  }, [fullAccess]);

  // 🔹 NEW — Auditor dashboard data fetch
  useEffect(() => {
    if (!user.id || !auditorUser) return;
    setAuditorLoading(true);

    (async () => {
      try {
        // Step 1: get the auditor's full name from /api/users/:id
        // (needed because Previous NC filter matches by user_name)
        let fullName = user.firstName;
        try {
          const u = await fetchApi<any>(`${API_BASE_URL}/users/${user.id}`);
          const fn = u?.first_name ?? u?.firstName ?? "";
          const ln = u?.last_name ?? u?.lastName ?? "";
          fullName = `${fn} ${ln}`.replace(/\s+/g, " ").trim() || fullName;
        } catch (e) {
          console.warn("[Auditor] /users/:id failed, using firstName only", e);
        }
        setAuditorFullName(fullName);
        console.log("[Auditor] resolved fullName =", JSON.stringify(fullName));


        // Step 2: fetch user's audits + NCs in parallel
        const [auditsRes, ncsRes] = await Promise.all([
          fetchApi<any>(AUDIT_LIST_ENDPOINT).catch(() => null),
          fetchApi<any>(`${PREVIOUS_NC_PAGED_ENDPOINT}?page=1&limit=9999${fullName ? `&user_name=${encodeURIComponent(fullName)}` : ""
            }`).catch(() => null),
        ]);

        // Parse audits — try common response shapes
        const audits =
          (auditsRes?.data ??
            auditsRes?.rows ??
            (Array.isArray(auditsRes) ? auditsRes : []) ??
            []) as any[];

        // Filter audits to those involving this user (lead_auditor / coordinator / team)
        const myAuditsFiltered = audits.filter((a: any) => {
          const lead = a?.lead_auditor_id ?? a?.leadAuditorId ?? a?.lead_auditor?.id;
          const coord = a?.coordinator_id ?? a?.coordinatorId ?? a?.coordinator?.id;
          const team =
            (a?.team ?? a?.audit_team ?? []).map((t: any) =>
              typeof t === "number" ? t : (t?.user_id ?? t?.id),
            ) || [];
          return (
            lead === user.id ||
            coord === user.id ||
            team.includes(user.id)
          );
        });

        // If the backend already scopes audits to the logged-in user, the
        // filter is a no-op. If it returns everything, we filter.
        const finalAudits =
          myAuditsFiltered.length > 0 || audits.length === 0
            ? myAuditsFiltered
            : audits;

        setMyAudits(finalAudits);

        const ncs = (ncsRes?.rows ?? ncsRes?.data ?? []) as any[];
        setMyNcs(ncs);
      } catch (err) {
        console.error("[Auditor Dashboard] fetch failed", err);
      } finally {
        setAuditorLoading(false);
      }
    })();
  }, [user.id, user.firstName, auditorUser, fullAccess]);

  // Marketing cards (unchanged)
  const marketingCards = useMemo(() => {
    const total = myInquiries.length;
    const pending = myInquiries.filter((i) => i.status === "PENDING").length;
    const draftReady = myInquiries.filter((i) => i.status === "DRAFT_READY").length;
    const changesNeeded = myInquiries.filter((i) => i.status === "CHANGES_REQUESTED").length;
    const confirmed = myInquiries.filter((i) => i.status === "CLIENT_CONFIRMED").length;
    const issued = myInquiries.filter((i) => i.status === "FINAL_ISSUED").length;
    return [
      { label: "My Inquiries", value: total.toString(), icon: <ClipboardList size={26} />, color: "#0f766e", action: () => router.push("/modules/inquiries") },
      { label: "Pending Review", value: pending.toString(), icon: <Send size={26} />, color: "#d97706", action: () => router.push("/modules/inquiries?status=PENDING") },
      { label: "Drafts Ready", value: draftReady.toString(), icon: <FileCheck size={26} />, color: "#7c3aed", action: () => router.push("/modules/inquiries?status=DRAFT_READY") },
      { label: "Action Needed", value: changesNeeded.toString(), icon: <AlertCircle size={26} />, color: "#dc2626", action: () => router.push("/modules/inquiries?status=CHANGES_REQUESTED") },
      { label: "Confirmed", value: confirmed.toString(), icon: <CheckCircle2 size={26} />, color: "#059669", action: () => router.push("/modules/inquiries?status=CLIENT_CONFIRMED") },
      { label: "Final Issued", value: issued.toString(), icon: <Award size={26} />, color: "#0f766e", action: () => router.push("/modules/inquiries?status=FINAL_ISSUED") },
    ];
  }, [myInquiries, router]);

  // 🔹 NEW — Auditor stats
  const auditorStats = useMemo(() => {
    const todayMs = Date.now();
    const dayMs = 24 * 60 * 60 * 1000;

    // Audits
    let totalAudits = myAudits.length;
    let upcomingAudits = 0;
    let completedAudits = 0;
    let inProgressAudits = 0;

    for (const a of myAudits) {
      const status = String(a?.status ?? "").toLowerCase();
      const auditDate = a?.audit_date ?? a?.start_date ?? a?.scheduled_date;
      const auditMs = auditDate ? new Date(auditDate).getTime() : 0;

      if (status.includes("complete") || status.includes("closed") || status.includes("done")) {
        completedAudits++;
      } else if (status.includes("progress") || status.includes("ongoing") || status.includes("active")) {
        inProgressAudits++;
      }
      if (auditMs && auditMs > todayMs && auditMs - todayMs <= 30 * dayMs) {
        upcomingAudits++;
      }
    }

    // NCs
    const totalNcs = myNcs.length;
    let openNcs = 0;
    let closedNcs = 0;
    let qrsNcs = 0;
    let tqsNcs = 0;
    const ncByType = { Major: 0, Minor: 0, Observation: 0, Other: 0 };

    for (const n of myNcs) {
      const status = String(n?.status ?? "").toLowerCase();
      if (status === "open") openNcs++;
      else if (status === "closed") closedNcs++;

      const src = String(n?.source ?? "").toUpperCase();
      if (src === "QRS") qrsNcs++;
      else if (src === "TQS") tqsNcs++;

      const t = String(n?.nc_type ?? "").toLowerCase();
      if (t.includes("major")) ncByType.Major++;
      else if (t.includes("minor")) ncByType.Minor++;
      else if (t.includes("observ")) ncByType.Observation++;
      else ncByType.Other++;
    }

    // Monthly trend — last 6 months
    const last6: { label: string; count: number; year: number; month: number }[] = [];
    const now = new Date();
    const monthName = (m: number) =>
      ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][m];
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      last6.push({ label: monthName(d.getMonth()), count: 0, year: d.getFullYear(), month: d.getMonth() });
    }
    for (const n of myNcs) {
      if (!n?.created_at) continue;
      const d = new Date(n.created_at);
      if (isNaN(d.getTime())) continue;
      const b = last6.find((x) => x.year === d.getFullYear() && x.month === d.getMonth());
      if (b) b.count++;
    }

    return {
      totalAudits, upcomingAudits, completedAudits, inProgressAudits,
      totalNcs, openNcs, closedNcs, qrsNcs, tqsNcs, ncByType,
      last6Months: last6,
    };
  }, [myAudits, myNcs]);

  // Render-mode logic
  const showFullDashboard = fullAccess;
  const showMarketingDashboard = marketingUser && !fullAccess;
  const showAuditorDashboard = auditorUser; // 🔹 shows whenever user has auditor role (even alongside admin/scheme)
  const showLimitedDashboard = !fullAccess && !marketingUser && !auditorUser;

  return (
    <div className={styles.page}>
      <style>{`
        .${styles.kpiCard}::before,
        .${styles.kpiCard}::after,
        .${styles.kpiBody}::before,
        .${styles.kpiBody}::after,
        .${styles.kpiLabel}::before,
        .${styles.kpiLabel}::after {
          content: none !important;
          display: none !important;
        }
        .${styles.kpiLabel} {
          white-space: normal !important;
          overflow: visible !important;
          text-overflow: clip !important;
          line-height: 1.3 !important;
          word-break: break-word !important;
          display: -webkit-box !important;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      `}</style>

      <div className={styles.header}>
        <h1 className={styles.greeting}>
          {greeting},{" "}
          <span className={styles.greetingAccent}>{user.firstName || "User"}</span>{" "}
          👋
        </h1>
        <p className={styles.greetingSub}>
          {new Date().toLocaleDateString("en-US", {
            weekday: "long", year: "numeric", month: "long", day: "numeric",
          })}
          {user.roleNames.length > 0 && (
            <span
              style={{
                marginLeft: 12, display: "inline-block",
                padding: "3px 10px", borderRadius: 12,
                fontSize: 11, fontWeight: 600,
                background: fullAccess
                  ? "rgba(15,118,110,0.2)"
                  : marketingUser
                    ? "rgba(102,126,234,0.2)"
                    : auditorUser
                      ? "rgba(6,182,212,0.2)"
                      : "rgba(156,163,175,0.2)",
                color: fullAccess
                  ? "#0f766e"
                  : marketingUser
                    ? "#667eea"
                    : auditorUser
                      ? "#06b6d4"
                      : "#6b7280",
                textTransform: "uppercase",
                letterSpacing: "0.05em",
              }}
            >
              {fullAccess
                ? "👑 " + user.roleNames.join(" + ")
                : marketingUser
                  ? "📣 Marketing"
                  : auditorUser
                    ? "🛡️ Auditor"
                    : user.roleNames.join(" + ")}
            </span>
          )}
        </p>
      </div>

      {/* ═══ FULL DASHBOARD — Super-admin & Scheme ═══ */}
      {showFullDashboard && (
        <>
          <div className={styles.cardPanel}>
            <div className={styles.kpiGrid}>
            {FULL_KPI_CARDS_CONFIG.map((card, idx) => {
              const count = kpiCounts[idx];
              const isAvailable = count !== null;
              const isLoading = kpiLoading;
              return (
                <div
                  key={card.label}
                  className={styles.kpiCard}
                  onClick={() => { if (isAvailable && !isLoading) router.push(card.route); }}
                  style={{
                    cursor: isAvailable && !isLoading ? "pointer" : "default",
                    transition: "transform 0.15s, box-shadow 0.15s",
                    opacity: isAvailable || isLoading ? 1 : 0.6,
                  }}
                  onMouseEnter={(e) => {
                    if (isAvailable && !isLoading) {
                      e.currentTarget.style.transform = "translateY(-2px)";
                      e.currentTarget.style.boxShadow = "0 8px 20px rgba(0,0,0,0.12)";
                    }
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = "translateY(0)";
                    e.currentTarget.style.boxShadow = "";
                  }}
                  title={isAvailable ? `Click to view ${card.label}` : `${card.label} module not available`}
                >
                  <div
                    className={styles.kpiIcon}
                    style={{
                      color: "#fff", backgroundColor: card.color,
                      borderRadius: 10, padding: 10,
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                    }}
                  >
                    {card.icon}
                  </div>
                  <div className={styles.kpiBody}>
                    <div className={styles.kpiValue}>
                      {isLoading ? (
                        <span style={{
                          display: "inline-block", width: 60, height: 28, borderRadius: 6,
                          background: "linear-gradient(90deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.15) 50%, rgba(255,255,255,0.08) 100%)",
                          backgroundSize: "200% 100%", animation: "shimmer 1.4s ease-in-out infinite",
                        }} />
                      ) : (formatCount(count))}
                    </div>
                    <div className={styles.kpiLabel}>{card.label}</div>
                  </div>
                </div>
              );
            })}
          </div>
          </div>

          <DashboardAnalytics
            scope="full"
            onGoToAudits={() => router.push("/modules/my-audits")}
            onGoToNcs={() => router.push("/modules/previous-nc")}
          />
        </>
      )}

      {/* ═══ MARKETING DASHBOARD ═══ */}
      {showMarketingDashboard && (
        <>
          <div style={{
            padding: "16px 20px",
            background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
            color: "#fff", borderRadius: 12, marginBottom: 20,
            boxShadow: "0 4px 14px rgba(102,126,234,0.3)",
          }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>📣 Marketing Dashboard</h2>
            <p style={{ margin: "6px 0 0", fontSize: 13, opacity: 0.9 }}>
              Track your inquiry submissions and their progress through the certification pipeline.
            </p>
          </div>

          {myInquiriesLoading ? (
            <div style={{ padding: 60, textAlign: "center", color: "#9ca3af" }}>
              <div style={{
                display: "inline-block", width: 32, height: 32,
                border: "3px solid #e5e7eb", borderTopColor: "#667eea",
                borderRadius: "50%", animation: "spin 0.7s linear infinite",
                marginBottom: 12,
              }} />
              <p style={{ margin: 0 }}>Loading your inquiries...</p>
            </div>
          ) : (
            <>
              <div className={styles.kpiGrid}>
                {marketingCards.map((card) => (
                  <div
                    key={card.label}
                    className={styles.kpiCard}
                    onClick={card.action}
                    style={{ cursor: "pointer", transition: "transform 0.15s, box-shadow 0.15s" }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.transform = "translateY(-2px)";
                      e.currentTarget.style.boxShadow = "0 8px 20px rgba(0,0,0,0.12)";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.transform = "translateY(0)";
                      e.currentTarget.style.boxShadow = "";
                    }}
                  >
                    <div className={styles.kpiIcon} style={{
                      color: "#fff", backgroundColor: card.color, borderRadius: 10, padding: 10,
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                    }}>
                      {card.icon}
                    </div>
                    <div className={styles.kpiBody}>
                      <div className={styles.kpiValue} style={{ color: card.color }}>{card.value}</div>
                      <div className={styles.kpiLabel}>{card.label}</div>
                    </div>
                  </div>
                ))}
              </div>

              {myInquiries.length > 0 ? (
                <div className={styles.panel} style={{ marginTop: 20 }}>
                  <div className={styles.panelHeader}>
                    <span className={styles.panelTitle}>📋 My Recent Inquiries</span>
                    <button onClick={() => router.push("/modules/inquiries")} style={{
                      background: "rgba(102,126,234,0.15)", border: "1px solid rgba(102,126,234,0.3)",
                      color: "#667eea", borderRadius: 6, padding: "4px 10px",
                      fontSize: 11, fontWeight: 600, cursor: "pointer",
                    }}>View All →</button>
                  </div>
                  <div className={styles.activityList}>
                    {myInquiries.slice(0, 5).map((inq: any) => {
                      const cfg = (INQUIRY_STATUS_CONFIG as any)[inq.status] ?? {
                        label: inq.status, color: "#6b7280", bg: "rgba(107,114,128,0.15)",
                      };
                      return (
                        <div key={inq.id} className={styles.activityItem}
                          onClick={() => router.push(`/modules/inquiries?id=${inq.id}`)}
                          style={{ cursor: "pointer" }}
                        >
                          <div className={styles.activityDot} style={{ background: cfg.color }} />
                          <div className={styles.activityContent}>
                            <div className={styles.activityText}>
                              <strong style={{ fontFamily: "monospace", marginRight: 8 }}>{inq.inquiry_ref}</strong>
                              {inq.company?.name ?? "—"}
                            </div>
                            <div className={styles.activityTime}>
                              {inq.audit_date
                                ? new Date(inq.audit_date).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })
                                : "No audit date"}
                            </div>
                          </div>
                          <div className={styles.activityStatus} style={{ background: cfg.bg, color: cfg.color }}>
                            {cfg.label}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ) : (
                <div className={styles.panel} style={{ marginTop: 20, padding: "40px 20px" }}>
                  <div style={{ textAlign: "center", color: "#9ca3af" }}>
                    <div style={{ fontSize: 36, marginBottom: 8 }}>📭</div>
                    <h3 style={{ margin: "0 0 6px", color: "#374151" }}>No inquiries yet</h3>
                    <p style={{ margin: 0, fontSize: 13 }}>Start by creating your first inquiry from the Inquiries module.</p>
                    <button onClick={() => router.push("/modules/inquiries")} style={{
                      marginTop: 14, padding: "8px 18px",
                      background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                      color: "#fff", border: "none", borderRadius: 8,
                      fontSize: 13, fontWeight: 600, cursor: "pointer",
                    }}>📋 Go to Inquiries →</button>
                  </div>
                </div>
              )}
            </>
          )}
        </>
      )}

      {/* ═══════════════════════════════════════════════════════════════ */}
      {/* 🔹 NEW — AUDITOR DASHBOARD                                       */}
      {/* ═══════════════════════════════════════════════════════════════ */}
      {showAuditorDashboard && (
        <>
          {/* Divider — visible only when stacked under another dashboard */}
          {(showFullDashboard || showMarketingDashboard) && (
            <div style={{
              height: 1,
              background: "linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.15) 50%, transparent 100%)",
              margin: "32px 0 24px",
            }} />
          )}
          <AuditorDashboard
            loading={auditorLoading}
            stats={auditorStats}
            fullName={auditorFullName || user.firstName}
            recentNcs={myNcs.slice(0, 5)}
            recentAudits={myAudits.slice(0, 5)}
            onGoToAudits={() => router.push("/modules/my-audits")}
            onGoToNcs={() => router.push("/modules/previous-nc")}
            onClickNc={(row: any) =>
              router.push(`/modules/previous-nc/view?source=${row.source}&id=${row.id}`)
            }
          />
          {/* 🔹 exact-count analytics — added BELOW the whole AuditorDashboard */}
          <DashboardAnalytics
            scope="auditor"
            auditorName={auditorFullName}
            onGoToAudits={() => router.push("/modules/my-audits")}
            onGoToNcs={() => router.push("/modules/previous-nc")}
          />
        </>
      )}

      {/* ═══ LIMITED DASHBOARD ═══ */}
      {showLimitedDashboard && (
        <div style={{
          padding: 40, textAlign: "center", color: "#6b7280",
          background: "#fff", borderRadius: 12, border: "1px solid #e5e7eb",
        }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>🔒</div>
          <h3 style={{ margin: "0 0 8px", color: "#111827" }}>Limited Dashboard Access</h3>
          <p style={{ margin: 0, fontSize: 14 }}>
            Your role does not have access to dashboard analytics. Please contact your administrator if you need access.
          </p>
        </div>
      )}

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// 🔹 NEW — Auditor dashboard component
// ═══════════════════════════════════════════════════════════════════════

const AUDITOR_TOKENS = {
  primary: "#06b6d4",
  primaryDark: "#0891b2",
  brandStart: "#0e7490",
  brandEnd: "#06b6d4",
  ink: "#0b1220",
  ink2: "#1f2937",
  ink3: "#475569",
  ink4: "#64748b",
  ink5: "#94a3b8",
  line: "#e2e8f0",
  line2: "#f1f5f9",
  surface: "#ffffff",
  success: "#16a34a",
  danger: "#dc2626",
  warning: "#f59e0b",
  major: "#dc2626",
  minor: "#f59e0b",
  observation: "#2563eb",
  qrs: "#6366f1",
  tqs: "#06b6d4",
};

function AuditorDashboard({
  loading,
  stats,
  fullName,
  recentNcs,
  recentAudits,
  onGoToAudits,
  onGoToNcs,
  onClickNc,
}: {
  loading: boolean;
  stats: any;
  fullName: string;
  recentNcs: any[];
  recentAudits: any[];
  onGoToAudits: () => void;
  onGoToNcs: () => void;
  onClickNc: (row: any) => void;
}) {
  if (loading) {
    return (
      <div style={{ padding: 60, textAlign: "center", color: "#9ca3af" }}>
        <div style={{
          display: "inline-block", width: 32, height: 32,
          border: "3px solid #e5e7eb", borderTopColor: AUDITOR_TOKENS.primary,
          borderRadius: "50%", animation: "spin 0.7s linear infinite", marginBottom: 12,
        }} />
        <p style={{ margin: 0 }}>Loading your audit data…</p>
      </div>
    );
  }

  return (
    <>
      {/* Hero banner */}
      <div style={{
        padding: "18px 22px",
        background: `linear-gradient(135deg, ${AUDITOR_TOKENS.brandStart} 0%, ${AUDITOR_TOKENS.brandEnd} 100%)`,
        color: "#fff", borderRadius: 12, marginBottom: 20,
        boxShadow: "0 4px 14px rgba(8,145,178,0.30)",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "radial-gradient(circle at 1px 1px, rgba(255,255,255,0.08) 1px, transparent 0)",
          backgroundSize: "20px 20px", opacity: 0.5, pointerEvents: "none",
        }} />
        <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 19, fontWeight: 800, letterSpacing: "-0.01em" }}>
              🛡️ Auditor Dashboard
            </h2>
            <p style={{ margin: "6px 0 0", fontSize: 13, opacity: 0.92 }}>
              Welcome <strong>{fullName}</strong> — your personal audit & non-conformity overview
            </p>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <PillButton onClick={onGoToAudits} icon={<ClipboardCheck size={13} />}>My Audits</PillButton>
            <PillButton onClick={onGoToNcs} icon={<ShieldAlert size={13} />}>My NCs</PillButton>
          </div>
        </div>
      </div>


    </>
  );
}

// ─── Auditor reusable sub-components ────────────────────────────────────

function SectionTitle({ text, icon }: { text: string; icon: React.ReactNode }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      marginBottom: 10, marginTop: 6,
    }}>
      <span style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        width: 24, height: 24, borderRadius: 6,
        background: "rgba(6,182,212,0.12)", color: AUDITOR_TOKENS.primaryDark,
      }}>{icon}</span>
      <span style={{
        fontSize: 12, fontWeight: 800, color: AUDITOR_TOKENS.ink2,
        textTransform: "uppercase", letterSpacing: "0.06em",
      }}>{text}</span>
    </div>
  );
}

function PillButton({ children, onClick, icon }: { children: React.ReactNode; onClick: () => void; icon?: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "7px 12px",
        background: "rgba(255,255,255,0.18)",
        border: "1px solid rgba(255,255,255,0.3)",
        color: "#fff", borderRadius: 8,
        fontSize: 12, fontWeight: 700, cursor: "pointer",
        transition: "background 0.15s",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.28)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.18)"; }}
    >
      {icon}
      {children}
    </button>
  );
}

function AuditorKpiCard({
  label, value, icon, accent, sub, hint, prominent,
}: {
  label: string;
  value: number;
  icon: React.ReactNode;
  accent: string;
  sub?: string;
  hint?: string;
  prominent?: boolean;
}) {
  return (
    <div style={{
      background: prominent
        ? `linear-gradient(135deg, ${AUDITOR_TOKENS.ink} 0%, ${AUDITOR_TOKENS.ink2} 100%)`
        : AUDITOR_TOKENS.surface,
      border: prominent ? "none" : `1px solid ${AUDITOR_TOKENS.line}`,
      borderRadius: 12, padding: "16px 18px",
      position: "relative", overflow: "hidden",
      color: prominent ? "#fff" : AUDITOR_TOKENS.ink,
      minHeight: 96,
      display: "flex", flexDirection: "column", justifyContent: "space-between",
      boxShadow: prominent ? "0 4px 14px rgba(15,23,42,0.20)" : "0 1px 3px rgba(15,23,42,0.04)",
    }}>
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 3, background: accent }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <span style={{
          fontSize: 11, fontWeight: 700,
          color: prominent ? "rgba(255,255,255,0.7)" : AUDITOR_TOKENS.ink4,
          textTransform: "uppercase", letterSpacing: "0.06em",
        }}>{label}</span>
        <span style={{
          color: prominent ? "#fff" : accent,
          opacity: prominent ? 0.95 : 0.85,
          display: "inline-flex", alignItems: "center",
          background: prominent ? "rgba(255,255,255,0.1)" : `${accent}12`,
          borderRadius: 8, padding: 6,
        }}>{icon}</span>
      </div>
      <div>
        <div style={{
          fontSize: prominent ? 30 : 26, fontWeight: 800,
          fontFamily: "'IBM Plex Mono', monospace",
          lineHeight: 1.05, letterSpacing: "-0.02em",
        }}>{value.toLocaleString()}</div>
        {sub && (
          <div style={{
            fontSize: 11, color: prominent ? "rgba(255,255,255,0.55)" : AUDITOR_TOKENS.ink5,
            marginTop: 4, fontWeight: 600,
          }}>{sub}</div>
        )}
        {hint && (
          <div style={{
            fontSize: 10, color: prominent ? "rgba(255,255,255,0.4)" : AUDITOR_TOKENS.ink5,
            marginTop: 2, fontWeight: 500, fontStyle: "italic",
          }}>{hint}</div>
        )}
      </div>
    </div>
  );
}

function ChartCard({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{
      background: AUDITOR_TOKENS.surface,
      border: `1px solid ${AUDITOR_TOKENS.line}`,
      borderRadius: 12, padding: 18,
      boxShadow: "0 1px 3px rgba(15,23,42,0.04)",
    }}>
      <div style={{
        fontSize: 13, fontWeight: 800, color: AUDITOR_TOKENS.ink2,
        marginBottom: 14,
      }}>{title}</div>
      {children}
    </div>
  );
}

function Donut({ segments }: { segments: { label: string; value: number; color: string }[] }) {
  const filtered = segments.filter((s) => s.value > 0);
  const sum = filtered.reduce((a, b) => a + b.value, 0);
  const size = 140;
  const stroke = 20;
  const r = (size - stroke) / 2;
  const cx = size / 2;
  const cy = size / 2;
  const C = 2 * Math.PI * r;
  let cumPct = 0;
  const arcs = filtered.map((s) => {
    const p = (s.value / sum) * 100;
    const len = (p / 100) * C;
    const off = C * (cumPct / 100);
    cumPct += p;
    return { ...s, len, off };
  });

  return (
    <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
      <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
        <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
          <circle cx={cx} cy={cy} r={r} fill="none" stroke={AUDITOR_TOKENS.line2} strokeWidth={stroke} />
          {sum > 0 && arcs.map((a, i) => (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={a.color} strokeWidth={stroke}
              strokeDasharray={`${a.len} ${C}`} strokeDashoffset={-a.off}
              strokeLinecap="butt" />
          ))}
        </svg>
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center", textAlign: "center",
        }}>
          <div style={{
            fontSize: 20, fontWeight: 800,
            fontFamily: "'IBM Plex Mono', monospace",
            color: AUDITOR_TOKENS.ink, lineHeight: 1,
          }}>{sum.toLocaleString()}</div>
          <div style={{
            fontSize: 9, color: AUDITOR_TOKENS.ink5, fontWeight: 700,
            marginTop: 2, textTransform: "uppercase", letterSpacing: 0.5,
          }}>Total</div>
        </div>
      </div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 7 }}>
        {filtered.length === 0 ? (
          <div style={{ fontSize: 12, color: AUDITOR_TOKENS.ink5 }}>No data yet</div>
        ) : filtered.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11 }}>
            <span style={{ width: 9, height: 9, borderRadius: 2, background: s.color, flexShrink: 0 }} />
            <span style={{ flex: 1, color: AUDITOR_TOKENS.ink2, fontWeight: 600 }}>{s.label}</span>
            <span style={{
              fontFamily: "'IBM Plex Mono', monospace",
              fontWeight: 700, color: AUDITOR_TOKENS.ink,
            }}>{s.value}</span>
            <span style={{
              fontFamily: "'IBM Plex Mono', monospace",
              fontSize: 10, color: AUDITOR_TOKENS.ink5, minWidth: 38, textAlign: "right",
            }}>{sum > 0 ? `${((s.value / sum) * 100).toFixed(0)}%` : "0%"}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TrendBars({ data }: { data: { label: string; count: number }[] }) {
  const max = Math.max(...data.map((d) => d.count), 1);
  return (
    <div>
      <div style={{
        display: "grid", gridTemplateColumns: `repeat(${data.length}, 1fr)`,
        gap: 10, alignItems: "end", height: 140,
      }}>
        {data.map((d, i) => {
          const h = (d.count / max) * 120;
          return (
            <div key={i} title={`${d.label}: ${d.count} NCs`}
              style={{
                display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "flex-end",
                gap: 4, height: "100%",
              }}
            >
              {d.count > 0 && (
                <span style={{
                  fontSize: 10, fontWeight: 700, color: AUDITOR_TOKENS.ink2,
                  fontFamily: "'IBM Plex Mono', monospace",
                }}>{d.count}</span>
              )}
              <div style={{
                width: "100%", maxWidth: 44,
                height: Math.max(h, d.count > 0 ? 8 : 3),
                background: d.count > 0
                  ? `linear-gradient(180deg, ${AUDITOR_TOKENS.primary} 0%, ${AUDITOR_TOKENS.primaryDark} 100%)`
                  : AUDITOR_TOKENS.line2,
                borderRadius: "5px 5px 0 0",
                transition: "height 0.4s",
              }} />
            </div>
          );
        })}
      </div>
      <div style={{
        display: "grid", gridTemplateColumns: `repeat(${data.length}, 1fr)`,
        gap: 10, marginTop: 10, paddingTop: 8,
        borderTop: `1px solid ${AUDITOR_TOKENS.line2}`,
      }}>
        {data.map((d, i) => (
          <div key={i} style={{
            fontSize: 10, fontWeight: 700, color: AUDITOR_TOKENS.ink4,
            textAlign: "center", fontFamily: "'IBM Plex Mono', monospace",
          }}>{d.label}</div>
        ))}
      </div>
    </div>
  );
}

function SrcChip({ source }: { source?: string }) {
  const upper = (source || "").toUpperCase();
  const color = upper === "TQS" ? AUDITOR_TOKENS.tqs : AUDITOR_TOKENS.qrs;
  return (
    <span style={{
      display: "inline-block", fontSize: 9, fontWeight: 800,
      color, background: `${color}15`,
      padding: "3px 7px", borderRadius: 5,
      textTransform: "uppercase", letterSpacing: 0.4,
      minWidth: 36, textAlign: "center", flexShrink: 0,
    }}>{upper || "—"}</span>
  );
}

function StatusChip({ status }: { status?: string }) {
  const s = String(status || "").toLowerCase();
  const isOpen = s === "open";
  const color = isOpen ? AUDITOR_TOKENS.danger : AUDITOR_TOKENS.success;
  const bg = isOpen ? "#fee2e2" : "#dcfce7";
  return (
    <span style={{
      display: "inline-block", fontSize: 9, fontWeight: 800,
      color, background: bg,
      padding: "3px 8px", borderRadius: 5,
      textTransform: "uppercase", letterSpacing: 0.4,
      flexShrink: 0,
    }}>{status || "—"}</span>
  );
}