import { localeCodes } from '@saasmakers/shared'
import { createRequire } from 'node:module'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineNuxtConfig } from 'nuxt/config'
import uno from './uno.config.js'

const currentDir = path.dirname(fileURLToPath(import.meta.url))
const isPostHogEnabled = process.env.NODE_ENV === 'production' && Boolean(process.env.NUXT_PUBLIC_POSTHOG_KEY)
const isSentryEnabled = process.env.NODE_ENV === 'production'

const bareCssPackageIds = new Set([
  '@unocss/reset/tailwind.css',
  'floating-vue/dist/style.css',
])

function resolveCssFromAppRoot(rootDir: string, specifier: string) {
  // Resolve from the consuming app so Vite's fs.allow covers the file (workspace layers
  // otherwise resolve into the layer monorepo's node_modules, outside the allow list).
  return createRequire(path.join(rootDir, 'package.json')).resolve(specifier)
}

export default defineNuxtConfig({
  modules: [
    '@nuxt/icon',
    '@nuxt/scripts',
    '@nuxtjs/color-mode',
    '@nuxtjs/i18n',
    '@nuxtjs/plausible',
    '@nuxtjs/robots',
    '@nuxtjs/sitemap',
    '@pinia/nuxt',
    'pinia-plugin-persistedstate/nuxt',
    '@unocss/nuxt',
    '@vueuse/nuxt',
    'floating-vue/nuxt',
    'motion-v/nuxt',
    ...(isPostHogEnabled ? ['@posthog/nuxt'] : []),
    ...(isSentryEnabled ? ['@sentry/nuxt/module'] : []),
    (_options, nuxt) => {
      // Rewrite bare package CSS ids (including floating-vue/nuxt's push) after modules load.
      nuxt.hook('modules:done', () => {
        nuxt.options.css = nuxt.options.css.map((entry) => {
          if (typeof entry === 'string' && bareCssPackageIds.has(entry)) {
            return resolveCssFromAppRoot(nuxt.options.rootDir, entry)
          }

          return entry
        })
      })
    },
  ],

  components: [
    {
      path: 'components/auth',
      pathPrefix: false,
    },
    {
      path: 'components/bases',
      pathPrefix: false,
    },
    {
      path: 'components/fields',
      pathPrefix: false,
    },
    {
      path: 'components/layout',
      pathPrefix: false,
    },
  ],

  // Design tokens (motion, stacking) are auto-imported like utils, in this layer and its consumers.
  imports: { dirs: ['tokens'] },

  devtools: { enabled: true },

  css: [
    '@unocss/reset/tailwind.css',
    path.join(currentDir, './app/assets/styles/base.css'),
    path.join(currentDir, './app/assets/styles/chartist.css'),
    path.join(currentDir, './app/assets/styles/motion.css'),
    path.join(currentDir, './app/assets/styles/radius.css'),
    path.join(currentDir, './app/assets/styles/spacing.css'),
    path.join(currentDir, './app/assets/styles/scrollbar.css'),
    path.join(currentDir, './app/assets/styles/v-popper.css'),
  ],

  piniaPluginPersistedstate: { storage: 'localStorage' },

  colorMode: {
    classSuffix: '',
    fallback: 'light',
    preference: 'light',
  },

  experimental: { typedPages: true },

  compatibilityDate: '2025-09-24',

  typescript: {
    strict: true,

    tsConfig: {
      compilerOptions: {
        noUncheckedIndexedAccess: false,
        noUnusedParameters: true,
      },

      vueCompilerOptions: { strictTemplates: true },
    },
  },

  i18n: {
    defaultLocale: 'en',
    locales: localeCodes,
    strategy: 'prefix_except_default',

    detectBrowserLanguage: {
      cookieKey: 'i18n_redirected',
      fallbackLocale: 'en',
      redirectOn: 'root',
      useCookie: true,
    },

    experimental: { typedPages: true },
  },

  ...(isPostHogEnabled
    ? {
        posthogConfig: {
          clientConfig: {
            capture_pageview: true,
            defaults: '2026-01-30',
            disable_session_recording: false,
            opt_out_capturing_by_default: false,
            person_profiles: 'identified_only',
            session_recording: { maskAllInputs: true },
            ui_host: 'https://eu.posthog.com',
          },
          host: 'https://eu.i.posthog.com',
          publicKey: process.env.NUXT_PUBLIC_POSTHOG_KEY!,
        },
      }
    : {}),

  plausible: {
    apiHost: 'https://plausible.saasmakers.dev',
    autoOutboundTracking: true,
    ignoreSubDomains: true,
    proxy: true,
  },

  robots: { credits: false },

  sourcemap: { client: 'hidden' },

  sitemap: {
    autoLastmod: true,
    credits: false,
    xslColumns: [
      {
        label: 'URL',
        width: '50%',
      },
      {
        label: 'Last Modified',
        select: 'sitemap:lastmod',
        width: '25%',
      },
    ],
    xslTips: false,
  },

  unocss: {
    nuxtLayers: true,
    preflights: uno.preflights,
    presets: uno.presets,
    rules: uno.rules,
    shortcuts: uno.shortcuts,
    theme: uno.theme,
  },
})
