/**
 * ESGAtGlance — ESG At a Glance Dashboard
 *
 * Architecture:
 *   GlobalFilters → active modules → flat summary grid + flat charts grid
 *   ComparisonView → same grids with Group 1 vs Group 2
 *
 * graphConfigs is a flat map: chartKey → chartConfig.
 * Module is derived from chartConfig.dataConfigs[0].widgetConfig.module[0]
 * or chartConfig.widgetConfig.module[0].
 * Each dataConfig is fetched separately; results are combined before rendering.
 */

import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import { useModuleSummary, useModuleGraphs, useComparisonModuleGraphs } from "./usageData";
import { ChartFactory } from "../../../../../ChartUtility/charts";
import { getFrequency, generateTimePeriodOptions, getStartingMonth } from "../../../../../../utils/PeriodCalculationUtils";
import { useFinancialYears, useSources } from "../../../../../../hooks/useApiData";
import { useCurrentUser } from "../../../../../../hooks/useCurrentUser";

import hrsrConfig from "./config/hrsr.config";
import brsrConfig from "./config/brsr.config";
import hrsrEmploymentConfig from "./config/hrsr-employment.config";
import hrsrDiversityConfig from "./config/hrsr-diversity.config";
import { compileAsync } from "sass";

// ─────────────────────────────────────────────────────────────────────────────
// THEME
// ─────────────────────────────────────────────────────────────────────────────
const THEME = {
  primary: "#3f88a7",
  primaryDark: "#2f6e8a",
  primaryLight: "#6aaec7",
  primaryFaint: "#e8f4f8",
  accent: "#f0a500",
  success: "#2ecc8b",
  danger: "#e05c5c",
  neutral: "#64748b",
  bg: "#f0f2f5",
  surface: "#ffffff",
  border: "#e2e8f0",
  text: "#1a2535",
  textMuted: "#94a3b8",
  textSub: "#64748b",
};

const MODULE_ICONS = {
  Energy:           "⚡",
  Water:            "💧",
  Waste:            "♻️",
  Emission:         "🌫️",
  Diversity:        "👥",
  Employment:       "🏢",
  Training:         "📚",
  "Health & Safety":"🦺",
  Occupancy:        "🏨",
};

export const ESG_FRAMEWORK_CONFIGS = {
  BRSR: brsrConfig,
  HRSR: hrsrConfig,
  "HRSR-Employment": hrsrEmploymentConfig,
  "HRSR-Diversity": hrsrDiversityConfig,
};

// ─────────────────────────────────────────────────────────────────────────────
// UTILITY COMPONENTS
// ─────────────────────────────────────────────────────────────────────────────

/** Compact multi-select dropdown with search + select-all */
const MultiSelect = ({
  label,
  options = [],
  value = [],
  onChange,
  placeholder = "Select...",
  showCount = false,
  single = false,
}) => {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const ref = useRef(null);

  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const filtered = options.filter((o) =>
    (o.label || o).toLowerCase().includes(search.toLowerCase())
  );

  const toggle = (v) => {
    if (single) { onChange([v]); setOpen(false); return; }
    const next = value.includes(v) ? value.filter((x) => x !== v) : [...value, v];
    onChange(next);
  };

  const allSelected = value.length === options.length;
  const toggleAll = () => onChange(allSelected ? [] : options.map((o) => o.value || o));

  const displayText = () => {
    if (!value.length) return placeholder;
    if (single) {
      const found = options.find((o) => (o.value || o) === value[0]);
      return found ? (found.label || found) : value[0];
    }
    if (value.length === options.length) return `All ${label || ""}`;
    if (showCount && value.length > 2) return `${value.length} selected`;
    return value
      .slice(0, 2)
      .map((v) => { const o = options.find((x) => (x.value || x) === v); return o ? (o.label || o) : v; })
      .join(", ") + (value.length > 2 ? ` +${value.length - 2}` : "");
  };

  return (
    <div ref={ref} style={{ position: "relative", minWidth: 160 }}>
      <button
        onClick={() => setOpen((p) => !p)}
        style={{
          width: "100%",
          padding: "7px 10px",
          border: `1px solid ${open ? THEME.primary : THEME.border}`,
          borderRadius: 6,
          background: THEME.surface,
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 6,
          fontSize: 13,
          color: value.length ? THEME.text : THEME.textMuted,
          boxShadow: open ? `0 0 0 3px ${THEME.primaryFaint}` : "none",
          transition: "all 0.15s",
        }}
      >
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {displayText()}
        </span>
        <span style={{ fontSize: 10, color: THEME.textMuted, flexShrink: 0 }}>
          {open ? "▲" : "▼"}
        </span>
      </button>

      {open && (
        <div
          style={{
            position: "absolute",
            top: "calc(100% + 4px)",
            left: 0,
            minWidth: "100%",
            background: THEME.surface,
            border: `1px solid ${THEME.border}`,
            borderRadius: 8,
            boxShadow: "0 8px 24px rgba(0,0,0,0.12)",
            zIndex: 1000,
            overflow: "hidden",
            maxHeight: 280,
            display: "flex",
            flexDirection: "column",
          }}
        >
          <div style={{ padding: "8px 10px", borderBottom: `1px solid ${THEME.border}` }}>
            <input
              autoFocus
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search..."
              style={{
                width: "100%",
                border: `1px solid ${THEME.border}`,
                borderRadius: 5,
                padding: "5px 8px",
                fontSize: 12,
                outline: "none",
                boxSizing: "border-box",
              }}
            />
          </div>
          {!single && (
            <button
              onClick={toggleAll}
              style={{
                textAlign: "left",
                padding: "8px 12px",
                border: "none",
                background: "none",
                fontSize: 12,
                cursor: "pointer",
                color: THEME.primary,
                fontWeight: 600,
                borderBottom: `1px solid ${THEME.border}`,
              }}
            >
              {allSelected ? "Deselect All" : "Select All"}
            </button>
          )}
          <div style={{ overflowY: "auto", flexGrow: 1 }}>
            {filtered.length === 0 && (
              <div style={{ padding: "10px 12px", fontSize: 12, color: THEME.textMuted }}>
                No results
              </div>
            )}
            {filtered.map((o) => {
              const v = o.value || o;
              const l = o.label || o;
              const checked = value.includes(v);
              return (
                <button
                  key={v}
                  onClick={() => toggle(v)}
                  style={{
                    width: "100%",
                    textAlign: "left",
                    padding: "8px 12px",
                    border: "none",
                    background: checked ? THEME.primaryFaint : "none",
                    cursor: "pointer",
                    fontSize: 13,
                    color: checked ? THEME.primaryDark : THEME.text,
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    transition: "background 0.1s",
                  }}
                >
                  {!single && (
                    <span
                      style={{
                        width: 14,
                        height: 14,
                        border: `2px solid ${checked ? THEME.primary : THEME.border}`,
                        borderRadius: 3,
                        background: checked ? THEME.primary : "white",
                        display: "inline-flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: 10,
                        color: "white",
                        flexShrink: 0,
                      }}
                    >
                      {checked ? "✓" : ""}
                    </span>
                  )}
                  {l}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

/** Loading skeleton shimmer */
const Shimmer = ({ width = "100%", height = 20, radius = 6 }) => (
  <div
    style={{
      width,
      height,
      borderRadius: radius,
      background: "linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",
      backgroundSize: "200% 100%",
      animation: "shimmer 1.4s infinite",
    }}
  />
);

// ─────────────────────────────────────────────────────────────────────────────
// SECTION HEADING — labels the all-summaries and all-graphs bands
// ─────────────────────────────────────────────────────────────────────────────
const SectionHeading = ({ title }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
    <span style={{
      fontSize: 13, fontWeight: 700, color: THEME.text,
      letterSpacing: "0.01em", whiteSpace: "nowrap",
    }}>
      {title}
    </span>
    <div style={{ flex: 1, height: 1, background: THEME.border }} />
  </div>
);


// ─────────────────────────────────────────────────────────────────────────────
// SUMMARY CARD — with YoY comparison + hover details
// ─────────────────────────────────────────────────────────────────────────────
const SummaryCard = ({
  card,
  value,
  loading,
  moduleIcon,
  accentColor
}) => {
  const currentUser = useCurrentUser();
  const companyId = currentUser?.companyId;

  const fmt = (v) => {
    if (v === undefined || v === null) return "—";
    if (typeof v !== "number") return v;

    const rounded = Number(v.toFixed(2));
    const isInteger = Number.isInteger(rounded);

    // if (rounded >= 1_000_000) {
    //   const kValue   = rounded / 1_000;
    //   const kRounded = Number(kValue.toFixed(2));
    //   const isKInt   = Number.isInteger(kRounded);
    //   return (
    //     new Intl.NumberFormat("en-IN", {
    //       minimumFractionDigits: isKInt ? 0 : 2,
    //       maximumFractionDigits: 2,
    //     }).format(kRounded) + "K"
    //   );
    // }

    return new Intl.NumberFormat("en-IN", {
      minimumFractionDigits: isInteger ? 0 : 2,
      maximumFractionDigits: 2,
    }).format(rounded);
  };

  const current  = value?.current  ?? null;
  const previous = value?.previous ?? null;
  const unit     = value?.unit     ?? '';

  const hasComparison =
    previous !== null &&
    previous !== undefined;

  const comparisonType = card?.comparison?.comparisonType || "percentage_delta";
  const isShare        = comparisonType === "percentage_share";

  const pctRaw = hasComparison
    ? isShare
      ? (current + previous === 0
          ? null
          : (current / (current + previous)) * 100)
      : ((current - previous) / previous) * 100
    : null;

  const pct        = pctRaw !== null ? Math.abs(pctRaw).toFixed(1) : null;
  const absDiff    = hasComparison ? current - previous : null;
  const numericPct = pctRaw !== null ? parseFloat(pctRaw) : null;

  const isIncrease = numericPct !== null && numericPct > 0;
  const isDecrease = numericPct !== null && numericPct < 0;

  let improved = null;
  if (!isShare && numericPct !== null) {
    if      (card.trendDirection === "up")   improved = isIncrease;
    else if (card.trendDirection === "down") improved = isDecrease;
  }

  const accent = accentColor || THEME.primary;

  const deltaColor =
    numericPct === null       ? THEME.textMuted
    : card.trendDirection === "neutral" ? THEME.textMuted
    : improved                ? THEME.success
    : THEME.danger;

  const deltaPrefix = isIncrease ? "▲" : isDecrease ? "▼" : "";

  const iconBg = accent + "18";

  // Shared text styles
  const T = {
    // Row 1-2: title
    title: {
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      fontSize:      13,
      fontWeight:    600,
      color:         "#374151",
      letterSpacing: "-0.01em",
      lineHeight:    1.4,
      display:       "-webkit-box",
      WebkitLineClamp: 2,
      WebkitBoxOrient: "vertical",
      overflow:      "hidden",
    },
    // Primary hero value
    heroValue: {
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      fontSize:      28,
      fontWeight:    800,
      letterSpacing: "-0.035em",
      lineHeight:    1.05,
      color:         "#0f172a",
    },
    // Unit beside hero
    heroUnit: {
      fontFamily:    "'DM Mono', monospace",
      fontSize:      12,
      fontWeight:    600,
      letterSpacing: "0.04em",
      textTransform: "uppercase",
      color:         accent,
      paddingBottom: 2,
    },
    // Row label (e.g. "FY 2025-26", "Previous Year")
    rowLabel: {
      fontFamily:    "'DM Mono', monospace",
      fontSize:      10,
      fontWeight:    600,
      letterSpacing: "0.06em",
      textTransform: "uppercase",
      color:         "#94a3b8",
    },
    // Secondary value (share bars, vs value)
    secondaryValue: {
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      fontSize:      13,
      fontWeight:    700,
      letterSpacing: "-0.02em",
      color:         "#374151",
    },
    // Delta badge text
    deltaBadge: {
      fontFamily:  "'DM Mono', monospace",
      fontSize:    11,
      fontWeight:  700,
      letterSpacing: "0.02em",
    },
    // Muted supporting text
    muted: {
      fontFamily: "'DM Sans', system-ui, sans-serif",
      fontSize:   12,
      color:      "#94a3b8",
    },
  };

  return (
    <div style={{
      background:     "#ffffff",
      borderRadius:   16,
      border:         `1px solid ${THEME.border}`,
      boxShadow:      "0 1px 4px rgba(0,0,0,0.06)",
      overflow:       "hidden",
      fontFamily:     "'DM Sans', system-ui, sans-serif",
      display:        "flex",
      flexDirection:  "column",
      minHeight:      150,
      width:          "100%",
      boxSizing:      "border-box",
    }}>

      {/* ── Top accent stripe ── */}
      <div style={{ height: 3, background: accent, flexShrink: 0 }} />

      {/* ── Body ── */}
      <div style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 0, flex: 1 }}>

        {/* ── ROW 1-2 : Title (max 2 lines) ── */}
        <div style={{
          display:        "flex",
          alignItems:     "flex-start",
          justifyContent: "space-between",
          gap:            8,
          marginBottom:   14,
        }}>
          <div style={{ ...T.title, flex: 1, paddingRight: moduleIcon ? 4 : 0 }}>
            {card.title}
          </div>
          {moduleIcon && (
            <div style={{
              flexShrink:     0,
              width:          38,
              height:         38,
              borderRadius:   10,
              background:     iconBg,
              display:        "flex",
              alignItems:     "center",
              justifyContent: "center",
              fontSize:       18,
            }}>
              {moduleIcon}
            </div>
          )}
        </div>

        {/* ── Divider ── */}
        <div style={{
          height:       1,
          background:   `linear-gradient(90deg, ${accent}40, #f1f5f9 60%, transparent)`,
          marginBottom: 14,
          flexShrink:   0,
        }} />

        {/* ── DATA ROWS ── */}
        {loading ? (
          <Shimmer height={32} width="60%" />
        ) : isShare && hasComparison ? (

          /* ════════════════════════════════
             percentage_share layout
             ROW 3 : current share
             ROW 4 : other share
             ════════════════════════════════ */
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>

            {/* ROW 3 — current share */}
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <span style={T.rowLabel}>
                {value.labels?.current ?? "Current"}
              </span>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={{ ...T.heroValue, color: accent }}>
                  ◐ {pct}%
                </span>
              </div>
            </div>

            {companyId !== 351 && (
              <>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{
                    ...T.muted,
                    padding:      "3px 0px",
                  }}>
                    {fmt(current)} {unit}
                  </span>
                </div>

                {/* ROW 4 — other share */}
                <div style={{ height: 1, background: "#f1f5f9", marginTop: 2 }} />
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span style={T.rowLabel}>
                    {value.labels?.previous ?? "Previous"}
                  </span>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 5 }}>
                    <span style={T.secondaryValue}>
                      {fmt(previous)}
                    </span>
                    {unit && (
                      <span style={{ ...T.muted, fontSize: 11 }}>{unit}</span>
                    )}
                  </div>
                </div>
              </>
            )}

          </div>

        ) : hasComparison ? (

          /* ════════════════════════════════
             percentage_delta layout
             ROW 3 : current value (hero)
             ROW 4 : % change
             ROW 5 : vs previous
             ════════════════════════════════ */
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>

            {/* ROW 3 — current value */}
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <span style={T.rowLabel}>
                {value.labels?.current ?? "Current"}
              </span>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={T.heroValue}>
                  {fmt(current)}
                </span>
                {unit && <span style={T.heroUnit}>{unit}</span>}
              </div>
            </div>

            {companyId !== 351 && (
              <>
                {/* ROW 4 — % change badge + abs diff */}
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  {pct !== null && (
                    <>
                      <span style={{
                        ...T.deltaBadge,
                        color:        deltaColor,
                        background:   deltaColor + "18",
                        borderRadius: 6,
                        padding:      "3px 8px",
                        lineHeight:   1.6,
                      }}>
                        {deltaPrefix} {pct}%
                      </span>
                      <span style={{ ...T.muted, fontSize: 11 }}>
                        {absDiff >= 0 ? "+" : ""}{fmt(absDiff)} {unit}
                      </span>
                    </>
                  )}
                </div>

                {/* ROW 5 — vs previous */}
                <div style={{ height: 1, background: "#f1f5f9", marginTop: 2 }} />
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span style={T.rowLabel}>
                    {value.labels?.previous ?? "Previous"}
                  </span>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 5 }}>
                    <span style={T.secondaryValue}>
                      {fmt(previous)}
                    </span>
                    {unit && (
                      <span style={{ ...T.muted, fontSize: 11 }}>{unit}</span>
                    )}
                  </div>
                </div>
              </>
            )}

          </div>

        ) : (

          /* ════════════════════════════════
             No comparison — plain value
             ROW 3 : value + unit only
             ════════════════════════════════ */
          <>
            {value && (
              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                <span style={T.rowLabel}>
                  {value.labels?.current ?? "Current"}
                </span>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span style={T.heroValue}>
                    {fmt(current)}
                  </span>
                  {unit && <span style={T.heroUnit}>{unit}</span>}
                </div>
              </div>
            )}
          </>
        )}

      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// PER-MODULE DATA COMPONENTS
// These call hooks and emit flat JSX — no surrounding box.
// They are composed inside the flat all-modules grids below.
// ─────────────────────────────────────────────────────────────────────────────

// Accent colors per module for icon bubbles
const MODULE_ACCENT = {
  Energy:    "#f0a500",
  Water:     "#3b82f6",
  Waste:     "#ef4444",
  Emissions: "#8b5cf6",
};

/** Renders summary cards for ONE module inside the flat summary grid. */
const ModuleSummaryCards = ({ moduleName, summaryConfig, filters, displayPeriodOrderMap }) => {
  const { values, loading } = useModuleSummary(summaryConfig, filters, displayPeriodOrderMap, false, true);
  if (!summaryConfig?.cards?.length) return null;
  const icon   = MODULE_ICONS[moduleName]  || "📊";
  const accent = MODULE_ACCENT[moduleName] || THEME.primary;
  return (
    <>
      {summaryConfig.cards.filter((card) => !card.skipFinancialView).map((card) => (
        <SummaryCard
          key={card.id}
          card={card}
          value={values[card.id]}
          loading={loading}
          moduleIcon={icon}
          accentColor={accent}
        />
      ))}
    </>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// CHART WRAPPER
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// GRAPH CARD — wraps ChartFactory; handles both pre-transformed and raw data
// ─────────────────────────────────────────────────────────────────────────────
const GraphCard = ({ title, description, chartResult, loading }) => {
  return (
    <div style={{
      background: THEME.surface,
      borderRadius: 10,
      border: `1px solid ${THEME.border}`,
      padding: "14px 16px",
      boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
    }}>
      <div style={{ marginBottom: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: THEME.text }}>{title}</div>
        {description && (
          <div style={{ fontSize: 11, color: THEME.textMuted, marginTop: 2 }}>{description}</div>
        )}
      </div>

      {loading ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <Shimmer height={10} width="30%" />
          <Shimmer height={140} />
        </div>
      ) : !chartResult ? (
        <div style={{ height: 140, display: "flex", alignItems: "center", justifyContent: "center", color: THEME.textMuted, fontSize: 13 }}>
          No data available
        </div>
      ) : (
          <ChartFactory
            chartData={chartResult.chartData}
            group_by={chartResult.group_by}
            chartOptions={{
              height: 420,
              transform: true
            }}
          />
      )}
    </div>
  );
};

/** Renders all graph cards for ONE module in the flat FY-view grid. */
const ModuleGraphCards = ({ moduleName, flatGraphConfigs, filters, displayPeriodOrderMap }) => {
  const { chartDataMap, loading } = useModuleGraphs(flatGraphConfigs, moduleName, filters, displayPeriodOrderMap);

  const myCharts = useMemo(
    () => Object.entries(flatGraphConfigs || {}).filter(
      ([, cfg]) => {
        const mod = cfg.dataConfigs?.length
          ? cfg.dataConfigs[0].widgetConfig.module[0]
          : cfg.widgetConfig?.module?.[0];
        return mod === moduleName;
      }
    ),
    [flatGraphConfigs, moduleName]
  );

  if (!myCharts.length) return null;

  return (
    <>
      {myCharts.map(([key, cfg]) => (
        <GraphCard
          key={key}
          title={cfg.title}
          description={cfg.description}
          chartResult={chartDataMap[key]}
          loading={loading}
        />
      ))}
    </>
  );
};

/** Renders all comparison graph cards for ONE module. */
const ComparisonModuleGraphCards = ({ moduleName, flatGraphConfigs, comparisonType, group1Filters, group2Filters, displayPeriodOrderMap }) => {
  const { chartDataMap, loading } = useComparisonModuleGraphs(
    flatGraphConfigs, moduleName, comparisonType, group1Filters, group2Filters, displayPeriodOrderMap
  );

  const myCharts = useMemo(
    () => Object.entries(flatGraphConfigs || {}).filter(
      ([, cfg]) => {
        const mod = cfg.dataConfigs?.length
          ? cfg.dataConfigs[0].widgetConfig.module[0]
          : cfg.widgetConfig?.module?.[0];
        return mod === moduleName;
      }
    ),
    [flatGraphConfigs, moduleName]
  );

  if (!myCharts.length) return null;

  return (
    <>
      {myCharts.map(([key, cfg]) => (
        <GraphCard
          key={key}
          title={cfg.title}
          description={cfg.description}
          chartResult={chartDataMap[key]}
          loading={loading}
        />
      ))}
    </>
  );
};


// ─────────────────────────────────────────────────────────────────────────────
// COMPARISON SUMMARY CARD
// Same shell as SummaryCard — large number shows % change + absolute diff.
// Hover overlay reveals Group 1 and Group 2 raw values.
// ─────────────────────────────────────────────────────────────────────────────
const ComparisonSummaryCard = ({
  card,
  group1,
  group2,
  loading,
  moduleIcon,
  accentColor,
  group1Label = "Group 1",
  group2Label = "Group 2",
}) => {
  const fmt = (v) => {
    if (v === undefined || v === null) return "—";
    if (typeof v !== "number") return v;

    const rounded = Number(v.toFixed(2));
    const isInteger = Number.isInteger(rounded);

    // if (rounded >= 1_000_000) {
    //   const kValue   = rounded / 1_000;
    //   const kRounded = Number(kValue.toFixed(2));
    //   const isKInt   = Number.isInteger(kRounded);
    //   return (
    //     new Intl.NumberFormat("en-IN", {
    //       minimumFractionDigits: isKInt ? 0 : 2,
    //       maximumFractionDigits: 2,
    //     }).format(kRounded) + "K"
    //   );
    // }

    return new Intl.NumberFormat("en-IN", {
      minimumFractionDigits: isInteger ? 0 : 2,
      maximumFractionDigits: 2,
    }).format(rounded);
  };

  const group1Value = group1?.value ?? null;
  const group1Unit  = group1?.unit  ?? '';
  const group2Value = group2?.value ?? null;
  const group2Unit  = group2?.unit  ?? '';
  const hasData = group1Value != null && group2Value != null && group1Value !== 0;

  const pctRaw     = hasData ? ((group2Value - group1Value) / group1Value) * 100 : null;
  const pct        = pctRaw !== null ? Math.abs(pctRaw).toFixed(1) : null;
  const absDiff    = hasData ? group2Value - group1Value : null;
  const numericPct = pctRaw !== null ? parseFloat(pctRaw) : null;

  const isIncrease = numericPct !== null && numericPct > 0;
  const isDecrease = numericPct !== null && numericPct < 0;

  const improved     = numericPct !== null && numericPct < 0; // lower = better (default)
  const deltaColor   =
    numericPct === null ? "#94a3b8"
    : improved          ? THEME.success
    : THEME.danger;
  const deltaPrefix  = isIncrease ? "▲" : isDecrease ? "▼" : "";

  const accent = accentColor || THEME.primary;
  const iconBg = accent + "18";

  const T = {
    title: {
      fontFamily:      "'DM Sans', system-ui, sans-serif",
      fontSize:        13,
      fontWeight:      600,
      color:           "#374151",
      letterSpacing:   "-0.01em",
      lineHeight:      1.4,
      display:         "-webkit-box",
      WebkitLineClamp: 2,
      WebkitBoxOrient: "vertical",
      overflow:        "hidden",
    },
    heroValue: {
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      fontSize:      28,
      fontWeight:    800,
      letterSpacing: "-0.035em",
      lineHeight:    1.05,
      color:         "#0f172a",
    },
    heroUnit: {
      fontFamily:    "'DM Mono', monospace",
      fontSize:      12,
      fontWeight:    600,
      letterSpacing: "0.04em",
      textTransform: "uppercase",
      color:         accent,
      paddingBottom: 2,
    },
    rowLabel: {
      fontFamily:    "'DM Mono', monospace",
      fontSize:      10,
      fontWeight:    600,
      letterSpacing: "0.06em",
      textTransform: "uppercase",
      color:         "#94a3b8",
    },
    secondaryValue: {
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      fontSize:      13,
      fontWeight:    700,
      letterSpacing: "-0.02em",
      color:         "#374151",
    },
    deltaBadge: {
      fontFamily:    "'DM Mono', monospace",
      fontSize:      11,
      fontWeight:    700,
      letterSpacing: "0.02em",
    },
    muted: {
      fontFamily: "'DM Sans', system-ui, sans-serif",
      fontSize:   12,
      color:      "#94a3b8",
    },
  };

  return (
    <div style={{
      background:    "#ffffff",
      borderRadius:  16,
      border:        `1px solid ${THEME.border}`,
      boxShadow:     "0 1px 4px rgba(0,0,0,0.06)",
      overflow:      "hidden",
      fontFamily:    "'DM Sans', system-ui, sans-serif",
      display:       "flex",
      flexDirection: "column",
      minHeight:     150,
      width:         "100%",
      boxSizing:     "border-box",
    }}>

      {/* ── Top accent stripe ── */}
      <div style={{ height: 3, background: accent, flexShrink: 0 }} />

      {/* ── Body ── */}
      <div style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 0, flex: 1 }}>

        {/* ── ROW 1-2 : Title ── */}
        <div style={{
          display:        "flex",
          alignItems:     "flex-start",
          justifyContent: "space-between",
          gap:            8,
          marginBottom:   14,
        }}>
          <div style={{ ...T.title, flex: 1, paddingRight: moduleIcon ? 4 : 0 }}>
            {card.title}
          </div>
          {moduleIcon && (
            <div style={{
              flexShrink:     0,
              width:          38,
              height:         38,
              borderRadius:   10,
              background:     iconBg,
              display:        "flex",
              alignItems:     "center",
              justifyContent: "center",
              fontSize:       18,
            }}>
              {moduleIcon}
            </div>
          )}
        </div>

        {/* ── Divider ── */}
        <div style={{
          height:       1,
          background:   `linear-gradient(90deg, ${accent}40, #f1f5f9 60%, transparent)`,
          marginBottom: 14,
          flexShrink:   0,
        }} />

        {/* ── DATA ROWS ── */}
        {loading ? (
          <Shimmer height={32} width="60%" />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>

            {/* ROW 3 — group2 value (hero, "current" equivalent) */}
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <span style={T.rowLabel}>{group2Label}</span>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={T.heroValue}>
                  {fmt(group2Value ?? null)}
                </span>
                {group2Unit && <span style={T.heroUnit}>{group2Unit}</span>}
              </div>
            </div>

            {/* ROW 4 — % change badge + abs diff */}
            <div style={{ display: "flex", alignItems: "center", gap: 6, minHeight: 26 }}>
              {pct !== null && (
                <>
                  <span style={{
                    ...T.deltaBadge,
                    color:        deltaColor,
                    background:   deltaColor + "18",
                    borderRadius: 6,
                    padding:      "3px 8px",
                    lineHeight:   1.6,
                  }}>
                    {deltaPrefix} {pct}%
                  </span>
                  <span style={{ ...T.muted, fontSize: 11 }}>
                    {absDiff >= 0 ? "+" : ""}{fmt(absDiff)} {group2Unit}
                  </span>
                </>
              )}
            </div>

            {/* ── Divider before group1 ── */}
            <div style={{ height: 1, background: "#f1f5f9", marginTop: 2 }} />

            {/* ROW 5 — group1 value ("previous" equivalent) */}
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <span style={T.rowLabel}>{group1Label}</span>
              <div style={{ display: "flex", alignItems: "baseline", gap: 5 }}>
                <span style={T.secondaryValue}>
                  {fmt(group1Value ?? null)}
                </span>
                {group2Unit && (
                  <span style={{ ...T.muted, fontSize: 11 }}>{group2Unit}</span>
                )}
              </div>
            </div>

          </div>
        )}

      </div>
    </div>
  );
};


/** Renders comparison summary cards for ONE module inside the flat grid. */
const ComparisonModuleSummaryCards = ({ moduleName, summaryConfig, group1Filters, group2Filters, displayPeriodOrderMap }) => {
  const { values: g1, loading: l1 } = useModuleSummary(summaryConfig, group1Filters, displayPeriodOrderMap, true);
  const { values: g2, loading: l2 } = useModuleSummary(summaryConfig, group2Filters, displayPeriodOrderMap, true);
  if (!summaryConfig?.cards?.length) return null;
  const icon   = MODULE_ICONS[moduleName]  || "📊";
  const accent = MODULE_ACCENT[moduleName] || THEME.primary;
  return (
    <>
      {summaryConfig.cards.filter((card) => !card.skipComparisonView).map((card) => (
        <ComparisonSummaryCard
          key={card.id}
          card={card}
          group1={g1[card.id]}
          group2={g2[card.id]}
          loading={l1 || l2}
          moduleIcon={icon}
          accentColor={accent}
        />
      ))}
    </>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// FINANCIAL YEAR VIEW
// All summary cards (2-col grid) → then all graphs below
// ─────────────────────────────────────────────────────────────────────────────
const FinancialYearView = ({ activeModules, frameworkConfig, filters, displayPeriodOrderMap }) => {
  if (!activeModules.length) {
    return (
      <div style={{ textAlign: "center", padding: "60px 0", color: THEME.textMuted, fontSize: 14 }}>
        Select at least one module to view data.
      </div>
    );
  }
  return (
    <div>
      {/* ── All summary cards — 2-col grid ───────────────────────────────── */}
      <div style={{ marginBottom: 24 }}>
        <SectionHeading title="Summary" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
          {activeModules.map((mod) => (
            <ModuleSummaryCards
              key={mod}
              moduleName={mod}
              summaryConfig={frameworkConfig?.summaryConfigs?.[mod]}
              filters={filters}
              displayPeriodOrderMap={displayPeriodOrderMap}
            />
          ))}
        </div>
      </div>

      {/* ── All graphs — flat graphConfigs filtered per module ─────────── */}
      <div>
        <SectionHeading title="Charts" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: 16 }}>
          {activeModules.map((mod) => (
            <ModuleGraphCards
              key={mod}
              moduleName={mod}
              flatGraphConfigs={frameworkConfig?.graphConfigs}
              filters={filters}
              displayPeriodOrderMap={displayPeriodOrderMap}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// COMPARISON VIEW
// All comparison summary cards → then all comparison graphs
// ─────────────────────────────────────────────────────────────────────────────
const ComparisonView = ({ activeModules, frameworkConfig, comparisonType, group1Values, group2Values, commonFilters, displayPeriodOrderMap }) => {
  const canCompare = group1Values.length > 0 && group2Values.length > 0;

  const buildFilters = (groupVals) => {
    const base = { ...commonFilters };
    if (comparisonType === "financial_year") return { ...base, financialYear: groupVals[0] || null };
    if (comparisonType === "displayPeriods")        return { ...base, periods: groupVals };
    if (comparisonType === "location_id")      return { ...base, locationIds: groupVals };
    return base;
  };

  if (!canCompare) {
    const dimLabel = { financial_year: "Financial Year", displayPeriods: "Period", location_id: "Location" }[comparisonType];
    return (
      <div style={{ textAlign: "center", padding: "60px 0", color: THEME.textMuted, fontSize: 14 }}>
        Select a <strong style={{ color: THEME.primary }}>{dimLabel}</strong> for both
        Group 1 and Group 2 in the filter bar above to start comparing.
      </div>
    );
  }

  const group1Filters = buildFilters(group1Values);
  const group2Filters = buildFilters(group2Values);

  if (!activeModules.length) {
    return (
      <div style={{ textAlign: "center", padding: "40px 0", color: THEME.textMuted, fontSize: 14 }}>
        Select at least one module to view comparisons.
      </div>
    );
  }

  return (
    <div>
      {/* ── All comparison summary cards — same 2-col grid as FY view ──────── */}
      <div style={{ marginBottom: 24 }}>
        <SectionHeading title="Summary Comparison" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
          {activeModules.map((mod) => (
            <ComparisonModuleSummaryCards
              key={mod}
              moduleName={mod}
              summaryConfig={frameworkConfig?.summaryConfigs?.[mod]}
              group1Filters={group1Filters}
              group2Filters={group2Filters}
              displayPeriodOrderMap={displayPeriodOrderMap}
            />
          ))}
        </div>
      </div>

      {/* ── All comparison graphs — flat graphConfigs filtered per module ─ */}
      <div>
        <SectionHeading title="Charts Comparison" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: 16 }}>
          {activeModules.map((mod) => (
            <ComparisonModuleGraphCards
              key={mod}
              moduleName={mod}
              flatGraphConfigs={frameworkConfig?.graphConfigs}
              comparisonType={comparisonType}
              group1Filters={group1Filters}
              group2Filters={group2Filters}
              displayPeriodOrderMap={displayPeriodOrderMap}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// HEADER — white bar with logo + title left, Modules dropdown + view tabs right
// ─────────────────────────────────────────────────────────────────────────────
const AppHeader = ({
  activeModules, setActiveModules, availableModules,
  activeView, setActiveView,
}) => (
  <div style={{
    background: THEME.surface,
    borderBottom: `1px solid ${THEME.border}`,
    padding: "0 32px",
    display: "flex",
    alignItems: "center",
    gap: 20,
    position: "sticky",
    top: 0,
    zIndex: 110,
    boxShadow: "0 1px 6px rgba(0,0,0,0.07)",
    minHeight: 64,
  }}>
    {/* Logo icon */}
    <div style={{
      width: 40, height: 40, borderRadius: 10,
      background: THEME.primary, flexShrink: 0,
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <span style={{ fontSize: 20 }}>📊</span>
    </div>

    <div style={{ width: 1, height: 28, background: THEME.border, flexShrink: 0 }} />

    {/* Modules dropdown — left side */}
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <span style={{
        fontSize: 11, fontWeight: 700, color: THEME.textMuted,
        textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap",
      }}>
        Modules
      </span>
      <MultiSelect
        label="Modules"
        options={availableModules}
        value={activeModules}
        onChange={setActiveModules}
        placeholder="All Modules"
        showCount
      />
    </div>

    {/* Spacer pushes view toggle to the right */}
    <div style={{ flex: 1 }} />

    {/* View toggle */}
    <div style={{ display: "flex", gap: 4, background: THEME.bg, borderRadius: 10, padding: 4 }}>
      {[
        { key: "financial",  label: "Financial Year View" },
        { key: "comparison", label: "Comparison View" },
      ].map(({ key, label }) => (
        <button
          key={key}
          onClick={() => setActiveView(key)}
          style={{
            padding: "8px 18px",
            borderRadius: 7,
            border: "none",
            background: activeView === key ? THEME.primary : "transparent",
            color: activeView === key ? "#fff" : THEME.textSub,
            fontSize: 13,
            fontWeight: activeView === key ? 600 : 400,
            cursor: "pointer",
            transition: "all 0.18s",
            whiteSpace: "nowrap",
          }}
        >
          {label}
        </button>
      ))}
    </div>
  </div>
);


// ─────────────────────────────────────────────────────────────────────────────
// CHIP
// ─────────────────────────────────────────────────────────────────────────────
const Chip = ({ label, onRemove }) => (
  <span style={{
    display: "inline-flex", alignItems: "center", gap: 5,
    padding: "3px 10px 3px 12px",
    background: THEME.primaryFaint,
    border: `1px solid ${THEME.primaryLight}60`,
    borderRadius: 20,
    fontSize: 12, fontWeight: 500, color: THEME.primaryDark,
    whiteSpace: "nowrap",
  }}>
    {label}
    <button
      onClick={onRemove}
      style={{
        width: 14, height: 14, borderRadius: "50%", border: "none",
        background: THEME.primaryLight + "60", color: THEME.primaryDark,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        cursor: "pointer", fontSize: 9, fontWeight: 700, padding: 0, flexShrink: 0,
      }}
    >✕</button>
  </span>
);

// ─────────────────────────────────────────────────────────────────────────────
// SELECTED TAGS MODAL — lists all selected values when overflow > 2
// ─────────────────────────────────────────────────────────────────────────────
const SelectedTagsModal = ({ title, items, onClose }) => (
  <div
    onClick={onClose}
    style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.35)",
      zIndex: 9000, display: "flex", alignItems: "center", justifyContent: "center",
    }}
  >
    <div
      onClick={(e) => e.stopPropagation()}
      style={{
        background: THEME.surface, borderRadius: 14, padding: "24px 28px",
        minWidth: 320, maxWidth: 480, boxShadow: "0 16px 48px rgba(0,0,0,0.18)",
        display: "flex", flexDirection: "column", gap: 16,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontSize: 15, fontWeight: 700, color: THEME.text }}>{title}</span>
        <button
          onClick={onClose}
          style={{
            border: "none", background: THEME.bg, borderRadius: 8,
            width: 28, height: 28, cursor: "pointer", fontSize: 14, color: THEME.textSub,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}
        >✕</button>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
        {items.map((item, i) => (
          <span key={i} style={{
            padding: "4px 12px", background: THEME.primaryFaint,
            border: `1px solid ${THEME.primaryLight}60`, borderRadius: 20,
            fontSize: 13, color: THEME.primaryDark, fontWeight: 500,
          }}>
            {item}
          </span>
        ))}
      </div>
    </div>
  </div>
);

// ─────────────────────────────────────────────────────────────────────────────
// SELECTED TAGS DISPLAY — 0-2 chips visible; +N link opens modal
// ─────────────────────────────────────────────────────────────────────────────
const SelectedTagsDisplay = ({ values, options, onRemove, modalTitle, labelPrefix = "" }) => {
  const [modalOpen, setModalOpen] = useState(false);
  if (!values.length) return null;

  const getLabel = (v) => {
    const opt = options.find((o) => (o.value || o) === v);
    return labelPrefix + (opt ? (opt.label || opt) : v);
  };

  const visible  = values.slice(0, 2);
  const overflow = values.length - 2;

  return (
    <>
      <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 6, marginTop: 6 }}>
        {visible.map((v) => (
          <Chip key={v} label={getLabel(v)} onRemove={() => onRemove(v)} />
        ))}
        {overflow > 0 && (
          <button
            onClick={() => setModalOpen(true)}
            style={{
              border: "none", background: "none", padding: 0, cursor: "pointer",
              fontSize: 12, fontWeight: 600, color: THEME.primary,
              textDecoration: "underline", textUnderlineOffset: 2,
            }}
          >
            +{overflow} more
          </button>
        )}
      </div>
      {modalOpen && (
        <SelectedTagsModal
          title={modalTitle || "Selected"}
          items={values.map(getLabel)}
          onClose={() => setModalOpen(false)}
        />
      )}
    </>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// FILTER SLOT
// Row structure:  [label (+ COMMON badge)]   ← same height as GroupDimensionPicker label row
//                 [dropdown]
//                 [chips]
// ─────────────────────────────────────────────────────────────────────────────
const FilterSlot = ({ label, note, options, value, onChange, single }) => {
  const removeChip = (v) => onChange(value.filter((x) => x !== v));

  return (
    <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 180 }}>
      {/* Label row — always 22px tall */}
      <div style={{ display: "flex", alignItems: "center", gap: 6, height: 22, marginBottom: 6 }}>
        <span style={{ fontSize: 13, fontWeight: 500, color: THEME.textSub }}>{label}</span>
        {note && (
          <span style={{
            fontSize: 9, fontWeight: 700, color: THEME.primaryLight,
            background: THEME.primaryFaint, borderRadius: 4,
            padding: "1px 6px", textTransform: "uppercase", letterSpacing: "0.04em",
          }}>
            {note}
          </span>
        )}
      </div>

      {/* Dropdown */}
      <MultiSelect
        label={label} options={options} value={value} onChange={onChange}
        placeholder={single ? "Select…" : `All ${label}s`}
        single={single} showCount={!single}
      />

      {/* Chips */}
      {!single && (
        <SelectedTagsDisplay
          values={value} options={options}
          onRemove={removeChip} modalTitle={label}
        />
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// GROUP DIMENSION PICKER
// Row structure:  [{label}  Group 1 ············ Group 2]  ← same label-row height
//                 [G1 dropdown]  vs  [G2 dropdown]
//                 [chips]
// G1/G2 labels sit INLINE in the label row (right side), so the dropdown row
// is always row-2, exactly matching FilterSlot.
// ─────────────────────────────────────────────────────────────────────────────
const GroupDimensionPicker = ({ label, options, group1, setGroup1, group2, setGroup2, singleSelect }) => {
  const removeG1 = (v) => setGroup1(group1.filter((x) => x !== v));
  const removeG2 = (v) => setGroup2(group2.filter((x) => x !== v));

  return (
    <div style={{ display: "flex", flexDirection: "column", flex: 2 }}>
      {/* Label row — same 22px height as FilterSlot label row */}
      <div style={{ display: "flex", alignItems: "center", height: 22, marginBottom: 6, gap: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 500, color: THEME.textSub }}>{label}</span>
        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 0 }}>
          {/* G1 label aligned over first dropdown */}
          <span style={{ flex: 1, fontSize: 11, fontWeight: 700, color: THEME.primary, textAlign: "center" }}>
            Group 1
          </span>
          {/* spacer for the "vs" */}
          <span style={{ width: 30 }} />
          {/* G2 label aligned over second dropdown */}
          <span style={{ flex: 1, fontSize: 11, fontWeight: 700, color: THEME.accent, textAlign: "center" }}>
            Group 2
          </span>
        </div>
      </div>

      {/* Dropdown row — row 2, same as FilterSlot */}
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ flex: 1 }}>
          <MultiSelect label={`G1 ${label}`} options={options} value={group1} onChange={setGroup1}
            placeholder="Select…" single={singleSelect} showCount={!singleSelect} />
        </div>
        <span style={{ fontSize: 12, fontWeight: 700, color: THEME.textMuted, flexShrink: 0, whiteSpace: "nowrap" }}>
          vs
        </span>
        <div style={{ flex: 1 }}>
          <MultiSelect label={`G2 ${label}`} options={options} value={group2} onChange={setGroup2}
            placeholder="Select…" single={singleSelect} showCount={!singleSelect} />
        </div>
      </div>

      {/* Chips with modal links — G1 and G2 use SelectedTagsDisplay */}
      <div style={{ display: "flex", gap: 24 }}>
        <div style={{ flex: 1 }}>
          <SelectedTagsDisplay
            values={group1}
            options={options}
            onRemove={removeG1}
            modalTitle={`Group 1 — ${label}`}
            labelPrefix="G1: "
          />
        </div>
        <div style={{ width: 30, flexShrink: 0 }} />
        <div style={{ flex: 1 }}>
          <SelectedTagsDisplay
            values={group2}
            options={options}
            onRemove={removeG2}
            modalTitle={`Group 2 — ${label}`}
            labelPrefix="G2: "
          />
        </div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// FILTERS BAR — white card with "Filters" heading, spacious dropdowns + chips
// ─────────────────────────────────────────────────────────────────────────────
const FiltersBar = ({
  activeView,
  financialYear, setFinancialYear,
  locationIds,     setLocationIds,
  periodValues,    setPeriodValues,
  comparisonType,  setComparisonType,
  group1Values,    setGroup1Values,
  group2Values,    setGroup2Values,
  financialYears, sources, periodOptions,
}) => {
  const fyOptions = financialYears.map((fy) => ({
    label: fy.financial_year_value,
    value: fy.financial_year_value,
  }));
  const sourceOptions = sources.map((src) => ({
    label: src.unitCode || src.location.area + ", " + src.location.city,
    value: String(src.id),
  }));

  const isComparison = activeView === "comparison";
  const COMP_TYPES = [
    { value: "financial_year", label: "Financial Year" },
    { value: "displayPeriods", label: "Period" },
    { value: "location_id", label: "Location" },
  ];

  return (
    <div style={{ padding: "16px 32px 0" }}>
      <div style={{
        background: THEME.surface,
        borderRadius: 16,
        border: `1px solid ${THEME.border}`,
        padding: "24px 28px 20px",
        boxShadow: "0 1px 4px rgba(0,0,0,0.05)",
      }}>
        {/* Heading row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
          <span style={{ fontSize: 16, fontWeight: 700, color: THEME.text }}>Filters</span>

          {/* Comparison type pills — only in comparison view */}
          {isComparison && (
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 12, color: THEME.textMuted, fontWeight: 500 }}>Compare by:</span>
              <div style={{ display: "flex", gap: 4, background: THEME.bg, borderRadius: 8, padding: 3 }}>
                {COMP_TYPES.map(({ value, label }) => (
                  <button
                    key={value}
                    onClick={() => { setComparisonType(value); setGroup1Values([]); setGroup2Values([]); }}
                    style={{
                      padding: "5px 13px", borderRadius: 6, border: "none",
                      background: comparisonType === value ? THEME.primary : "transparent",
                      color: comparisonType === value ? "#fff" : THEME.textSub,
                      fontSize: 12, fontWeight: comparisonType === value ? 600 : 400,
                      cursor: "pointer", transition: "all 0.15s", whiteSpace: "nowrap",
                    }}
                  >
                    {label}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Filter slots row — all columns share the same 2-row structure so dropdowns always align */}
        <div style={{ display: "flex", gap: 24, flexWrap: "wrap", alignItems: "flex-start" }}>

          {/* Financial Year */}
          {isComparison && comparisonType === "financial_year" ? (
            <GroupDimensionPicker
              label="Financial Year" options={fyOptions}
              group1={group1Values} setGroup1={setGroup1Values}
              group2={group2Values} setGroup2={setGroup2Values}
              singleSelect={true}
            />
          ) : (
            <FilterSlot
              label="Financial Year"
              options={fyOptions}
              value={financialYear ? [financialYear] : []}
              onChange={(v) => setFinancialYear(v[0] || null)}
              single={true}
              note={isComparison ? "common" : null}
            />
          )}

          {/* Location */}
          {isComparison && comparisonType === "location_id" ? (
            <GroupDimensionPicker
              label="Location" options={sourceOptions}
              group1={group1Values} setGroup1={setGroup1Values}
              group2={group2Values} setGroup2={setGroup2Values}
              singleSelect={false}
            />
          ) : (
            <FilterSlot
              label="Location"
              options={sourceOptions}
              value={locationIds}
              onChange={setLocationIds}
              single={false}
              note={isComparison ? "common" : null}
            />
          )}

          {/* Period */}
          {isComparison && comparisonType === "displayPeriods" ? (
            <GroupDimensionPicker
              label="Period" options={periodOptions}
              group1={group1Values} setGroup1={setGroup1Values}
              group2={group2Values} setGroup2={setGroup2Values}
              singleSelect={false}
            />
          ) : (
            <FilterSlot
              label="Period"
              options={periodOptions}
              value={periodValues}
              onChange={setPeriodValues}
              single={false}
              note={isComparison ? "common" : null}
            />
          )}

        </div>
      </div>
    </div>
  );
};


// ─────────────────────────────────────────────────────────────────────────────
// ROOT
// ─────────────────────────────────────────────────────────────────────────────
const ESGDashboard = ({
  frameworkName
}) => {
  // Framework — resolved from first API record, never user-selectable
  const [frameworkConfig, setFrameworkConfig] = useState(null);
  const [activeModules, setActiveModules] = useState([]);

  useEffect(() => {
    if (!frameworkName || !ESG_FRAMEWORK_CONFIGS[frameworkName]) return;
    const resolved = ESG_FRAMEWORK_CONFIGS[frameworkName];
    setFrameworkConfig(resolved);
    setActiveModules([...resolved.modules]);
  }, [frameworkName]);

  const availableModules = frameworkConfig?.modules || [];

  // View
  const [activeView, setActiveView] = useState("financial");

  // Shared filter state
  const [financialYear, setFinancialYear] = useState(null);
  const [financialYearId, setFinancialYearId] = useState(null);
  const [locationIds,     setLocationIds]     = useState([]);
  const [periodValues,    setPeriodValues]     = useState([]);
  const [periodOptions,   setPeriodOptions]   = useState([]);
  const [displayPeriodOrderMap, setDisplayPeriodOrderMap] = useState([]);

  // Comparison state — lifted here so FiltersBar and ComparisonView share it
  const [comparisonType, setComparisonType] = useState("financial_year");
  const [group1Values,   setGroup1Values]   = useState([]);
  const [group2Values,   setGroup2Values]   = useState([]);

  const handleSetComparisonType = useCallback((type) => {
    setComparisonType(type);
    setGroup1Values([]);
    setGroup2Values([]);
  }, []);

  // Data
  const financialYears = useFinancialYears();
  const sources        = useSources();

  // Auto-select latest FY (index 0, list assumed sorted desc from API)
  useEffect(() => {
    if (financialYears.length && !financialYear) {
      setFinancialYear(financialYears[0].financial_year_value);
    }
  }, [financialYears, financialYear]);

  useEffect(() => {
    if (financialYears && financialYear) {
      const financialYearId = financialYears.find(fy => fy.financial_year_value === financialYear)?.id;
      setFinancialYearId(financialYearId);
    }
  }, [financialYear, financialYears]);

  // Regenerate period options when FY changes
  useEffect(() => {
    if (!financialYearId) return;
    getFrequency(financialYearId).then((freq) => {
      if (freq) {
        const timePeriodOptions = generateTimePeriodOptions(freq, getStartingMonth()).map(option => {
          return {
            ...option,
            label: option.label.replaceAll(' ', '')
          }
        });
        setPeriodOptions(timePeriodOptions.map(option => ({value: option.label, label: option.label})));
        setPeriodValues([]);
        setDisplayPeriodOrderMap(timePeriodOptions.reduce((acc, option) => {
          acc[option.label] = Number(option.value);
          return acc;
        }, {}));
      }
    });
  }, [financialYearId]);

  // Filters for Financial Year view
  const filters = useMemo(() => ({
    financialYear: financialYear,
    locationIds,
    periods: periodValues,
  }), [financialYear, locationIds, periodValues]);

  // Common filters for Comparison view — excludes the compared dimension
  const commonFilters = useMemo(() => {
    if (comparisonType === "financial_year") return { locationIds, periods: periodValues };
    if (comparisonType === "displayPeriods")        return { financialYear: financialYear, locationIds };
    /* location */                          return { financialYear: financialYear, periods: periodValues };
  }, [comparisonType, financialYear, locationIds, periodValues]);

  return (
    <div style={{ minHeight: "100vh", background: "#f0f2f5", fontFamily: "'DM Sans', 'Segoe UI', sans-serif" }}>

      {/* Header — logo, title, modules, view toggle */}
      <AppHeader
        activeModules={activeModules}
        setActiveModules={setActiveModules}
        availableModules={availableModules}
        activeView={activeView}
        setActiveView={setActiveView}
      />

      {/* Filters card */}
      <FiltersBar
        activeView={activeView}
        financialYear={financialYear} setFinancialYear={setFinancialYear}
        locationIds={locationIds}         setLocationIds={setLocationIds}
        periodValues={periodValues}       setPeriodValues={setPeriodValues}
        comparisonType={comparisonType}   setComparisonType={handleSetComparisonType}
        group1Values={group1Values}       setGroup1Values={setGroup1Values}
        group2Values={group2Values}       setGroup2Values={setGroup2Values}
        financialYears={financialYears}
        sources={sources}
        periodOptions={periodOptions}
      />

      {/* Content */}
      <div style={{ padding: "20px 32px 32px" }}>
        {activeView === "financial" ? (
          <FinancialYearView
            activeModules={activeModules}
            frameworkConfig={frameworkConfig}
            filters={filters}
            displayPeriodOrderMap={displayPeriodOrderMap}
          />
        ) : (
          <ComparisonView
            activeModules={activeModules}
            frameworkConfig={frameworkConfig}
            comparisonType={comparisonType}
            group1Values={group1Values}
            group2Values={group2Values}
            commonFilters={commonFilters}
            displayPeriodOrderMap={displayPeriodOrderMap}
          />
        )}
      </div>

      <style>{`
        @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
        * { box-sizing: border-box; }
        button:focus { outline: 2px solid ${THEME.primaryLight}; outline-offset: 2px; }
      `}</style>
    </div>
  );
};

export default ESGDashboard;