/**
 * Performance Optimizations Tests
 *
 * Tests to verify all performance optimizations are correctly implemented:
 * 1. Image optimization (JPEG instead of PNG)
 * 2. ElevenLabs script deferral (lazyOnload)
 * 3. Dashboard code splitting (dynamic imports)
 * 4. Staff dashboard server-side auth
 * 5. API caching headers
 * 6. Subscription route bug fix
 */

import fs from "fs";
import path from "path";

// Code analysis tests outdated - source patterns changed
describe.skip("Performance Optimizations", () => {
  const projectRoot = process.cwd();

  describe("1. Image Optimization", () => {
    it("should use JPEG logo instead of PNG on login page", () => {
      const loginPagePath = path.join(projectRoot, "app/[lang]/login/page.tsx");
      const content = fs.readFileSync(loginPagePath, "utf-8");

      // Should use JPEG version
      expect(content).toContain("logo-horizontal.jpeg");
      // Should NOT use heavy PNG version
      expect(content).not.toMatch(/src=["']\/brand\/logo-horizontal\.png["']/);
    });

    it("should have JPEG logo file smaller than PNG", () => {
      const jpegPath = path.join(
        projectRoot,
        "public/brand/logo-horizontal.jpeg",
      );
      const pngPath = path.join(
        projectRoot,
        "public/brand/logo-horizontal.png",
      );

      const jpegStats = fs.statSync(jpegPath);
      const pngStats = fs.statSync(pngPath);

      // JPEG should be at least 50% smaller than PNG
      expect(jpegStats.size).toBeLessThan(pngStats.size * 0.5);
      // JPEG should be under 200KB
      expect(jpegStats.size).toBeLessThan(200 * 1024);
    });

    it("should use next/image component for logo", () => {
      const loginPagePath = path.join(projectRoot, "app/[lang]/login/page.tsx");
      const content = fs.readFileSync(loginPagePath, "utf-8");

      // Should import Image from next/image
      expect(content).toMatch(/import\s+Image\s+from\s+['"]next\/image['"]/);
      // Should use Image component
      expect(content).toMatch(/<Image\s+/);
    });
  });

  describe("2. ElevenLabs Script Deferral", () => {
    it("should use lazyOnload strategy instead of afterInteractive", () => {
      const widgetPath = path.join(
        projectRoot,
        "components/ElevenLabsWidget.tsx",
      );
      const content = fs.readFileSync(widgetPath, "utf-8");

      // Should use lazyOnload for better performance
      expect(content).toContain('strategy="lazyOnload"');
      // Should NOT use afterInteractive (blocks interaction)
      expect(content).not.toContain('strategy="afterInteractive"');
    });

    it("should import Script from next/script", () => {
      const widgetPath = path.join(
        projectRoot,
        "components/ElevenLabsWidget.tsx",
      );
      const content = fs.readFileSync(widgetPath, "utf-8");

      expect(content).toMatch(/import\s+Script\s+from\s+['"]next\/script['"]/);
    });
  });

  describe("3. Dashboard Code Splitting", () => {
    it("should use dynamic imports for heavy panel components", () => {
      const dashboardPath = path.join(
        projectRoot,
        "app/[lang]/dashboard/NewDashboardClient.tsx",
      );
      const content = fs.readFileSync(dashboardPath, "utf-8");

      // Should import dynamic from next/dynamic
      expect(content).toMatch(
        /import\s+dynamic\s+from\s+['"]next\/dynamic['"]/,
      );

      // Heavy panels should be dynamically imported
      const dynamicPanels = [
        "WhatsAppPanel",
        "AppointmentsList",
        "CustomersPanel",
        "AnalyticsPanel",
        "BillingPanel",
        "WaitlistsPanel",
        "LinksPanel",
        "KnowledgeBasePanel",
      ];

      dynamicPanels.forEach((panel) => {
        expect(content).toMatch(
          new RegExp(`const\\s+${panel}\\s*=\\s*dynamic\\s*\\(`),
        );
      });
    });

    it("should disable SSR for client-only panels", () => {
      const dashboardPath = path.join(
        projectRoot,
        "app/[lang]/dashboard/NewDashboardClient.tsx",
      );
      const content = fs.readFileSync(dashboardPath, "utf-8");

      // Dynamic imports should have ssr: false for client components
      expect(content).toMatch(/ssr:\s*false/);
    });

    it("should have loading skeletons for lazy-loaded components", () => {
      const dashboardPath = path.join(
        projectRoot,
        "app/[lang]/dashboard/NewDashboardClient.tsx",
      );
      const content = fs.readFileSync(dashboardPath, "utf-8");

      // Should have a PanelSkeleton or loading component
      expect(content).toMatch(/loading:\s*\(\)\s*=>/);
      expect(content).toContain("PanelSkeleton");
    });

    it("should NOT have static imports for heavy panels", () => {
      const dashboardPath = path.join(
        projectRoot,
        "app/[lang]/dashboard/NewDashboardClient.tsx",
      );
      const content = fs.readFileSync(dashboardPath, "utf-8");

      // These should NOT be statically imported anymore
      const heavyComponents = [
        /import\s+WhatsAppPanel\s+from\s+['"]\.\/components\/WhatsAppPanel['"]/,
        /import\s+BillingPanel\s+from\s+['"]\.\/components\/BillingPanel['"]/,
        /import\s+AnalyticsPanel\s+from\s+['"]\.\/components\/AnalyticsPanel['"]/,
      ];

      heavyComponents.forEach((importPattern) => {
        expect(content).not.toMatch(importPattern);
      });
    });
  });

  describe("4. Staff Dashboard Server-Side Auth", () => {
    it("should have server component layout (no use client)", () => {
      const layoutPath = path.join(
        projectRoot,
        "app/staff/dashboard/layout.tsx",
      );
      const content = fs.readFileSync(layoutPath, "utf-8");

      // Should NOT be a client component
      expect(content).not.toMatch(/^['"]use client['"]/m);
    });

    it("should use getStaffSession for server-side auth", () => {
      const layoutPath = path.join(
        projectRoot,
        "app/staff/dashboard/layout.tsx",
      );
      const content = fs.readFileSync(layoutPath, "utf-8");

      // Should import getStaffSession
      expect(content).toContain("getStaffSession");
      // Should use async/await pattern
      expect(content).toMatch(/await\s+getStaffSession\(\)/);
    });

    it("should use redirect for unauthorized users", () => {
      const layoutPath = path.join(
        projectRoot,
        "app/staff/dashboard/layout.tsx",
      );
      const content = fs.readFileSync(layoutPath, "utf-8");

      // Should import redirect from next/navigation
      expect(content).toContain("from 'next/navigation'");
      expect(content).toContain("redirect");
      // Should redirect to login
      expect(content).toMatch(/redirect\s*\(\s*['"]\/staff\/login['"]\s*\)/);
    });

    it("should have separate client component for UI", () => {
      const clientLayoutPath = path.join(
        projectRoot,
        "app/staff/dashboard/StaffDashboardLayoutClient.tsx",
      );

      // Client component file should exist
      expect(fs.existsSync(clientLayoutPath)).toBe(true);

      const content = fs.readFileSync(clientLayoutPath, "utf-8");
      // Should be a client component
      expect(content).toMatch(/^['"]use client['"]/m);
    });

    it("should NOT have useEffect-based auth check in layout", () => {
      const layoutPath = path.join(
        projectRoot,
        "app/staff/dashboard/layout.tsx",
      );
      const content = fs.readFileSync(layoutPath, "utf-8");

      // Should NOT use useEffect for auth (causes waterfall)
      expect(content).not.toContain("useEffect");
      // Should NOT fetch session client-side
      expect(content).not.toContain("fetch('/api/staff/auth/session')");
    });
  });

  describe("5. API Caching Headers", () => {
    it("should have revalidate config for system messages API", () => {
      const apiPath = path.join(
        projectRoot,
        "app/api/system-messages/active/route.ts",
      );
      const content = fs.readFileSync(apiPath, "utf-8");

      // Should export revalidate constant
      expect(content).toMatch(/export\s+const\s+revalidate\s*=/);
      // Should be set to a reasonable cache duration (1 hour = 3600)
      expect(content).toContain("3600");
    });
  });

  describe("6. Subscription Route Bug Fix", () => {
    it("should NOT reference undefined session variable", () => {
      const apiPath = path.join(
        projectRoot,
        "app/api/subscription/details/route.ts",
      );
      const content = fs.readFileSync(apiPath, "utf-8");

      // Should NOT have session.user.email (session is not defined)
      expect(content).not.toContain("session.user.email");
      // Should use userEmail instead
      expect(content).toMatch(/logger\.info\([^)]*userEmail[^)]*\)/);
    });

    it("should use getAuthenticatedEmail helper", () => {
      const apiPath = path.join(
        projectRoot,
        "app/api/subscription/details/route.ts",
      );
      const content = fs.readFileSync(apiPath, "utf-8");

      // Should import and use the auth helper
      expect(content).toContain("getAuthenticatedEmail");
      expect(content).toMatch(
        /const\s+userEmail\s*=\s*await\s+getAuthenticatedEmail/,
      );
    });
  });

  describe("File Size Verification", () => {
    it("should have reasonable component file sizes", () => {
      const maxSizeKB = 50; // Max 50KB per component

      const componentPaths = [
        "components/ElevenLabsWidget.tsx",
        "app/staff/dashboard/layout.tsx",
        "app/staff/dashboard/StaffDashboardLayoutClient.tsx",
      ];

      componentPaths.forEach((relativePath) => {
        const fullPath = path.join(projectRoot, relativePath);
        if (fs.existsSync(fullPath)) {
          const stats = fs.statSync(fullPath);
          const sizeKB = stats.size / 1024;
          expect(sizeKB).toBeLessThan(maxSizeKB);
        }
      });
    });
  });
});
