import React, { useState, useEffect, useRef, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import { COUNTRY_URL, LOCATIONS_URL } from "../../../utils/config";
import {
  parseSatDataArray,
  siteRowId,
  siteRowLabel,
  departmentRowId,
  departmentRowLabel,
} from "../../../utils/masterDashboardLocationUtils";
import { getDisplayNameFromToken } from "../../../utils/authUtils";
import { clearMasterStoredAuth } from "hse-auth";
import { openProject, isLaunchableProject } from "../../../utils/appLaunch.js";
import { useTheme } from "../../../contexts/ThemeContext";
import "./styles/MasterDashboard.css";
import "./styles/MasterDashboardTheme.css";

const STORAGE_COUNTRY = "masterDashboardCountryId";
const STORAGE_SITE = "masterDashboardLocationId";
const STORAGE_WORKAREA = "masterDashboardDepartmentId";

// Logos commented off – card and sidebar use SVG icons instead
// const SAT_CARD_LOGO_IMAGE = `${"" || ""}/vsat-logo-without-text.png`;
// const SAT_SIDEBAR_ICON_IMAGE = `${"" || ""}/vsat-like.png`;

const PROJECTS = [
  {
    id: "sat",
    name: "SAT - Safety Audit Observation",
    description:
      "Site Audit & Ticketing – Manage audits, forms, tickets, and compliance in one place.",
    available: true,
    icon: "clipboard",
  },
  {
    id: "project-2",
    name: "Asset Management",
    description: "Coming soon.",
    available: false,
    icon: "box",
  },
  {
    id: "project-3",
    name: "Permit to Work (PTW)",
    description: "Permit to Work management dashboard.",
    available: true,
    icon: "box",
  },
  {
    id: "project-4",
    name: "Action Item Management (CAPA)",
    description: "Coming soon.",
    available: false,
    icon: "box",
  },
  {
    id: "swi",
    name: "SWI/SOP Management",
    description:
      "Standard Work Instructions – Create, assign, and manage SWI/SOP documents.",
    available: true,
    icon: "clipboard",
  },
  {
    id: "project-6",
    name: "HSE - Learning Management System",
    description: "Coming soon.",
    available: false,
    icon: "box",
  },
  {
    id: "risk-assessment",
    name: "Risk Assessment",
    description:
      "Comprehensive risk management – Analyze, evaluate, and mitigate potential hazards efficiently.",
    available: true,
    icon: "clipboard",
  },
];

const PROJECTS_ORDER_STORAGE_KEY = "masterDashboardProjectsOrder";
const availableCount = PROJECTS.filter((p) => p.available).length;

function ProjectIcon({ icon, iconImage }) {
  const [imageError, setImageError] = useState(false);
  const useImage = iconImage && !imageError;

  if (useImage) {
    return (
      <img
        key={iconImage}
        src={iconImage}
        alt=""
        className="master-project-icon master-project-icon--img"
        onError={() => setImageError(true)}
      />
    );
  }
  if (icon === "clipboard") {
    return (
      <svg className="master-project-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  }
  return (
    <svg className="master-project-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M3.27 6.96L12 12.01l8.73-5.05M12 22.08V12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function MasterDashboard() {
  const navigate = useNavigate();
  const displayName = getDisplayNameFromToken();
  const { theme, toggleTheme } = useTheme();
  const [loggingOut, setLoggingOut] = useState(false);
  const [launchingProjectId, setLaunchingProjectId] = useState(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [showLogoutModal, setShowLogoutModal] = useState(false);
  const [showHeroTip, setShowHeroTip] = useState(() => {
    const dismissed = localStorage.getItem("masterDashboardHeroTipDismissed");
    return dismissed !== "true";
  });

  // Country / Site / Work area dropdown state
  const [countries, setCountries] = useState([]);
  const [sites, setSites] = useState([]);
  const [workAreas, setWorkAreas] = useState([]);
  const [selectedCountryId, setSelectedCountryId] = useState(() => localStorage.getItem(STORAGE_COUNTRY) || "");
  const [selectedSiteId, setSelectedSiteId] = useState(() => localStorage.getItem(STORAGE_SITE) || "");
  const [selectedWorkAreaId, setSelectedWorkAreaId] = useState(() => localStorage.getItem(STORAGE_WORKAREA) || "");
  const [loadingSites, setLoadingSites] = useState(false);
  const [loadingWorkAreas, setLoadingWorkAreas] = useState(false);
  const [projects, setProjects] = useState(() => {
    try {
      const stored = localStorage.getItem(PROJECTS_ORDER_STORAGE_KEY);
      if (!stored) return PROJECTS;
      const order = JSON.parse(stored);
      if (!Array.isArray(order)) return PROJECTS;
      const byId = new Map(PROJECTS.map((p) => [p.id, p]));
      const ordered = [];
      order.forEach((id) => {
        const proj = byId.get(id);
        if (proj) {
          ordered.push(proj);
          byId.delete(id);
        }
      });
      if (byId.size) {
        byId.forEach((proj) => ordered.push(proj));
      }
      return ordered;
    } catch (e) {
      console.error("Error loading project order from storage:", e);
      return PROJECTS;
    }
  });
  const [draggedProjectId, setDraggedProjectId] = useState(null);
  const [dragOverProjectId, setDragOverProjectId] = useState(null);

  const selectedSiteIdRef = useRef(selectedSiteId);
  selectedSiteIdRef.current = selectedSiteId;
  const skipInitialSiteResetOnCountry = useRef(true);

  // Fetch countries on mount
  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const res = await axiosInstance.get(COUNTRY_URL);
        if (res.data?.success) setCountries(res.data.data || []);
      } catch (err) {
        console.error("Error fetching countries:", err);
      }
    };
    fetchCountries();
  }, []);

  // Fetch sites when country changes (cancel stale requests; align selection with options)
  useEffect(() => {
    if (!selectedCountryId) {
      setSites([]);
      setWorkAreas([]);
      setSelectedSiteId("");
      setSelectedWorkAreaId("");
      return;
    }
    if (!skipInitialSiteResetOnCountry.current) {
      setSelectedSiteId("");
      setSelectedWorkAreaId("");
    }
    skipInitialSiteResetOnCountry.current = false;

    let cancelled = false;
    setLoadingSites(true);
    const fetchSites = async () => {
      try {
        const res = await axiosInstance.get(`${LOCATIONS_URL}/country/${selectedCountryId}`);
        if (cancelled) return;
        const list = parseSatDataArray(res);
        setSites(list);
        const sid = selectedSiteIdRef.current;
        const validSite = list.some((s) => String(siteRowId(s)) === String(sid));
        if (!validSite && sid) {
          setSelectedSiteId("");
          setSelectedWorkAreaId("");
        }
      } catch (err) {
        if (!cancelled) {
          console.error("Error fetching sites:", err);
          setSites([]);
          setSelectedSiteId("");
          setSelectedWorkAreaId("");
        }
      } finally {
        if (!cancelled) setLoadingSites(false);
      }
    };
    fetchSites();
    return () => {
      cancelled = true;
    };
  }, [selectedCountryId]);

  // Fetch work areas for the selected site only (departments linked to that location)
  useEffect(() => {
    if (!selectedSiteId) {
      setWorkAreas([]);
      setSelectedWorkAreaId("");
      return;
    }
    let cancelled = false;
    setLoadingWorkAreas(true);
    const fetchWorkAreas = async () => {
      try {
        const res = await axiosInstance.get(`${LOCATIONS_URL}/${selectedSiteId}/departments`);
        if (cancelled) return;
        const list = parseSatDataArray(res);
        setWorkAreas(list);
        setSelectedWorkAreaId((prev) => {
          const valid = list.some((w) => String(departmentRowId(w)) === String(prev));
          return valid ? prev : "";
        });
      } catch (err) {
        if (!cancelled) {
          console.error("Error fetching work areas:", err);
          setWorkAreas([]);
          setSelectedWorkAreaId("");
        }
      } finally {
        if (!cancelled) setLoadingWorkAreas(false);
      }
    };
    fetchWorkAreas();
    return () => {
      cancelled = true;
    };
  }, [selectedSiteId]);

  /** Sites for the current country (API: GET .../locations/country/:id), sorted by name. */
  const sitesForDisplay = useMemo(
    () =>
      [...sites].sort((a, b) =>
        siteRowLabel(a).localeCompare(siteRowLabel(b), undefined, { sensitivity: "base" })
      ),
    [sites]
  );

  /** Work areas for the current site only, sorted by name. */
  const workAreasForDisplay = useMemo(
    () =>
      [...workAreas].sort((a, b) =>
        departmentRowLabel(a).localeCompare(departmentRowLabel(b), undefined, { sensitivity: "base" })
      ),
    [workAreas]
  );

  // Persist selection to localStorage
  useEffect(() => {
    if (selectedCountryId) localStorage.setItem(STORAGE_COUNTRY, selectedCountryId);
    else localStorage.removeItem(STORAGE_COUNTRY);
  }, [selectedCountryId]);
  useEffect(() => {
    if (selectedSiteId) localStorage.setItem(STORAGE_SITE, selectedSiteId);
    else localStorage.removeItem(STORAGE_SITE);
  }, [selectedSiteId]);
  useEffect(() => {
    if (selectedWorkAreaId) localStorage.setItem(STORAGE_WORKAREA, selectedWorkAreaId);
    else localStorage.removeItem(STORAGE_WORKAREA);
  }, [selectedWorkAreaId]);

  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === "Escape") setSidebarOpen(false);
    };
    if (sidebarOpen) {
      document.addEventListener("keydown", handleEscape);
      document.body.style.overflow = "hidden";
    }
    return () => {
      document.removeEventListener("keydown", handleEscape);
      document.body.style.overflow = "";
    };
  }, [sidebarOpen]);

  const handleProjectClick = async (project) => {
    if (!project.available || launchingProjectId) return;
    setLaunchingProjectId(project.id);
    try {
      await openProject(project.id, navigate);
    } catch (error) {
      console.error("Failed to launch app:", error);
    } finally {
      setLaunchingProjectId(null);
    }
  };

  const handleProjectDragStart = (e, projectId) => {
    e.dataTransfer.setData("projectId", projectId);
    e.dataTransfer.effectAllowed = "move";
    setDraggedProjectId(projectId);
  };

  const handleProjectDragEnd = () => {
    setDraggedProjectId(null);
    setDragOverProjectId(null);
  };

  const handleProjectDragOver = (e, targetProjectId) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    if (draggedProjectId && draggedProjectId !== targetProjectId) {
      setDragOverProjectId(targetProjectId);
    }
  };

  const handleProjectDragLeave = () => {
    setDragOverProjectId(null);
  };

  const handleProjectDrop = (e, targetProjectId) => {
    e.preventDefault();
    const draggedId = e.dataTransfer.getData("projectId");
    setDraggedProjectId(null);
    setDragOverProjectId(null);
    if (!draggedId || draggedId === targetProjectId) return;
    const fromIndex = projects.findIndex((p) => p.id === draggedId);
    const toIndex = projects.findIndex((p) => p.id === targetProjectId);
    if (fromIndex === -1 || toIndex === -1) return;
    const nextProjects = [...projects];
    const [moved] = nextProjects.splice(fromIndex, 1);
    nextProjects.splice(toIndex, 0, moved);
    setProjects(nextProjects);
    try {
      localStorage.setItem(
        PROJECTS_ORDER_STORAGE_KEY,
        JSON.stringify(nextProjects.map((p) => p.id))
      );
    } catch (err) {
      console.error("Error saving project order to storage:", err);
    }
  };

  const handleLogout = () => {
    setLoggingOut(true);
    localStorage.removeItem("masterDashboardHeroTipDismissed");
    clearMasterStoredAuth();
    navigate("/login");
  };

  const closeSidebar = () => setSidebarOpen(false);

  const resolvedSiteSelectValue =
    selectedCountryId &&
    !loadingSites &&
    selectedSiteId &&
    sites.some((s) => String(siteRowId(s)) === String(selectedSiteId))
      ? String(selectedSiteId)
      : "";

  const resolvedWorkAreaSelectValue =
    selectedSiteId &&
    !loadingWorkAreas &&
    selectedWorkAreaId &&
    workAreas.some((w) => String(departmentRowId(w)) === String(selectedWorkAreaId))
      ? String(selectedWorkAreaId)
      : "";

  return (
    <div className="master-dashboard">
      {showLogoutModal && (
        <div
          className="master-logout-modal-overlay"
          role="dialog"
          aria-modal="true"
          aria-labelledby="logout-modal-title"
        >
          <div className="master-logout-modal">
            <h2 id="logout-modal-title" className="master-logout-modal-title">
              Sign out
            </h2>
            <p className="master-logout-modal-text">
              Are you sure you want to sign out from the Master Dashboard?
            </p>
            <div className="master-logout-modal-actions">
              <button
                type="button"
                className="master-logout-modal-btn master-logout-modal-btn--secondary"
                onClick={() => setShowLogoutModal(false)}
                disabled={loggingOut}
              >
                Cancel
              </button>
              <button
                type="button"
                className="master-logout-modal-btn master-logout-modal-btn--primary"
                onClick={handleLogout}
                disabled={loggingOut}
              >
                {loggingOut ? "Signing out..." : "Sign out"}
              </button>
            </div>
          </div>
        </div>
      )}
      {/* Sliding sidebar overlay */}
      <div
        className={`master-dashboard-overlay ${sidebarOpen ? "master-dashboard-overlay--open" : ""}`}
        onClick={closeSidebar}
        onKeyDown={(e) => e.key === "Enter" && closeSidebar()}
        role="button"
        tabIndex={-1}
        aria-hidden={!sidebarOpen}
        aria-label="Close menu"
      />

      {/* Sliding sidebar */}
      <aside
        className={`master-dashboard-sidebar ${sidebarOpen ? "master-dashboard-sidebar--open" : ""}`}
        aria-label="Navigation"
        aria-hidden={!sidebarOpen}
      >
        <div className="master-dashboard-sidebar-header">
          <span className="master-dashboard-sidebar-title">Menu</span>
          <button
            type="button"
            className="master-dashboard-sidebar-close"
            onClick={closeSidebar}
            aria-label="Close sidebar"
          >
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </div>
        <div className="master-dashboard-sidebar-user">
          {displayName && (
            <>
              <span className="master-dashboard-sidebar-user-label">Signed in as</span>
              <span className="master-dashboard-sidebar-user-name" title={displayName}>
                {displayName}
              </span>
            </>
          )}
        </div>
        <nav className="master-dashboard-sidebar-nav">
          <ul className="master-dashboard-sidebar-list">
            <li>
              <button
                type="button"
                className="master-dashboard-sidebar-item master-dashboard-sidebar-item--active"
                onClick={() => closeSidebar()}
              >
                <svg className="master-dashboard-sidebar-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>Master Dashboard</span>
              </button>
            </li>
            <li>
              <button
                type="button"
                className="master-dashboard-sidebar-item master-dashboard-sidebar-item--available"
                onClick={() => {
                  navigate("/personalized-dashboard");
                  closeSidebar();
                }}
              >
                <svg className="master-dashboard-sidebar-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>Personalised Dashboard</span>
              </button>
            </li>
            {projects.map((project) => {
              const isAvailable = project.available && isLaunchableProject(project.id);
              return (
                <li key={project.id}>
                  <button
                    type="button"
                    className={`master-dashboard-sidebar-item ${
                      isAvailable
                        ? "master-dashboard-sidebar-item--available"
                        : "master-dashboard-sidebar-item--disabled"
                    }`}
                    onClick={() => {
                      if (!isAvailable) return;
                      handleProjectClick(project);
                      closeSidebar();
                    }}
                    disabled={!isAvailable || launchingProjectId === project.id}
                    title={project.name}
                  >
                    <ProjectIcon icon={project.icon} iconImage={project.iconImageSidebar ?? project.iconImage} />
                    <span>{project.name}</span>
                  </button>
                </li>
              );
            })}
          </ul>
        </nav>
        <div className="master-dashboard-sidebar-footer">
          <button
            type="button"
            className="master-dashboard-sidebar-logout"
            onClick={() => {
              closeSidebar();
              setShowLogoutModal(true);
            }}
            disabled={loggingOut}
          >
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            Sign out
          </button>
        </div>
      </aside>

      {/* Top bar */}
      <div className="master-dashboard-topbar">
        <div className="master-dashboard-topbar-inner">
          <div className="master-dashboard-topbar-left">
            <button
              type="button"
              className="master-dashboard-menu-btn"
              onClick={() => setSidebarOpen(true)}
              aria-label="Open menu"
              aria-expanded={sidebarOpen}
            >
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              type="button"
              className="master-dashboard-menu-btn"
              onClick={toggleTheme}
              aria-label={theme === 'light' ? 'Switch to Night Mode' : 'Switch to Light Mode'}
              title={theme === 'light' ? 'Switch to Night Mode' : 'Switch to Light Mode'}
            >
              {theme === 'light' ? (
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              ) : (
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="12" cy="12" r="5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </button>
          </div>
          <div className="master-dashboard-brand">
            <div className="master-dashboard-logo">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <span className="master-dashboard-brand-text">Master Dashboard</span>
          </div>
          <div className="master-dashboard-topbar-filters" aria-label="Filter by location">
            <label className="master-dashboard-filter-label" htmlFor="master-filter-country">
              Country
            </label>
            <select
              id="master-filter-country"
              className="master-dashboard-filter-select"
              value={selectedCountryId}
              onChange={(e) => setSelectedCountryId(e.target.value)}
              aria-label="Select country"
            >
              <option value="">All countries</option>
              {countries.map((c) => (
                <option key={c.country_id} value={c.country_id}>
                  {c.country_name}
                </option>
              ))}
            </select>
            <label className="master-dashboard-filter-label" htmlFor="master-filter-site">
              Site
            </label>
            <select
              id="master-filter-site"
              className="master-dashboard-filter-select"
              value={resolvedSiteSelectValue}
              onChange={(e) => setSelectedSiteId(e.target.value)}
              disabled={!selectedCountryId || loadingSites}
              aria-label="Select site"
            >
              <option value="">All sites</option>
              {sitesForDisplay.map((s) => {
                const sid = siteRowId(s);
                return (
                  <option key={String(sid)} value={sid}>
                    {siteRowLabel(s)}
                  </option>
                );
              })}
            </select>
            <label className="master-dashboard-filter-label" htmlFor="master-filter-workarea">
              Work area
            </label>
            <select
              id="master-filter-workarea"
              className="master-dashboard-filter-select"
              value={resolvedWorkAreaSelectValue}
              onChange={(e) => setSelectedWorkAreaId(e.target.value)}
              disabled={!selectedSiteId || loadingWorkAreas}
              aria-label="Select work area"
            >
              <option value="">All work areas</option>
              {workAreasForDisplay.map((w) => {
                const wid = departmentRowId(w);
                return (
                  <option key={String(wid)} value={wid}>
                    {departmentRowLabel(w)}
                  </option>
                );
              })}
            </select>
          </div>
          <div className="master-dashboard-topbar-actions">
            {displayName && (
              <div className="master-dashboard-user-pill" title={displayName}>
                <span className="master-dashboard-user-avatar" aria-hidden>
                  {displayName
                    .split(/\s+/)
                    .map((s) => s[0])
                    .join("")
                    .slice(0, 2)}
                </span>
                <span className="master-dashboard-user-name">{displayName}</span>
              </div>
            )}
            <button
              type="button"
              className="master-dashboard-logout-btn"
            onClick={() => setShowLogoutModal(true)}
              disabled={loggingOut}
              aria-label="Sign out"
            >
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <span>Sign out</span>
            </button>
          </div>
        </div>
      </div>

      {/* Hero / Welcome */}
      <header className="master-dashboard-hero">
        <div className="master-dashboard-hero-inner">
          <p className="master-dashboard-hero-badge" role="status" aria-label="Page context">
            Application hub
          </p>
          <h1 className="master-dashboard-title">
            {displayName ? (
              <>
                Welcome, <span className="master-dashboard-title-highlight">{displayName.split(/\s+/)[0]}!</span>
              </>
            ) : (
              "Welcome to the Master Dashboard"
            )}
          </h1>
          <p className="master-dashboard-subtitle">
            This is your central hub. Choose an application below to open its dashboard and tools. Cards marked <strong>Available</strong> can be opened; others are coming soon.
          </p>
          <div className="master-dashboard-stats" aria-label="Summary">
            <span className="master-dashboard-stat">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
                <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              {PROJECTS.length} total applications
            </span>
            <span className="master-dashboard-stat master-dashboard-stat--available">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M22 4L12 14.01l-3-3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              {availableCount} available to open
            </span>
          </div>
          <div
            className={`master-dashboard-hero-tip ${
              showHeroTip ? "master-dashboard-hero-tip--visible" : "master-dashboard-hero-tip--hidden"
            }`}
            role="complementary"
            aria-label="Quick tip"
          >
              <button
                type="button"
                className="master-dashboard-hero-tip-close"
                onClick={() => {
                  setShowHeroTip(false);
                  localStorage.setItem("masterDashboardHeroTipDismissed", "true");
                }}
                aria-label="Hide this tip"
              >
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="16" height="16">
                  <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
              <span className="master-dashboard-hero-tip-icon" aria-hidden>
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                  <path d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </span>
              <p className="master-dashboard-hero-tip-text">
                Use the <strong>menu</strong> (top left) to go to your Personalised Dashboard or to sign out.
              </p>
            </div>
        </div>
      </header>

      {/* Projects section */}
        <div className="master-dashboard-content">
        <div className="master-dashboard-section-head">
          <h2 className="master-dashboard-section-title">Your Applications</h2>
          <p className="master-dashboard-section-desc">
            Click on an application to open its dashboard.
          </p>
        </div>
        <div className="master-projects-grid">
          {projects.map((project, index) => {
            const isDragging = draggedProjectId === project.id;
            const isDragOver = dragOverProjectId === project.id;
            const isAvailable = project.available;
            const cardRole = isAvailable ? "button" : "article";
            const cardTabIndex = isAvailable ? 0 : -1;
            return (
            <div
              key={project.id}
              className={`master-project-card ${
                isAvailable ? "master-project-card--available" : "master-project-card--disabled"
              } master-project-card--animate master-project-card--draggable ${
                isDragging ? "master-project-card--dragging" : ""
              } ${isDragOver ? "master-project-card--drag-over" : ""}`}
              style={{ animationDelay: `${index * 0.06}s` }}
              onClick={() => handleProjectClick(project)}
              onKeyDown={(e) =>
                isAvailable &&
                (e.key === "Enter" || e.key === " ") &&
                (e.preventDefault(), handleProjectClick(project))
              }
              role={cardRole}
              tabIndex={cardTabIndex}
              title={
                isAvailable
                  ? `Open ${project.name} dashboard`
                  : `${project.name} — coming soon`
              }
              aria-label={
                isAvailable
                  ? `Open ${project.name} dashboard`
                  : `${project.name} (coming soon)`
              }
              draggable
              onDragStart={(e) => handleProjectDragStart(e, project.id)}
              onDragEnd={handleProjectDragEnd}
              onDragOver={(e) => handleProjectDragOver(e, project.id)}
              onDragLeave={handleProjectDragLeave}
              onDrop={(e) => handleProjectDrop(e, project.id)}
            >
              <div className="master-project-card-icon-wrap" aria-hidden>
                <ProjectIcon icon={project.icon} iconImage={project.iconImage} />
              </div>
              <h3 className="master-project-card-title">{project.name}</h3>
              <p className="master-project-card-desc">{project.description}</p>
              <div className="master-project-card-footer">
                {project.available ? (
                  <>
                    <span className="master-project-card-badge master-project-card-badge--available">Available</span>
                    <span className="master-project-card-cta">
                      Open application
                      <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
                        <path d="M5 12h14M12 5l7 7-7 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    </span>
                  </>
                ) : (
                  <span className="master-project-card-badge master-project-card-badge--progress">
                    <span className="master-project-card-badge-dot" aria-hidden />
                    Coming soon
                  </span>
                )}
              </div>
            </div>
          );
          })}
        </div>
      </div>

      {/* Footer */}
      <footer className="master-dashboard-footer">
        <div className="master-dashboard-footer-inner">
          <p className="master-dashboard-footer-text">
            Need help? Contact your administrator or platform support.
          </p>
          <p className="master-dashboard-footer-copy">&copy; {new Date().getFullYear()} Platform. All rights reserved.</p>
        </div>
      </footer>
    </div>
  );
}

export default MasterDashboard;
