import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
import svelteConfig from './svelte.config.js';

/**
 * Flat-config ESLint for the SvelteKit frontend. Type-aware where it's cheap; Prettier owns
 * formatting (its config is last so it disables every stylistic rule that would fight the formatter).
 */
export default ts.config(
	js.configs.recommended,
	...ts.configs.recommended,
	...svelte.configs.recommended,
	prettier,
	...svelte.configs.prettier,
	{
		languageOptions: {
			globals: { ...globals.browser, ...globals.node }
		}
	},
	{
		files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
		languageOptions: {
			parserOptions: {
				projectService: true,
				extraFileExtensions: ['.svelte'],
				parser: ts.parser,
				svelteConfig
			}
		}
	},
	{
		rules: {
			// A leading underscore is the deliberate "intentionally unused" marker (e.g. `{#each x as _}`).
			'@typescript-eslint/no-unused-vars': [
				'error',
				{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }
			],
			// Off on purpose. This rule wants every `goto('/x')` / `href="/x"` wrapped in `resolve()`
			// for typed routes. That is a taste/ergonomics preference, not a correctness rule — string
			// routes work fine and the app uses them deliberately. We keep the rules that catch actual
			// bugs (require-each-key, prefer-svelte-reactivity) and drop this churn.
			'svelte/no-navigation-without-resolve': 'off',
			// Off: `svelte-ignore` comments are consumed by the Svelte compiler / svelte-check, which
			// ESLint cannot see — so it reports every one as "unused" even when it is actively
			// suppressing a real svelte-check a11y warning. Removing them on ESLint's say-so would
			// reintroduce those warnings. svelte-check is the authority on these, not ESLint.
			'svelte/no-unused-svelte-ignore': 'off'
		}
	},
	{
		// Test fixtures legitimately use `any` for partial/mock shapes (e.g. a stub upload that only
		// sets the two fields the function under test reads). Not worth threading full types through.
		files: ['**/*.test.ts'],
		rules: { '@typescript-eslint/no-explicit-any': 'off' }
	},
	{
		ignores: [
			// `**/` matters: these patterns are relative to this config's directory, so a bare
			// `.svelte-kit/` matched only the top-level one and left `export-viewer/.svelte-kit/`
			// — SvelteKit's GENERATED types, gitignored but present after a viewer build — being
			// linted, for 10 errors in code nobody wrote. Rebuilding the viewer is a required
			// step whenever its source changes (it is embedded in the binary via include_dir!),
			// so that directory exists in any normal working tree.
			'**/.svelte-kit/',
			'**/build/',
			'**/dist/',
			'**/node_modules/',
			'static/export-viewer/',
			'*.config.js',
			'*.config.ts'
		]
	}
);
