/**
 * Client Portal — granular page + section configuration types.
 *
 * The agency controls exactly which pages and which sections within
 * each page are visible to clients. Stored as JSON on ClientPortal.
 */

export interface SectionConfig { [sectionId: string]: boolean }

export interface PageConfig {
  enabled: boolean;
  sections?: SectionConfig;
}

export interface PortalPagesConfig {
  [pageId: string]: PageConfig;
}

export interface PortalConfig {
  pages: PortalPagesConfig;
}

// ─── Page + section definitions (single source of truth) ─────────────────────

export interface SectionDef { id: string; label: string; defaultEnabled: boolean }
export interface PageDef { id: string; label: string; desc: string; icon: string; href: string; sections?: SectionDef[] }

export const PAGE_DEFS: PageDef[] = [
  {
    id: "dashboard", label: "Dashboard", desc: "KPI cards, traffic, health", icon: "LayoutDashboard", href: "dashboard",
    sections: [
      { id: "kpis", label: "KPI Cards", defaultEnabled: true },
      { id: "chart", label: "Traffic Chart", defaultEnabled: true },
      { id: "techIssues", label: "Technical Issues Summary", defaultEnabled: false },
      { id: "conversions", label: "Conversion Data", defaultEnabled: true },
      { id: "rankSummary", label: "Rank Tracking Summary", defaultEnabled: true },
    ],
  },
  {
    id: "report", label: "Performance Report", desc: "Full brand report", icon: "BarChart3", href: "report",
    sections: [
      { id: "wins", label: "Wins", defaultEnabled: true },
      { id: "declines", label: "Declines", defaultEnabled: true },
      { id: "opportunities", label: "Opportunities", defaultEnabled: true },
      { id: "aiInsights", label: "AI Insights", defaultEnabled: false },
    ],
  },
  { id: "rankings", label: "Rank Tracker", desc: "Keyword positions + history", icon: "Crosshair", href: "rankings" },
  { id: "conversions", label: "Conversion Intelligence", desc: "Attribution + forms/calls", icon: "TrendingUp", href: "conversions" },
  {
    id: "audit", label: "Technical Audit Summary", desc: "Health score + top issues", icon: "ShieldCheck", href: "audit",
    sections: [
      { id: "issues", label: "Issue List", defaultEnabled: true },
      { id: "recommendations", label: "Recommendations", defaultEnabled: false },
    ],
  },
  { id: "launcher", label: "Page Launch Tracker", desc: "New page launches + status", icon: "Rocket", href: "launcher" },
  { id: "search_performance", label: "Search Performance", desc: "Top pages + keywords", icon: "Search", href: "search" },
  { id: "ai_summary", label: "AI Analysis Summary", desc: "Read-only AI strategist output", icon: "Sparkles", href: "ai-summary" },
  { id: "recommendations", label: "Recommendations", desc: "Current action items", icon: "Lightbulb", href: "recommendations" },
];

// ─── Default config (used when portalConfig is null) ─────────────────────────

export function buildDefaultConfig(): PortalConfig {
  const pages: PortalPagesConfig = {};
  for (const def of PAGE_DEFS) {
    const defaultEnabled = ["dashboard", "report", "rankings", "conversions", "audit"].includes(def.id);
    const sections: SectionConfig = {};
    if (def.sections) {
      for (const s of def.sections) sections[s.id] = s.defaultEnabled;
    }
    pages[def.id] = { enabled: defaultEnabled, ...(def.sections ? { sections } : {}) };
  }
  return { pages };
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/**
 * Resolve a PortalConfig from the DB value. Falls back to deriving from
 * the legacy allowedPages[] if portalConfig is null.
 */
export function resolvePortalConfig(
  portalConfig: unknown,
  allowedPages?: string[],
): PortalConfig {
  if (portalConfig && typeof portalConfig === "object" && "pages" in (portalConfig as Record<string, unknown>)) {
    return portalConfig as PortalConfig;
  }
  // Legacy fallback: derive from allowedPages string array.
  const config = buildDefaultConfig();
  if (allowedPages) {
    const allowed = new Set(allowedPages);
    for (const key of Object.keys(config.pages)) {
      config.pages[key].enabled = allowed.has(key);
    }
  }
  return config;
}

export function isPageEnabled(config: PortalConfig, pageId: string): boolean {
  return config.pages[pageId]?.enabled ?? false;
}

export function isSectionEnabled(config: PortalConfig, pageId: string, sectionId: string): boolean {
  const page = config.pages[pageId];
  if (!page?.enabled) return false;
  if (!page.sections) return true; // no sections defined → all visible
  return page.sections[sectionId] !== false; // default true if not specified
}

/** Return the list of enabled page ids for sidebar rendering. */
export function enabledPageIds(config: PortalConfig): string[] {
  return Object.entries(config.pages).filter(([, v]) => v.enabled).map(([k]) => k);
}
