import prettier from 'eslint-config-prettier';
import { fileURLToPath } from 'node:url';
import { includeIgnoreFile } from '@eslint/compat';
import js from '@eslint/js';
import svelte from 'eslint-plugin-svelte';
import { defineConfig } from 'eslint/config';
import globals from 'globals';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';

const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));

export default defineConfig(
	includeIgnoreFile(gitignorePath),
	// Vendored third-party source. Tracked, so .gitignore does not cover it.
	// static/pdfjs is the pdf.js viewer, vendored the same way as src/lib/vendor/foliate-js;
	// linting it produced 1717 of the 1804 errors this config used to report.
	{ ignores: ['src/lib/vendor/**', 'static/pdfjs/**'] },
	js.configs.recommended,
	...ts.configs.recommended,
	...svelte.configs.recommended,
	prettier,
	...svelte.configs.prettier,
	{
		languageOptions: {
			globals: { ...globals.browser, ...globals.node }
		},
		rules: {
			// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
			// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
			'no-undef': 'off',
			// A leading underscore marks a binding that exists to hold a position — a callback
			// parameter the signature requires, or the discarded half of a destructure.
			'@typescript-eslint/no-unused-vars': [
				'error',
				{
					argsIgnorePattern: '^_',
					varsIgnorePattern: '^_',
					caughtErrorsIgnorePattern: '^_',
					destructuredArrayIgnorePattern: '^_'
				}
			]
		}
	},
	{
		// Generated shadcn components take href as a prop and cannot resolve it —
		// that is the caller's job. Editing them here would be lost on regeneration.
		files: ['src/lib/components/ui/**'],
		rules: { 'svelte/no-navigation-without-resolve': 'off' }
	},
	{
		// no-useless-assignment joined eslint:recommended in ESLint 10, and its flow analysis
		// does not model runes: it reads `let { ref = $bindable(null) } = $props()` as a value
		// that is never read. Deleting the default, as it suggests, breaks the binding.
		//
		// no-unused-expressions is off for the same reason: a bare `book;` inside an $effect is
		// how a reactive dependency is declared when the read would otherwise be untracked.
		// Removing the statement stops the effect re-running.
		files: ['**/*.svelte'],
		rules: {
			'no-useless-assignment': 'off',
			'@typescript-eslint/no-unused-expressions': 'off'
		}
	},
	{
		files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
		languageOptions: {
			parserOptions: {
				projectService: true,
				extraFileExtensions: ['.svelte'],
				parser: ts.parser,
				svelteConfig
			}
		}
	}
);
