import withMintelConfig from '@mintel/next-config';
import withBundleAnalyzer from '@next/bundle-analyzer';
import { withSentryConfig } from '@sentry/nextjs';

import { withPayload } from '@payloadcms/next/withPayload';

const isProd = process.env.NODE_ENV === 'production';
/** @type {import('next').NextConfig} */
const nextConfig = {
  onDemandEntries: {
    // Make sure entries are not disposed too quickly
    maxInactiveAge: 60 * 1000,
  },
  experimental: {
    staleTimes: {
      dynamic: 0,
      static: 30,
    },
    optimizePackageImports: ['lucide-react', 'framer-motion', '@/components/ui'],
    cpus: 3,
    workerThreads: false,
    serverActions: {
      allowedOrigins: ["*.klz-cables.com", "*.branch.klz-cables.com", "localhost:3000", "klz.localhost"],
    },
  },
  reactStrictMode: false,
  productionBrowserSourceMaps: false,
  logging: {
    fetches: {
      fullUrl: true,
    },
  },
  ...(isProd ? { output: 'standalone' } : {}),
  async headers() {
    const isProd = process.env.NODE_ENV === 'production';
    const umamiDomain = new URL(process.env.UMAMI_API_ENDPOINT || 'https://analytics.infra.mintel.me').origin;
    const glitchtipDomain = new URL(process.env.SENTRY_DSN ? new URL(process.env.SENTRY_DSN).origin : 'https://errors.infra.mintel.me').origin;
    const extraImgDomains = [
      'https://klz-cables.com',
      'https://staging.klz-cables.com',
      'https://testing.klz-cables.com',
      'http://klz.localhost',
      'https://www.gravatar.com',
      'https://gravatar.com',
      'https://*.tile.openstreetmap.org',
      'https://tile.openstreetmap.org',
      'https://unpkg.com',
    ].join(' ');

    const cspHeader = `
      default-src 'self';
      script-src 'self' 'unsafe-inline' 'unsafe-eval' ${umamiDomain};
      style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
      font-src 'self' https://fonts.gstatic.com;
      img-src 'self' data: blob: ${extraImgDomains};
      connect-src 'self' ${umamiDomain} ${glitchtipDomain};
      frame-src 'self';
      object-src 'none';
      base-uri 'self';
      form-action 'self';
      frame-ancestors 'none';
      ${isProd ? 'upgrade-insecure-requests;' : ''}
    `.replace(/\s{2,}/g, ' ').trim();

    const secureHeaders = [
      {
        key: 'Content-Security-Policy',
        value: cspHeader,
      },
      {
        key: 'X-Frame-Options',
        value: 'DENY',
      },
      {
        key: 'X-Content-Type-Options',
        value: 'nosniff',
      },
      {
        key: 'Referrer-Policy',
        value: 'strict-origin-when-cross-origin',
      },
      {
        key: 'Permissions-Policy',
        value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()',
      },
      {
        key: 'Strict-Transport-Security',
        value: 'max-age=63072000; includeSubDomains; preload',
      },
    ];

    return [
      {
        source: '/:path*',
        headers: secureHeaders,
      },
    ];
  },
  async redirects() {
    return [
      // Blog redirects
      {
        source: '/blog',
        destination: '/en/blog',
        permanent: true,
      },
      // Contact redirects
      {
        source: '/contact',
        destination: '/en/contact',
        permanent: true,
      },
      // Team redirects
      {
        source: '/team',
        destination: '/en/team',
        permanent: true,
      },
      // Products redirects
      {
        source: '/products',
        destination: '/en/products',
        permanent: true,
      },
      // Blog post redirects (English)
      {
        source: '/posts/100-renewable-energy-only-with-the-right-cable-infrastructure.html',
        destination: '/en/blog/100-renewable-energy-only-with-the-right-cable-infrastructure',
        permanent: true,
      },
      {
        source: '/posts/billion-euro-package-for-infrastructure-the-cable-boom-is-coming.html',
        destination: '/en/blog/billion-euro-package-for-infrastructure-the-cable-boom-is-coming',
        permanent: true,
      },
      {
        source: '/posts/cable-abbreviations-decoded-the-key-to-choosing-the-right-cable.html',
        destination: '/en/blog/cable-abbreviations-decoded-the-key-to-choosing-the-right-cable',
        permanent: true,
      },
      {
        source: '/posts/cable-drum-quality-the-foundation-of-cable-reliability.html',
        destination: '/en/blog/cable-drum-quality-the-foundation-of-cable-reliability',
        permanent: true,
      },
      {
        source: '/posts/cable-drum-safety-ensuring-smooth-operations-and-accident-free-environments.html',
        destination: '/en/blog/cable-drum-safety-ensuring-smooth-operations-and-accident-free-environments',
        permanent: true,
      },
      {
        source: '/posts/climate-neutral-by-2050-what-we-need-to-do-to-achieve-this-goal.html',
        destination: '/en/blog/climate-neutral-by-2050-what-we-need-to-do-to-achieve-this-goal',
        permanent: true,
      },
      {
        source: '/posts/cost-comparison-copper-vs-aluminum-cables-in-wind-farms-which-is-worthwhile-in-the-long-term.html',
        destination: '/en/blog/cost-comparison-copper-vs-aluminum-cables-in-wind-farms-which-is-worthwhile-in-the-long-term',
        permanent: true,
      },
      {
        source: '/posts/expanding-the-grid-by-2025-building-the-foundation-for-a-successful-energy-transition.html',
        destination: '/en/blog/expanding-the-grid-by-2025-building-the-foundation-for-a-successful-energy-transition',
        permanent: true,
      },
      {
        source: '/posts/eye-opening-realities-of-green-energy-transformation.html',
        destination: '/en/blog/eye-opening-realities-of-green-energy-transformation',
        permanent: true,
      },
      {
        source: '/posts/focus-on-wind-farm-construction-three-typical-cable-challenges.html',
        destination: '/en/blog/focus-on-wind-farm-construction-three-typical-cable-challenges',
        permanent: true,
      },
      {
        source: '/posts/from-smart-to-sustainable-this-is-what-the-energy-industry-will-look-like-in-the-near-future.html',
        destination: '/en/blog/from-smart-to-sustainable-this-is-what-the-energy-industry-will-look-like-in-the-near-future',
        permanent: true,
      },
      {
        source: '/posts/green-energy-starts-underground-and-with-a-plan.html',
        destination: '/en/blog/green-energy-starts-underground-and-with-a-plan',
        permanent: true,
      },
      {
        source: '/posts/how-the-cable-industry-is-driving-sustainability-and-renewable-energies-forward.html',
        destination: '/en/blog/how-the-cable-industry-is-driving-sustainability-and-renewable-energies-forward',
        permanent: true,
      },
      {
        source: '/posts/how-the-right-cables-quietly-power-the-green-energy-revolution.html',
        destination: '/en/blog/how-the-right-cables-quietly-power-the-green-energy-revolution',
        permanent: true,
      },
      {
        source: '/posts/how-to-choose-the-right-cable-for-your-next-project.html',
        destination: '/en/blog/how-to-choose-the-right-cable-for-your-next-project',
        permanent: true,
      },
      {
        source: '/posts/is-wind-energy-really-enough-a-deeper-dive-behind-the-headlines.html',
        destination: '/en/blog/is-wind-energy-really-enough-a-deeper-dive-behind-the-headlines',
        permanent: true,
      },
      {
        source: '/posts/klz-in-the-directory-of-wind-energy-2025.html',
        destination: '/en/blog/klz-in-the-directory-of-wind-energy-2025',
        permanent: true,
      },
      {
        source: '/posts/na2xsf2y-three-conductor-medium-voltage-cable-available.html',
        destination: '/en/blog/na2xsf2y-three-conductor-medium-voltage-cable-available',
        permanent: true,
      },
      {
        source: '/posts/recycling-of-cable-drums-sustainability-in-wind-power-projects.html',
        destination: '/en/blog/recycling-of-cable-drums-sustainability-in-wind-power-projects',
        permanent: true,
      },
      {
        source: '/posts/securing-the-future-with-h1z2z2-k-our-solar-cable-for-intersolar-2025.html',
        destination: '/en/blog/securing-the-future-with-h1z2z2-k-our-solar-cable-for-intersolar-2025',
        permanent: true,
      },
      {
        source: '/posts/the-art-of-cable-logistics-moving-the-backbone-of-modern-energy-networks.html',
        destination: '/en/blog/the-art-of-cable-logistics-moving-the-backbone-of-modern-energy-networks',
        permanent: true,
      },
      {
        source: '/posts/the-best-underground-cables-for-wind-power-and-solar-order-from-us-now.html',
        destination: '/en/blog/the-best-underground-cables-for-wind-power-and-solar-order-from-us-now',
        permanent: true,
      },
      {
        source: '/posts/the-perfect-cable-inquiry-how-to-save-yourself-unnecessary-queries.html',
        destination: '/en/blog/the-perfect-cable-inquiry-how-to-save-yourself-unnecessary-queries',
        permanent: true,
      },
      {
        source: '/posts/this-what-you-need-to-know-about-renewable-energies-in-2025.html',
        destination: '/en/blog/this-what-you-need-to-know-about-renewable-energies-in-2025',
        permanent: true,
      },
      {
        source: '/posts/welcome-to-the-future-of-klz-our-new-website-is-live.html',
        destination: '/en/blog/welcome-to-the-future-of-klz-our-new-website-is-live',
        permanent: true,
      },
      {
        source: '/posts/what-makes-a-first-class-cable-find-out-here.html',
        destination: '/en/blog/what-makes-a-first-class-cable-find-out-here',
        permanent: true,
      },
      {
        source: '/posts/which-cables-for-wind-power-differences-from-low-to-extra-high-voltage-explained-2.html',
        destination: '/en/blog/which-cables-for-wind-power-differences-from-low-to-extra-high-voltage-explained-2',
        permanent: true,
      },
      {
        source: '/posts/why-the-n2xsf2y-is-the-ideal-cable-for-your-energy-project.html',
        destination: '/de/blog/why-the-n2xsf2y-is-the-ideal-cable-for-your-energy-project',
        permanent: true,
      },
      {
        source: '/posts/why-wind-farm-grid-connection-cables-must-withstand-extreme-loads.html',
        destination: '/en/blog/why-wind-farm-grid-connection-cables-must-withstand-extreme-loads',
        permanent: true,
      },
      // Product redirects (English)
      {
        source: '/products/power-cables/high-voltage-cables/n2xsfl2y',
        destination: '/en/products/n2xsfl2y-hv',
        permanent: true,
      },
      {
        source: '/products/power-cables/high-voltage-cables/na2xsfl2y-3',
        destination: '/en/products/na2xsfl2y-hv',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/n2x2y',
        destination: '/en/products/n2x2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/n2xy',
        destination: '/en/products/n2xy',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/na2x2y',
        destination: '/en/products/na2x2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/na2xy',
        destination: '/en/products/na2xy',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/nay2y',
        destination: '/en/products/nay2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/naycwy',
        destination: '/en/products/naycwy',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/nayy',
        destination: '/en/products/nayy',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/ny2y',
        destination: '/en/products/ny2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/nycwy',
        destination: '/en/products/nycwy',
        permanent: true,
      },
      {
        source: '/products/power-cables/low-voltage-cables/nyy',
        destination: '/en/products/nyy',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/n2xs2y',
        destination: '/en/products/n2xs2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/n2xsf2y',
        destination: '/en/products/n2xsf2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/n2xsfl2y-3',
        destination: '/en/products/n2xsfl2y-mv',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/na2xs2y',
        destination: '/en/products/na2xs2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/na2xsf2y',
        destination: '/en/products/na2xsf2y',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/na2xsfl2y',
        destination: '/en/products/na2xsfl2y-mv',
        permanent: true,
      },
      {
        source: '/products/power-cables/medium-voltage-cables/na2xsy',
        destination: '/en/products/na2xsy',
        permanent: true,
      },
      {
        source: '/products/solar-cables/h1z2z2-k',
        destination: '/en/products/solar-cables/h1z2z2-k',
        permanent: true,
      },
      // Product redirects (German)
      {
        source: '/de/produkte/stromkabel/solarkabel/h1z2z2-k',
        destination: '/de/produkte/solarkabel/h1z2z2-k',
        permanent: true,
      },
      {
        source: '/de/produkte/stromkabel/niederspannungskabel/naycwy-2',
        destination: '/de/produkte/niederspannungskabel/naycwy',
        permanent: true,
      },
      {
        source: '/de/produkte/stromkabel/niederspannungskabel/ny2y-2',
        destination: '/de/produkte/niederspannungskabel/ny2y',
        permanent: true,
      },
      // VCF redirects
      {
        source: '/vcf/klaus-mintel',
        destination: '/klaus-mintel.vcf',
        permanent: true,
      },
      {
        source: '/vcf/michael-bodemer',
        destination: '/michael-bodemer.vcf',
        permanent: true,
      }
    ];
  },
  images: {
    formats: ['image/webp'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'klz-cables.com',
      },
      {
        protocol: 'https',
        hostname: '*.klz-cables.com',
      },
      {
        protocol: 'http',
        hostname: 'klz-cables.com',
      },
      {
        protocol: 'http',
        hostname: '*.klz-cables.com',
      },
      {
        protocol: 'http',
        hostname: 'klz.localhost',
      },
      {
        protocol: 'http',
        hostname: 'localhost',
      },
    ],
  },
  async rewrites() {
    return {
      beforeFiles: [
        {
          source: '/de/produkte',
          destination: '/de/products',
        },
        {
          source: '/de/produkte/:path*',
          destination: '/de/products/:path*',
        },
        {
          source: '/de/kontakt',
          destination: '/de/contact',
        },
        // Safety rewrites for English locale using German slugs (legacy or content errors)
        {
          source: '/en/produkte',
          destination: '/en/products',
        },
        {
          source: '/en/produkte/:path*',
          destination: '/en/products/:path*',
        },
        {
          source: '/en/kontakt',
          destination: '/en/contact',
        },
        {
          source: '/en/impressum',
          destination: '/en/legal-notice',
        },
        {
          source: '/en/datenschutz',
          destination: '/en/privacy-policy',
        },
      ],
      afterFiles: [],
      fallback: [],
    };
  },
};

const withAnalyzer = withBundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
});

// withMintelConfig internally sets output:'standalone' and wraps with withSentryConfig.
// In dev mode, standalone triggers @vercel/nft file tracing on every compile through
// VirtioFS, which hammers CPU. Strip it for dev.
let resolvedConfig = withPayload(withAnalyzer(withMintelConfig(nextConfig)));

if (!isProd) {
  delete resolvedConfig.output;
}

export default resolvedConfig;
