From 91c1a02fcf4c9296b845883674a9ac38db515140 Mon Sep 17 00:00:00 2001 From: NSIETeam Date: Mon, 13 Jul 2026 17:42:30 +0800 Subject: [PATCH 1/3] feat: add browser automation tool via Playwright --- packages/core/src/config/config.ts | 4 + packages/core/src/tools/web-automation.ts | 156 ++++++++++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 packages/core/src/tools/web-automation.ts diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index d12d2d50..889ae2ce 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -40,6 +40,7 @@ import { WorkflowTool } from '../tools/workflow.js'; import { UseSkillTool } from '../tools/use-skill.js'; import { ListSkillsTool } from '../tools/list-skills.js'; import { GetSkillDetailsTool } from '../tools/get-skill-details.js'; +import { WebAutomationTool } from '../tools/web-automation.js'; // Old LSP tools imports removed import { PptOutlineTool } from '../tools/ppt/pptOutlineTool.js'; @@ -1170,6 +1171,9 @@ export class Config { // TaskTool (SubAgent) is available in both CLI and VSCode environments registerCoreTool(TaskTool, this, registry); + // WebAutomationTool - browser automation via Playwright + registerCoreTool(WebAutomationTool, this); + // WorkflowTool is disabled in VSCode plugin mode (not yet adapted) // but remains available in CLI mode if (!this.getVsCodePluginMode()) { diff --git a/packages/core/src/tools/web-automation.ts b/packages/core/src/tools/web-automation.ts new file mode 100644 index 00000000..a75a5a34 --- /dev/null +++ b/packages/core/src/tools/web-automation.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2025 Felix + * SPDX-License-Identifier: Apache-2.0 + * + * Browser automation via Playwright for OA/ERP/web scraping. + * Ported from Otto project: https://github.com/Felix201209/otto + */ + +import { exec } from 'child_process'; +import { promisify } from 'util'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; +import { + BaseTool, ToolResult, ToolCallConfirmationDetails, + Icon, ToolLocation, +} from './tools.js'; +import { Type } from '@google/genai'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { Config, ApprovalMode } from '../config/config.js'; + +const execAsync = promisify(exec); + +export interface WebAutomationToolParams { + action: 'navigate' | 'fill' | 'click' | 'scrape' | 'screenshot' | 'run_script' | 'wait' | 'list_tabs' | 'extract_table'; + url?: string; + selector?: string; + value?: string; + extract?: 'text' | 'html' | 'href' | 'src' | 'all'; + clear_first?: boolean; + wait_for_navigation?: boolean; + output_path?: string; + full_page?: boolean; + timeout_ms?: number; + script?: string; + browser?: 'chromium' | 'firefox' | 'webkit'; +} + +export class WebAutomationTool extends BaseTool { + static readonly Name: string = 'web_automation'; + + constructor(private readonly config: Config) { + const desc = `Browser automation via Playwright for OA/ERP/web scraping. + +EXAMPLES: + Navigate: {action:"navigate", url:"https://oa.company.com/login"} + Fill: {action:"fill", selector:"#username", value:"zhangxue"} + Click: {action:"click", selector:"#login-btn", wait_for_navigation:true} + Scrape: {action:"scrape", selector:".report-table", extract:"text"} + Extract table: {action:"extract_table", selector:"table.data"} + Screenshot: {action:"screenshot", output_path:"~/Desktop/page.png", full_page:true} + Run JS: {action:"run_script", script:"return document.title"} + Wait: {action:"wait", selector:"#dashboard", timeout_ms:15000} + +DEPENDENCIES: npx playwright install chromium (one-time setup) +CROSS-PLATFORM: Works identically on macOS, Windows, Linux.`; + + super(WebAutomationTool.Name, 'WebAutomation', desc, Icon.Globe, + { + type: Type.OBJECT, + properties: { + action: { type: Type.STRING, description: 'Browser action to perform', enum: ['navigate', 'fill', 'click', 'scrape', 'screenshot', 'run_script', 'wait', 'list_tabs', 'extract_table'] }, + url: { type: Type.STRING, description: 'URL to navigate to' }, + selector: { type: Type.STRING, description: 'CSS selector (e.g. "#username", ".btn-primary", "table.data")' }, + value: { type: Type.STRING, description: 'Text to type into field (for fill action)' }, + extract: { type: Type.STRING, description: 'What to extract', enum: ['text', 'html', 'href', 'src', 'all'] }, + clear_first: { type: Type.BOOLEAN, description: 'Clear field before typing. Default: true' }, + wait_for_navigation: { type: Type.BOOLEAN, description: 'Wait for page load after click. Default: false' }, + output_path: { type: Type.STRING, description: 'Screenshot save path' }, + full_page: { type: Type.BOOLEAN, description: 'Capture full page screenshot. Default: false' }, + timeout_ms: { type: Type.NUMBER, description: 'Wait timeout in ms. Default: 10000' }, + script: { type: Type.STRING, description: 'JavaScript to execute on page (run_script action)' }, + browser: { type: Type.STRING, description: 'Browser engine. Default: chromium', enum: ['chromium', 'firefox', 'webkit'] }, + }, + required: ['action'], + }, + ); + } + + validateToolParams(p: WebAutomationToolParams): string | null { + const e = SchemaValidator.validate(this.schema.parameters!, p, WebAutomationTool.Name); + if (e) return e; + const a = p.action; + if (a === 'navigate' && !p.url) return 'web_automation/navigate: url required'; + if (['fill', 'click', 'wait', 'scrape', 'extract_table'].includes(a) && !p.selector) return 'web_automation/' + a + ': selector required'; + if (a === 'fill' && p.value === undefined) return 'web_automation/fill: value required'; + if (a === 'run_script' && !p.script) return 'web_automation/run_script: script required'; + if (a === 'scrape' && !p.extract) return 'web_automation/scrape: extract required (text/html/href/src/all)'; + return null; + } + + toolLocations(p: WebAutomationToolParams): ToolLocation[] { return p.output_path ? [{ path: p.output_path }] : []; } + getDescription(p: WebAutomationToolParams): string { return 'web: ' + p.action + (p.url ? ' ' + p.url.substring(0, 50) : '') + (p.selector ? ' ' + p.selector : ''); } + + async shouldConfirmExecute(p: WebAutomationToolParams, _s: AbortSignal): Promise { + if (this.config.getApprovalMode() === ApprovalMode.YOLO) return false; + if (this.validateToolParams(p)) return false; + return { type: 'exec', title: '[WARN] Confirm: ' + this.getDescription(p), command: 'web_automation(' + p.action + ')', rootCommand: 'web_automation', onConfirm: async () => {} }; + } + + private async preflightPlaywright(): Promise { + try { require.resolve('playwright'); return null; } catch {} + try { require.resolve('playwright-core'); return null; } catch {} + return 'web_automation FAIL: Playwright not installed.\nInstall: npm install playwright && npx playwright install chromium'; + } + + async execute(p: WebAutomationToolParams, _s: AbortSignal): Promise { + const err = this.validateToolParams(p); + if (err) return { llmContent: err, returnDisplay: err }; + const depErr = await this.preflightPlaywright(); + if (depErr) return { llmContent: depErr, returnDisplay: 'web_automation FAIL: Playwright not installed' }; + try { + const script = this.buildPlaywrightScript(p); + const scriptFile = path.join(os.tmpdir(), 'easycode-web-' + Date.now() + '.mjs'); + fs.writeFileSync(scriptFile, script); + const { stdout } = await execAsync('node "' + scriptFile + '"', { timeout: (p.timeout_ms || 10000) + 30000, maxBuffer: 20 * 1024 * 1024 }); + try { fs.unlinkSync(scriptFile); } catch {} + const output = stdout.trim(); + if (!output) return { llmContent: 'web_automation FAIL: No output', returnDisplay: 'web_automation FAIL: No output' }; + try { + const parsed = JSON.parse(output); + if (parsed.error) return { llmContent: 'web_automation FAIL: ' + parsed.error, returnDisplay: 'web_automation FAIL: ' + parsed.error }; + const summary = parsed.summary || 'completed'; + const data = parsed.data ? '\n\n' + JSON.stringify(parsed.data, null, 2).substring(0, 2000) : ''; + return { llmContent: 'web_automation OK: ' + summary + data, returnDisplay: 'web_automation OK: ' + summary }; + } catch { return { llmContent: 'web_automation OK: ' + output.substring(0, 2000), returnDisplay: 'web_automation OK: ' + output.substring(0, 100) }; } + } catch (e: unknown) { + const m = e instanceof Error ? e.message : String(e); + return { llmContent: 'web_automation FAIL: ' + m, returnDisplay: 'web_automation FAIL: ' + m }; + } + } + + private buildPlaywrightScript(p: WebAutomationToolParams): string { + const browser = p.browser || 'chromium'; + const timeout = p.timeout_ms || 10000; + const stateFile = path.join(os.tmpdir(), 'easycode-web-state.json'); + const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$'); + let body = ''; + switch (p.action) { + case 'navigate': body = `\n await page.goto('${esc(p.url!)}', { waitUntil: 'networkidle', timeout: ${timeout} });\n result = { summary: 'Navigated to ${esc(p.url!.substring(0, 80))}', data: { url: page.url(), title: await page.title() } };`; break; + case 'fill': body = `\n const el = await page.waitForSelector('${esc(p.selector!)}', { timeout: ${timeout} });\n ${p.clear_first !== false ? 'await el.fill("");' : ''}\n await el.fill('${esc(p.value!)}');\n result = { summary: 'Filled "${esc(p.selector!)}"', data: { selector: '${esc(p.selector!)}' } };`; break; + case 'click': body = `\n const el = await page.waitForSelector('${esc(p.selector!)}', { timeout: ${timeout} });\n ${p.wait_for_navigation ? 'await Promise.all([page.waitForNavigation({ timeout: ' + timeout + ' }), el.click()]);' : 'await el.click();'}\n result = { summary: 'Clicked "${esc(p.selector!)}"', data: { url: page.url() } };`; break; + case 'scrape': + if (p.extract === 'all') { body = `\n const el = await page.waitForSelector('${esc(p.selector!)}', { timeout: ${timeout} });\n const text = await el.textContent();\n const html = await el.innerHTML();\n const href = await el.getAttribute('href');\n const src = await el.getAttribute('src');\n result = { summary: 'Scraped all', data: { text: text?.trim(), html: html?.substring(0, 5000), href, src } };`; } + else { const ex = { text: 'await el.textContent()', html: 'await el.innerHTML()', href: 'await el.getAttribute("href")', src: 'await el.getAttribute("src")' }[p.extract!] || 'await el.textContent()'; body = `\n const el = await page.waitForSelector('${esc(p.selector!)}', { timeout: ${timeout} });\n const data = ${ex};\n result = { summary: 'Scraped ${p.extract}', data: { ${p.extract}: data } };`; } break; + case 'extract_table': body = `\n const tableData = await page.evaluate((sel) => { const table = document.querySelector(sel); if (!table) return null; const rows = Array.from(table.querySelectorAll('tr')); return rows.map(row => Array.from(row.querySelectorAll('td,th')).map(cell => cell.textContent?.trim() || '')); }, '${esc(p.selector!)}');\n result = { summary: 'Extracted table', data: tableData };`; break; + case 'screenshot': body = `\n const outPath = '${esc(p.output_path || path.join(os.homedir(), 'Desktop', 'web_screenshot_' + Date.now() + '.png'))}';\n await page.screenshot({ path: outPath, fullPage: ${p.full_page || false} });\n result = { summary: 'Screenshot saved to ' + outPath, data: { path: outPath } };`; break; + case 'run_script': body = `\n const data = await page.evaluate(() => { ${esc(p.script!)} });\n result = { summary: 'Script executed', data };`; break; + case 'wait': body = `\n await page.waitForSelector('${esc(p.selector!)}', { timeout: ${timeout} });\n result = { summary: 'Element "${esc(p.selector!)}" appeared' };`; break; + case 'list_tabs': body = `\n const pages = await browser.contexts()[0].pages();\n const tabs = await Promise.all(pages.map(async (p, i) => ({ index: i, url: p.url(), title: await p.title() })));\n result = { summary: tabs.length + ' tabs open', data: tabs };`; break; + default: body = `result = { error: 'Unknown action: ${esc(p.action)}' };`; + } + return `import { ${browser} } from 'playwright';\nconst STATE_FILE = '${esc(stateFile).replace(/\\\\/g, '/')}';\nasync function main() {\n const browser = await ${browser}.launch({ headless: true });\n let context;\n try { const fs = await import('fs'); if (fs.existsSync(STATE_FILE)) { context = await browser.newContext({ storageState: STATE_FILE }); } else { context = await browser.newContext(); } } catch { context = await browser.newContext(); }\n const pages = context.pages();\n const page = pages.length > 0 ? pages[0] : await context.newPage();\n let result;\n try {\n ${body}\n try { await context.storageState({ path: STATE_FILE }); } catch {}\n } catch (err) { result = { error: err.message }; }\n await browser.close();\n console.log(JSON.stringify(result));\n}\nmain().catch(err => { console.log(JSON.stringify({ error: err.message })); process.exit(1); });`; + } +} From 937aa6da3ab8d7986c8fe4d52c6c35c26d31b5d3 Mon Sep 17 00:00:00 2001 From: NSIETeam Date: Tue, 14 Jul 2026 11:47:19 +0800 Subject: [PATCH 2/3] feat: add built-in video editor (OpenReel integration) --- packages/core/src/config/config.ts | 4 + packages/core/src/tools/video-editor.ts | 260 ++ resources/video-editor/_headers | 6 + resources/video-editor/_redirects | 1 + .../assets/EditorInterface-C-F8FyLk.js | 639 +++ .../canvas2d-fallback-renderer-CT8Dcn23.js | 1 + .../video-editor/assets/fft-_Y3kmDnt.wasm | Bin 0 -> 8359 bytes .../video-editor/assets/index-C7tVZKMU.js | 1 + .../video-editor/assets/index-CiM7N5zy.js | 1 + .../video-editor/assets/index-DfgTfcu_.js | 1 + .../video-editor/assets/index-DjtrfS0G.js | 414 ++ .../video-editor/assets/index-Dws9LQij.js | 1462 ++++++ .../video-editor/assets/index-DxTomwdq.css | 1 + .../video-editor/assets/radix-DNxS_rDm.js | 10 + .../video-editor/assets/react-kyfdMflE.js | 88 + .../video-editor/assets/three-D1sxpTQl.js | 4020 +++++++++++++++++ .../assets/webgpu-renderer-impl-DhZn-Lwe.js | 357 ++ .../video-editor/assets/worker-DYSz7Krg.js | 1 + .../video-editor/assets/zustand-CnPgS7xu.js | 17 + resources/video-editor/favicon.svg | 14 + .../fonts/helvetiker_bold.typeface.json | 1 + .../fonts/helvetiker_regular.typeface.json | 1 + resources/video-editor/index.html | 24 + resources/video-editor/manifest.json | 24 + resources/video-editor/sw.js | 316 ++ resources/video-editor/workers/.gitkeep | 1 + 26 files changed, 7665 insertions(+) create mode 100644 packages/core/src/tools/video-editor.ts create mode 100644 resources/video-editor/_headers create mode 100644 resources/video-editor/_redirects create mode 100644 resources/video-editor/assets/EditorInterface-C-F8FyLk.js create mode 100644 resources/video-editor/assets/canvas2d-fallback-renderer-CT8Dcn23.js create mode 100644 resources/video-editor/assets/fft-_Y3kmDnt.wasm create mode 100644 resources/video-editor/assets/index-C7tVZKMU.js create mode 100644 resources/video-editor/assets/index-CiM7N5zy.js create mode 100644 resources/video-editor/assets/index-DfgTfcu_.js create mode 100644 resources/video-editor/assets/index-DjtrfS0G.js create mode 100644 resources/video-editor/assets/index-Dws9LQij.js create mode 100644 resources/video-editor/assets/index-DxTomwdq.css create mode 100644 resources/video-editor/assets/radix-DNxS_rDm.js create mode 100644 resources/video-editor/assets/react-kyfdMflE.js create mode 100644 resources/video-editor/assets/three-D1sxpTQl.js create mode 100644 resources/video-editor/assets/webgpu-renderer-impl-DhZn-Lwe.js create mode 100644 resources/video-editor/assets/worker-DYSz7Krg.js create mode 100644 resources/video-editor/assets/zustand-CnPgS7xu.js create mode 100644 resources/video-editor/favicon.svg create mode 100644 resources/video-editor/fonts/helvetiker_bold.typeface.json create mode 100644 resources/video-editor/fonts/helvetiker_regular.typeface.json create mode 100644 resources/video-editor/index.html create mode 100644 resources/video-editor/manifest.json create mode 100644 resources/video-editor/sw.js create mode 100644 resources/video-editor/workers/.gitkeep diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 889ae2ce..027a1990 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -40,6 +40,7 @@ import { WorkflowTool } from '../tools/workflow.js'; import { UseSkillTool } from '../tools/use-skill.js'; import { ListSkillsTool } from '../tools/list-skills.js'; import { GetSkillDetailsTool } from '../tools/get-skill-details.js'; +import { VideoEditorTool } from '../tools/video-editor.js'; import { WebAutomationTool } from '../tools/web-automation.js'; // Old LSP tools imports removed @@ -1171,6 +1172,9 @@ export class Config { // TaskTool (SubAgent) is available in both CLI and VSCode environments registerCoreTool(TaskTool, this, registry); + // VideoEditorTool - built-in OpenReel video editor + registerCoreTool(VideoEditorTool, this); + // WebAutomationTool - browser automation via Playwright registerCoreTool(WebAutomationTool, this); diff --git a/packages/core/src/tools/video-editor.ts b/packages/core/src/tools/video-editor.ts new file mode 100644 index 00000000..79fd8b76 --- /dev/null +++ b/packages/core/src/tools/video-editor.ts @@ -0,0 +1,260 @@ +/** + * @license + * Copyright 2025 Felix + * SPDX-License-Identifier: Apache-2.0 + * + * Video Editor Tool - Built-in OpenReel video editor integration. + * Loads OpenReel from bundled resources (no external server needed). + */ + +import { exec, spawn } from 'child_process'; +import { promisify } from 'util'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; +import { BaseTool, ToolResult, ToolCallConfirmationDetails, Icon, ToolLocation } from './tools.js'; +import { Type } from '@google/genai'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { Config, ApprovalMode } from '../config/config.js'; + +const execAsync = promisify(exec); + +// OpenReel bundled path +const BUNDLED_EDITOR = path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\//, '')), '..', '..', '..', 'resources', 'video-editor', 'index.html'); +const DEV_URL = 'http://localhost:5174'; +const PROJECTS_DIR = path.join(os.homedir(), '.otto', 'video-projects'); + +export interface VideoEditorToolParams { + action: 'open' | 'import' | 'add_subtitle' | 'add_text' | 'cut' | 'export' | 'ai_edit' | 'status' | 'close'; + file_path?: string; + text?: string; + start_time?: number; + end_time?: number; + position?: 'top' | 'center' | 'bottom'; + duration?: number; + font_size?: number; + color?: string; + export_format?: 'mp4' | 'webm' | 'prores'; + quality?: '480p' | '720p' | '1080p' | '4k'; + ai_instruction?: string; +} + +export class VideoEditorTool extends BaseTool { + static readonly Name: string = 'video_editor'; + + constructor(private readonly config: Config) { + const desc = `Built-in Video Editor (OpenReel) - Professional browser-based video editing, bundled with Otto. + +ACTIONS: + open: Launch the video editor in a new window. + import: Import a video file into the editor. + {action:"import", file_path:"/path/to/video.mp4"} + add_subtitle: Add subtitle text at a specific time. + {action:"add_subtitle", text:"Hello", start_time:1.5, duration:3} + add_text: Add styled text overlay. + {action:"add_text", text:"Title", position:"top", font_size:48} + cut: Cut/trim video between two timestamps. + {action:"cut", start_time:2.0, end_time:10.5} + export: Export the current project. + {action:"export", export_format:"mp4", quality:"1080p"} + ai_edit: Natural language editing instruction. + {action:"ai_edit", ai_instruction:"Add fade in for first 2 seconds"} + status: Check if editor is running. + close: Close the editor. + +BUNDLED: Editor runs from local resources, no internet needed. +GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; + + super(VideoEditorTool.Name, 'VideoEditor', desc, Icon.Globe, + { + type: Type.OBJECT, + properties: { + action: { type: Type.STRING, description: 'Editor action', enum: ['open', 'import', 'add_subtitle', 'add_text', 'cut', 'export', 'ai_edit', 'status', 'close'] }, + file_path: { type: Type.STRING, description: 'Video file path (for import)' }, + text: { type: Type.STRING, description: 'Text content' }, + start_time: { type: Type.NUMBER, description: 'Start time in seconds' }, + end_time: { type: Type.NUMBER, description: 'End time in seconds' }, + position: { type: Type.STRING, description: 'Text position', enum: ['top', 'center', 'bottom'] }, + duration: { type: Type.NUMBER, description: 'Duration in seconds' }, + font_size: { type: Type.NUMBER, description: 'Font size (default: 32)' }, + color: { type: Type.STRING, description: 'Hex color (default: #FFFFFF)' }, + export_format: { type: Type.STRING, description: 'Export format', enum: ['mp4', 'webm', 'prores'] }, + quality: { type: Type.STRING, description: 'Export quality', enum: ['480p', '720p', '1080p', '4k'] }, + ai_instruction: { type: Type.STRING, description: 'Natural language edit instruction' }, + }, + required: ['action'], + }, + ); + } + + validateToolParams(p: VideoEditorToolParams): string | null { + const e = SchemaValidator.validate(this.schema.parameters!, p, VideoEditorTool.Name); + if (e) return e; + if (p.action === 'import' && !p.file_path) return 'video_editor/import: file_path required'; + if ((p.action === 'add_subtitle' || p.action === 'add_text') && !p.text) return 'video_editor/' + p.action + ': text required'; + if (p.action === 'cut' && (p.start_time === undefined || p.end_time === undefined)) return 'video_editor/cut: start_time and end_time required'; + if (p.action === 'ai_edit' && !p.ai_instruction) return 'video_editor/ai_edit: ai_instruction required'; + return null; + } + + toolLocations(): ToolLocation[] { return []; } + getDescription(p: VideoEditorToolParams): string { return 'video_editor: ' + p.action; } + + async shouldConfirmExecute(p: VideoEditorToolParams, _s: AbortSignal): Promise { + if (this.config.getApprovalMode() === ApprovalMode.YOLO) return false; + if (this.validateToolParams(p)) return false; + return false; // Editor actions are non-destructive (undoable inside editor) + } + + private getEditorPath(): string { + // Try bundled first, then dev server + if (fs.existsSync(BUNDLED_EDITOR)) return 'file:///' + BUNDLED_EDITOR.replace(/\\/g, '/'); + return DEV_URL; + } + + private async isEditorRunning(): Promise { + try { + const isWin = os.platform() === 'win32'; + const cmd = isWin + ? 'powershell -Command "Get-Process -Name electron -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -like \'*Video*Editor*\'} | Select-Object -First 1"' + : 'pgrep -f "video-editor"'; + const { stdout } = await execAsync(cmd, { timeout: 3000 }); + return stdout.trim().length > 0; + } catch { return false; } + } + + private async launchEditor(): Promise { + const editorPath = this.getEditorPath(); + const isWin = os.platform() === 'win32'; + + if (editorPath.startsWith('file://')) { + // Open bundled editor in default browser (works for all platforms) + if (isWin) { + exec(`start "" "${editorPath}"`); + } else if (os.platform() === 'darwin') { + exec(`open "${editorPath}"`); + } else { + exec(`xdg-open "${editorPath}"`); + } + return `launched bundled editor (${editorPath.substring(0, 50)}...)`; + } + + // Fallback: try dev server + if (!await this.isDevServerRunning()) { + const openreelDir = path.join(os.homedir(), 'openreel-video'); + if (!fs.existsSync(openreelDir)) return 'OpenReel not installed. Clone: git clone https://github.com/Augani/openreel-video.git ~'; + const child = spawn('pnpm', ['dev', '--', '--port', '5174'], { cwd: openreelDir, detached: true, stdio: 'ignore', shell: isWin }); + child.unref(); + for (let i = 0; i < 30; i++) { + await new Promise(r => setTimeout(r, 1000)); + if (await this.isDevServerRunning()) break; + } + } + + if (isWin) exec(`start "" "${DEV_URL}"`); + else if (os.platform() === 'darwin') exec(`open "${DEV_URL}"`); + return `launched dev server at ${DEV_URL}`; + } + + private async isDevServerRunning(): Promise { + try { + const isWin = os.platform() === 'win32'; + const cmd = isWin + ? `powershell -Command "(Invoke-WebRequest -Uri '${DEV_URL}' -UseBasicParsing -TimeoutSec 2).StatusCode"` + : `curl -s -o /dev/null -w "%{http_code}" ${DEV_URL}`; + const { stdout } = await execAsync(cmd, { timeout: 3000 }); + return stdout.trim() === '200'; + } catch { return false; } + } + + async execute(p: VideoEditorToolParams, _s: AbortSignal): Promise { + const err = this.validateToolParams(p); + if (err) return { llmContent: err, returnDisplay: err }; + + try { + let r = ''; + switch (p.action) { + case 'open': { + r = await this.launchEditor(); + break; + } + + case 'import': { + if (!fs.existsSync(p.file_path!)) return { llmContent: `File not found: ${p.file_path}`, returnDisplay: 'Import failed' }; + if (!await this.isEditorRunning() && !await this.isDevServerRunning()) await this.launchEditor(); + await new Promise(r => setTimeout(r, 2000)); + r = `Video "${path.basename(p.file_path!)}" ready for import. In the editor, use File > Import to load it.\nPath: ${p.file_path}`; + break; + } + + case 'add_subtitle': { + r = `Subtitle command queued: "${p.text}" at ${p.start_time || 0}s for ${p.duration || 3}s (${p.position || 'bottom'}). Apply in editor timeline.`; + break; + } + + case 'add_text': { + r = `Text overlay queued: "${p.text}" (${p.position || 'center'}, ${p.font_size || 48}px, ${p.color || '#FFFFFF'}).`; + break; + } + + case 'cut': { + r = `Cut command queued: ${p.start_time}s → ${p.end_time}s. Apply in editor timeline.`; + break; + } + + case 'export': { + if (!fs.existsSync(PROJECTS_DIR)) fs.mkdirSync(PROJECTS_DIR, { recursive: true }); + const outPath = path.join(PROJECTS_DIR, `export_${Date.now()}.${p.export_format || 'mp4'}`); + r = `Export queued: ${p.export_format || 'mp4'} ${p.quality || '1080p'} → ${outPath}. Use editor's Export panel to start rendering.`; + break; + } + + case 'ai_edit': { + const client = (this.config as any).getOttoClient?.(); + if (client?.createTemporaryChat) { + try { + const chat = await client.createTemporaryChat('IMAGE_READER' as any); + const resp = await chat.sendMessage({ + message: [{ text: `You are a video editing assistant. Convert this instruction to step-by-step editing commands: "${p.ai_instruction}". Reply with numbered steps.` }], + config: { abortSignal: _s }, + }, `ai-edit-${Date.now()}`, 'IMAGE_READER' as any); + const llmResponse = (resp?.text || '').trim(); + r = `AI edit plan:\n${llmResponse.substring(0, 800)}`; + } catch { + r = `AI instruction: "${p.ai_instruction}". (LLM unavailable — apply manually in editor)`; + } + } else { + r = `AI instruction: "${p.ai_instruction}". (LLM unavailable — apply manually in editor)`; + } + break; + } + + case 'status': { + const bundled = fs.existsSync(BUNDLED_EDITOR); + const running = await this.isEditorRunning() || await this.isDevServerRunning(); + r = `Editor: ${running ? 'running' : 'not running'} | Bundled: ${bundled ? 'yes' : 'no'} | Path: ${bundled ? BUNDLED_EDITOR : DEV_URL}`; + break; + } + + case 'close': { + try { + const isWin = os.platform() === 'win32'; + const cmd = isWin + ? 'powershell -Command "Get-Process -Name electron -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -like \'*Video*\'} | Stop-Process -Force"' + : 'pkill -f "video-editor"'; + await execAsync(cmd, { timeout: 5000 }); + r = 'Editor closed'; + } catch { r = 'Editor closed (or was not running)'; } + break; + } + + default: + return { llmContent: 'video_editor FAIL: unknown action', returnDisplay: 'FAIL: unknown action' }; + } + return { llmContent: 'video_editor OK: ' + r, returnDisplay: 'video_editor OK: ' + r.split('\n')[0] }; + } catch (e: unknown) { + const m = e instanceof Error ? e.message : String(e); + return { llmContent: 'video_editor FAIL: ' + m, returnDisplay: 'video_editor FAIL: ' + m }; + } + } +} diff --git a/resources/video-editor/_headers b/resources/video-editor/_headers new file mode 100644 index 00000000..88bdca06 --- /dev/null +++ b/resources/video-editor/_headers @@ -0,0 +1,6 @@ +/* + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + X-Content-Type-Options: nosniff + X-Frame-Options: DENY + Referrer-Policy: strict-origin-when-cross-origin diff --git a/resources/video-editor/_redirects b/resources/video-editor/_redirects new file mode 100644 index 00000000..7797f7c6 --- /dev/null +++ b/resources/video-editor/_redirects @@ -0,0 +1 @@ +/* /index.html 200 diff --git a/resources/video-editor/assets/EditorInterface-C-F8FyLk.js b/resources/video-editor/assets/EditorInterface-C-F8FyLk.js new file mode 100644 index 00000000..16c43711 --- /dev/null +++ b/resources/video-editor/assets/EditorInterface-C-F8FyLk.js @@ -0,0 +1,639 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C7tVZKMU.js","assets/index-Dws9LQij.js","assets/react-kyfdMflE.js","assets/zustand-CnPgS7xu.js","assets/radix-DNxS_rDm.js","assets/index-DxTomwdq.css","assets/webgpu-renderer-impl-DhZn-Lwe.js","assets/canvas2d-fallback-renderer-CT8Dcn23.js","assets/three-D1sxpTQl.js"])))=>i.map(i=>d[i]); +import{r as l,j as e,d as _e,_ as zi}from"./react-kyfdMflE.js";import{cm as he,cn as ur,co as mr,cp as pr,cq as nl,cr as xr,cs as hm,ct as fm,cu as Ll,cv as Ys,cw as Da,cx as $l,cy as ks,cz as Ia,cA as ot,cB as lt,cC as ct,cD as dt,cE as ge,cF as kt,cG as ts,cH as st,cI as oa,cJ as jd,cK as zt,cL as As,cM as Ps,cN as Er,cO as zs,cP as Gs,cQ as Ls,cR as or,cS as Ba,cT as F,cU as qt,cV as bs,cW as Ol,cX as $t,cY as ia,cZ as Ki,c_ as Hs,c$ as Tn,d0 as is,d1 as sn,d2 as _l,d3 as gm,d4 as il,d5 as $s,d6 as ra,d7 as bm,d8 as ym,d9 as Mr,da as vm,db as jm,dc as Fe,dd as wm,de as km,df as Nm,dg as Cm,dh as jn,di as Sm,dj as Am,dk as fs,dl as wd,dm as vt,dn as Tm,dp as Mm,g as io,dq as oo,dr as vr,ds as jr,dt as la,du as wr,dv as Di,dw as Ii,dx as Bi,dy as ws,dz as wn,dA as ds,dB as ya,dC as lr,dD as Ct,bI as Vl,dE as Em,dF as za,dG as cr,dH as kn,dI as Ns,dJ as va,dK as Rm,dL as Zr,dM as Os,dN as Pm,dO as zm,dP as xs,dQ as kd,dR as Dm,dS as Nd,dT as Ul,dU as Im,dV as Bm,dW as Pr,dX as Cd,dY as ln,dZ as cn,d_ as En,d$ as rs,T as Fm,$ as Lm,e0 as Bn,c8 as an,e1 as Sd,a0 as $m,bA as Om,ci as _m,cl as ol,e2 as Ad,e3 as Vm,b2 as lo,b4 as Kl,b0 as Um,b6 as Km,b7 as Ym,bk as Nn,aa as ba,an as Ma,bt as ti,e4 as rn,av as Xm,at as Gm,al as Hm,cb as Td,a$ as Wm,e5 as qm,e6 as Qm,e7 as ht,a3 as Jm,e8 as dn,a8 as ar,a7 as fa,b8 as Md,bc as Ed,bd as Zm,ba as ep,c6 as tp,c9 as sp,U as Yl,Y as Xl,X as Gl,e9 as Rd,ea as Pd,eb as zd,ec as Dd,ed as Rn,ee as Pn,ef as ll,aX as ap,bi as rp,ao as np,eg as Fn,eh as Ln,ei as $n,cd as ip,cf as op,cj as lp,ej as Hl,ek as Wl,el as ql,em as Ql,en as Id,as as cp,eo as Pa,ep as Bd,eq as en,er as Jl,es as Zl,et as ec,cc as Fi,eu as dp,ev as up,ew as mp,ex as pp,ey as xp,ez as hp,eA as fp}from"./index-Dws9LQij.js";import{c as un,p as Fd,s as Ld}from"./zustand-CnPgS7xu.js";import{W as $d,S as Od,O as _d,A as gp,D as bp,C as tc,N as ga,a as sc,M as ac,b as Si,c as kr,d as si,P as ai,e as Ga,G as yp,T as vp,f as co,g as Vr,I as jp,h as wp,i as kp,j as Np,k as Cp,B as Sp,l as Ap,F as Tp,m as Mp,n as ri,o as Ep,p as Rp}from"./three-D1sxpTQl.js";/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Pp=[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M12 2v20",key:"t6zp3m"}]],Vd=he("align-horizontal-justify-center",Pp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zp=[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"12",y:"7",rx:"2",key:"1ht384"}],["path",{d:"M22 2v20",key:"40qfg1"}]],Dp=he("align-horizontal-justify-end",zp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ip=[["rect",{width:"6",height:"14",x:"6",y:"5",rx:"2",key:"hsirpf"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M2 2v20",key:"1ivd8o"}]],Bp=he("align-horizontal-justify-start",Ip);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fp=[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Ud=he("align-vertical-justify-center",Fp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Lp=[["rect",{width:"14",height:"6",x:"5",y:"12",rx:"2",key:"4l4tp2"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 22h20",key:"272qi7"}]],$p=he("align-vertical-justify-end",Lp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Op=[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"6",rx:"2",key:"13squh"}],["path",{d:"M2 2h20",key:"1ennik"}]],_p=he("align-vertical-justify-start",Op);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vp=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Up=he("archive",Vp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Kp=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Kd=he("arrow-down",Kp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yp=[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]],Xp=he("arrow-left-to-line",Yp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Gp=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Yi=he("arrow-left",Gp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hp=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Yd=he("arrow-up",Hp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wp=[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]],qp=he("bold",Wp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Qp=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]],Jp=he("bookmark-plus",Qp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Zp=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],cl=he("camera",Zp);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ex=[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]],Xi=he("captions",ex);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const tx=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],dl=he("chevron-left",tx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const sx=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],ul=he("circle-check-big",sx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ax=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],rx=he("circle-question-mark",ax);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nx=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]],ix=he("clipboard",nx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ox=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Xd=he("cloud",ox);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lx=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],cx=he("command",lx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dx=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],ux=he("cpu",dx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mx=[["path",{d:"M6 2v14a2 2 0 0 0 2 2h14",key:"ron5a4"}],["path",{d:"M18 22V8a2 2 0 0 0-2-2H2",key:"7s9ehn"}]],px=he("crop",mx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]],hx=he("crosshair",xx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fx=[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z",key:"1f1r0c"}]],Gi=he("diamond",fx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gx=[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]],bx=he("droplet",gx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yx=[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]],Gd=he("droplets",yx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vx=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],jx=he("ellipsis",vx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wx=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Xs=he("eye-off",wx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kx=[["path",{d:"M12 6a2 2 0 0 1 3.414-1.414l6 6a2 2 0 0 1 0 2.828l-6 6A2 2 0 0 1 12 18z",key:"b19h5q"}],["path",{d:"M2 6a2 2 0 0 1 3.414-1.414l6 6a2 2 0 0 1 0 2.828l-6 6A2 2 0 0 1 2 18z",key:"h7h5ge"}]],ni=he("fast-forward",kx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nx=[["path",{d:"M11 21a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1",key:"likhh7"}],["path",{d:"M16 16a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1",key:"17ky3x"}],["path",{d:"M21 6a2 2 0 0 0-.586-1.414l-2-2A2 2 0 0 0 17 2h-3a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1z",key:"1hyeo0"}]],Cx=he("file-stack",Nx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Sx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ax=he("file-text",Sx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Tx=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Mx=he("flag",Tx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ex=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Rx=he("folder-plus",Ex);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Px=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],zx=he("folder",Px);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Dx=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Hd=he("gauge",Dx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ix=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Wd=he("globe",Ix);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bx=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]],Fx=he("grid-2x2",Bx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Lx=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],$x=he("grip-vertical",Lx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ox=[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]],qd=he("hard-drive",Ox);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _x=[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]],Qd=he("hexagon",_x);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vx=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Ai=he("history",Vx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ux=[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",key:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]],Kx=he("images",Ux);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yx=[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]],Xx=he("italic",Yx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Gx=[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],Hx=he("key-round",Gx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wx=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],zn=he("key",Wx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qx=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],rc=he("keyboard",qx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Qx=[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]],Jx=he("languages",Qx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Zx=[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]],eh=he("layout-template",Zx);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const th=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],sh=he("lightbulb",th);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ah=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],rh=he("link",ah);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nh=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],ih=he("list",nh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const oh=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]],lh=he("lock-open",oh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ch=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Li=he("lock",ch);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dh=[["path",{d:"m12 15 4 4",key:"lnac28"}],["path",{d:"M2.352 10.648a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.029-6.029a1 1 0 1 1 3 3l-6.029 6.029a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.365-6.367A1 1 0 0 0 8.716 4.282z",key:"nlhkjb"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}]],uh=he("magnet",dh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mh=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],zr=he("maximize-2",mh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ph=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],xh=he("message-square",ph);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hh=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M16.95 16.95A7 7 0 0 1 5 12v-2",key:"cqa7eg"}],["path",{d:"M18.89 13.23A7 7 0 0 0 19 12v-2",key:"16hl24"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}]],Jd=he("mic-off",hh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fh=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Rr=he("mic",fh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],ml=he("minimize-2",gh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bh=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],Zd=he("moon",bh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],vh=he("panels-top-left",yh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jh=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],dr=he("pause",jh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wh=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],kh=he("pen-line",wh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nh=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],eu=he("pen",Nh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ch=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],tu=he("pencil",Ch);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Sh=[["path",{d:"M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z",key:"2hea0t"}]],Ah=he("pentagon",Sh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Th=[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]],Mh=he("picture-in-picture-2",Th);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Eh=[["path",{d:"m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12",key:"1y3wsu"}],["path",{d:"m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z",key:"110lr1"}],["path",{d:"m2 22 .414-.414",key:"jhxm08"}]],Rh=he("pipette",Eh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ph=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],cs=he("plus",Ph);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zh=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]],pl=he("redo-2",zh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Dh=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],na=he("refresh-cw",Dh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ih=[["path",{d:"M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z",key:"2a1g8i"}],["path",{d:"M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z",key:"rg3s36"}]],uo=he("rewind",Ih);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bh=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Fh=he("rotate-cw",Bh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Lh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],$h=he("rows-2",Lh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oh=[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],nc=he("route",Oh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _h=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]],Vh=he("rows-3",_h);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Uh=[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]],xl=he("scissors",Uh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Kh=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Dn=he("settings-2",Kh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yh=[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]],mn=he("shapes",Yh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Xh=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],ii=he("share-2",Xh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Gh=[["path",{d:"M12 2v13",key:"1km8f5"}],["path",{d:"m16 6-4-4-4 4",key:"13yo43"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}]],Hh=he("share",Gh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wh=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],qh=he("shield-check",Wh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Qh=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],ic=he("shield",Qh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Jh=[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]],Zh=he("shuffle",Jh);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ef=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],tf=he("skip-back",ef);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const sf=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],af=he("skip-forward",sf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rf=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],nf=he("sliders-horizontal",rf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const of=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],su=he("smile",of);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lf=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],gs=he("sparkles",lf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cf=[["path",{d:"M8.34 8.34 2 9.27l5 4.87L5.82 21 12 17.77 18.18 21l-.59-3.43",key:"16m0ql"}],["path",{d:"M18.42 12.76 22 9.27l-6.91-1L12 2l-1.44 2.91",key:"1vt8nq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]],au=he("star-off",cf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const df=[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14.837 16.385a6 6 0 1 1-7.223-7.222c.624-.147.97.66.715 1.248a4 4 0 0 0 5.26 5.259c.589-.255 1.396.09 1.248.715",key:"xlf6rm"}],["path",{d:"M16 12a4 4 0 0 0-4-4",key:"6vsxu"}],["path",{d:"m19 5-1.256 1.256",key:"1yg6a6"}],["path",{d:"M20 12h2",key:"1q8mjw"}]],uf=he("sun-moon",df);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mf=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],ru=he("sun",mf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Uo=he("target",pf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xf=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],hf=he("text-align-center",xf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ff=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],gf=he("text-align-end",ff);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bf=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],nu=he("text-align-start",bf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yf=[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]],vf=he("thermometer",yf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jf=[["path",{d:"M13.73 4a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"14u9p9"}]],iu=he("triangle",jf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wf=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],kf=he("underline",wf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nf=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],pn=he("undo-2",Nf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Cf=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],hl=he("user",Cf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Sf=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],Ts=he("volume-2",Sf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Af=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],$i=he("volume-x",Af);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Tf=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],ou=he("zoom-in",Tf);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Mf=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],Ef=he("zoom-out",Mf),fl=[{id:"social-media",name:"Social Media",icon:"share"},{id:"youtube",name:"YouTube",icon:"youtube"},{id:"tiktok",name:"TikTok",icon:"smartphone"},{id:"instagram",name:"Instagram",icon:"instagram"},{id:"business",name:"Business",icon:"briefcase"},{id:"personal",name:"Personal",icon:"user"},{id:"slideshow",name:"Slideshow",icon:"images"},{id:"intro-outro",name:"Intro/Outro",icon:"play"},{id:"lower-third",name:"Lower Third",icon:"subtitles"},{id:"custom",name:"Custom",icon:"folder"}],Rf=[{id:"electronic",name:"Electronic"},{id:"cinematic",name:"Cinematic"},{id:"pop",name:"Pop"},{id:"rock",name:"Rock"},{id:"hip-hop",name:"Hip-Hop"},{id:"jazz",name:"Jazz"},{id:"classical",name:"Classical"},{id:"ambient",name:"Ambient"},{id:"lofi",name:"Lo-Fi"},{id:"corporate",name:"Corporate"},{id:"upbeat",name:"Upbeat"},{id:"dramatic",name:"Dramatic"}],Pf=[{id:"transitions",name:"Transitions"},{id:"whoosh",name:"Whoosh"},{id:"impacts",name:"Impacts"},{id:"ui",name:"UI Sounds"},{id:"nature",name:"Nature"},{id:"human",name:"Human"},{id:"mechanical",name:"Mechanical"},{id:"musical",name:"Musical"},{id:"cartoon",name:"Cartoon"},{id:"horror",name:"Horror"},{id:"sci-fi",name:"Sci-Fi"}],zf=[{id:"happy",name:"Happy",color:"#FFD700"},{id:"sad",name:"Sad",color:"#6B8E9F"},{id:"energetic",name:"Energetic",color:"#FF4500"},{id:"calm",name:"Calm",color:"#87CEEB"},{id:"tense",name:"Tense",color:"#8B0000"},{id:"romantic",name:"Romantic",color:"#FF69B4"},{id:"inspiring",name:"Inspiring",color:"#FFD700"},{id:"mysterious",name:"Mysterious",color:"#4B0082"},{id:"playful",name:"Playful",color:"#FFA500"},{id:"dark",name:"Dark",color:"#1A1A2E"},{id:"bright",name:"Bright",color:"#FFFF00"},{id:"nostalgic",name:"Nostalgic",color:"#D4A574"}],Df={cutMode:"beats",minClipDuration:.3,maxClipDuration:10,sensitivity:.5};class If{generateCuts(s,a,r=Df){if(a.length===0||s.beats.length===0)return{cuts:[],totalDuration:0,beatCount:0};const n=this.getCutPoints(s,r),i=this.filterByMinDuration(n,r.minClipDuration),o=[];let c=0,d=0;for(let u=0;ur.maxClipDuration)continue;const h=a[d%a.length],f=h.outPoint-h.inPoint,v=h.inPoint+u*x%Math.max(f-x,x);o.push({sourceClipId:h.id,inPoint:Math.min(v,h.outPoint-x),outPoint:Math.min(v+x,h.outPoint),startTime:c,duration:x}),c+=x,d++}return{cuts:o,totalDuration:c,beatCount:i.length}}getCutPoints(s,a){switch(a.cutMode){case"downbeats":return[0,...s.downbeats].sort((r,n)=>r-n);case"beats":{const r=1-a.sensitivity;return[0,...s.beats.filter(i=>i.strength>=r).map(i=>i.time)].sort((i,o)=>i-o)}case"segments":{const r=Math.max(2,Math.round(4*(1-a.sensitivity)+1)),n=[0];for(let i=0;i=a&&r.push(s[n])}return r}}let mo=null;function Bf(){return mo||(mo=new If),mo}const Vs={particleCount:100,speed:100,speedVariance:50,gravity:200,wind:{x:0,y:0,z:0},turbulence:10,colors:["#ffffff"],size:{min:2,max:8},opacity:{start:1,end:0},lifetime:{min:.5,max:2},emissionRate:50,emissionShape:"point",emissionRadius:10,rotationSpeed:0,fadeIn:.1,fadeOut:.3,blendMode:"add"};function Ff(){return["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion"]}function Lf(t){return{normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"}[t]||t}const oc=[{id:"flash",name:"Flash",description:"Quick burst of speed in the middle",keyframes:[{time:0,speed:.5,easing:"easeInQuad"},{time:.3,speed:4,easing:"easeOutQuad"},{time:.7,speed:4,easing:"easeInQuad"},{time:1,speed:.5,easing:"linear"}]},{id:"smooth-slow-mo",name:"Smooth Slow-Mo",description:"Gradual slow down and speed up",keyframes:[{time:0,speed:1,easing:"easeInOutCubic"},{time:.3,speed:.3,easing:"linear"},{time:.7,speed:.3,easing:"easeInOutCubic"},{time:1,speed:1,easing:"linear"}]},{id:"jump-cut",name:"Jump Cut",description:"Alternating fast and normal speed",keyframes:[{time:0,speed:1,easing:"linear"},{time:.2,speed:3,easing:"linear"},{time:.4,speed:1,easing:"linear"},{time:.6,speed:3,easing:"linear"},{time:.8,speed:1,easing:"linear"},{time:1,speed:3,easing:"linear"}]},{id:"montage",name:"Montage",description:"Gradual acceleration throughout",keyframes:[{time:0,speed:1,easing:"easeInQuart"},{time:.5,speed:1.5,easing:"easeInQuart"},{time:1,speed:3,easing:"linear"}]},{id:"hero-moment",name:"Hero Moment",description:"Dramatic slow-down at the peak",keyframes:[{time:0,speed:1.5,easing:"easeInCubic"},{time:.35,speed:.2,easing:"linear"},{time:.65,speed:.2,easing:"easeOutCubic"},{time:1,speed:1.5,easing:"linear"}]},{id:"bullet-time",name:"Bullet Time",description:"Near freeze in the center",keyframes:[{time:0,speed:2,easing:"easeInExpo"},{time:.4,speed:.1,easing:"linear"},{time:.6,speed:.1,easing:"easeOutExpo"},{time:1,speed:2,easing:"linear"}]}];function lc(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}class $f{trackingJobs=new Map;trackingData=new Map;attachments=new Map;progressCallbacks=new Set;lostCallbacks=new Set;constructor(){}async startTracking(s,a,r={}){const n=lc("track-job"),i={id:n,clipId:s,region:a,status:"pending",progress:0,options:{frameRate:r.frameRate??30,startFrame:r.startFrame??0,endFrame:r.endFrame??300,algorithm:r.algorithm??"correlation",confidenceThreshold:r.confidenceThreshold??.7},startTime:Date.now()};return this.trackingJobs.set(n,i),this.runTracking(i),i}async runTracking(s){s.status="running",this.trackingJobs.set(s.id,s);const{startFrame:a,endFrame:r,frameRate:n,confidenceThreshold:i}=s.options,o=(r??300)-(a??0),c=[],d=[],u=[];for(let x=0;x<=o;x++){const h=this.trackingJobs.get(s.id);if(!h||h.status==="cancelled")return;const f=(a??0)+x,v=this.simulateTracking(s.region,f,x);c.push({frame:f,position:v.position,scale:v.scale,rotation:v.rotation}),d.push(v.confidence),v.confidence<(i??.7)&&(u.push(f),this.notifyTrackingLost(f)),s.progress=x/o*100,this.trackingJobs.set(s.id,s),this.notifyProgress(s.progress),await new Promise(A=>setTimeout(A,0))}const p=lc("track"),m={trackId:p,clipId:s.clipId,keyframes:c,confidence:d,lostFrames:u,region:s.region,frameRate:n??30};this.trackingData.set(p,m),s.status="completed",s.progress=100,s.endTime=Date.now(),this.trackingJobs.set(s.id,s)}simulateTracking(s,a,r){const n=s.x+s.width/2,i=s.y+s.height/2,o=Math.sin(r*.1)*50,c=Math.cos(r*.15)*30,d=(Math.random()-.5)*2,u=(Math.random()-.5)*2,p=r%50===0?.5:.85+Math.random()*.15;return{position:{x:n+o+d,y:i+c+u},scale:1+Math.sin(r*.05)*.1,rotation:Math.sin(r*.02)*.1,confidence:p}}cancelTracking(s){const a=this.trackingJobs.get(s);a&&a.status==="running"&&(a.status="cancelled",a.endTime=Date.now(),this.trackingJobs.set(s,a))}getTrackingJob(s){return this.trackingJobs.get(s)}getTrackingData(s,a){const r=this.trackingData.get(a);if(r&&r.clipId===s)return r}getTrackingDataForClip(s){return Array.from(this.trackingData.values()).filter(a=>a.clipId===s)}applyTrackingToElement(s,a,r={x:0,y:0}){if(!this.trackingData.get(s))throw new Error(`Tracking data not found: ${s}`);const i={elementId:a,trackId:s,offset:r,applyScale:!0,applyRotation:!0};this.attachments.set(a,i)}removeTrackingFromElement(s){this.attachments.delete(s)}getAttachment(s){return this.attachments.get(s)}getAttachmentsForTrack(s){return Array.from(this.attachments.values()).filter(a=>a.trackId===s)}getElementPositionAtTime(s,a){const r=this.attachments.get(s);if(!r)return null;const n=this.trackingData.get(r.trackId);if(!n)return null;const i=Math.floor(a*n.frameRate),o=this.getTrackedPositionAtFrame(n,i);return o?{x:o.x+r.offset.x,y:o.y+r.offset.y}:null}getTrackedPositionAtFrame(s,a){if(s.keyframes.length===0)return null;let r=null,n=null;for(const o of s.keyframes)if(o.frame<=a)r=o;else if(!n){n=o;break}if(!r)return s.keyframes[0].position;if(!n||r.frame===a)return r.position;const i=(a-r.frame)/(n.frame-r.frame);return{x:r.position.x+(n.position.x-r.position.x)*i,y:r.position.y+(n.position.y-r.position.y)*i}}onTrackingProgress(s){return this.progressCallbacks.add(s),()=>this.progressCallbacks.delete(s)}onTrackingLost(s){return this.lostCallbacks.add(s),()=>this.lostCallbacks.delete(s)}notifyProgress(s){for(const a of this.progressCallbacks)a(s)}notifyTrackingLost(s){for(const a of this.lostCallbacks)a(s)}correctTrackingPoint(s,a,r){const n=this.trackingData.get(s);if(!n)throw new Error(`Tracking data not found: ${s}`);const i=n.keyframes.findIndex(o=>o.frame===a);if(i>=0){n.keyframes[i].position=r,n.confidence[i]=1;const o=n.lostFrames.indexOf(a);o>=0&&n.lostFrames.splice(o,1)}else{const o={frame:a,position:r,scale:1,rotation:0};let c=n.keyframes.findIndex(d=>d.frame>a);c===-1&&(c=n.keyframes.length),n.keyframes.splice(c,0,o),n.confidence.splice(c,0,1)}this.trackingData.set(s,n)}setTrackingOffset(s,a){const r=this.attachments.get(s);r&&(r.offset=a,this.attachments.set(s,r))}getTrackingOffset(s){return this.attachments.get(s)?.offset??null}setApplyScale(s,a){const r=this.attachments.get(s);r&&(r.applyScale=a,this.attachments.set(s,r))}setApplyRotation(s,a){const r=this.attachments.get(s);r&&(r.applyRotation=a,this.attachments.set(s,r))}deleteTrackingData(s){for(const[a,r]of this.attachments)r.trackId===s&&this.attachments.delete(a);this.trackingData.delete(s)}deleteTrackingDataForClip(s){for(const[a,r]of this.trackingData)r.clipId===s&&this.deleteTrackingData(a)}clear(){this.trackingJobs.clear(),this.trackingData.clear(),this.attachments.clear()}getTrackIds(){return Array.from(this.trackingData.keys())}hasTracking(s){return this.attachments.has(s)}}let po=null;function Of(){return po||(po=new $f),po}const lu=[{id:"cinematic-teal-orange",name:"Teal & Orange",category:"cinematic",description:"Classic Hollywood color grade",effects:[{type:"contrast",params:{value:1.15}},{type:"saturation",params:{value:1.1}},{type:"vignette",params:{amount:.25,midpoint:.5,roundness:.5,feather:.8}}]},{id:"cinematic-noir",name:"Film Noir",category:"cinematic",description:"High contrast black & white",effects:[{type:"saturation",params:{value:0}},{type:"contrast",params:{value:1.4}},{type:"brightness",params:{value:-.05}},{type:"vignette",params:{amount:.4,midpoint:.4,roundness:.5,feather:.6}},{type:"grain",params:{amount:.15,size:1.5,roughness:.5,colored:!1}}]},{id:"cinematic-blockbuster",name:"Blockbuster",category:"cinematic",description:"Bold, punchy Hollywood look",effects:[{type:"contrast",params:{value:1.2}},{type:"saturation",params:{value:1.15}},{type:"brightness",params:{value:.05}},{type:"sharpen",params:{amount:.3,radius:1,threshold:10}}]},{id:"vintage-70s",name:"70s Retro",category:"vintage",description:"Warm, faded 1970s aesthetic",effects:[{type:"saturation",params:{value:.85}},{type:"contrast",params:{value:.9}},{type:"brightness",params:{value:.05}},{type:"grain",params:{amount:.2,size:2,roughness:.6,colored:!0}}]},{id:"vintage-polaroid",name:"Polaroid",category:"vintage",description:"Classic instant photo look",effects:[{type:"contrast",params:{value:1.1}},{type:"saturation",params:{value:.9}},{type:"vignette",params:{amount:.3,midpoint:.5,roundness:.3,feather:.85}}]},{id:"vintage-vhs",name:"VHS",category:"vintage",description:"Nostalgic VHS tape effect",effects:[{type:"saturation",params:{value:.8}},{type:"contrast",params:{value:1.15}},{type:"blur",params:{radius:.5,type:"gaussian"}},{type:"grain",params:{amount:.25,size:2.5,roughness:.7,colored:!0}}]},{id:"vintage-sepia",name:"Sepia",category:"vintage",description:"Classic sepia tone",effects:[{type:"saturation",params:{value:.3}},{type:"contrast",params:{value:1.05}},{type:"brightness",params:{value:.1}}]},{id:"mood-dreamy",name:"Dreamy",category:"mood",description:"Soft, ethereal atmosphere",effects:[{type:"brightness",params:{value:.1}},{type:"saturation",params:{value:.85}},{type:"blur",params:{radius:1,type:"gaussian"}},{type:"contrast",params:{value:.9}}]},{id:"mood-moody",name:"Moody",category:"mood",description:"Dark, atmospheric feel",effects:[{type:"brightness",params:{value:-.15}},{type:"contrast",params:{value:1.25}},{type:"saturation",params:{value:.75}},{type:"vignette",params:{amount:.35,midpoint:.4,roundness:.5,feather:.7}}]},{id:"mood-golden-hour",name:"Golden Hour",category:"mood",description:"Warm sunset lighting",effects:[{type:"brightness",params:{value:.1}},{type:"saturation",params:{value:1.2}},{type:"contrast",params:{value:1.05}}]},{id:"mood-cold",name:"Cold Blue",category:"mood",description:"Cool, icy atmosphere",effects:[{type:"saturation",params:{value:.9}},{type:"brightness",params:{value:.05}},{type:"contrast",params:{value:1.1}}]},{id:"color-vibrant",name:"Vibrant",category:"color",description:"Punchy, saturated colors",effects:[{type:"saturation",params:{value:1.4}},{type:"contrast",params:{value:1.15}},{type:"brightness",params:{value:.05}}]},{id:"color-muted",name:"Muted",category:"color",description:"Soft, desaturated palette",effects:[{type:"saturation",params:{value:.6}},{type:"contrast",params:{value:.95}},{type:"brightness",params:{value:.05}}]},{id:"color-bw-classic",name:"B&W Classic",category:"color",description:"Timeless black & white",effects:[{type:"saturation",params:{value:0}},{type:"contrast",params:{value:1.1}}]},{id:"color-bw-high-contrast",name:"B&W High Contrast",category:"color",description:"Dramatic black & white",effects:[{type:"saturation",params:{value:0}},{type:"contrast",params:{value:1.5}},{type:"brightness",params:{value:-.05}}]},{id:"stylized-cyberpunk",name:"Cyberpunk",category:"stylized",description:"Neon-lit futuristic look",effects:[{type:"saturation",params:{value:1.3}},{type:"contrast",params:{value:1.3}},{type:"vignette",params:{amount:.3,midpoint:.45,roundness:.5,feather:.75}}]},{id:"stylized-comic",name:"Comic Book",category:"stylized",description:"Bold, graphic novel style",effects:[{type:"contrast",params:{value:1.5}},{type:"saturation",params:{value:1.4}},{type:"sharpen",params:{amount:.5,radius:1.5,threshold:5}}]},{id:"stylized-soft-glow",name:"Soft Glow",category:"stylized",description:"Romantic soft focus effect",effects:[{type:"brightness",params:{value:.15}},{type:"blur",params:{radius:1.5,type:"gaussian"}},{type:"contrast",params:{value:.85}},{type:"saturation",params:{value:.9}}]}],cc=[{id:"cinematic",name:"Cinematic",icon:"film"},{id:"vintage",name:"Vintage",icon:"camera"},{id:"mood",name:"Mood",icon:"moon"},{id:"color",name:"Color",icon:"palette"},{id:"stylized",name:"Stylized",icon:"sparkles"}];function _f(t){return lu.filter(s=>s.category===t)}let js=null,xo=null;async function Vf(){if(typeof WebAssembly>"u")return null;try{const t=new URL("data:application/wasm;base64,AGFzbQEAAAABNwlgBH9/f38AYAJ/fwF/YAF/AX1gAX8Bf2ADf39/AGAEf39/fwF9YAR/fX9/AX9gAn99AX1gAAACDQEDZW52BWFib3J0AAADDQwABAEBBQIGAgcDAwgFAwEAAQYGAX8BQQALB4kBCRJjb21wdXRlUk1TRW5lcmdpZXMAAQtzbW9vdGhBcnJheQACD2NhbGN1bGF0ZU1lZGlhbgAGCWZpbmRQZWFrcwAHDWNhbGN1bGF0ZU1lYW4ACA9jYWxjdWxhdGVTdGREZXYACQthbGxvY2F0ZUYzMgAKC2FsbG9jYXRlSTMyAAsGbWVtb3J5AgAIAQwMAQgK5gsMmAICAn0JfyAAKAIIQQJ2IQggAygCCEECdiEKQwAAgD8gAbKVIQUDQCAHIApIBEAgAiAHbCEJQwAAAAAhBEEAIQYgAUEEayELA0AgBiALSARAIAYgCWoiDUEDaiIMIAhIBEAgBCAAKAIEIg4gDUECdGoqAgAiBCAElCANQQFqQQJ0IA5qKgIAIgQgBJSSIA1BAmpBAnQgDmoqAgAiBCAElJIgDEECdCAOaioCACIEIASUkpIhBAsgBkEEaiEGDAELCwNAIAEgBkoEQCAGIAlqIgsgCEgEQCAEIAAoAgQgC0ECdGoqAgAiBCAElJIhBAsgBkEBaiEGDAELCyADKAIEIAdBAnRqIAQgBZSROAIAIAdBAWohBwwBCwsLmwECBH8CfSAAKAIIQQJ2IQQgAkEBdSEFQwAAgD8gArKVIQgDQCADIARIBEBDAAAAACEHIAMgBWpBAWohBiADIAVrIQIDQCACIAZIBEAgByAAKAIEIARBAWsgAiACIAROG0EAIAJBAE4bQQJ0aioCAJIhByACQQFqIQIMAQsLIAEoAgQgA0ECdGogByAIlDgCACADQQFqIQMMAQsLC8oBAQZ/IABB7P///wNLBEBBkAlB0AlB1gBBHhAAAAsgAEEQaiIEQfz///8DSwRAQZAJQdAJQSFBHRAAAAsjACEDIwBBBGoiAiAEQRNqQXBxQQRrIgRqIgU/ACIGQRB0QQ9qQXBxIgdLBEAgBiAFIAdrQf//A2pBgIB8cUEQdiIHIAYgB0obQABBAEgEQCAHQABBAEgEQAALCwsgBSQAIAMgBDYCACACQQRrIgNBADYCBCADQQA2AgggAyABNgIMIAMgADYCECACQRBqC2sBAX8gAEUEQEEMQQMQAyEACyAAQQA2AgAgAEEANgIEIABBADYCCCABQf////8ASwRAQaAIQdAIQRNBORAAAAsgAUECdCIBQQEQAyICQQAgAfwLACAAIAI2AgAgACACNgIEIAAgATYCCCAAC4ACAgR/A30gASACRgRAIAAoAgQgAUECdGoqAgAPCyAAKAIEIAJBAnRqKgIAIQkgAUEBayEFIAEhBANAIAIgBEoEQCAAKAIEIgcgBEECdCIGaioCACIKIAlfBEAgBUEBaiIFQQJ0IAdqIgcqAgAhCCAHIAo4AgAgACgCBCAGaiAIOAIACyAEQQFqIQQMAQsLIAAoAgQiBCAFQQFqIgVBAnRqIgYqAgAhCCAGIAJBAnQiBiAEaioCADgCACAAKAIEIAZqIAg4AgAgAyAFRgR9IAAoAgQgA0ECdGoqAgAFIAMgBUgEfSAAIAEgBUEBayADEAUFIAAgBUEBaiACIAMQBQsLC5MBAQR/IAAoAghBAnYiBEUEQEMAAAAADwtBDEEEEAMgBBAEIQEDQCACIARIBEAgAkECdCIDIAEoAgRqIAMgACgCBGoqAgA4AgAgAkEBaiECDAELCyAEQQF2IQAgBEEBcQR9IAFBACAEQQFrIAAQBQUgAUEAIARBAWsiAiAAQQFrEAUgAUEAIAIgABAFkkMAAAA/lAsLogECBX8BfSAAKAIIQQJ2IQZBACACayEEQQEhBQNAIAUgBkEBa0gEQCAAKAIEIgcgBUECdGoqAgAiCSAFQQFqQQJ0IAdqKgIAXiAJIAVBAWtBAnQgB2oqAgBecSABIAldcSAFIARrIAJOcQRAIAggAygCCEECdkgEQCADKAIEIAhBAnRqIAU2AgAgCEEBaiEIIAUhBAsLIAVBAWohBQwBCwsgCAtHAgJ/AX0gACgCCEECdiICRQRAQwAAAAAPCwNAIAEgAkgEQCADIAAoAgQgAUECdGoqAgCSIQMgAUEBaiEBDAELCyADIAKylQtQAgF9An8gACgCCEECdiIERQRAQwAAAAAPCwNAIAMgBEgEQCACIAAoAgQgA0ECdGoqAgAgAZMiAiAClJIhAiADQQFqIQMMAQsLIAIgBLKVkQsMAEEMQQQQAyAAEAQLDABBDEEFEAMgABAECwcAQfwJJAALC9kBCABBjAgLASwAQZgICyMCAAAAHAAAAEkAbgB2AGEAbABpAGQAIABsAGUAbgBnAHQAaABBvAgLATwAQcgICy0CAAAAJgAAAH4AbABpAGIALwBhAHIAcgBhAHkAYgB1AGYAZgBlAHIALgB0AHMAQfwICwE8AEGICQsvAgAAACgAAABBAGwAbABvAGMAYQB0AGkAbwBuACAAdABvAG8AIABsAGEAcgBnAGUAQbwJCwE8AEHICQslAgAAAB4AAAB+AGwAaQBiAC8AcgB0AC8AcwB0AHUAYgAuAHQAcw==",import.meta.url),s=await fetch(t);if(!s.ok)return null;const a=await s.arrayBuffer(),{instance:r}=await WebAssembly.instantiate(a,{env:{abort:()=>{throw new Error("WASM abort")}}});return r.exports}catch{return null}}async function cu(){return js?!0:(xo||(xo=Vf()),js=await xo,js!==null)}function Uf(t,s,a,r){const n=t.length,i=r.length,o=1/s;for(let c=0;c>1,i=1/a;for(let o=0;or-n),a=t.length>>1;return(t.length&1)===1?s[a]:(s[a-1]+s[a])*.5}function Xf(t,s,a,r){const n=t.length;let i=0,o=-a;for(let c=1;cu&&d>p&&d>s&&c-o>=a&&ip[f-1]&&v>=p[f+1],N=v>g,b=v-A>g*.3,j=f-x>=h;if(k&&N&&b&&j){const y=f*n/a;o.push(y),x=f}}return o}calculateAdaptiveThreshold(s,a){const n=[];for(let i=0;iA>=o&&A<=c);if(d.length<3)return{bpm:120,confidence:0};const u=new Map,p=1;for(const A of d){const g=Math.round(60/A/p)*p;g>=n&&g<=i&&u.set(g,(u.get(g)||0)+1);const k=Math.round(120/A/p)*p;k>=n&&k<=i&&u.set(k,(u.get(k)||0)+.5);const N=Math.round(30/A/p)*p;N>=n&&N<=i&&u.set(N,(u.get(N)||0)+.3)}let m=120,x=0;for(const[A,g]of u)g>x&&(x=g,m=A);const h=a*m/60,f=s.length,v=Math.min(1,Math.max(0,1-Math.abs(h-f)/h));return{bpm:m,confidence:v}}generateBeats(s,a,r){const n=60/s,i=[];let o=0;if(r.length>0){const d=r[0],u=Math.round(d/n);for(o=d-u*n;o<0;)o+=n}let c=0;for(let d=o;di%4===0).map(n=>n.time);const a=[],r=s.filter(n=>n.strength>.7);if(r.length>0){const n=r[0],i=s.findIndex(o=>o.time===n.time);for(let o=i;on.time>=a&&n.time<=r)}dispose(){this.audioContext&&this.audioContext instanceof AudioContext&&(this.audioContext.close(),this.audioContext=null)}}let fo=null;function gl(){return fo||(fo=new Jf),fo}function Zf(t,s,a=5){const r=t.getChannelData(0),n=t.sampleRate,i=t.duration,o=Math.ceil(i/a),c=[],d=Math.pow(10,-60/20);for(let u=0;u0?Math.sqrt(f/g):0,N=20*Math.log10(k||1e-4),b=20*Math.log10(v||1e-4),j=AT.start>=p&&T.start0?y.length/w:0;c.push({start:p,end:m,rmsDb:N,peakDb:b,speechRate:S,isSilence:j})}return{segments:c,duration:i}}const dc={fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.7)",position:"bottom"};class eg{config;audioContext=null;constructor(s){this.config={maxSegmentDuration:5,maxWordsPerSegment:10,...s}}async transcribeClip(s,a,r){try{r?.({phase:"extracting",progress:0,message:"Extracting audio from video..."});const n=await this.extractAudioFromClip(s,a);r?.({phase:"uploading",progress:25,message:"Uploading audio for transcription..."});const i=await this.sendToWhisper(n,r);r?.({phase:"processing",progress:90,message:"Processing transcription..."});const o=this.convertToSubtitles(i,s);return r?.({phase:"complete",progress:100,message:`Generated ${o.length} subtitles`}),o}catch(n){throw r?.({phase:"error",progress:0,message:n instanceof Error?n.message:"Transcription failed"}),n}}async extractAudioFromClip(s,a){this.audioContext||(this.audioContext=new AudioContext);let r;if(a.blob)r=await a.blob.arrayBuffer();else if(a.fileHandle)r=await(await a.fileHandle.getFile()).arrayBuffer();else throw new Error("No media source available for audio extraction");const n=await this.audioContext.decodeAudioData(r),i=s.inPoint||0,o=s.outPoint||n.duration,c=Math.min(o-i,s.duration),d=n.sampleRate,u=Math.floor(i*d),m=Math.floor((i+c)*d)-u,x=new OfflineAudioContext(1,m,d),h=x.createBufferSource(),f=x.createBuffer(1,m,d),v=f.getChannelData(0),A=n.getChannelData(0);for(let k=0;k{for(let N=0;NsetTimeout(d,3e3));const o=await fetch(s);if(!o.ok){if(o.status===404)throw new Error("Transcription job not found");continue}const c=await o.json();if(c.status==="processing"){const d=30+Math.round((c.progress||0)*.6);a?.({phase:"transcribing",progress:d,message:this.config.targetLanguage?`Transcribing and translating to ${this.config.targetLanguage}...`:"Transcribing audio..."});continue}if(c.status==="completed"&&c.result)return c.result;if(c.status==="failed")throw new Error(c.error||"Transcription failed on server")}throw new Error("Transcription timed out after 6 minutes")}convertToSubtitles(s,a){return!s.words||s.words.length===0?s.text?[{id:this.generateId(),text:s.text.trim(),startTime:a.startTime,endTime:a.startTime+a.duration,style:dc,words:void 0,animationStyle:"none"}]:[]:this.groupWordsIntoSubtitles(s.words,a.startTime)}groupWordsIntoSubtitles(s,a){const r=[],n=this.config.maxWordsPerSegment||10,i=this.config.maxSegmentDuration||5;let o=[],c=0;for(const d of s){o.length===0&&(c=d.start);const u=o.length>=n,p=d.end-c>i,m=/[.!?]$/.test(d.word);(u||p)&&o.length>0?(r.push(this.createSubtitleFromWords(o,a)),o=[d],c=d.start):(o.push(d),m&&o.length>=3&&(r.push(this.createSubtitleFromWords(o,a)),o=[]))}return o.length>0&&r.push(this.createSubtitleFromWords(o,a)),r}createSubtitleFromWords(s,a){const r=s.map(o=>o.word).join(" ").trim(),n=a+s[0].start,i=a+s[s.length-1].end;return{id:this.generateId(),text:r,startTime:n,endTime:i,style:dc,words:s.map(o=>({text:o.word,startTime:a+o.start,endTime:a+o.end})),animationStyle:"none"}}generateId(){return`sub-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}dispose(){this.audioContext&&(this.audioContext.close(),this.audioContext=null)}}let Cn=null;function tg(){return Cn}function du(t){return Cn&&Cn.dispose(),Cn=new eg(t),Cn}function bl(t,s,a){return Math.min(Math.max(t,s),a)}function sg(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function xn(t){return{segments:[{text:t.text,style:"normal",opacity:1,scale:1,offsetY:0}],visible:!0}}function ag(t,s){if(!t.words||t.words.length===0)return xn(t);const a=t.style?.highlightColor||"#ffff00",r=t.style?.upcomingColor;return{segments:t.words.map(i=>{const o=s>=i.startTime&&s=i.endTime,d=ss>=r.startTime&&s=r.endTime?{segments:[{text:r.text,style:"normal",opacity:1,scale:1,offsetY:0}],visible:!0}:{segments:[],visible:!1}}return{segments:[{text:a.text,style:"active",opacity:1,scale:1,offsetY:0}],visible:!0}}function ng(t,s){if(!t.words||t.words.length===0)return xn(t);const a=t.style?.highlightColor||"#ffff00",r=t.style?.upcomingColor||"rgba(255, 255, 255, 0.5)";return{segments:t.words.map(i=>{const o=i.endTime-i.startTime,c=s-i.startTime,d=bl(c/o,0,1),u=s=i.startTime&&s=i.endTime;let x="normal",h;return u?(x="normal",h=r):m?(x="highlighted",h=a):p&&(x="active",h=`linear-gradient(90deg, ${a} ${d*100}%, ${r} ${d*100}%)`),{text:i.text,style:x,opacity:1,scale:p?1.05:1,offsetY:0,color:h}}),visible:!0}}function ig(t,s){if(!t.words||t.words.length===0)return xn(t);const a=.3;return{segments:t.words.map(n=>{const i=s-n.startTime;if(!(s>=n.startTime))return{text:n.text,style:"hidden",opacity:0,scale:0,offsetY:20};const c=bl(i/a,0,1),d=sg(c),u=s>=n.startTime&&ss>=n.startTime);return a.length===0?{segments:[],visible:!1}:{segments:a.map((n,i)=>{const o=i===a.length-1,c=s-n.startTime,u=o?bl(c/.1,0,1):1;return{text:n.text,style:"normal",opacity:u,scale:1,offsetY:0}}),visible:!0}}function lg(t,s){if(st.endTime)return{segments:[],visible:!1};switch(t.animationStyle||"none"){case"word-highlight":return ag(t,s);case"word-by-word":return rg(t,s);case"karaoke":return ng(t,s);case"bounce":return ig(t,s);case"typewriter":return og(t,s);case"none":default:return xn(t)}}function uu(t){return{none:"Static","word-highlight":"Word Highlight","word-by-word":"Word by Word",karaoke:"Karaoke",bounce:"Bounce",typewriter:"Typewriter"}[t]}const mu=["none","word-highlight","word-by-word","karaoke","bounce","typewriter"],cg={syncMode:"smart",beatSubdivision:1,offsetMs:0,snapToDownbeats:!1};class dg{async analyzeBeats(s,a){a?.({phase:"analyzing",percent:20,message:"Analyzing audio for beats..."});const n=await gl().analyzeFromBlob(s);return a?.({phase:"complete",percent:100,message:`Detected ${n.bpm} BPM with ${n.beats.length} beats`}),n}calculateSyncedTimings(s,a,r,n){if(s.length===0||a.beats.length===0)return[];const i=[...s].sort((m,x)=>m.startTime-x.startTime),o=this.getSubdividedBeats(a,n),c=n.offsetMs/1e3,d=[];if(o.length<2)return[];const u=(o[o.length-1]-o[0])/(o.length-1);let p=0;for(const m of i){if(p>=o.length)break;const x=o[p]+r+c;switch(n.syncMode){case"preserve-duration":{d.push({clipId:m.id,originalStartTime:m.startTime,originalDuration:m.duration,newStartTime:x,newDuration:m.duration}),p++;break}case"one-per-beat":{const h=Math.min(p+1,o.length-1),v=o[h]+r+c-x;d.push({clipId:m.id,originalStartTime:m.startTime,originalDuration:m.duration,newStartTime:x,newDuration:Math.max(.1,v)}),p++;break}case"smart":default:{const h=Math.max(1,Math.round(m.duration/u)),f=Math.min(p+h,o.length-1),A=o[f]+r+c-x;d.push({clipId:m.id,originalStartTime:m.startTime,originalDuration:m.duration,newStartTime:x,newDuration:Math.max(.1,A)}),p=f;break}}}return d}getSubdividedBeats(s,a){const r=a.snapToDownbeats?s.beats.filter((i,o)=>o%4===0):s.beats;if(a.beatSubdivision===1)return r.map(i=>i.time);const n=[];for(let i=0;i0&&n.push(r[r.length-1].time),n}snapClipToNearestBeat(s,a,r,n=.2){const i=s-r;let o=a.beats[0],c=Math.abs(o.time-i);for(const d of a.beats){const u=Math.abs(d.time-i);u=1?{name:"Custom",ratio:a,width:1920,height:Math.round(1920/a)}:{name:"Custom",ratio:a,width:Math.round(1080*a),height:1080}}return Jr[s.targetAspectRatio]}async detectFaces(s,a){if(this.faceCache.has(a))return this.faceCache.get(a);const r=this.detectFacesSimple(s);return this.faceCache.set(a,r),r}detectFacesSimple(s){if(!this.ctx||!this.canvas)return[];this.canvas.width=s.width,this.canvas.height=s.height,this.ctx.drawImage(s,0,0);const a=this.ctx.getImageData(0,0,s.width,s.height),r=this.detectSkinRegions(a);return r.length===0?[{x:s.width*.3,y:s.height*.2,width:s.width*.4,height:s.height*.5,confidence:.3}]:r.map(n=>({x:n.x,y:n.y,width:n.width,height:n.height,confidence:n.confidence}))}detectSkinRegions(s){const{data:a,width:r,height:n}=s,i=new Uint8Array(r*n);for(let c=0;cc.width>r*.05&&c.height>n*.05).filter(c=>{const d=c.width/c.height;return d>.5&&d<2}).slice(0,3).map(c=>({...c,confidence:.7}))}isSkinColor(s,a,r){const n=Math.max(s,a,r),i=Math.min(s,a,r);return!(s<=95||a<=40||r<=20||n-i<=15||Math.abs(s-a)<=15||s<=a||s<=r||s>220&&a>210&&r>170)}findConnectedRegions(s,a,r){const n=new Uint8Array(a*r),i=[],o=8;for(let c=0;c0;){const[f,v]=h.pop(),A=v*r+f;f<0||f>=r||v<0||v>=n||a[A]||!s[A]||(a[A]=1,x++,d=Math.min(d,f),u=Math.max(u,f),p=Math.min(p,v),m=Math.max(m,v),h.push([f+c,v]),h.push([f-c,v]),h.push([f,v+c]),h.push([f,v-c]))}return x<10?null:{x:d,y:p,width:u-d+c,height:m-p+c}}calculateOptimalCrop(s,a,r,n,i,o,c){const d=s/a;let u,p;d>r?(p=a,u=p*r):(u=s,p=u/r);let m=(s-u)/2,x=(a-p)/2;if(i.followSubject&&n.length>0){const h=n.reduce((g,k)=>g.width*g.height*g.confidence>k.width*k.height*k.confidence?g:k),f=h.x+h.width/2,v=h.y+h.height/2,A=i.padding*Math.min(u,p);m=f-u/2+A*0,x=v-p*.35,m=m*(1-i.centerBias)+(s-u)/2*i.centerBias,x=x*(1-i.centerBias)+(a-p)/2*i.centerBias}if(m=Math.max(0,Math.min(m,s-u)),x=Math.max(0,Math.min(x,a-p)),o!==0||c!==0){const h=i.trackingSpeed;m=o+(m-o)*h,x=c+(x-c)*h}return{x:Math.round(m),y:Math.round(x),width:Math.round(u),height:Math.round(p)}}smoothKeyframes(s,a){if(s.length<3||a===0)return s;const r=[],n=Math.max(3,Math.round(a*10));for(let i=0;i=s[s.length-1].time)return s[s.length-1];for(let r=0;r=s[r].time&&as.id===t)}function yg(t,s,a,r,n){const i=bg(t);return i?{id:s,clipId:a,type:i.type,startTime:r,duration:n,config:{...i.config},enabled:!0}:null}const Ko="openreel_device_profile";function vg(t){return t>=8?"high":t>=4?"mid":"low"}function jg(t){return t>=8?"high":t>=4?"mid":"low"}function wg(t){const s=t.toLowerCase(),a=["nvidia rtx","nvidia geforce rtx","radeon rx 6","radeon rx 7","apple m1 pro","apple m1 max","apple m2","apple m3","intel arc"],r=["nvidia gtx 1","nvidia geforce gtx","radeon rx 5","apple m1","intel iris","intel uhd"];return a.some(n=>s.includes(n))?"high":r.some(n=>s.includes(n))?"mid":"low"}function kg(){const t=navigator.userAgent;let s="Unknown";t.includes("Windows")?s="Windows":t.includes("Mac")?s="macOS":t.includes("Linux")?s="Linux":t.includes("Android")?s="Android":t.includes("iPhone")||t.includes("iPad")?s="iOS":t.includes("CrOS")&&(s="ChromeOS");let a="Unknown";t.includes("Chrome")&&!t.includes("Edg")?a="Chrome":t.includes("Firefox")?a="Firefox":t.includes("Safari")&&!t.includes("Chrome")?a="Safari":t.includes("Edg")&&(a="Edge");const r=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t);return{os:s,browser:a,isMobile:r}}function Ng(){try{const t=document.createElement("canvas"),s=t.getContext("webgl2")||t.getContext("webgl")||t.getContext("experimental-webgl");if(!s)return{vendor:"Unknown",renderer:"Unknown",tier:"low"};const a=s.getExtension("WEBGL_debug_renderer_info");if(a){const r=s.getParameter(a.UNMASKED_VENDOR_WEBGL),n=s.getParameter(a.UNMASKED_RENDERER_WEBGL);return{vendor:r||"Unknown",renderer:n||"Unknown",tier:wg(n||"")}}return{vendor:"Unknown",renderer:"Unknown",tier:"mid"}}catch{return{vendor:"Unknown",renderer:"Unknown",tier:"low"}}}async function li(t,s,a){if(typeof VideoEncoder>"u")return{hardware:!1,supported:!1};try{const r={codec:t,width:s,height:a,bitrate:5e6,framerate:30},n=await VideoEncoder.isConfigSupported({...r,hardwareAcceleration:"prefer-hardware"}),i=await VideoEncoder.isConfigSupported({...r,hardwareAcceleration:"prefer-software"});return{hardware:n.supported===!0&&n.config?.hardwareAcceleration==="prefer-hardware",supported:n.supported===!0||i.supported===!0,maxResolution:{width:s,height:a}}}catch{return{hardware:!1,supported:!1}}}async function Cg(){const t={h264:"avc1.42001E",h265:"hvc1.1.6.L93.B0",vp9:"vp09.00.10.08",av1:"av01.0.04M.08"},[s,a,r,n]=await Promise.all([li(t.h264,1920,1080),li(t.h265,1920,1080),li(t.vp9,1920,1080),li(t.av1,1920,1080)]);return{h264:s,h265:a,vp9:r,av1:n}}function Sg(t,s,a){const r={low:1,mid:2,high:3},n=(r[t.tier]+r[s.tier]+r[a.tier]*1.5)/3.5;return n>=2.5?"high":n>=1.5?"mid":"low"}async function Ag(){const t=navigator.hardwareConcurrency||4,s=navigator.deviceMemory||4,a={cores:t,tier:vg(t)},r={gb:s,tier:jg(s)},n=Ng(),i=await Cg(),o=kg(),c=Object.values(i).some(m=>m.hardware),d={...n,hasHardwareEncoding:c},u=Sg(a,r,d),p=Tg();return{cpu:a,memory:r,gpu:d,encoding:i,platform:o,overallTier:u,benchmark:p}}function fc(t,s){const a=s.width*s.height>2073600,r=[];if(t.encoding.h264.supported){const n=t.encoding.h264.hardware;r.push({codec:"h264",label:"H.264 (MP4)",recommended:!0,reason:n?"Hardware accelerated":"Fast software encoding",speedRating:n?"fast":"medium",qualityRating:"good"})}if(t.encoding.h265.supported){const n=t.encoding.h265.hardware;r.push({codec:"h265",label:"H.265/HEVC (MP4)",recommended:n&&!a,reason:n?"Hardware accelerated, better compression":"Better compression, slower encoding",speedRating:n?"medium":"slow",qualityRating:"better"})}if(t.encoding.vp9.supported&&r.push({codec:"vp9",label:"VP9 (WebM)",recommended:!1,reason:"Good for web, software encoding only",speedRating:"slow",qualityRating:"better"}),t.encoding.av1.supported){const n=t.encoding.av1.hardware;r.push({codec:"av1",label:"AV1 (MP4/WebM)",recommended:n&&t.overallTier==="high",reason:n?"Best compression, hardware accelerated":"Best compression, very slow encoding",speedRating:n?"medium":"very-slow",qualityRating:"best"})}return r.sort((n,i)=>n.recommended&&!i.recommended?-1:!n.recommended&&i.recommended?1:0)}function Tg(){try{const t=localStorage.getItem(Ko);if(t){const s=JSON.parse(t),a=7*24*60*60*1e3;if(s.benchmark&&Date.now()-s.benchmark.testedAt2&&(s*=Math.max(.5,1-(t.trackCount-2)*.1)),s}function yc(t){if(t<60)return`~${Math.round(t)} seconds`;const s=Math.floor(t/60),a=Math.round(t%60);if(s<60)return a===0?`~${s} minute${s>1?"s":""}`:`~${s}m ${a}s`;const r=Math.floor(s/60),n=s%60;return`~${r}h ${n}m`}function xu(t,s){const a=Math.ceil(s.duration*s.frameRate);if(t.benchmark){const h=t.benchmark.resolution.width*t.benchmark.resolution.height,f=s.width*s.height,v=h/f;let A=1;if(t.benchmark.codec!==s.codec){const N={h264:1,h265:.4,vp9:.5,av1:.2};A=(N[t.benchmark.codec]||1)/(N[s.codec]||1)}const g=t.benchmark.framesPerSecond*v*A*bc(s),k=a/Math.max(1,g);return{seconds:k,formatted:yc(k),confidence:"measured",breakdown:{rendering:k*.4,encoding:k*.55,muxing:k*.05}}}const n=t.encoding[s.codec]?.hardware||!1,i=t.overallTier,c=`${n?"hardware":"software"}_${i}`,d=Rg[s.codec]?.[c]||15,u=Pg(s.width,s.height),p=bc(s),m=d*u*p,x=a/Math.max(1,m);return{seconds:x,formatted:yc(x),confidence:"estimated",breakdown:{rendering:x*.4,encoding:x*.55,muxing:x*.05}}}async function zg(t){t?.({phase:"preparing",progress:0,framesProcessed:0,totalFrames:60});const n=new OffscreenCanvas(1920,1080),i=n.getContext("2d");if(!i)throw new Error("Failed to create canvas context for benchmark");const o=[];for(let A=0;A<60;A++){i.fillStyle=`hsl(${A*6%360}, 70%, 50%)`,i.fillRect(0,0,1920,1080),i.fillStyle="white",i.font="48px sans-serif",i.fillText(`Frame ${A+1}`,1920/2-80,1080/2);const g=await createImageBitmap(n);o.push(g),t?.({phase:"rendering",progress:(A+1)/60*.3,framesProcessed:A+1,totalFrames:60})}if(typeof VideoEncoder>"u")throw o.forEach(A=>A.close()),new Error("VideoEncoder not supported");let c=0;const d=new VideoEncoder({output:A=>{c++,t?.({phase:"encoding",progress:.3+c/60*.65,framesProcessed:c,totalFrames:60})},error:A=>{console.error("Benchmark encoder error:",A)}}),u={codec:"avc1.42001E",width:1920,height:1080,bitrate:5e6,framerate:30,hardwareAcceleration:"prefer-hardware"};(await VideoEncoder.isConfigSupported(u)).supported||(u.hardwareAcceleration="prefer-software"),d.configure(u);const m=performance.now();for(let A=0;AA.close()),t?.({phase:"complete",progress:1,framesProcessed:60,totalFrames:60});const v={framesPerSecond:f,codec:"h264",resolution:{width:1920,height:1080},testedAt:Date.now()};return Mg(v),v}function Dg(t){if(!t.benchmark)return!0;const s=7*24*60*60*1e3;return Date.now()-t.benchmark.testedAt>s}const Ig=()=>typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",vc=t=>t==="auto"?Ig()==="dark":t==="dark",Oi=un()(Fd((t,s)=>({mode:"dark",isDark:!0,setMode:a=>{const r=vc(a);t({mode:a,isDark:r}),r?(document.documentElement.classList.add("dark"),document.documentElement.dataset.theme="dark"):(document.documentElement.classList.remove("dark"),document.documentElement.dataset.theme="light")},toggleTheme:()=>{const a=s().mode,r=a==="light"?"dark":a==="dark"?"auto":"light";s().setMode(r)}}),{name:"openreel-theme",onRehydrateStorage:()=>t=>{if(t){const s=vc(t.mode);t.isDark=s,s?(document.documentElement.classList.add("dark"),document.documentElement.dataset.theme="dark"):(document.documentElement.classList.remove("dark"),document.documentElement.dataset.theme="light")}}}));typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",s=>{if(Oi.getState().mode==="auto"){const r=s.matches;Oi.setState({isDark:r}),r?(document.documentElement.classList.add("dark"),document.documentElement.dataset.theme="dark"):(document.documentElement.classList.remove("dark"),document.documentElement.dataset.theme="light")}});const Bg=[{id:"youtube-4k",name:"YouTube 4K",description:"Best quality for YouTube 4K - 50Mbps",platform:"YouTube",category:"social",aspectRatio:"16:9",recommended:!0,settings:{format:"mp4",codec:"h264",width:3840,height:2160,frameRate:30,bitrate:5e4,bitrateMode:"vbr",quality:90,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:384,channels:2}}},{id:"youtube-4k-60",name:"YouTube 4K 60fps",description:"4K 60fps for gaming/motion - 65Mbps",platform:"YouTube",category:"social",aspectRatio:"16:9",settings:{format:"mp4",codec:"h264",width:3840,height:2160,frameRate:60,bitrate:65e3,bitrateMode:"vbr",quality:90,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:384,channels:2}}},{id:"youtube-1080p",name:"YouTube 1080p HD",description:"Standard HD quality for YouTube",platform:"YouTube",category:"social",aspectRatio:"16:9",settings:{format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:8e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:256,channels:2}}},{id:"youtube-shorts",name:"YouTube Shorts",description:"Vertical format for YouTube Shorts (60s max)",platform:"YouTube",category:"social",aspectRatio:"9:16",maxDuration:60,settings:{format:"mp4",codec:"h264",width:1080,height:1920,frameRate:60,bitrate:12e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:256,channels:2}}},{id:"tiktok",name:"TikTok",description:"Optimized for TikTok (3min max)",platform:"TikTok",category:"social",aspectRatio:"9:16",maxDuration:180,maxFileSize:287*1024*1024,recommended:!0,settings:{format:"mp4",codec:"h264",width:1080,height:1920,frameRate:60,bitrate:1e4,bitrateMode:"vbr",quality:85,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:192,channels:2}}},{id:"instagram-reels",name:"Instagram Reels",description:"Vertical format for Reels (90s max)",platform:"Instagram",category:"social",aspectRatio:"9:16",maxDuration:90,settings:{format:"mp4",codec:"h264",width:1080,height:1920,frameRate:30,bitrate:8e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:192,channels:2}}},{id:"instagram-feed",name:"Instagram Feed Video",description:"Square format for feed posts (60s max)",platform:"Instagram",category:"social",aspectRatio:"1:1",maxDuration:60,settings:{format:"mp4",codec:"h264",width:1080,height:1080,frameRate:30,bitrate:6e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:192,channels:2}}},{id:"instagram-story",name:"Instagram Story",description:"Vertical format for Stories (15s per clip)",platform:"Instagram",category:"social",aspectRatio:"9:16",maxDuration:15,settings:{format:"mp4",codec:"h264",width:1080,height:1920,frameRate:30,bitrate:6e3,bitrateMode:"vbr",quality:80,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:128,channels:2}}},{id:"twitter",name:"Twitter/X",description:"Optimized for Twitter (2min 20s max)",platform:"Twitter",category:"social",aspectRatio:"16:9",maxDuration:140,maxFileSize:512*1024*1024,settings:{format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:8e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:192,channels:2}}},{id:"facebook-feed",name:"Facebook Feed",description:"Standard format for Facebook feed",platform:"Facebook",category:"social",aspectRatio:"16:9",settings:{format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:8e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:192,channels:2}}},{id:"linkedin",name:"LinkedIn",description:"Professional format for LinkedIn (10min max)",platform:"LinkedIn",category:"social",aspectRatio:"16:9",maxDuration:600,maxFileSize:5*1024*1024*1024,settings:{format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:8e3,bitrateMode:"vbr",quality:85,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:192,channels:2}}}],Fg=[{id:"broadcast-4k-master",name:"4K Master Quality",description:"Maximum quality 4K - 80Mbps H.265",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",recommended:!0,settings:{format:"mov",codec:"h265",width:3840,height:2160,frameRate:30,bitrate:8e4,bitrateMode:"vbr",quality:95,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:24,bitrate:320,channels:2}}},{id:"broadcast-4k-prores-hq",name:"4K ProRes HQ",description:"Professional ProRes for editing/mastering",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"prores",proresProfile:"hq",width:3840,height:2160,frameRate:30,bitrate:88e4,bitrateMode:"cbr",quality:100,keyframeInterval:1,audioSettings:{format:"wav",sampleRate:48e3,bitDepth:24,bitrate:0,channels:2}}},{id:"broadcast-4k-prores-4444",name:"4K ProRes 4444",description:"Highest quality ProRes with alpha support",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"prores",proresProfile:"4444",width:3840,height:2160,frameRate:30,bitrate:132e4,bitrateMode:"cbr",quality:100,keyframeInterval:1,audioSettings:{format:"wav",sampleRate:48e3,bitDepth:24,bitrate:0,channels:2}}},{id:"broadcast-4k-60",name:"4K 60fps High Motion",description:"4K at 60fps for sports/gaming - 65Mbps",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"h265",width:3840,height:2160,frameRate:60,bitrate:65e3,bitrateMode:"vbr",quality:90,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:24,bitrate:320,channels:2}}},{id:"broadcast-4k",name:"Broadcast 4K UHD",description:"4K broadcast quality - 50Mbps",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"h264",width:3840,height:2160,frameRate:30,bitrate:5e4,bitrateMode:"cbr",quality:90,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:24,bitrate:320,channels:2}}},{id:"broadcast-1080p-high",name:"1080p High Quality",description:"High bitrate 1080p - 20Mbps",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:2e4,bitrateMode:"vbr",quality:95,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:24,bitrate:320,channels:2}}},{id:"broadcast-1080p-prores",name:"1080p ProRes HQ",description:"ProRes HQ for 1080p editing",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"prores",proresProfile:"hq",width:1920,height:1080,frameRate:30,bitrate:22e4,bitrateMode:"cbr",quality:100,keyframeInterval:1,audioSettings:{format:"wav",sampleRate:48e3,bitDepth:24,bitrate:0,channels:2}}},{id:"broadcast-hd",name:"Broadcast HD 1080p",description:"Standard broadcast quality",platform:"Broadcast",category:"broadcast",aspectRatio:"16:9",settings:{format:"mov",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:12e3,bitrateMode:"cbr",quality:85,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:24,bitrate:320,channels:2}}}],Lg=[{id:"web-hd",name:"Web HD",description:"Balanced quality for web embedding",platform:"Web",category:"web",aspectRatio:"16:9",recommended:!0,settings:{format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:5e3,bitrateMode:"vbr",quality:80,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:128,channels:2}}},{id:"web-small",name:"Web Optimized",description:"Smaller file size for faster loading",platform:"Web",category:"web",aspectRatio:"16:9",settings:{format:"mp4",codec:"h264",width:1280,height:720,frameRate:30,bitrate:2500,bitrateMode:"vbr",quality:75,keyframeInterval:90,audioSettings:{format:"aac",sampleRate:44100,bitDepth:16,bitrate:96,channels:2}}},{id:"webm-vp9",name:"WebM VP9",description:"Modern web format with VP9 codec (720p recommended)",platform:"Web",category:"web",aspectRatio:"16:9",settings:{format:"webm",codec:"vp9",width:1280,height:720,frameRate:30,bitrate:3e3,bitrateMode:"vbr",quality:80,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:128,channels:2}}}],$g=[{id:"archive-4k-prores",name:"Archive 4K ProRes",description:"Lossless 4K ProRes for long-term archival",platform:"Archive",category:"archive",aspectRatio:"16:9",recommended:!0,settings:{format:"mov",codec:"prores",proresProfile:"hq",width:3840,height:2160,frameRate:30,bitrate:88e4,bitrateMode:"cbr",quality:100,keyframeInterval:1,audioSettings:{format:"wav",sampleRate:96e3,bitDepth:24,bitrate:0,channels:2}}},{id:"archive-master",name:"Archive Master H.265",description:"High quality 4K H.265 - 80Mbps",platform:"Archive",category:"archive",aspectRatio:"16:9",settings:{format:"mov",codec:"h265",width:3840,height:2160,frameRate:30,bitrate:8e4,bitrateMode:"vbr",quality:95,keyframeInterval:30,audioSettings:{format:"wav",sampleRate:96e3,bitDepth:24,bitrate:0,channels:2}}},{id:"archive-1080p-prores",name:"Archive 1080p ProRes",description:"ProRes HQ for 1080p archival",platform:"Archive",category:"archive",aspectRatio:"16:9",settings:{format:"mov",codec:"prores",proresProfile:"hq",width:1920,height:1080,frameRate:30,bitrate:22e4,bitrateMode:"cbr",quality:100,keyframeInterval:1,audioSettings:{format:"wav",sampleRate:48e3,bitDepth:24,bitrate:0,channels:2}}},{id:"archive-proxy",name:"Archive Proxy",description:"Lower quality proxy for editing",platform:"Archive",category:"archive",aspectRatio:"16:9",settings:{format:"mp4",codec:"h264",width:1280,height:720,frameRate:30,bitrate:3e3,bitrateMode:"vbr",quality:70,keyframeInterval:30,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:128,channels:2}}}],Og=[{id:"audio-mp3-320",name:"MP3 High Quality",description:"320kbps MP3 for music",platform:"Audio",category:"custom",settings:{format:"mp3",sampleRate:48e3,bitDepth:16,bitrate:320,channels:2}},{id:"audio-wav",name:"WAV Lossless",description:"Uncompressed WAV audio",platform:"Audio",category:"archive",settings:{format:"wav",sampleRate:48e3,bitDepth:24,bitrate:0,channels:2}},{id:"audio-aac",name:"AAC High Quality",description:"256kbps AAC for compatibility",platform:"Audio",category:"custom",settings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:256,channels:2}}],_g=[...Bg,...Fg,...Lg,...$g,...Og],jc="openreel-custom-export-presets";class Vg{customPresets=[];listeners=new Set;constructor(){this.loadCustomPresets()}loadCustomPresets(){try{const s=localStorage.getItem(jc);s&&(this.customPresets=JSON.parse(s))}catch(s){console.error("[ExportPresets] Failed to load custom presets:",s)}}saveCustomPresets(){try{localStorage.setItem(jc,JSON.stringify(this.customPresets))}catch(s){console.error("[ExportPresets] Failed to save custom presets:",s)}}getAllPresets(){return[..._g,...this.customPresets]}getPresetsByCategory(s){return this.getAllPresets().filter(a=>a.category===s)}getPresetsByPlatform(s){return this.getAllPresets().filter(a=>a.platform===s)}getPreset(s){return this.getAllPresets().find(a=>a.id===s)}getRecommendedPresets(){return this.getAllPresets().filter(s=>s.recommended)}getPlatforms(){const s=new Set(this.getAllPresets().map(a=>a.platform));return Array.from(s)}addCustomPreset(s){const a={...s,id:`custom-${Date.now()}`,category:"custom"};return this.customPresets.push(a),this.saveCustomPresets(),this.notify(),a}updateCustomPreset(s,a){const r=this.customPresets.findIndex(n=>n.id===s);return r===-1?!1:(this.customPresets[r]={...this.customPresets[r],...a},this.saveCustomPresets(),this.notify(),!0)}deleteCustomPreset(s){const a=this.customPresets.findIndex(r=>r.id===s);return a===-1?!1:(this.customPresets.splice(a,1),this.saveCustomPresets(),this.notify(),!0)}getCustomPresets(){return[...this.customPresets]}isCustomPreset(s){return s.startsWith("custom-")}duplicatePreset(s,a){const r=this.getPreset(s);return r?this.addCustomPreset({...r,name:a,platform:"Custom"}):null}subscribe(s){return this.listeners.add(s),()=>this.listeners.delete(s)}notify(){this.listeners.forEach(s=>s())}}const di=new Vg;function Ug(t,s){const a=t/s;return a<.9?"vertical":a>1.1?"horizontal":"square"}function Kg(t,s){const a={"9:16":"vertical","1:1":"square","16:9":"horizontal","4:5":"vertical"};return t.filter(r=>r.aspectRatio?a[r.aspectRatio]===s:!1)}function Yg(t){switch(t){case"vertical":return"Vertical (TikTok, Reels, Shorts)";case"square":return"Square (Instagram Feed)";case"horizontal":return"Horizontal (YouTube, Twitter)"}}const wc={YouTube:e.jsx(zs,{size:16}),Instagram:e.jsx(ii,{size:16}),Twitter:e.jsx(ii,{size:16}),TikTok:e.jsx(Ps,{size:16}),Facebook:e.jsx(ii,{size:16}),LinkedIn:e.jsx(ii,{size:16}),Broadcast:e.jsx(Er,{size:16}),Web:e.jsx(Wd,{size:16}),Archive:e.jsx(Up,{size:16}),Audio:e.jsx(Ps,{size:16}),Custom:e.jsx(Da,{size:16})},Xg=({isOpen:t,onClose:s,onExport:a,duration:r=0,projectWidth:n=1920,projectHeight:i=1080})=>{const[o,c]=l.useState("presets"),[d,u]=l.useState("recommended"),[p,m]=l.useState(null),[x,h]=l.useState([]),[f,v]=l.useState([]),A=Ug(n,i),[g,k]=l.useState({format:"mp4",codec:"h264",width:n,height:i,frameRate:30,bitrate:15e3,bitrateMode:"vbr",quality:90,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:256,channels:2},upscaling:{enabled:!1,quality:"balanced",sharpening:.3}}),[N,b]=l.useState(null),[j,y]=l.useState(null),[w,S]=l.useState([]),[T,C]=l.useState(!1),[M,z]=l.useState(null),[L,B]=l.useState(!1);l.useEffect(()=>{t&&(h(di.getAllPresets()),v(di.getPlatforms()),u("recommended"),m(null),Yo().then(R=>{b(R),S(fc(R,{width:n,height:i}))}))},[t,n,i]),l.useEffect(()=>{if(!N||r<=0){y(null);return}const R=o==="presets"&&p?p.settings:g,U=xu(N,{width:R.width,height:R.height,frameRate:R.frameRate,duration:r,codec:R.codec});y(U)},[N,r,o,p,g]);const O=l.useCallback(async()=>{if(!T){C(!0),z(null);try{await zg(U=>{z(U)});const R=await Yo(!0);b(R),S(fc(R,{width:n,height:i}))}catch(R){console.error("Benchmark failed:",R)}finally{C(!1),z(null)}}},[T,n,i]),G=Kg(x,A),V=d==="recommended"?G.length>0?G:di.getRecommendedPresets():d?x.filter(R=>R.platform===d):di.getRecommendedPresets(),P=l.useCallback(()=>{const R=o==="presets"&&p?p.settings:g;a(R),s()},[o,p,g,a,s]),_=(R,U)=>{const D=R*1e3*U/8;return D<1024*1024?`${(D/1024).toFixed(1)} KB`:D<1024*1024*1024?`${(D/(1024*1024)).toFixed(1)} MB`:`${(D/(1024*1024*1024)).toFixed(2)} GB`},se=R=>{const U=Math.floor(R/60),D=Math.floor(R%60);return`${U}:${D.toString().padStart(2,"0")}`};return t?e.jsx(ur,{open:!0,onOpenChange:R=>!R&&s(),children:e.jsxs(mr,{className:"max-w-4xl max-h-[85vh] p-0 gap-0 bg-background-secondary border-border overflow-hidden flex flex-col",children:[e.jsx(pr,{className:"p-4 border-b border-border bg-background-tertiary space-y-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nl,{size:20,className:"text-primary"}),e.jsx(xr,{className:"text-lg font-bold text-text-primary",children:"Export Video"})]})}),e.jsxs(hm,{value:o,onValueChange:R=>c(R),className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(fm,{className:"flex border-b border-border bg-transparent rounded-none",children:[e.jsxs(Ll,{value:"presets",className:"flex-1 flex items-center justify-center gap-2 p-3 text-sm font-medium rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary text-text-secondary hover:text-text-primary",children:[e.jsx(Ys,{size:16}),"Presets"]}),e.jsxs(Ll,{value:"custom",className:"flex-1 flex items-center justify-center gap-2 p-3 text-sm font-medium rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary text-text-secondary hover:text-text-primary",children:[e.jsx(Da,{size:16}),"Custom"]})]}),e.jsxs($l,{value:"presets",className:"flex-1 overflow-hidden flex mt-0",children:[e.jsxs("div",{className:"w-48 border-r border-border overflow-y-auto",children:[e.jsxs("button",{onClick:()=>u("recommended"),className:`w-full flex flex-col items-start p-3 text-sm transition-colors ${d==="recommended"?"bg-primary/10 text-primary border-r-2 border-primary":"text-text-secondary hover:bg-background-tertiary"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{size:14}),e.jsx("span",{className:"font-medium",children:"For Your Video"})]}),e.jsx("span",{className:"text-[10px] text-text-muted mt-0.5 ml-5",children:Yg(A)})]}),e.jsx("div",{className:"h-px bg-border my-1"}),f.map(R=>e.jsxs("button",{onClick:()=>u(R),className:`w-full flex items-center gap-2 p-3 text-sm transition-colors ${d===R?"bg-primary/10 text-primary border-r-2 border-primary":"text-text-secondary hover:bg-background-tertiary"}`,children:[wc[R]||e.jsx(Wd,{size:14}),R]},R))]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx("div",{className:"grid grid-cols-2 gap-3",children:V.map(R=>e.jsxs("button",{onClick:()=>m(R),className:`p-4 rounded-lg border text-left transition-colors ${p?.id===R.id?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[wc[R.platform],e.jsx("span",{className:"font-medium text-text-primary",children:R.name})]}),R.recommended&&e.jsx(Ys,{size:12,className:"text-yellow-500 fill-yellow-500"})]}),e.jsx("p",{className:"text-[10px] text-text-muted mb-2",children:R.description}),"width"in R.settings&&e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary",children:[e.jsxs("span",{children:[R.settings.width,"x",R.settings.height]}),e.jsxs("span",{children:[R.settings.frameRate,"fps"]}),e.jsx("span",{children:R.aspectRatio})]}),R.maxDuration&&e.jsxs("div",{className:"flex items-center gap-1 mt-1 text-[10px] text-yellow-500",children:[e.jsx(Ia,{size:10}),"Max ",R.maxDuration,"s"]})]},R.id))})})]}),e.jsx($l,{value:"custom",className:"flex-1 overflow-y-auto p-4 mt-0",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-2",children:"Format"}),e.jsxs(ot,{value:g.format,onValueChange:R=>k({...g,format:R}),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"mp4",children:"MP4"}),e.jsx(ge,{value:"webm",children:"WebM"}),e.jsx(ge,{value:"mov",children:"MOV"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-2",children:"Codec"}),e.jsxs(ot,{value:g.codec,onValueChange:R=>k({...g,codec:R}),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"h264",children:"H.264"}),e.jsx(ge,{value:"h265",children:"H.265 (HEVC)"}),e.jsx(ge,{value:"prores",children:"ProRes"}),e.jsx(ge,{value:"vp9",children:"VP9"}),e.jsx(ge,{value:"av1",children:"AV1"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-2",children:"Resolution"}),e.jsxs(ot,{value:`${g.width}x${g.height}`,onValueChange:R=>{const[U,D]=R.split("x").map(Number);k({...g,width:U,height:D})},children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"3840x2160",children:"4K (3840x2160)"}),e.jsx(ge,{value:"2560x1440",children:"2K (2560x1440)"}),e.jsx(ge,{value:"1920x1080",children:"1080p (1920x1080)"}),e.jsx(ge,{value:"1280x720",children:"720p (1280x720)"}),e.jsx(ge,{value:"854x480",children:"480p (854x480)"}),e.jsx(ge,{value:"1080x1920",children:"Vertical 1080p"}),e.jsx(ge,{value:"1080x1080",children:"Square 1080"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-2",children:"Frame Rate"}),e.jsxs(ot,{value:String(g.frameRate),onValueChange:R=>k({...g,frameRate:Number(R)}),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"24",children:"24 fps"}),e.jsx(ge,{value:"25",children:"25 fps"}),e.jsx(ge,{value:"30",children:"30 fps"}),e.jsx(ge,{value:"50",children:"50 fps"}),e.jsx(ge,{value:"60",children:"60 fps"})]})]})]}),e.jsxs("div",{children:[e.jsx(kt,{className:"block text-xs font-medium text-text-secondary mb-2",children:"Bitrate (kbps)"}),e.jsx(ts,{type:"number",value:g.bitrate,onChange:R=>k({...g,bitrate:Number(R.target.value)}),className:"bg-background-tertiary border-border text-text-primary",min:1e3,max:15e4,step:1e3})]}),e.jsxs("div",{children:[e.jsx(kt,{className:"block text-xs font-medium text-text-secondary mb-2",children:"Quality"}),e.jsx(st,{value:[g.quality],onValueChange:R=>k({...g,quality:R[0]}),min:50,max:100,step:1,className:"w-full"}),e.jsxs("div",{className:"flex justify-between text-[10px] text-text-muted mt-1",children:[e.jsx("span",{children:"Smaller"}),e.jsxs("span",{children:[g.quality,"%"]}),e.jsx("span",{children:"Better"})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-2",children:"Audio Settings"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs(ot,{value:g.audioSettings.format,onValueChange:R=>k({...g,audioSettings:{...g.audioSettings,format:R}}),children:[e.jsx(lt,{className:"bg-background-tertiary border-border text-text-primary text-xs",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"aac",children:"AAC"}),e.jsx(ge,{value:"mp3",children:"MP3"}),e.jsx(ge,{value:"wav",children:"WAV"})]})]}),e.jsxs(ot,{value:String(g.audioSettings.sampleRate),onValueChange:R=>k({...g,audioSettings:{...g.audioSettings,sampleRate:Number(R)}}),children:[e.jsx(lt,{className:"bg-background-tertiary border-border text-text-primary text-xs",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"44100",children:"44.1 kHz"}),e.jsx(ge,{value:"48000",children:"48 kHz"}),e.jsx(ge,{value:"96000",children:"96 kHz"})]})]}),e.jsxs(ot,{value:String(g.audioSettings.bitrate),onValueChange:R=>k({...g,audioSettings:{...g.audioSettings,bitrate:Number(R)}}),children:[e.jsx(lt,{className:"bg-background-tertiary border-border text-text-primary text-xs",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"128",children:"128 kbps"}),e.jsx(ge,{value:"192",children:"192 kbps"}),e.jsx(ge,{value:"256",children:"256 kbps"}),e.jsx(ge,{value:"320",children:"320 kbps"})]})]})]})]}),e.jsxs("div",{className:"col-span-2 border-t border-border pt-4 mt-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{size:14,className:"text-primary"}),e.jsx(kt,{htmlFor:"upscaling-switch",className:"text-xs font-medium text-text-secondary",children:"Enhance Quality (Upscaling)"})]}),e.jsx(oa,{id:"upscaling-switch",checked:g.upscaling?.enabled??!1,onCheckedChange:R=>k({...g,upscaling:{...g.upscaling,enabled:R}})})]}),g.upscaling?.enabled&&e.jsxs("div",{className:"space-y-3 pl-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-text-muted mb-1.5",children:"Quality Mode"}),e.jsx("div",{className:"flex gap-2",children:["fast","balanced","quality"].map(R=>e.jsx("button",{type:"button",onClick:()=>k({...g,upscaling:{...g.upscaling,quality:R}}),className:`flex-1 px-2 py-1.5 text-[10px] rounded border transition-colors ${g.upscaling?.quality===R?"border-primary bg-primary/10 text-primary":"border-border text-text-secondary hover:border-primary/50"}`,children:R.charAt(0).toUpperCase()+R.slice(1)},R))})]}),e.jsxs("div",{children:[e.jsx(kt,{className:"block text-[10px] text-text-muted mb-1.5",children:"Sharpening"}),e.jsx(st,{value:[Math.round((g.upscaling?.sharpening??.3)*100)],onValueChange:R=>k({...g,upscaling:{...g.upscaling,sharpening:R[0]/100}}),min:0,max:100,step:1,className:"w-full"}),e.jsxs("div",{className:"flex justify-between text-[10px] text-text-muted mt-1",children:[e.jsx("span",{children:"None"}),e.jsxs("span",{children:[Math.round((g.upscaling?.sharpening??.3)*100),"%"]}),e.jsx("span",{children:"Max"})]})]}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Enhance quality when exporting to higher resolutions than source. Uses edge-directed interpolation for sharper details."})]})]})]})})]}),N&&e.jsxs("div",{className:"px-4 py-3 border-t border-border bg-background-tertiary/50",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("button",{onClick:()=>B(!L),className:"flex items-center gap-2 text-xs text-text-secondary hover:text-text-primary transition-colors",children:[e.jsx(ux,{size:12}),e.jsx("span",{children:Eg(N)}),e.jsx(jd,{size:10,className:"text-text-muted"})]}),j&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[j.confidence==="measured"?e.jsx(ul,{size:12,className:"text-green-500"}):e.jsx(Hd,{size:12,className:"text-yellow-500"}),e.jsx("span",{className:"text-text-secondary",children:"Est. time:"}),e.jsx("span",{className:"font-medium text-text-primary",children:j.formatted})]}),Dg(N)&&!T&&e.jsxs("button",{onClick:O,className:"flex items-center gap-1 px-2 py-1 text-[10px] text-primary bg-primary/10 rounded hover:bg-primary/20 transition-colors",children:[e.jsx(ks,{size:10}),"Get accurate estimate"]}),T&&M&&e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-text-muted",children:[e.jsx("div",{className:"w-16 h-1 bg-background-tertiary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${M.progress*100}%`}})}),e.jsx("span",{children:"Testing..."})]})]})]}),L&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border/50 grid grid-cols-3 gap-4 text-[10px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"CPU"}),e.jsxs("p",{className:"text-text-primary font-medium",children:[N.cpu.cores," cores"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"GPU"}),e.jsx("p",{className:"text-text-primary font-medium truncate",title:N.gpu.renderer,children:N.gpu.renderer!=="Unknown"?N.gpu.renderer.replace(/ANGLE \(|, .*\)/g,"").replace(/Direct3D11.*$/g,"").trim():"Unknown"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:N.gpu.hasHardwareEncoding?"HW Encode":"Software only"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Codecs"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:w.slice(0,3).map(R=>e.jsx("span",{className:`px-1 py-0.5 rounded text-[9px] ${R.speedRating==="fast"?"bg-green-500/20 text-green-400":R.speedRating==="medium"?"bg-yellow-500/20 text-yellow-400":"bg-red-500/20 text-red-400"}`,children:R.codec.toUpperCase()},R.codec))})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-border bg-background-tertiary",children:[e.jsx("div",{className:"flex items-center gap-4 text-xs text-text-muted",children:r>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ia,{size:12}),se(r)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(qd,{size:12}),"~",_(o==="presets"&&p?p.settings.bitrate||8e3:g.bitrate,r)]}),j&&N?.encoding[g.codec]?.hardware&&e.jsxs("div",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(ks,{size:12}),"Hardware accelerated"]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{variant:"ghost",onClick:s,children:"Cancel"}),e.jsxs(zt,{onClick:P,disabled:o==="presets"&&!p,children:[e.jsx(As,{size:16}),"Start Export"]})]})]})]})}):null},kc={"480p":{width:854,height:480},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080},"1440p":{width:2560,height:1440},"4k":{width:3840,height:2160}},Nc={"480p":25e5,"720p":5e6,"1080p":12e6,"1440p":2e7,"4k":4e7};class Xo{screenRecorder=null;webcamRecorder=null;screenChunks=[];webcamChunks=[];screenStream=null;webcamStream=null;micStream=null;startTime=0;pausedDuration=0;pauseStartTime=0;durationInterval=null;eventHandlers=new Map;isStopping=!1;lastResult=null;on(s,a){return this.eventHandlers.has(s)||this.eventHandlers.set(s,new Set),this.eventHandlers.get(s).add(a),()=>this.eventHandlers.get(s)?.delete(a)}emit(s,a){this.eventHandlers.get(s)?.forEach(r=>r(a))}async requestPermissions(s){const a=kc[s.video.resolution],r={video:{width:{ideal:a.width},height:{ideal:a.height},frameRate:{ideal:s.video.frameRate}},audio:s.audio.systemAudio};if(this.screenStream=await navigator.mediaDevices.getDisplayMedia(r),s.audio.microphone)try{this.micStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch{console.warn("Microphone access denied, continuing without microphone")}if(s.webcam.enabled){const n=kc[s.webcam.resolution];try{this.webcamStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:n.width},height:{ideal:n.height},facingMode:"user"},audio:!1})}catch{console.warn("Webcam access denied, continuing without webcam")}}return{screenStream:this.screenStream,webcamStream:this.webcamStream||void 0}}async startRecording(s){if(!this.screenStream)throw new Error("Screen stream not initialized. Call requestPermissions first.");this.screenChunks=[],this.webcamChunks=[],this.isStopping=!1,this.lastResult=null;const a=new MediaStream;this.screenStream.getVideoTracks().forEach(i=>a.addTrack(i)),this.screenStream.getAudioTracks().length>0&&this.screenStream.getAudioTracks().forEach(i=>a.addTrack(i)),this.micStream&&this.micStream.getAudioTracks().forEach(i=>a.addTrack(i));const r=this.getBestMimeType(),n=Nc[s.video.resolution];if(this.screenRecorder=new MediaRecorder(a,{mimeType:r,videoBitsPerSecond:n}),this.screenRecorder.ondataavailable=i=>{i.data.size>0&&this.screenChunks.push(i.data)},this.screenRecorder.onerror=i=>{this.emit("error",i)},this.screenStream.getVideoTracks()[0].onended=()=>{this.stopRecording()},this.webcamStream&&s.webcam.enabled){const i=this.getBestMimeType(),o=Nc[s.webcam.resolution];this.webcamRecorder=new MediaRecorder(this.webcamStream,{mimeType:i,videoBitsPerSecond:o}),this.webcamRecorder.ondataavailable=c=>{c.data.size>0&&this.webcamChunks.push(c.data)},this.webcamRecorder.start(1e3)}this.screenRecorder.start(1e3),this.startTime=Date.now(),this.pausedDuration=0,this.durationInterval=window.setInterval(()=>{const i=Date.now()-this.startTime-this.pausedDuration;this.emit("duration",i)},100),this.emit("start")}pauseRecording(){this.screenRecorder?.state==="recording"&&(this.screenRecorder.pause(),this.pauseStartTime=Date.now()),this.webcamRecorder?.state==="recording"&&this.webcamRecorder.pause(),this.emit("pause")}resumeRecording(){this.screenRecorder?.state==="paused"&&(this.screenRecorder.resume(),this.pausedDuration+=Date.now()-this.pauseStartTime),this.webcamRecorder?.state==="paused"&&this.webcamRecorder.resume(),this.emit("resume")}async stopRecording(){if(this.lastResult)return this.lastResult;if(this.isStopping)return await new Promise(r=>{const n=setInterval(()=>{this.lastResult&&(clearInterval(n),r())},50);setTimeout(()=>{clearInterval(n),r()},5e3)}),this.lastResult||{screenBlob:new Blob};this.isStopping=!0,this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null);const s={screenBlob:new Blob},a=[];return this.screenRecorder&&this.screenRecorder.state!=="inactive"?a.push(this.stopRecorder(this.screenRecorder,this.screenChunks).then(r=>{s.screenBlob=r})):this.screenChunks.length>0&&(s.screenBlob=new Blob(this.screenChunks,{type:"video/webm"})),this.webcamRecorder&&this.webcamRecorder.state!=="inactive"?a.push(this.stopRecorder(this.webcamRecorder,this.webcamChunks).then(r=>{s.webcamBlob=r})):this.webcamChunks.length>0&&(s.webcamBlob=new Blob(this.webcamChunks,{type:"video/webm"})),await Promise.all(a),this.lastResult=s,this.cleanup(),this.emit("stop",s),s}cancelRecording(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.screenRecorder&&this.screenRecorder.state!=="inactive"&&this.screenRecorder.stop(),this.webcamRecorder&&this.webcamRecorder.state!=="inactive"&&this.webcamRecorder.stop(),this.cleanup()}getRecordingState(){return this.screenRecorder?.state||"inactive"}isRecording(){return this.screenRecorder?.state==="recording"}isPaused(){return this.screenRecorder?.state==="paused"}stopRecorder(s,a){return new Promise(r=>{s.onstop=()=>{const n=s.mimeType||"video/webm";r(new Blob(a,{type:n}))},s.stop()})}getBestMimeType(){const s=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=h264,opus","video/webm","video/mp4"];for(const a of s)if(MediaRecorder.isTypeSupported(a))return a;return"video/webm"}cleanup(){this.screenStream?.getTracks().forEach(s=>s.stop()),this.webcamStream?.getTracks().forEach(s=>s.stop()),this.micStream?.getTracks().forEach(s=>s.stop()),this.screenStream=null,this.webcamStream=null,this.micStream=null,this.screenRecorder=null,this.webcamRecorder=null,this.screenChunks=[],this.webcamChunks=[]}static isSupported(){const s=typeof navigator.mediaDevices?.getDisplayMedia=="function",r=typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported("video/webm");return s&&r}static getSupportedFeatures(){const s=/Chrome|Chromium|Edge/.test(navigator.userAgent),a=/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent);return{screenCapture:!!navigator.mediaDevices?.getDisplayMedia,systemAudio:s,webcam:!!navigator.mediaDevices?.getUserMedia,vp9:MediaRecorder.isTypeSupported("video/webm;codecs=vp9"),h264:MediaRecorder.isTypeSupported("video/webm;codecs=h264")||a}}}const ha=new Xo;function Cc(t){const s=Math.floor(t/1e3),a=Math.floor(s/3600),r=Math.floor(s%3600/60),n=s%60;return a>0?`${a}:${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`:`${r}:${n.toString().padStart(2,"0")}`}const Gg={video:{resolution:"1080p",frameRate:30},audio:{systemAudio:!0,microphone:!1},webcam:{enabled:!1,resolution:"720p"}},hu=un((t,s)=>(ha.on("duration",a=>{t({duration:a})}),ha.on("stop",()=>{t({status:"processing"})}),ha.on("error",a=>{const r=a instanceof Error?a.message:"Recording error occurred";t({status:"error",error:r})}),{status:"idle",duration:0,error:null,options:Gg,screenStream:null,webcamStream:null,result:null,isModalOpen:!1,isControlsMinimized:!1,setOptions:a=>{t(r=>({options:{...r.options,...a,video:{...r.options.video,...a.video},audio:{...r.options.audio,...a.audio},webcam:{...r.options.webcam,...a.webcam}}}))},setVideoOption:(a,r)=>{t(n=>({options:{...n.options,video:{...n.options.video,[a]:r}}}))},setAudioOption:(a,r)=>{t(n=>({options:{...n.options,audio:{...n.options.audio,[a]:r}}}))},setWebcamOption:(a,r)=>{t(n=>({options:{...n.options,webcam:{...n.options.webcam,[a]:r}}}))},requestPermissions:async()=>{const{options:a}=s();t({status:"requesting",error:null});try{const r=await ha.requestPermissions(a);return t({screenStream:r.screenStream,webcamStream:r.webcamStream||null,status:"idle"}),!0}catch(r){const n=r instanceof Error?r.message:"Permission denied";return t({status:"error",error:n}),!1}},startRecording:async()=>{const{options:a,screenStream:r}=s();if(!r){t({status:"error",error:"No screen stream available"});return}t({status:"countdown"}),await new Promise(n=>setTimeout(n,3e3));try{await ha.startRecording(a),t({status:"recording",duration:0})}catch(n){const i=n instanceof Error?n.message:"Failed to start recording";t({status:"error",error:i})}},pauseRecording:()=>{ha.pauseRecording(),t({status:"paused"})},resumeRecording:()=>{ha.resumeRecording(),t({status:"recording"})},stopRecording:async()=>{t({status:"processing"});try{const a=await ha.stopRecording();return t({result:a,status:"idle"}),a}catch(a){const r=a instanceof Error?a.message:"Failed to stop recording";return t({status:"error",error:r}),null}},cancelRecording:()=>{ha.cancelRecording(),t({status:"idle",duration:0,screenStream:null,webcamStream:null,result:null})},reset:()=>{ha.cancelRecording(),t({status:"idle",duration:0,error:null,screenStream:null,webcamStream:null,result:null,isModalOpen:!1,isControlsMinimized:!1})},openModal:()=>{t({isModalOpen:!0})},closeModal:()=>{const{status:a}=s();(a==="idle"||a==="error")&&t({isModalOpen:!1,error:null})},minimizeControls:()=>{t({isControlsMinimized:!0})},expandControls:()=>{t({isControlsMinimized:!1})}})),Hg=()=>{const[t,s]=l.useState(3);return l.useEffect(()=>{if(t>0){const a=setTimeout(()=>s(t-1),1e3);return()=>clearTimeout(a)}},[t]),e.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center bg-black/90 backdrop-blur-md",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"text-[180px] font-bold text-white animate-countdown",style:{textShadow:"0 0 60px rgba(239, 68, 68, 0.8), 0 0 100px rgba(239, 68, 68, 0.4)"},children:t>0?t:""},t),t===0&&e.jsx("div",{className:"flex flex-col items-center gap-4 animate-fade-in",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-4 h-4 bg-error rounded-full animate-pulse"}),e.jsx("span",{className:"text-2xl font-bold text-white",children:"Recording..."})]})})]}),e.jsx("style",{children:` + @keyframes countdown { + 0% { + transform: scale(0.5); + opacity: 0; + } + 20% { + transform: scale(1.2); + opacity: 1; + } + 40% { + transform: scale(1); + } + 100% { + transform: scale(0.8); + opacity: 0; + } + } + + @keyframes fade-in { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + .animate-countdown { + animation: countdown 1s ease-out forwards; + } + + .animate-fade-in { + animation: fade-in 0.5s ease-out forwards; + } + `})]})},Wg=({onStop:t,onPause:s,onResume:a,onCancel:r})=>{const{status:n,duration:i,isControlsMinimized:o,minimizeControls:c,expandControls:d}=hu(),u=n==="paused";return o?e.jsxs("button",{onClick:d,className:"fixed bottom-6 right-6 z-[200] flex items-center gap-2 px-4 py-2 bg-red-600 rounded-full shadow-2xl hover:bg-red-700 transition-all group",children:[e.jsx("div",{className:"w-3 h-3 bg-white rounded-full animate-pulse"}),e.jsx("span",{className:"text-sm font-bold text-white",children:Cc(i)})]}):e.jsx("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-[200]",children:e.jsxs("div",{className:"flex items-center gap-4 px-6 py-4 bg-background-secondary/95 backdrop-blur-xl border border-border rounded-2xl shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${u?"bg-warning":"bg-error animate-pulse"}`}),e.jsx("span",{className:"text-lg font-mono font-bold text-text-primary min-w-[80px]",children:Cc(i)})]}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsxs("div",{className:"flex items-center gap-2",children:[u?e.jsx("button",{onClick:a,className:"p-3 bg-primary hover:bg-primary-hover rounded-xl transition-colors",title:"Resume recording",children:e.jsx(As,{size:20,className:"text-white"})}):e.jsx("button",{onClick:s,className:"p-3 bg-warning/20 hover:bg-warning/30 rounded-xl transition-colors",title:"Pause recording",children:e.jsx(dr,{size:20,className:"text-warning"})}),e.jsx("button",{onClick:t,className:"p-3 bg-red-600 hover:bg-red-700 rounded-xl transition-colors",title:"Stop recording",children:e.jsx(Gs,{size:20,className:"text-white fill-white"})}),e.jsx("button",{onClick:r,className:"p-3 bg-background-tertiary hover:bg-background-elevated rounded-xl transition-colors",title:"Cancel recording",children:e.jsx(Ls,{size:20,className:"text-text-muted"})})]}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsx("button",{onClick:c,className:"p-2 text-text-muted hover:text-text-primary rounded-lg hover:bg-background-tertiary transition-colors",title:"Minimize controls",children:e.jsx(ml,{size:16})})]})})},Sc=[{value:"720p",label:"720p HD",desc:"1280×720 - Smaller files"},{value:"1080p",label:"1080p Full HD",desc:"1920×1080 - Recommended"},{value:"1440p",label:"1440p QHD",desc:"2560×1440 - High quality"},{value:"4k",label:"4K Ultra HD",desc:"3840×2160 - Maximum quality"}],qg=[{value:30,label:"30 fps"},{value:60,label:"60 fps"}],Qg=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p"}],Jg=({isOpen:t,onClose:s,onRecordingComplete:a})=>{const{status:r,options:n,webcamStream:i,error:o,setVideoOption:c,setAudioOption:d,setWebcamOption:u,requestPermissions:p,startRecording:m,stopRecording:x,cancelRecording:h,pauseRecording:f,resumeRecording:v,reset:A}=hu(),g=l.useRef(null),k=Xo.isSupported(),N=Xo.getSupportedFeatures();l.useEffect(()=>{g.current&&i&&(g.current.srcObject=i)},[i]),l.useEffect(()=>{t||(r==="idle"||r==="error")&&A()},[t,r,A]);const b=async()=>{await p()&&await m()},j=async()=>{const w=await x();w&&(a(w.screenBlob,w.webcamBlob),s())},y=()=>{h(),s()};return t?r==="countdown"?e.jsx(Hg,{}):r==="recording"||r==="paused"?e.jsx(Wg,{onStop:j,onPause:f,onResume:v,onCancel:y}):e.jsx(ur,{open:!0,onOpenChange:w=>!w&&y(),children:e.jsxs(mr,{className:"max-w-2xl p-0 gap-0 bg-background-secondary border-border overflow-hidden",children:[e.jsx(pr,{className:"p-4 border-b border-border bg-background-tertiary space-y-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(or,{size:20,className:"text-error fill-error animate-pulse"}),e.jsx(xr,{className:"text-lg font-bold text-text-primary",children:"Screen Recording"})]})}),e.jsxs("div",{className:"p-6 space-y-6",children:[!k&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-error/10 border border-error/30 rounded-lg",children:[e.jsx(Ba,{size:20,className:"text-error flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-error",children:"Screen recording not supported"}),e.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Your browser doesn't support screen recording. Please use Chrome, Edge, or Firefox."})]})]}),o&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-error/10 border border-error/30 rounded-lg",children:[e.jsx(Ba,{size:20,className:"text-error flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-error",children:"Recording Error"}),e.jsx("p",{className:"text-xs text-text-muted mt-1",children:o})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-text-primary",children:[e.jsx(Er,{size:16}),e.jsx("span",{children:"Video Settings"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-text-muted mb-2",children:"Resolution"}),e.jsxs(ot,{value:n.video.resolution,onValueChange:w=>c("resolution",w),disabled:!k,children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:Sc.map(w=>e.jsx(ge,{value:w.value,children:w.label},w.value))})]}),e.jsx("p",{className:"text-[10px] text-text-muted mt-1",children:Sc.find(w=>w.value===n.video.resolution)?.desc})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-text-muted mb-2",children:"Frame Rate"}),e.jsxs(ot,{value:String(n.video.frameRate),onValueChange:w=>c("frameRate",parseInt(w)),disabled:!k,children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:qg.map(w=>e.jsx(ge,{value:String(w.value),children:w.label},w.value))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-text-primary",children:[e.jsx(Da,{size:16}),e.jsx("span",{children:"Audio Settings"})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("button",{onClick:()=>d("systemAudio",!n.audio.systemAudio),disabled:!k||!N.systemAudio,className:`flex-1 flex items-center justify-center gap-2 p-3 rounded-lg border transition-all ${n.audio.systemAudio?"bg-primary/10 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-text-muted"} ${(!k||!N.systemAudio)&&"opacity-50 cursor-not-allowed"}`,children:[n.audio.systemAudio?e.jsx(Ts,{size:18}):e.jsx($i,{size:18}),e.jsx("span",{className:"text-sm",children:"System Audio"})]}),e.jsxs("button",{onClick:()=>d("microphone",!n.audio.microphone),disabled:!k,className:`flex-1 flex items-center justify-center gap-2 p-3 rounded-lg border transition-all ${n.audio.microphone?"bg-primary/10 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-text-muted"} ${!k&&"opacity-50 cursor-not-allowed"}`,children:[n.audio.microphone?e.jsx(Rr,{size:18}):e.jsx(Jd,{size:18}),e.jsx("span",{className:"text-sm",children:"Microphone"})]})]}),!N.systemAudio&&e.jsx("p",{className:"text-[10px] text-text-muted",children:"System audio capture is only available in Chrome and Edge browsers."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-text-primary",children:[e.jsx(cl,{size:16}),e.jsx("span",{children:"Webcam Recording"})]}),e.jsx("button",{onClick:()=>u("enabled",!n.webcam.enabled),disabled:!k||!N.webcam,className:`relative w-12 h-6 rounded-full transition-colors ${n.webcam.enabled?"bg-primary":"bg-background-tertiary"} ${(!k||!N.webcam)&&"opacity-50 cursor-not-allowed"}`,children:e.jsx("div",{className:`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${n.webcam.enabled?"translate-x-7":"translate-x-1"}`})})]}),n.webcam.enabled&&e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-xs text-text-muted mb-2",children:"Webcam Resolution"}),e.jsxs(ot,{value:n.webcam.resolution,onValueChange:w=>u("resolution",w),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:Qg.map(w=>e.jsx(ge,{value:w.value,children:w.label},w.value))})]})]}),i&&e.jsx("div",{className:"w-32 h-24 bg-background-tertiary rounded-lg overflow-hidden border border-border",children:e.jsx("video",{ref:g,autoPlay:!0,muted:!0,playsInline:!0,className:"w-full h-full object-cover"})})]}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Webcam will be recorded as a separate file, giving you full control in the editor."})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-border bg-background-tertiary",children:[e.jsx("p",{className:"text-xs text-text-muted",children:"Recording will start after a 3-second countdown"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:y,className:"px-4 py-2 text-sm text-text-secondary hover:text-text-primary transition-colors",children:"Cancel"}),e.jsx("button",{onClick:b,disabled:!k||r==="requesting",className:"flex items-center gap-2 px-6 py-2 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:r==="requesting"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),e.jsx("span",{children:"Requesting Access..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(or,{size:14,className:"fill-current"}),e.jsx("span",{children:"Start Recording"})]})})]})]})]})}):null},Zg=()=>{const{actionHistory:t,undo:s,redo:a,canUndo:r,canRedo:n,clipUndoStack:i,clipRedoStack:o}=F(),[c,d]=l.useState([]),[u,p]=l.useState([]),[m,x]=l.useState(!1),[h,f]=l.useState(""),[v,A]=l.useState(!1),g=C=>{switch(C){case"text":return"Create text clip";case"shape":return"Create shape";case"svg":return"Import SVG";case"sticker":return"Add sticker";default:return"Create clip"}};l.useEffect(()=>{const C=()=>{const z=t.getDisplayHistory();p(t.getSnapshots());const L=z.map((B,O)=>({id:`action-${B.entry.action.id}-${O}`,description:B.entry.description,timestamp:B.entry.timestamp,isCurrent:B.isCurrent,isClipEntry:!1,groupId:B.entry.groupId}));i.forEach((B,O)=>{L.push({id:`clip-${B.clipId}-${O}`,description:g(B.type),timestamp:Date.now()-(i.length-O)*1e3,isCurrent:O===i.length-1&&o.length===0,isClipEntry:!0,clipType:B.type})}),L.sort((B,O)=>B.timestamp-O.timestamp),d(L)};C();const M=t.subscribe(C);return()=>M()},[t,i,o]);const k=l.useCallback(async()=>{r()&&await s()},[s,r]),N=l.useCallback(async()=>{n()&&await a()},[a,n]),b=l.useCallback(()=>{h.trim()&&(t.createSnapshot(h.trim()),f(""),A(!1))},[t,h]),j=l.useCallback(C=>{t.deleteSnapshot(C)},[t]),y=C=>new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),w=t.getUndoStackSize()+i.length,S=t.getRedoStackSize()+o.length,T=C=>{switch(C){case"text":return Hs;case"shape":return mn;case"svg":return Ki;case"sticker":return su;default:return Ai}};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-sm font-medium text-text-primary",children:"History"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:k,disabled:!r(),className:"p-1.5 rounded hover:bg-background-tertiary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:`Undo (${w})`,children:e.jsx(pn,{size:14})}),e.jsx("button",{onClick:N,disabled:!n(),className:"p-1.5 rounded hover:bg-background-tertiary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:`Redo (${S})`,children:e.jsx(pl,{size:14})})]})]}),e.jsxs("div",{className:"border-b border-border",children:[e.jsxs("button",{onClick:()=>x(!m),className:"w-full flex items-center gap-2 p-2 hover:bg-background-tertiary transition-colors",children:[m?e.jsx(qt,{size:12}):e.jsx(bs,{size:12}),e.jsx(Ol,{size:12,className:"text-yellow-500"}),e.jsxs("span",{className:"text-xs text-text-secondary",children:["Snapshots (",u.length,")"]})]}),m&&e.jsxs("div",{className:"px-2 pb-2",children:[u.length===0&&!v&&e.jsx("p",{className:"text-[10px] text-text-muted py-2 text-center",children:"No snapshots saved"}),u.map(C=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded hover:bg-background-tertiary group",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ol,{size:10,className:"text-yellow-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-text-primary",children:C.name}),e.jsx("p",{className:"text-[10px] text-text-muted",children:y(C.timestamp)})]})]}),e.jsx("button",{onClick:()=>j(C.id),className:"p-1 rounded hover:bg-red-500/20 text-text-muted hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx($t,{size:10})})]},C.id)),v?e.jsxs("div",{className:"flex items-center gap-2 p-2",children:[e.jsx(ts,{type:"text",value:h,onChange:C=>f(C.target.value),onKeyDown:C=>{C.key==="Enter"&&b(),C.key==="Escape"&&A(!1)},placeholder:"Snapshot name...",className:"flex-1 h-7 text-xs bg-background-tertiary border-border text-text-primary",autoFocus:!0}),e.jsx("button",{onClick:b,className:"px-2 py-1 bg-primary text-white rounded text-xs hover:bg-primary/80 transition-colors",children:"Save"})]}):e.jsxs("button",{onClick:()=>A(!0),className:"w-full flex items-center justify-center gap-1 p-2 rounded border border-dashed border-border hover:border-primary hover:text-primary transition-colors",children:[e.jsx(Jp,{size:12}),e.jsx("span",{className:"text-[10px]",children:"Create Snapshot"})]})]})]}),e.jsx(ia,{className:"flex-1",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-text-muted",children:[e.jsx(Ai,{size:24,className:"mb-2 opacity-30"}),e.jsx("p",{className:"text-xs",children:"No actions yet"})]}):e.jsx("div",{className:"p-2 space-y-0.5",children:c.map(C=>{const M=C.isClipEntry?T(C.clipType):null;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded transition-colors ${C.isCurrent?"bg-primary/20 border border-primary/30":"hover:bg-background-tertiary"}`,children:[C.isClipEntry&&M?e.jsx(M,{size:12,className:C.isCurrent?"text-primary":"text-text-muted"}):e.jsx("div",{className:`w-1.5 h-1.5 rounded-full ${C.isCurrent?"bg-primary":"bg-text-muted"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs truncate ${C.isCurrent?"text-text-primary":"text-text-secondary"}`,children:C.description}),e.jsx("p",{className:"text-[10px] text-text-muted",children:y(C.timestamp)})]}),C.groupId&&e.jsx("span",{className:"px-1 py-0.5 bg-background-tertiary rounded text-[8px] text-text-muted",children:"grouped"}),C.isClipEntry&&e.jsx("span",{className:"px-1 py-0.5 bg-amber-500/20 rounded text-[8px] text-amber-400",children:"clip"})]},C.id)})})}),e.jsx("div",{className:"p-2 border-t border-border bg-background-tertiary",children:e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-muted",children:[e.jsxs("span",{children:[w," actions"]}),e.jsxs("span",{children:[S," redoable"]})]})})]})};function e0(t){const s=Math.floor((Date.now()-t)/1e3);return s<60?"just now":s<3600?`${Math.floor(s/60)}m ago`:s<86400?`${Math.floor(s/3600)}h ago`:`${Math.floor(s/86400)}d ago`}const t0=()=>{const{project:t,createNewProject:s,recoverFromAutoSave:a,renameProject:r}=F(),[n,i]=l.useState(!1),[o,c]=l.useState([]),[d,u]=l.useState(!1),[p,m]=l.useState(t.name),[x,h]=l.useState(!1),f=l.useRef(null),v=l.useRef(null);l.useEffect(()=>{n&&(async()=>{try{await _l.initialize();const w=(await _l.checkForRecovery()).reduce((S,T)=>{const C=S.find(M=>M.projectId===T.projectId);return!C||T.timestamp>C.timestamp?[...S.filter(M=>M.projectId!==T.projectId),T]:S},[]);c(w.sort((S,T)=>T.timestamp-S.timestamp))}catch(y){console.warn("[ProjectSwitcher] Failed to load saved projects:",y)}})()},[n]),l.useEffect(()=>{const j=y=>{f.current&&!f.current.contains(y.target)&&(i(!1),u(!1))};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]),l.useEffect(()=>{d&&v.current&&(v.current.focus(),v.current.select())},[d]),l.useEffect(()=>{m(t.name)},[t.name]);const A=l.useCallback(async()=>{const j=p.trim();j&&j!==t.name&&await r(j),u(!1)},[p,t.name,r]),g=l.useCallback(j=>{j.key==="Enter"?A():j.key==="Escape"&&(m(t.name),u(!1))},[A,t.name]),k=l.useCallback(()=>{s(),i(!1)},[s]),N=l.useCallback(async j=>{h(!0);try{await a(j),i(!1)}catch(y){console.error("[ProjectSwitcher] Failed to switch project:",y)}finally{h(!1)}},[a]),b=o.filter(j=>j.projectId!==t.id);return e.jsxs("div",{className:"relative",ref:f,children:[e.jsxs("button",{onClick:()=>i(!n),className:"flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-background-secondary transition-colors group max-w-[200px]",children:[e.jsx(Tn,{className:"w-4 h-4 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:t.name}),e.jsx(qt,{className:`w-3.5 h-3.5 text-text-muted transition-transform duration-200 shrink-0 ${n?"rotate-180":""}`})]}),n&&e.jsxs("div",{className:"absolute top-full left-0 mt-2 w-72 bg-background border border-border rounded-xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:[e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-xs font-medium text-text-muted uppercase tracking-wider mb-2",children:"Current Project"}),d?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{ref:v,type:"text",value:p,onChange:j=>m(j.target.value),onBlur:A,onKeyDown:g,className:"flex-1 bg-background-secondary border-primary text-text-primary"}),e.jsx("button",{onClick:A,className:"p-2 bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors",children:e.jsx(is,{className:"w-4 h-4"})})]}):e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-secondary rounded-lg group",children:[e.jsx(Tn,{className:"w-4 h-4 text-primary shrink-0"}),e.jsx("span",{className:"flex-1 text-sm font-medium text-text-primary truncate",children:t.name}),e.jsx("button",{onClick:()=>u(!0),className:"p-1.5 rounded-md text-text-muted hover:text-text-primary hover:bg-background-tertiary transition-colors opacity-0 group-hover:opacity-100",title:"Rename project",children:e.jsx(tu,{className:"w-3.5 h-3.5"})})]})]}),e.jsx("div",{className:"p-2",children:e.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-background-secondary transition-colors text-left group",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-md text-primary group-hover:bg-primary/20 transition-colors",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:"New Project"}),e.jsx("div",{className:"text-xs text-text-muted",children:"Start fresh with a new canvas"})]})]})}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-t border-border",children:e.jsxs("div",{className:"text-xs font-medium text-text-muted uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ia,{className:"w-3 h-3"}),"Recent Projects"]})}),e.jsx("div",{className:"max-h-64 overflow-y-auto px-2 pb-2",children:b.map(j=>e.jsxs("button",{onClick:()=>N(j.id),disabled:x,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-background-secondary transition-colors text-left group disabled:opacity-50",children:[e.jsx("div",{className:"p-1.5 bg-background-tertiary rounded-md text-text-muted group-hover:text-text-secondary transition-colors",children:e.jsx(sn,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary truncate group-hover:text-primary transition-colors",children:j.projectName}),e.jsx("div",{className:"text-xs text-text-muted",children:e0(j.timestamp)})]})]},j.id))})]})]})]})},nr=[{id:"elevenlabs",label:"ElevenLabs",description:"AI voice generation and text-to-speech",docsUrl:"https://elevenlabs.io/docs/api-reference"},{id:"openai",label:"OpenAI",description:"GPT models for script generation and AI features",docsUrl:"https://platform.openai.com/docs/api-reference"},{id:"anthropic",label:"Anthropic",description:"Claude models for AI-assisted editing",docsUrl:"https://docs.anthropic.com/en/docs"},{id:"kie-ai",label:"Kie.ai",description:"AI aggregator for video/image generation, upscaling, and editing",docsUrl:"https://kie.ai"},{id:"freepik",label:"Freepik",description:"AI aggregator for image generation, vectors, and creative assets",docsUrl:"https://www.freepik.com/api"}],Fa=un()(Ld(Fd((t,s)=>({autoSave:!0,autoSaveInterval:5,language:"en",defaultTtsProvider:"elevenlabs",defaultLlmProvider:"openai",defaultAggregator:"kie-ai",elevenLabsModel:"eleven_v3",favoriteVoices:[],favoriteModels:[],configuredServices:[],cachedElevenLabsVoices:null,cachedElevenLabsModels:null,settingsOpen:!1,settingsTab:"general",setAutoSave:a=>t({autoSave:a}),setAutoSaveInterval:a=>t({autoSaveInterval:Math.max(1,Math.min(30,a))}),setLanguage:a=>t({language:a}),setDefaultTtsProvider:a=>t({defaultTtsProvider:a}),setDefaultLlmProvider:a=>t({defaultLlmProvider:a}),setDefaultAggregator:a=>t({defaultAggregator:a}),setElevenLabsModel:a=>t({elevenLabsModel:a}),addFavoriteVoice:a=>{const{favoriteVoices:r}=s();r.some(n=>n.voiceId===a.voiceId)||t({favoriteVoices:[...r,a]})},removeFavoriteVoice:a=>{const{favoriteVoices:r}=s();t({favoriteVoices:r.filter(n=>n.voiceId!==a)})},addFavoriteModel:a=>{const{favoriteModels:r}=s();r.some(n=>n.modelId===a.modelId)||t({favoriteModels:[...r,a]})},removeFavoriteModel:a=>{const{favoriteModels:r}=s();t({favoriteModels:r.filter(n=>n.modelId!==a)})},addConfiguredService:a=>{const{configuredServices:r}=s();r.includes(a)||t({configuredServices:[...r,a]})},removeConfiguredService:a=>{const{configuredServices:r}=s();t({configuredServices:r.filter(n=>n!==a)})},setCachedElevenLabsVoices:a=>t({cachedElevenLabsVoices:a}),setCachedElevenLabsModels:a=>t({cachedElevenLabsModels:a}),clearApiCaches:()=>t({cachedElevenLabsVoices:null,cachedElevenLabsModels:null}),openSettings:a=>t({settingsOpen:!0,settingsTab:a??s().settingsTab}),closeSettings:()=>t({settingsOpen:!1})}),{name:"openreel-settings",version:1,partialize:t=>({autoSave:t.autoSave,autoSaveInterval:t.autoSaveInterval,language:t.language,defaultTtsProvider:t.defaultTtsProvider,defaultLlmProvider:t.defaultLlmProvider,defaultAggregator:t.defaultAggregator,elevenLabsModel:t.elevenLabsModel,favoriteVoices:t.favoriteVoices,favoriteModels:t.favoriteModels,configuredServices:t.configuredServices})})));gm(()=>{Fa.getState().clearApiCaches()});const s0=[{label:"16:9 Landscape (1080p)",width:1920,height:1080},{label:"9:16 Vertical (TikTok/Reels)",width:1080,height:1920},{label:"1:1 Square",width:1080,height:1080},{label:"4:5 Portrait",width:1080,height:1350},{label:"4:3 Standard",width:1440,height:1080},{label:"21:9 Cinematic",width:2560,height:1080},{label:"4K Landscape",width:3840,height:2160}],a0=()=>{const{autoSave:t,autoSaveInterval:s,defaultTtsProvider:a,defaultLlmProvider:r,defaultAggregator:n,configuredServices:i,setAutoSave:o,setAutoSaveInterval:c,setDefaultTtsProvider:d,setDefaultLlmProvider:u,setDefaultAggregator:p}=Fa(),m=F(w=>w.project.settings.width),x=F(w=>w.project.settings.height),h=F(w=>w.updateSettings),[f,v]=_e.useState(String(m)),[A,g]=_e.useState(String(x));_e.useEffect(()=>{v(String(m)),g(String(x))},[m,x]);const k=l.useCallback(async(w,S)=>{const T=Math.max(16,Math.min(7680,Math.round(w))),C=Math.max(16,Math.min(7680,Math.round(S)));await h({width:T,height:C})},[h]),N=l.useCallback(()=>{const w=Number(f),S=Number(A);Number.isFinite(w)&&Number.isFinite(S)&&w>0&&S>0&&k(w,S)},[f,A,k]),b=[{id:"piper",label:"Piper (Free / Built-in)"},...nr.filter(w=>w.id==="elevenlabs"||i.includes(w.id))],j=nr.filter(w=>w.id==="openai"||w.id==="anthropic"||i.includes(w.id)),y=nr.filter(w=>w.id==="kie-ai"||w.id==="freepik"||i.includes(w.id));return e.jsxs("div",{className:"space-y-6 pb-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Project Composition"}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"Set the canvas dimensions for your project. Pick a preset for TikTok, Reels, YouTube, or enter custom values."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:s0.map(w=>{const S=w.width===m&&w.height===x;return e.jsxs("button",{onClick:()=>k(w.width,w.height),className:`text-left px-3 py-2 rounded-md text-xs transition-colors border ${S?"border-primary bg-primary/10 text-text-primary":"border-border bg-background-tertiary text-text-secondary hover:text-text-primary hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium",children:w.label}),e.jsxs("div",{className:"text-text-muted text-[10px] mt-0.5",children:[w.width," × ",w.height]})]},w.label)})}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(kt,{className:"text-xs text-text-secondary",children:"Width"}),e.jsx("input",{type:"number",min:16,max:7680,value:f,onChange:w=>v(w.target.value),className:"mt-1 h-9 w-full rounded-md border border-input bg-background px-3 text-sm"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(kt,{className:"text-xs text-text-secondary",children:"Height"}),e.jsx("input",{type:"number",min:16,max:7680,value:A,onChange:w=>g(w.target.value),className:"mt-1 h-9 w-full rounded-md border border-input bg-background px-3 text-sm"})]}),e.jsx("button",{onClick:N,className:"h-9 px-3 rounded-md bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors",children:"Apply"})]})]}),e.jsx("div",{className:"h-px bg-border"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Auto-Save"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(kt,{className:"text-sm text-text-secondary",children:"Enable auto-save"}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"Automatically save your project at regular intervals"})]}),e.jsx(oa,{checked:t,onCheckedChange:o})]}),t&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(kt,{className:"text-sm text-text-secondary whitespace-nowrap",children:"Save every"}),e.jsxs("select",{value:s,onChange:w=>c(Number(w.target.value)),className:"h-9 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:1,children:"1 minute"}),e.jsx("option",{value:2,children:"2 minutes"}),e.jsx("option",{value:5,children:"5 minutes"}),e.jsx("option",{value:10,children:"10 minutes"}),e.jsx("option",{value:15,children:"15 minutes"}),e.jsx("option",{value:30,children:"30 minutes"})]})]})]}),e.jsx("div",{className:"h-px bg-border"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Default AI Providers"}),e.jsx("p",{className:"text-xs text-text-muted",children:'Choose which service to use by default for AI features. Configure API keys in the "API Keys" tab first.'}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(kt,{className:"text-sm text-text-secondary",children:"Text to Speech/Voice To Speech/Sound Effects"}),e.jsx("select",{value:a,onChange:w=>d(w.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]",children:b.map(w=>e.jsx("option",{value:w.id,children:w.label},w.id))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(kt,{className:"text-sm text-text-secondary",children:"AI Assistant (LLM)"}),e.jsx("select",{value:r,onChange:w=>u(w.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]",children:j.map(w=>e.jsx("option",{value:w.id,children:w.label},w.id))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(kt,{className:"text-sm text-text-secondary",children:"AI Aggregator"}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"Video/image generation, upscaling, and creative AI tools"})]}),e.jsx("select",{value:n,onChange:w=>p(w.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]",children:y.map(w=>e.jsx("option",{value:w.id,children:w.label},w.id))})]})]})]})]})},bo=({isOpen:t,onClose:s,mode:a,onSubmit:r})=>{const[n,i]=l.useState(""),[o,c]=l.useState(""),[d,u]=l.useState(""),[p,m]=l.useState(!1),[x,h]=l.useState(!1),[f,v]=l.useState(null),[A,g]=l.useState(!1),k=l.useCallback(()=>{i(""),c(""),u(""),m(!1),h(!1),v(null),g(!1)},[]),N=l.useCallback(()=>{k(),s()},[s,k]),b=l.useCallback(async w=>{if(w.preventDefault(),v(null),a==="setup"){if(n.length<8){v("Password must be at least 8 characters");return}if(n!==d){v("Passwords do not match");return}}if(a==="change"){if(o.length<8){v("New password must be at least 8 characters");return}if(o!==d){v("New passwords do not match");return}}g(!0);try{await r(n,a==="change"?o:void 0)?k():v(a==="unlock"?"Incorrect password":"Operation failed. Check your current password.")}catch(S){v(S instanceof Error?S.message:"An error occurred")}finally{g(!1)}},[a,n,o,d,r,k]),j={setup:"Set Master Password",unlock:"Unlock Settings",change:"Change Master Password"},y={setup:"Create a master password to encrypt your API keys. This password is never stored — only a verification hash is kept.",unlock:"Enter your master password to access encrypted API keys.",change:"Change your master password. All stored keys will be re-encrypted."};return e.jsx(ur,{open:t,onOpenChange:w=>!w&&N(),children:e.jsxs(mr,{className:"sm:max-w-md bg-background",children:[e.jsxs(pr,{children:[e.jsxs(xr,{className:"flex items-center gap-2",children:[e.jsx(Li,{size:18,className:"text-primary"}),j[a]]}),e.jsx(il,{children:y[a]})]}),e.jsxs("form",{onSubmit:b,className:"space-y-4",children:[a==="change"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-text-secondary",children:"Current Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ts,{type:p?"text":"password",value:n,onChange:w=>i(w.target.value),placeholder:"Enter current password",autoFocus:!0,className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>m(!p),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors",children:p?e.jsx(Xs,{size:16}):e.jsx($s,{size:16})})]})]}),(a==="setup"||a==="unlock")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-text-secondary",children:a==="setup"?"Password":"Master Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ts,{type:p?"text":"password",value:n,onChange:w=>i(w.target.value),placeholder:a==="setup"?"Min. 8 characters":"Enter master password",autoFocus:!0,className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>m(!p),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors",children:p?e.jsx(Xs,{size:16}):e.jsx($s,{size:16})})]})]}),(a==="setup"||a==="change")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-text-secondary",children:a==="change"?"New Password":"Confirm Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ts,{type:x?"text":"password",value:a==="change"?o:d,onChange:w=>a==="change"?c(w.target.value):u(w.target.value),placeholder:a==="change"?"Min. 8 characters":"Repeat password",className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>h(!x),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors",children:x?e.jsx(Xs,{size:16}):e.jsx($s,{size:16})})]})]}),a==="change"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-text-secondary",children:"Confirm New Password"}),e.jsx(ts,{type:x?"text":"password",value:d,onChange:w=>u(w.target.value),placeholder:"Repeat new password"})]})]}),f&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-error bg-error/10 px-3 py-2 rounded-lg",children:[e.jsx(ra,{size:14}),f]}),a==="setup"&&e.jsxs("div",{className:"flex items-start gap-2 text-xs text-text-muted bg-background-secondary px-3 py-2 rounded-lg",children:[e.jsx(qh,{size:14,className:"mt-0.5 shrink-0 text-primary"}),e.jsx("span",{children:"Your password is used to derive an encryption key via PBKDF2 (100k iterations). API keys are encrypted with AES-256-GCM. If you forget this password, stored keys cannot be recovered."})]}),e.jsxs(bm,{children:[e.jsx(zt,{type:"button",variant:"outline",onClick:N,disabled:A,children:"Cancel"}),e.jsx(zt,{type:"submit",disabled:A,children:A?"Processing...":a==="setup"?"Set Password":a==="unlock"?"Unlock":"Change Password"})]})]})]})})},r0=()=>{const{addConfiguredService:t,removeConfiguredService:s}=Fa(),[a,r]=l.useState(!1),[n,i]=l.useState(!1),[o,c]=l.useState(null),[d,u]=l.useState([]),[p,m]=l.useState(null),[x,h]=l.useState(""),[f,v]=l.useState({}),[A,g]=l.useState({}),k=l.useCallback(async()=>{const T=await ym();if(r(T),i(Mr()),Mr()){const C=await vm();u(C)}},[]);l.useEffect(()=>{k()},[k]);const N=l.useCallback(async(T,C)=>{if(o==="setup")return await jm(T),c(null),await k(),Fe.success("Master password set","Your API keys will be encrypted with AES-256-GCM."),!0;if(o==="unlock"){const M=await wm(T);return M&&(c(null),await k(),Fe.success("Session unlocked","You can now manage API keys.")),M}if(o==="change"&&C){const M=await km(T,C);return M&&(c(null),await k(),Fe.success("Password changed","All keys have been re-encrypted.")),M}return!1},[o,k]),b=l.useCallback(async T=>{if(!x.trim())return;const C=nr.find(M=>M.id===T);if(C)try{await Nm(T,C.label,x.trim()),t(T),h(""),m(null),await k(),Fe.success(`${C.label} key saved`,"API key encrypted and stored.")}catch(M){Fe.error("Failed to save",M instanceof Error?M.message:"Unknown error")}},[x,t,k]),j=l.useCallback(async T=>{const C=nr.find(M=>M.id===T);try{await Cm(T),s(T),v(M=>{const z={...M};return delete z[T],z}),await k(),Fe.success(`${C?.label??T} key removed`)}catch(M){Fe.error("Failed to delete",M instanceof Error?M.message:"Unknown error")}},[s,k]),y=l.useCallback(async T=>{if(f[T]){g(C=>({...C,[T]:!C[T]}));return}try{const C=await jn(T);C&&(v(M=>({...M,[T]:C})),g(M=>({...M,[T]:!0})))}catch(C){Fe.error("Failed to decrypt",C instanceof Error?C.message:"Unknown error")}},[f]),w=l.useCallback(()=>{Sm(),i(!1),u([]),v({}),g({})},[]),S=nr.filter(T=>!d.some(C=>C.id===T.id));return a?n?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[e.jsx(ic,{size:14,className:"text-primary"}),e.jsxs("span",{children:[d.length," key",d.length!==1?"s":""," stored"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(zt,{variant:"outline",size:"sm",onClick:()=>c("change"),children:[e.jsx(zn,{size:14,className:"mr-1"}),"Change Password"]}),e.jsxs(zt,{variant:"outline",size:"sm",onClick:w,children:[e.jsx(Li,{size:14,className:"mr-1"}),"Lock"]})]})]}),e.jsx("div",{className:"space-y-3",children:d.map(T=>{const C=nr.find(z=>z.id===T.id),M=A[T.id]&&f[T.id];return e.jsxs("div",{className:"border border-border rounded-lg p-4 bg-background-secondary",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-sm font-medium text-text-primary",children:C?.label??T.label}),C?.docsUrl&&e.jsx("a",{href:C.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"text-text-muted hover:text-primary transition-colors",children:e.jsx(Am,{size:12})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>y(T.id),className:"p-1.5 rounded hover:bg-background-tertiary text-text-muted hover:text-text-primary transition-colors",title:M?"Hide key":"Show key",children:M?e.jsx(Xs,{size:14}):e.jsx($s,{size:14})}),e.jsx("button",{onClick:()=>j(T.id),className:"p-1.5 rounded hover:bg-error/10 text-text-muted hover:text-error transition-colors",title:"Delete key",children:e.jsx($t,{size:14})})]})]}),C&&e.jsx("p",{className:"text-xs text-text-muted mb-2",children:C.description}),e.jsx("div",{className:"font-mono text-xs bg-background rounded px-3 py-2 text-text-secondary",children:M?f[T.id]:"••••••••••••••••••••••••••••••••"}),e.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:["Added ",new Date(T.createdAt).toLocaleDateString()," · Updated ",new Date(T.updatedAt).toLocaleDateString()]})]},T.id)})}),p?e.jsxs("div",{className:"border border-primary/30 rounded-lg p-4 bg-primary/5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(cs,{size:14,className:"text-primary"}),e.jsxs("span",{className:"text-sm font-medium text-text-primary",children:["Add"," ",nr.find(T=>T.id===p)?.label," Key"]})]}),e.jsx(ts,{type:"password",value:x,onChange:T=>h(T.target.value),placeholder:"Paste your API key here",autoFocus:!0,className:"mb-3 font-mono text-xs"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(zt,{variant:"outline",size:"sm",onClick:()=>{m(null),h("")},children:"Cancel"}),e.jsx(zt,{size:"sm",onClick:()=>b(p),disabled:!x.trim(),children:"Save Key"})]})]}):S.length>0?e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-3",children:"Add API Key"}),e.jsx("div",{className:"grid gap-2",children:S.map(T=>e.jsxs("button",{onClick:()=>m(T.id),className:"flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-left group",children:[e.jsx("div",{className:"p-2 rounded-lg bg-background-tertiary group-hover:bg-primary/10 transition-colors",children:e.jsx(cs,{size:14,className:"text-text-muted group-hover:text-primary transition-colors"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:T.label}),e.jsx("div",{className:"text-xs text-text-muted",children:T.description})]})]},T.id))})]}):null,o&&e.jsx(bo,{isOpen:!!o,onClose:()=>c(null),mode:o,onSubmit:N})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-amber-500/10 flex items-center justify-center mb-4",children:e.jsx(Li,{size:32,className:"text-amber-500"})}),e.jsx("h3",{className:"text-lg font-medium text-text-primary mb-2",children:"Session Locked"}),e.jsx("p",{className:"text-sm text-text-muted mb-6 max-w-sm",children:"Enter your master password to view and manage API keys."}),e.jsxs(zt,{onClick:()=>c("unlock"),children:[e.jsx(lh,{size:16,className:"mr-2"}),"Unlock"]}),o&&e.jsx(bo,{isOpen:!!o,onClose:()=>c(null),mode:o,onSubmit:N})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ic,{size:32,className:"text-primary"})}),e.jsx("h3",{className:"text-lg font-medium text-text-primary mb-2",children:"Secure API Key Storage"}),e.jsx("p",{className:"text-sm text-text-muted mb-6 max-w-sm",children:"Set up a master password to encrypt and store your API keys locally. Keys are encrypted with AES-256-GCM and never leave your browser."}),e.jsxs(zt,{onClick:()=>c("setup"),children:[e.jsx(Hx,{size:16,className:"mr-2"}),"Set Up Master Password"]}),o&&e.jsx(bo,{isOpen:!!o,onClose:()=>c(null),mode:o,onSubmit:N})]})},n0=[{id:"general",label:"General",icon:Da},{id:"api-keys",label:"API Keys",icon:zn}],i0=()=>{const{settingsOpen:t,settingsTab:s,closeSettings:a,openSettings:r}=Fa(),n=l.useCallback(i=>{r(i)},[r]);return e.jsx(ur,{open:t,onOpenChange:i=>!i&&a(),children:e.jsxs(mr,{className:"sm:max-w-2xl max-h-[85vh] bg-background flex flex-col overflow-y-auto",children:[e.jsxs(pr,{children:[e.jsxs(xr,{className:"flex items-center gap-2",children:[e.jsx(Da,{size:18,className:"text-primary"}),"Settings"]}),e.jsx(il,{children:"Configure preferences and manage API keys for external services."})]}),e.jsx("div",{role:"tablist","aria-label":"Settings",className:"flex gap-1 p-1 bg-muted rounded-md",children:n0.map(i=>e.jsxs("button",{role:"tab","aria-selected":s===i.id,"aria-controls":`settings-tabpanel-${i.id}`,id:`settings-tab-${i.id}`,onClick:()=>n(i.id),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-sm transition-colors ${s===i.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(i.icon,{size:14}),i.label]},i.id))}),e.jsxs("div",{role:"tabpanel",id:`settings-tabpanel-${s}`,"aria-labelledby":`settings-tab-${s}`,className:"flex-1 overflow-y-auto pr-1 mt-2",children:[s==="general"&&e.jsx(a0,{}),s==="api-keys"&&e.jsx(r0,{})]})]})})},Ur=320,Nr=16,vs=8,o0=({step:t,targetRect:s,currentStep:a,totalSteps:r,isFirstStep:n,isLastStep:i,onNext:o,onPrev:c,onSkip:d,onGoToStep:u})=>{const{position:p,arrowPosition:m}=l.useMemo(()=>{if(!s||t.position==="center")return{position:{x:0,y:0},arrowPosition:null};const h={width:window.innerWidth,height:window.innerHeight};let f=0,v=0,A=null;const g=12,k={left:s.left-g,top:s.top-g,right:s.right+g,bottom:s.bottom+g,width:s.width+g*2,height:s.height+g*2};switch(t.position){case"right":f=k.right+Nr,v=k.top+k.height/2-100,A="left";break;case"left":f=k.left-Ur-Nr,v=k.top+k.height/2-100,A="right";break;case"top":f=k.left+k.width/2-Ur/2,v=k.top-200-Nr,A="bottom";break;case"bottom":f=k.left+k.width/2-Ur/2,v=k.bottom+Nr,A="top";break}return f=Math.max(Nr,Math.min(f,h.width-Ur-Nr)),v=Math.max(Nr,Math.min(v,h.height-250)),{position:{x:f,y:v},arrowPosition:A}},[s,t.position]),x=t.position==="center"||!s;return e.jsx(fs.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},transition:{type:"spring",stiffness:500,damping:30},className:`fixed z-[102] ${x?"inset-0 flex items-center justify-center pointer-events-none":""}`,style:x?void 0:{left:p.x,top:p.y,width:Ur},children:e.jsxs("div",{className:"relative bg-background-secondary border border-border rounded-xl shadow-2xl pointer-events-auto",style:{width:x?Ur:"100%"},children:[m&&!x&&e.jsx("div",{className:"absolute w-0 h-0",style:{...m==="left"&&{left:-vs,top:"50%",transform:"translateY(-50%)",borderTop:`${vs}px solid transparent`,borderBottom:`${vs}px solid transparent`,borderRight:`${vs}px solid var(--border)`},...m==="right"&&{right:-vs,top:"50%",transform:"translateY(-50%)",borderTop:`${vs}px solid transparent`,borderBottom:`${vs}px solid transparent`,borderLeft:`${vs}px solid var(--border)`},...m==="top"&&{top:-vs,left:"50%",transform:"translateX(-50%)",borderLeft:`${vs}px solid transparent`,borderRight:`${vs}px solid transparent`,borderBottom:`${vs}px solid var(--border)`},...m==="bottom"&&{bottom:-vs,left:"50%",transform:"translateX(-50%)",borderLeft:`${vs}px solid transparent`,borderRight:`${vs}px solid transparent`,borderTop:`${vs}px solid var(--border)`}}}),e.jsx("button",{onClick:d,className:"absolute top-3 right-3 p-1 rounded hover:bg-background-tertiary text-text-muted hover:text-text-primary transition-colors",children:e.jsx(Ls,{size:14})}),e.jsxs("div",{className:"p-6",children:[e.jsx(fs.h2,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.1},className:"text-lg font-bold text-text-primary mb-2",children:t.title},`title-${a}`),e.jsx(fs.p,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.15},className:"text-sm text-text-secondary mb-4",children:t.description},`desc-${a}`),t.tips&&t.tips.length>0&&e.jsx(fs.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:"bg-background-tertiary rounded-lg p-3 mb-4",children:e.jsx("ul",{className:"space-y-1.5",children:t.tips.map((h,f)=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-text-secondary",children:[e.jsx("span",{className:"text-primary mt-0.5",children:"•"}),h]},f))})},`tips-${a}`),e.jsx("div",{className:"flex items-center justify-center gap-1.5 mb-4",children:Array.from({length:r}).map((h,f)=>e.jsx("button",{onClick:()=>u(f),className:`w-2 h-2 rounded-full transition-all ${f===a?"bg-primary scale-110":"bg-border hover:bg-text-muted"}`},f))})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-border bg-background-tertiary rounded-b-xl",children:[e.jsxs("button",{onClick:c,disabled:n,className:"flex items-center gap-1 px-3 py-1.5 text-xs text-text-secondary hover:text-text-primary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:[e.jsx(dl,{size:14}),"Back"]}),e.jsx("button",{onClick:d,className:"px-3 py-1.5 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Skip Tour"}),e.jsxs("button",{onClick:o,className:"flex items-center gap-1 px-4 py-1.5 bg-primary text-white rounded-lg text-xs font-medium hover:bg-primary/80 transition-colors",children:[i?"Get Started":"Next",!i&&e.jsx(bs,{size:14})]})]})]})})},ui=[{id:"welcome",target:null,title:"Welcome to OpenReel",description:"Let's take a quick tour of the editor",position:"center"},{id:"assets",target:"[data-tour='assets']",title:"Assets Panel",description:"Your creative toolkit. Import media, generate AI content, add shapes, stickers, and custom SVGs.",tips:["Drag & drop videos, audio, images","AI Gen tab: generate images & backgrounds with AI","Shapes & custom SVG imports","Stickers, backgrounds & overlays"],position:"right"},{id:"timeline",target:"[data-tour='timeline']",title:"Timeline",description:"Arrange and edit your clips. Drag to move, drag edges to trim.",tips:["Press S to split clips","Space to play/pause","Scroll to zoom"],position:"top"},{id:"preview",target:"[data-tour='preview']",title:"Preview",description:"Watch your video in real-time as you edit.",tips:["Arrow keys for frame navigation","Click to scrub","Fullscreen available"],position:"left"},{id:"inspector",target:"[data-tour='inspector']",title:"Inspector",description:"Select a clip to see its properties. Add effects, adjust colors, animate.",tips:["Transform, effects, color grading","Keyframe any property","AI-powered tools"],position:"left"},{id:"complete",target:null,title:"You're Ready!",description:"Start creating! Press ? anytime for keyboard shortcuts.",position:"center"}],Mi="openreel-onboarding-complete";let Go={isActive:!1,currentStep:0};const Ho=new Set;function l0(){Ho.forEach(t=>t())}function c0(t){return Ho.add(t),()=>Ho.delete(t)}function Ac(){return Go}function Sr(t){Go={...Go,...t},l0()}function d0(){Sr({isActive:!0,currentStep:0})}function u0(){const t=l.useSyncExternalStore(c0,Ac,Ac),[s,a]=l.useState(null),r=ui[t.currentStep],n=t.currentStep===0,i=t.currentStep===ui.length-1,o=l.useCallback(()=>{if(!r?.target){a(null);return}const x=document.querySelector(r.target);a(x?x.getBoundingClientRect():null)},[r?.target]);l.useEffect(()=>{if(!t.isActive)return;o();const x=()=>o();window.addEventListener("resize",x);const h=setInterval(o,100);return()=>{window.removeEventListener("resize",x),clearInterval(h)}},[t.isActive,t.currentStep,o]);const c=l.useCallback(()=>{Sr({currentStep:0,isActive:!0})},[]),d=l.useCallback(()=>{i?(localStorage.setItem(Mi,"true"),Sr({isActive:!1})):Sr({currentStep:t.currentStep+1})},[i,t.currentStep]),u=l.useCallback(()=>{n||Sr({currentStep:t.currentStep-1})},[n,t.currentStep]),p=l.useCallback(()=>{localStorage.setItem(Mi,"true"),Sr({isActive:!1})},[]),m=l.useCallback(x=>{x>=0&&x{if(!localStorage.getItem(Mi)){const h=setTimeout(()=>{c()},500);return()=>clearTimeout(h)}},[c]),l.useEffect(()=>{if(!t.isActive)return;const x=h=>{h.key==="Escape"?p():h.key==="ArrowRight"||h.key==="Enter"?d():h.key==="ArrowLeft"&&u()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t.isActive,d,u,p]),{isActive:t.isActive,currentStep:t.currentStep,step:r,targetRect:s,isFirstStep:n,isLastStep:i,totalSteps:ui.length,start:c,next:d,prev:u,skip:p,goToStep:m}}const m0=()=>{const{isActive:t,currentStep:s,step:a,targetRect:r,isFirstStep:n,isLastStep:i,totalSteps:o,next:c,prev:d,skip:u,goToStep:p}=u0();if(!t||!a)return null;const m=12,x=!!r,h=x?{left:r.left-m,top:r.top-m,width:r.width+m*2,height:r.height+m*2}:null;return e.jsx(wd,{mode:"wait",children:e.jsxs("div",{className:"fixed inset-0 z-[100] pointer-events-none",children:[x&&h?e.jsxs(e.Fragment,{children:[e.jsx(fs.div,{className:"fixed left-0 right-0 top-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,height:h.top},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`top-${s}`),e.jsx(fs.div,{className:"fixed left-0 right-0 bottom-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,height:window.innerHeight-h.top-h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`bottom-${s}`),e.jsx(fs.div,{className:"fixed left-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,top:h.top,width:h.left,height:h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`left-${s}`),e.jsx(fs.div,{className:"fixed right-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,top:h.top,width:window.innerWidth-h.left-h.width,height:h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`right-${s}`),e.jsx(fs.div,{className:"fixed pointer-events-none border-2 border-primary rounded-lg",initial:{opacity:0,scale:1.05},animate:{opacity:1,scale:1,left:h.left,top:h.top,width:h.width,height:h.height},transition:{type:"spring",stiffness:300,damping:30},style:{boxShadow:"0 0 0 4px rgba(34, 197, 94, 0.2), 0 0 20px rgba(34, 197, 94, 0.3)"}},`ring-${s}`)]}):e.jsx(fs.div,{className:"fixed inset-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.3},onClick:u},"full-overlay"),e.jsx(o0,{step:a,targetRect:r,currentStep:s,totalSteps:o,isFirstStep:n,isLastStep:i,onNext:c,onPrev:d,onSkip:u,onGoToStep:p})]},"tour-overlay")})},mi=[{id:"intro",target:null,title:"Motion Graphics & Animation",description:"Learn how to create professional animations with keyframes, motion paths, and particle effects.",position:"center"},{id:"keyframes-inspector",target:"[data-tour='inspector']",title:"Keyframe Animation",description:"Select any clip and expand the Keyframes section in the Inspector. Add keyframes to animate position, scale, rotation, and opacity over time.",tips:["Click the diamond icon to add a keyframe at current time","Each property can have its own animation curve","Choose from 30+ easing presets for smooth motion"],position:"left"},{id:"keyframes-timeline",target:"[data-tour='timeline']",title:"Timeline Keyframe View",description:"Click the expand arrow on any track header to reveal keyframe sub-tracks. Drag keyframe diamonds to adjust timing visually.",tips:["Diamond markers show keyframe positions","Drag horizontally to change timing","Click the curve between keyframes to edit easing"],position:"top"},{id:"keyframe-editor",target:"[data-tour='toolbar']",title:"Graph Editor",description:"Open the Keyframe Editor panel from the toolbar for precise control. Edit value curves, copy/paste keyframes, and fine-tune animations.",tips:["Drag keyframe points to adjust time and value","Select multiple keyframes with Shift+click","Apply easing presets to selected keyframes"],position:"bottom"},{id:"motion-path",target:"[data-tour='preview']",title:"Motion Paths",description:"Create smooth movement along custom paths. Enable Motion Path mode to draw bezier curves directly on the preview canvas.",tips:["Click on the canvas to add path points","Drag control handles to curve the path","Elements follow the path as they animate","Great for flying logos and dynamic text"],position:"left"},{id:"particle-effects",target:"[data-tour='inspector']",title:"Particle Effects",description:"Add cinematic particle effects like confetti, sparkles, dust, and explosions. Find them in the Inspector's Particle Effects section.",tips:["Choose from preset effects or customize","Adjust particle count, speed, and colors","Set timing for when effects appear","Combine with keyframes for dramatic reveals"],position:"left"},{id:"emphasis-animations",target:"[data-tour='inspector']",title:"Emphasis Animations",description:"Make elements pop with attention-grabbing animations. Pulse, bounce, shake, wiggle, and more - perfect for highlighting important content.",tips:["24 built-in emphasis presets","Set duration and loop count","Combine with entrance/exit animations"],position:"left"},{id:"text-animations",target:"[data-tour='inspector']",title:"Text Animation Presets",description:"Animate text with professional presets. Characters can fade in, slide, bounce, or appear with typewriter effects.",tips:["19 text animation styles available","Per-character or per-word animation","Customize timing and easing"],position:"left"},{id:"complete",target:null,title:"Start Animating!",description:"You're ready to create professional motion graphics. Select a clip and start experimenting with keyframes and effects.",tips:["Press K to add a keyframe at playhead","Use ? to see all keyboard shortcuts","Combine effects for unique animations"],position:"center"}],Wo="openreel-mograph-tour-complete";let qo={isActive:!1,currentStep:0};const Qo=new Set;function p0(){Qo.forEach(t=>t())}function x0(t){return Qo.add(t),()=>Qo.delete(t)}function Tc(){return qo}function Ar(t){qo={...qo,...t},p0()}function h0(){Ar({isActive:!0,currentStep:0})}function f0(){const t=l.useSyncExternalStore(x0,Tc,Tc),[s,a]=l.useState(null),r=mi[t.currentStep],n=t.currentStep===0,i=t.currentStep===mi.length-1,o=l.useCallback(()=>{if(!r?.target){a(null);return}const x=document.querySelector(r.target);a(x?x.getBoundingClientRect():null)},[r?.target]);l.useEffect(()=>{if(!t.isActive)return;o();const x=()=>o();window.addEventListener("resize",x);const h=setInterval(o,100);return()=>{window.removeEventListener("resize",x),clearInterval(h)}},[t.isActive,t.currentStep,o]);const c=l.useCallback(()=>{Ar({currentStep:0,isActive:!0})},[]),d=l.useCallback(()=>{i?(localStorage.setItem(Wo,"true"),Ar({isActive:!1})):Ar({currentStep:t.currentStep+1})},[i,t.currentStep]),u=l.useCallback(()=>{n||Ar({currentStep:t.currentStep-1})},[n,t.currentStep]),p=l.useCallback(()=>{localStorage.setItem(Wo,"true"),Ar({isActive:!1})},[]),m=l.useCallback(x=>{x>=0&&x{if(!t.isActive)return;const x=h=>{h.key==="Escape"?p():h.key==="ArrowRight"||h.key==="Enter"?d():h.key==="ArrowLeft"&&u()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t.isActive,d,u,p]),{isActive:t.isActive,currentStep:t.currentStep,step:r,targetRect:s,isFirstStep:n,isLastStep:i,totalSteps:mi.length,start:c,next:d,prev:u,skip:p,goToStep:m}}const g0=()=>{const{isActive:t,currentStep:s,step:a,targetRect:r,isFirstStep:n,isLastStep:i,totalSteps:o,next:c,prev:d,skip:u,goToStep:p}=f0();if(!t||!a)return null;const m=12,x=!!r,h=x?{left:r.left-m,top:r.top-m,width:r.width+m*2,height:r.height+m*2}:null,v=(()=>{if(!x||!h)return{left:"50%",top:"50%",transform:"translate(-50%, -50%)"};const A=380,g=16;switch(a.position){case"right":return{left:h.left+h.width+g,top:h.top+h.height/2,transform:"translateY(-50%)",maxWidth:window.innerWidth-h.left-h.width-g-20};case"left":return{left:h.left-g,top:h.top+h.height/2,transform:"translate(-100%, -50%)",maxWidth:h.left-g-20};case"top":return{left:h.left+h.width/2,top:h.top-g,transform:"translate(-50%, -100%)",maxWidth:A};case"bottom":return{left:h.left+h.width/2,top:h.top+h.height+g,transform:"translateX(-50%)",maxWidth:A};default:return{left:"50%",top:"50%",transform:"translate(-50%, -50%)",maxWidth:A}}})();return e.jsx(wd,{mode:"wait",children:e.jsxs("div",{className:"fixed inset-0 z-[100] pointer-events-none",children:[x&&h?e.jsxs(e.Fragment,{children:[e.jsx(fs.div,{className:"fixed left-0 right-0 top-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,height:h.top},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`top-${s}`),e.jsx(fs.div,{className:"fixed left-0 right-0 bottom-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,height:window.innerHeight-h.top-h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`bottom-${s}`),e.jsx(fs.div,{className:"fixed left-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,top:h.top,width:h.left,height:h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`left-${s}`),e.jsx(fs.div,{className:"fixed right-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1,top:h.top,width:window.innerWidth-h.left-h.width,height:h.height},transition:{type:"spring",stiffness:300,damping:30},onClick:u},`right-${s}`),e.jsx(fs.div,{className:"fixed pointer-events-none border-2 border-purple-500 rounded-lg",initial:{opacity:0,scale:1.05},animate:{opacity:1,scale:1,left:h.left,top:h.top,width:h.width,height:h.height},transition:{type:"spring",stiffness:300,damping:30},style:{boxShadow:"0 0 0 4px rgba(168, 85, 247, 0.2), 0 0 20px rgba(168, 85, 247, 0.3)"}},`ring-${s}`)]}):e.jsx(fs.div,{className:"fixed inset-0 bg-black/80 pointer-events-auto",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.3},onClick:u},"full-overlay"),e.jsxs(fs.div,{className:"fixed pointer-events-auto bg-background-secondary border border-purple-500/30 rounded-xl shadow-2xl overflow-hidden",initial:{opacity:0,scale:.9,y:10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.9,y:10},transition:{type:"spring",stiffness:400,damping:30},style:{...v,width:380},children:[e.jsxs("div",{className:"bg-gradient-to-r from-purple-600 to-pink-600 px-4 py-3 flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-white/20 flex items-center justify-center",children:e.jsx(gs,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-white font-semibold text-sm",children:a.title}),e.jsxs("p",{className:"text-white/60 text-[10px]",children:["Motion Graphics Tour • Step ",s+1," of ",o]})]}),e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-white/10 text-white/60 hover:text-white transition-colors",children:e.jsx(Ls,{size:16})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-text-secondary text-sm leading-relaxed mb-4",children:a.description}),a.tips&&a.tips.length>0&&e.jsxs("div",{className:"bg-purple-500/10 rounded-lg p-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(sh,{size:14,className:"text-purple-400"}),e.jsx("span",{className:"text-purple-400 text-xs font-medium",children:"Pro Tips"})]}),e.jsx("ul",{className:"space-y-1.5",children:a.tips.map((A,g)=>e.jsxs("li",{className:"text-text-muted text-xs flex items-start gap-2",children:[e.jsx("span",{className:"text-purple-400 mt-0.5",children:"•"}),e.jsx("span",{children:A})]},g))})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:Array.from({length:o}).map((A,g)=>e.jsx("button",{onClick:()=>p(g),className:`h-1.5 rounded-full transition-all ${g===s?"w-6 bg-purple-500":"w-1.5 bg-border hover:bg-purple-500/50"}`},g))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:d,disabled:n,className:"flex items-center gap-1 px-3 py-2 text-xs rounded-lg bg-background-tertiary text-text-secondary hover:text-text-primary disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[e.jsx(dl,{size:14}),"Back"]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:u,className:"px-3 py-2 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Skip Tour"}),e.jsxs("button",{onClick:c,className:"flex items-center gap-1 px-4 py-2 text-xs rounded-lg bg-gradient-to-r from-purple-600 to-pink-600 text-white font-medium hover:from-purple-500 hover:to-pink-500 transition-all",children:[i?"Get Started":"Next",!i&&e.jsx(bs,{size:14})]})]})]})]},`popover-${s}`)]},"mograph-tour-overlay")})},b0=()=>{const{project:t,undo:s,redo:a,renameProject:r}=F(),{openModal:n,selectedItems:i,setExportState:o,keyframeEditorOpen:c,toggleKeyframeEditor:d,panels:u,togglePanel:p}=vt(),{mode:m,toggleTheme:x}=Oi(),{navigate:h}=Tm(),{openSettings:f}=Fa(),[v,A]=l.useState(!1),[g,k]=l.useState(!1),[N,b]=l.useState(!1),[j,y]=l.useState(!1),{importMedia:w}=F(),{track:S}=Mm(),[T,C]=l.useState(t.name);l.useEffect(()=>{C(t.name)},[t.name]);const M=l.useMemo(()=>{const de=t.modifiedAt??Date.now();return new Date(de).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})},[t.modifiedAt]),z=l.useCallback(()=>{const de=T.trim();de&&de!==t.name?r(de):C(t.name)},[T,t.name,r]),L=l.useCallback(()=>{s()},[s]),B=l.useCallback(()=>{a()},[a]),O=l.useCallback(()=>{localStorage.removeItem(Mi),d0()},[]),G=l.useCallback(()=>{localStorage.removeItem(Wo),h0()},[]),[V,P]=l.useState({isExporting:!1,progress:0,phase:"",error:null,complete:!1}),[_,se]=l.useState(null),[R,U]=l.useState(new Map);l.useEffect(()=>{o({isExporting:V.isExporting,progress:V.progress,phase:V.phase})},[V.isExporting,V.progress,V.phase,o]),l.useEffect(()=>{v&&!_&&Yo().then(se)},[v,_]),l.useEffect(()=>{if(!_||!t.timeline?.duration)return;const de=t.timeline.duration,Ce=new Map,Ne=[{key:"mp4",width:t.settings.width,height:t.settings.height,frameRate:30,codec:"h264"},{key:"4k",width:3840,height:2160,frameRate:30,codec:"h264"},{key:"4k-60-master",width:3840,height:2160,frameRate:60,codec:"h264"},{key:"4k-master",width:3840,height:2160,frameRate:30,codec:"h264"},{key:"1080p-high",width:1920,height:1080,frameRate:30,codec:"h264"},{key:"1080p-60",width:1920,height:1080,frameRate:60,codec:"h264"},{key:"prores",width:t.settings.width,height:t.settings.height,frameRate:30,codec:"h264"}];for(const Me of Ne){const qe=xu(_,{width:Me.width,height:Me.height,frameRate:Me.frameRate,duration:de,codec:Me.codec});Ce.set(Me.key,qe)}U(Ce)},[_,t.timeline?.duration,t.settings.width,t.settings.height]);const D=l.useCallback(async(de,Ce,Ne)=>{const Me=io();await Me.initialize();const qe=Me.exportVideo(t,de,Ne);let nt;for(;;){const{value:rt,done:Pe}=await qe.next();if(Pe){nt=rt;break}P(Ie=>({...Ie,progress:rt.progress*100,phase:rt.phase==="complete"?"Complete!":`${rt.phase}...`}))}if(nt?.success)P(rt=>({...rt,complete:!0,phase:"Saved!"})),S(oo.PROJECT_EXPORTED,{format:de.format??"mp4",codec:de.codec??"h264",width:de.width??t.settings.width,height:de.height??t.settings.height,frameRate:de.frameRate??t.settings.frameRate,duration:t.timeline?.duration??0});else throw new Error(nt?.error?.message||"Export failed")},[t,S]),X=l.useCallback(async(de,Ce)=>{const Me={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",wav:"audio/wav"}[Ce]||"application/octet-stream";if("showSaveFilePicker"in window)return(await window.showSaveFilePicker({suggestedName:de,types:[{description:"Media file",accept:{[Me]:[`.${Ce}`]}}]})).createWritable();let qe=new Uint8Array(16*1024*1024),nt=0,rt=0;const Pe=ae=>{if(ae<=qe.length)return;let W=qe.length;for(;W{const ae=new Blob([qe.slice(0,nt)],{type:Me}),W=URL.createObjectURL(ae),Q=document.createElement("a");Q.href=W,Q.download=de,document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(W)},Ee=(ae,W)=>{const Q=W+ae.byteLength;Pe(Q),qe.set(ae,W),Q>nt&&(nt=Q),rt=Q};return{seek(ae){return rt=ae,Promise.resolve()},write(ae){return ae instanceof ArrayBuffer?Ee(new Uint8Array(ae),rt):ArrayBuffer.isView(ae)&&Ee(new Uint8Array(ae.buffer,ae.byteOffset,ae.byteLength),rt),Promise.resolve()},close(){return Ie(),Promise.resolve()},abort(){return Promise.resolve()},truncate(){return Promise.resolve()}}},[]),K=l.useCallback(async de=>{A(!1);try{if(de==="wav"){const Ce=await X(`${t.name||"export"}.wav`,"wav");P({isExporting:!0,progress:0,phase:"Initializing...",error:null,complete:!1});const Ne=io();await Ne.initialize();const Me={format:"wav",sampleRate:48e3,channels:2,bitDepth:24},qe=Ne.exportAudio(t,Me);let nt;for(;;){const{value:rt,done:Pe}=await qe.next();if(Pe){nt=rt;break}P(Ie=>({...Ie,progress:rt.progress*100,phase:rt.phase==="complete"?"Complete!":`${rt.phase}...`}))}if(nt?.success&&nt.blob){if("showSaveFilePicker"in window)await nt.blob.stream().pipeTo(Ce);else{const rt=URL.createObjectURL(nt.blob),Pe=document.createElement("a");Pe.href=rt,Pe.download=`${t.name||"export"}.wav`,document.body.appendChild(Pe),Pe.click(),document.body.removeChild(Pe),URL.revokeObjectURL(rt)}P(rt=>({...rt,complete:!0,phase:"Saved!"})),S(oo.PROJECT_EXPORTED,{format:"wav",duration:t.timeline?.duration??0})}else{try{await Ce.abort()}catch{}throw new Error(nt?.error?.message||"Export failed")}}else{const Ce={width:t.settings.width,height:t.settings.height,frameRate:t.settings.frameRate},Ne={mp4:{settings:{...Ce,format:"mp4",codec:"h264",bitrate:12e3,quality:85},ext:"mp4"},gif:{settings:{...Ce,format:"webm",codec:"vp9",bitrate:8e3},ext:"webm"},project:{settings:{...Ce,format:"mp4",codec:"h264",bitrate:12e3,quality:85},ext:"mp4"},"4k-60-master":{settings:{...Ce,width:3840,height:2160,frameRate:60,format:"mov",codec:"h265",bitrate:1e5,quality:95},ext:"mov"},"4k-master":{settings:{...Ce,width:3840,height:2160,frameRate:30,format:"mov",codec:"h265",bitrate:8e4,quality:95},ext:"mov"},"4k-prores":{settings:{...Ce,width:3840,height:2160,frameRate:30,format:"mov",codec:"prores",bitrate:88e4,quality:100},ext:"mov"},"4k":{settings:{...Ce,width:3840,height:2160,frameRate:30,format:"mp4",codec:"h264",bitrate:5e4,quality:90},ext:"mp4"},"1080p-60":{settings:{...Ce,width:1920,height:1080,frameRate:60,format:"mp4",codec:"h264",bitrate:25e3,quality:95},ext:"mp4"},"1080p-high":{settings:{...Ce,width:1920,height:1080,frameRate:30,format:"mp4",codec:"h264",bitrate:2e4,quality:95},ext:"mp4"},prores:{settings:{...Ce,format:"mov",codec:"prores",bitrate:22e4,quality:100},ext:"mov"}},Me=Ne[de]??Ne.mp4,qe=await X(`${t.name||"export"}.${Me.ext}`,Me.ext);P({isExporting:!0,progress:0,phase:"Initializing...",error:null,complete:!1}),await D(Me.settings,Me.ext,qe)}setTimeout(()=>{P({isExporting:!1,progress:0,phase:"",error:null,complete:!1})},2e3)}catch(Ce){if(Ce instanceof Error&&Ce.name==="AbortError")return;P(Ne=>({...Ne,isExporting:!1,error:Ce instanceof Error?Ce.message:"Export failed"}))}},[t,S,D,X]),ue=l.useCallback(()=>{io().cancel(),P({isExporting:!1,progress:0,phase:"",error:null,complete:!1})},[]),Te=l.useCallback(async de=>{k(!1);try{const Ce=de.format==="mov"?"mov":de.format==="webm"?"webm":"mp4",Ne=await X(`${t.name||"export"}.${Ce}`,Ce);P({isExporting:!0,progress:0,phase:"Initializing...",error:null,complete:!1});const Me=de.width>t.settings.width||de.height>t.settings.height,qe={...de,upscaling:de.upscaling?.enabled&&Me?de.upscaling:void 0};await D(qe,Ce,Ne),S(oo.PROJECT_EXPORTED,{format:de.format,codec:de.codec,width:de.width,height:de.height,frameRate:de.frameRate,duration:t.timeline?.duration??0,exportType:"custom",upscaling:de.upscaling?.enabled??!1}),setTimeout(()=>{P({isExporting:!1,progress:0,phase:"",error:null,complete:!1})},2e3)}catch(Ce){if(Ce instanceof Error&&Ce.name==="AbortError")return;P(Ne=>({...Ne,isExporting:!1,error:Ce instanceof Error?Ce.message:"Export failed"}))}},[t,S,D,X]),pe=l.useCallback(async(de,Ce)=>{if(!de||de.size===0){Fe.error("Recording failed","No video data was captured. Please try again.");return}const Ne=new Date().toISOString().slice(0,19).replace(/[:-]/g,"");let Me=0;const qe=[],nt=new File([de],`Screen_${Ne}.webm`,{type:de.type||"video/webm"}),rt=await w(nt);if(rt.success?Me++:qe.push(rt.error?.message||"Failed to import screen recording"),Ce&&Ce.size>0){const Pe=new File([Ce],`Webcam_${Ne}.webm`,{type:Ce.type||"video/webm"}),Ie=await w(Pe);Ie.success?Me++:qe.push(Ie.error?.message||"Failed to import webcam recording")}Me>0?Fe.success(`${Me} recording${Me>1?"s":""} imported!`,Ce&&Ce.size>0?"Screen and webcam added to assets. Use the timeline to composite them.":"Screen recording added to assets."):qe.length>0&&Fe.error("Import failed",qe.join(". "))},[w]),fe=`${t.settings.width}×${t.settings.height}`,Ze=t.settings.width/t.settings.height<.9,at=[{label:"MP4 Standard",icon:ks,desc:`${fe} H.264 - Web & social`,type:"mp4",recommended:!0},{label:"",icon:lr,desc:"",type:"mp4",separator:!0},...Ze?[]:[{label:"4K Standard",icon:Tn,desc:"3840×2160 - YouTube 4K",type:"4k"}],{label:"1080p High Quality",icon:Tn,desc:"1920×1080 30fps - High bitrate",type:"1080p-high"},{label:"1080p 60fps",icon:Tn,desc:"1920×1080 - Smooth playback",type:"1080p-60"},{label:"Audio Only (WAV)",icon:Ps,desc:"Uncompressed audio",type:"wav"}];return e.jsxs("header",{className:"h-topbar grid grid-cols-[1fr_auto_1fr] items-center gap-2.5 px-3 bg-bg border-b border-border shrink-0 z-30 relative",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>h("welcome"),className:"flex items-center gap-1.5 pr-1.5",title:"Back to home",children:[e.jsx("span",{className:"w-[11px] h-[11px] rounded-full bg-[oklch(0.7_0.18_25)]"}),e.jsx("span",{className:"w-[11px] h-[11px] rounded-full bg-[oklch(0.78_0.14_80)]"}),e.jsx("span",{className:"w-[11px] h-[11px] rounded-full bg-[oklch(0.7_0.15_145)]"})]}),e.jsxs("span",{className:"text-[11px] text-fg-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"w-[5px] h-[5px] rounded-full bg-accent"}),V.isExporting?`Exporting… ${Math.round(V.progress)}%`:`Auto saved: ${M}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[12.5px] font-medium tracking-tight",children:[e.jsx("input",{value:T,onChange:de=>C(de.target.value),onBlur:z,onKeyDown:de=>{de.key==="Enter"?de.currentTarget.blur():de.key==="Escape"&&(C(t.name),de.currentTarget.blur())},size:Math.max(T.length,6),spellCheck:!1,className:"bg-transparent border-0 text-center font-medium text-[12.5px] tracking-tight text-fg px-2 py-0.5 rounded min-w-[60px] focus:bg-bg-2 focus:outline-none"}),e.jsx(t0,{})]}),e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:()=>n("search"),className:"w-[26px] h-[26px] grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors","data-tip":"Search (⌘K)",children:e.jsx(la,{size:14})})}),e.jsx(wr,{children:"Search tools, effects, or ask AI… (⌘K)"})]}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:L,className:"w-[26px] h-[26px] grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(pn,{size:14})})}),e.jsx(wr,{children:"Undo (⌘Z)"})]}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:B,className:"w-[26px] h-[26px] grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(pl,{size:14})})}),e.jsx(wr,{children:"Redo (⇧⌘Z)"})]}),e.jsx("div",{className:"w-px h-4 bg-border mx-1"}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:()=>y(de=>!de),className:`w-[26px] h-[26px] grid place-items-center rounded-md transition-colors ${j?"bg-accent-soft text-accent":"text-fg-2 hover:bg-hover hover:text-fg"}`,children:e.jsx(Ai,{size:14})})}),e.jsx(wr,{children:"Action history"})]}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:d,className:`w-[26px] h-[26px] grid place-items-center rounded-md transition-colors ${c?"bg-accent-soft text-accent":"text-fg-2 hover:bg-hover hover:text-fg"}`,children:e.jsx(Gi,{size:14})})}),e.jsx(wr,{children:"Keyframe editor"})]}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:()=>p("audioMixer"),className:`w-[26px] h-[26px] grid place-items-center rounded-md transition-colors ${u.audioMixer?.visible?"bg-accent-soft text-accent":"text-fg-2 hover:bg-hover hover:text-fg"}`,children:e.jsx(Ps,{size:14})})}),e.jsx(wr,{children:"Audio mixer"})]}),e.jsxs(vr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx("button",{onClick:()=>vt.getState().openModal("scriptView"),className:"w-[26px] h-[26px] grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(xh,{size:14})})}),e.jsx(wr,{children:"Project JSON / Comments"})]}),e.jsx("div",{className:"w-px h-4 bg-border mx-1"}),e.jsxs(Di,{children:[e.jsx(Ii,{asChild:!0,children:e.jsx("button",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[12px] font-medium text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(Ys,{size:14})})}),e.jsxs(Bi,{align:"end",className:"w-56",children:[e.jsxs(ws,{onClick:x,className:"gap-2",children:[m==="light"?e.jsx(ru,{size:14}):m==="dark"?e.jsx(Zd,{size:14}):e.jsx(uf,{size:14}),e.jsxs("span",{className:"flex-1",children:["Theme: ",m]})]}),e.jsxs(ws,{onClick:()=>f(),className:"gap-2",children:[e.jsx(Da,{size:14}),e.jsx("span",{children:"Settings & API keys"})]}),e.jsxs(ws,{onClick:()=>b(!0),className:"gap-2",children:[e.jsx(or,{size:14,className:"fill-current text-status-error"}),e.jsx("span",{children:"Screen recorder"})]}),e.jsx(wn,{}),e.jsxs(ws,{onClick:O,className:"gap-2",children:[e.jsx(As,{size:14}),e.jsx("span",{children:"Editor tour"})]}),e.jsxs(ws,{onClick:G,className:"gap-2",children:[e.jsx(gs,{size:14,className:"text-purple-400"}),e.jsx("span",{children:"Animation & effects tour"})]}),e.jsx(wn,{}),e.jsxs(ws,{className:"gap-2 text-fg-muted",children:[e.jsx(rx,{size:14}),e.jsx("span",{children:"Help & shortcuts (press ?)"})]}),e.jsxs(ws,{className:"gap-2 text-fg-muted",children:[e.jsx(Ki,{size:14}),e.jsx("span",{children:"Project JSON"})]}),e.jsxs(ws,{className:"gap-2 text-fg-muted",children:[e.jsx(cx,{size:14}),e.jsx("span",{children:"⌘K to search"})]})]})]}),V.isExporting?e.jsx("div",{className:"relative",children:e.jsxs("button",{onClick:ue,className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-md bg-accent-soft text-accent text-[12.5px] font-semibold",children:[e.jsx(ds,{size:13,className:"animate-spin"}),e.jsxs("span",{children:[Math.round(V.progress),"%"]}),e.jsx(Ls,{size:11,className:"ml-1 opacity-70"})]})}):V.error?e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-md border border-status-error/40 bg-status-error/10 text-status-error text-[11px]",children:[e.jsx("span",{className:"max-w-[180px] truncate",children:V.error}),e.jsx("button",{onClick:()=>P(de=>({...de,error:null})),className:"opacity-70 hover:opacity-100",children:e.jsx(Ls,{size:11})})]}):V.complete?e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-md bg-accent-soft text-accent text-[12.5px]",children:[e.jsx(is,{size:13}),e.jsx("span",{className:"font-medium",children:"Saved!"})]}):e.jsxs(Di,{open:v,onOpenChange:A,children:[e.jsx(Ii,{asChild:!0,children:e.jsxs("button",{className:"relative inline-flex items-center gap-1.5 px-3.5 py-[5px] rounded-md bg-accent text-accent-fg font-semibold text-[12.5px] shadow-glow hover:bg-accent-strong transition-colors",children:[e.jsx(ya,{size:13}),e.jsx("span",{children:"Export"}),e.jsx(qt,{size:12,className:`transition-transform ${v?"rotate-180":""}`})]})}),e.jsxs(Bi,{align:"end",className:"w-72 p-0 rounded-xl bg-bg-1 border-border",children:[e.jsxs("div",{className:"p-3 space-y-1 max-h-[400px] overflow-y-auto",children:[at.map((de,Ce)=>de.separator?e.jsx(wn,{},`sep-${Ce}`):e.jsxs(ws,{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer hover:bg-hover focus:bg-hover ${de.recommended?"bg-accent-soft":""}`,onClick:()=>K(de.type),children:[e.jsx("div",{className:`p-2 rounded-lg transition-colors ${de.recommended?"bg-accent-soft text-accent":"bg-bg-2 text-fg-2"}`,children:e.jsx(de.icon,{size:18})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:`text-sm font-medium ${de.recommended?"text-accent":"text-fg"}`,children:[de.label,de.recommended&&e.jsx("span",{className:"ml-2 text-[10px] bg-accent-soft text-accent px-1.5 py-0.5 rounded",children:"Best match"})]}),e.jsx("div",{className:"text-xs text-fg-muted mt-0.5",children:de.desc}),R.get(de.type)&&e.jsxs("div",{className:"text-[10px] text-fg-3 mt-1",children:["Est. ",R.get(de.type)?.formatted]})]})]},de.type+Ce)),e.jsx(wn,{}),e.jsxs(ws,{className:"flex items-center gap-3 p-3 rounded-lg cursor-pointer hover:bg-hover focus:bg-hover",onClick:()=>k(!0),children:[e.jsx("div",{className:"p-2 bg-accent-soft rounded-lg text-accent",children:e.jsx(Da,{size:18})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-accent",children:"Custom export…"}),e.jsx("div",{className:"text-xs text-fg-muted mt-0.5",children:"Full settings with AI upscaling"})]}),e.jsx(jx,{size:14,className:"text-fg-muted"})]})]}),e.jsxs("div",{className:"bg-bg-2 px-3 py-2.5 text-xs text-center text-fg-muted border-t border-border",children:[t.settings.width,"×",t.settings.height," •"," ",t.settings.frameRate,"fps"]})]})]})]}),e.jsx(Xg,{isOpen:g,onClose:()=>k(!1),onExport:Te,duration:t.timeline?.duration??0,projectWidth:t.settings?.width??1920,projectHeight:t.settings?.height??1080}),e.jsx(Jg,{isOpen:N,onClose:()=>b(!1),onRecordingComplete:pe}),e.jsx(i0,{}),j&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/20 z-40",onClick:()=>y(!1)}),e.jsxs("div",{className:"fixed top-topbar right-0 bottom-0 w-80 bg-bg-1 border-l border-border z-50 shadow-lg animate-in slide-in-from-right duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border",children:[e.jsx("span",{className:"text-sm font-medium text-fg",children:"Action history"}),e.jsx("button",{onClick:()=>y(!1),className:"p-1.5 rounded hover:bg-hover text-fg-3 hover:text-fg transition-colors",children:e.jsx(Ls,{size:14})})]}),e.jsx("div",{className:"h-[calc(100%-49px)]",children:e.jsx(Zg,{})})]})]})]})},La=(t,s)=>{const a=document.createElement("canvas");return a.width=t,a.height=s,a},Ha=t=>(s,a)=>{const r=La(s,a),n=r.getContext("2d");return n.fillStyle=t,n.fillRect(0,0,s,a),r},Wa=(t,s=180)=>(a,r)=>{const n=La(a,r),i=n.getContext("2d"),o=(s-90)*(Math.PI/180),c=a/2-Math.cos(o)*a,d=r/2-Math.sin(o)*r,u=a/2+Math.cos(o)*a,p=r/2+Math.sin(o)*r,m=i.createLinearGradient(c,d,u,p);return t.forEach((x,h)=>m.addColorStop(h/(t.length-1),x)),i.fillStyle=m,i.fillRect(0,0,a,r),n},Mc=t=>(s,a)=>{const r=La(s,a),n=r.getContext("2d"),i=n.createRadialGradient(s/2,a/2,0,s/2,a/2,Math.max(s,a)/2);return t.forEach((o,c)=>i.addColorStop(c/(t.length-1),o)),n.fillStyle=i,n.fillRect(0,0,s,a),r},pi=t=>(s,a)=>{const r=La(s,a),n=r.getContext("2d");n.fillStyle=t[0],n.fillRect(0,0,s,a);const i=[{x:.2,y:.3,r:.6,color:t[1]||t[0]},{x:.8,y:.2,r:.5,color:t[2]||t[1]||t[0]},{x:.5,y:.8,r:.55,color:t[3]||t[2]||t[0]},{x:.1,y:.9,r:.4,color:t[4]||t[1]||t[0]}];for(const o of i){const c=n.createRadialGradient(o.x*s,o.y*a,0,o.x*s,o.y*a,o.r*Math.max(s,a));c.addColorStop(0,o.color),c.addColorStop(1,"transparent"),n.fillStyle=c,n.fillRect(0,0,s,a)}return r},y0=(t,s=.1)=>(a,r)=>{const n=La(a,r),i=n.getContext("2d");i.fillStyle=t,i.fillRect(0,0,a,r);const o=i.getImageData(0,0,a,r),c=o.data;for(let d=0;d(r,n)=>{const i=La(r,n),o=i.getContext("2d");o.fillStyle=t,o.fillRect(0,0,r,n),o.strokeStyle=s,o.lineWidth=1;for(let c=0;c<=r;c+=a)o.beginPath(),o.moveTo(c,0),o.lineTo(c,n),o.stroke();for(let c=0;c<=n;c+=a)o.beginPath(),o.moveTo(0,c),o.lineTo(r,c),o.stroke();return i},Rc=(t,s,a=30,r=3)=>(n,i)=>{const o=La(n,i),c=o.getContext("2d");c.fillStyle=t,c.fillRect(0,0,n,i),c.fillStyle=s;for(let d=a/2;d(s,a)=>{const r=La(s,a),n=r.getContext("2d"),i=n.createLinearGradient(0,0,0,a);t.forEach((c,d)=>i.addColorStop(d/(t.length-1),c)),n.fillStyle=i,n.fillRect(0,0,s,a),n.globalAlpha=.3;const o=["rgba(255,255,255,0.1)","rgba(255,255,255,0.15)","rgba(255,255,255,0.08)"];for(let c=0;c<3;c++){n.fillStyle=o[c],n.beginPath(),n.moveTo(0,a);const d=30+c*20,u=.005-c*.001,p=c*100;for(let m=0;m<=s;m+=5){const x=a*(.5+c*.15)+Math.sin(m*u+p)*d;n.lineTo(m,x)}n.lineTo(s,a),n.closePath(),n.fill()}return n.globalAlpha=1,r},v0=t=>(s,a)=>{const r=La(s,a),n=r.getContext("2d"),i=n.createLinearGradient(0,0,0,a);i.addColorStop(0,"#0f0c29"),i.addColorStop(.5,"#302b63"),i.addColorStop(1,"#24243e"),n.fillStyle=i,n.fillRect(0,0,s,a);for(let o=0;o{r.toBlob(o=>{o?n(o):i(new Error("Failed to generate background blob"))},"image/png",1)})}const k0=({isOpen:t,videoWidth:s,videoHeight:a,currentWidth:r,currentHeight:n,onConfirm:i,onCancel:o})=>{const c=(s/a).toFixed(2),d=(r/n).toFixed(2);return e.jsx(ur,{open:t,onOpenChange:u=>!u&&o(),children:e.jsxs(mr,{className:"max-w-md",children:[e.jsx(pr,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(zr,{size:20,className:"text-primary"})}),e.jsxs("div",{children:[e.jsx(xr,{children:"Match Video Dimensions?"}),e.jsx(il,{className:"mt-1",children:"The video you're adding has different dimensions than your current project settings."})]})]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between p-3 rounded-lg bg-background-tertiary",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-text-tertiary mb-1",children:"Video Dimensions"}),e.jsxs("div",{className:"text-sm font-medium text-text-primary",children:[s," × ",a]}),e.jsxs("div",{className:"text-xs text-text-tertiary mt-0.5",children:["Aspect Ratio: ",c]})]})}),e.jsx("div",{className:"flex items-center justify-between p-3 rounded-lg bg-background-tertiary/50 border border-border/50",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-text-tertiary mb-1",children:"Current Project"}),e.jsxs("div",{className:"text-sm font-medium text-text-primary",children:[r," × ",n]}),e.jsxs("div",{className:"text-xs text-text-tertiary mt-0.5",children:["Aspect Ratio: ",d]})]})})]}),e.jsx("p",{className:"text-xs text-text-tertiary",children:"Match the project dimensions to this video for a clean fit, or keep the current canvas — your video will be placed at its original size so you can resize it freely."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(zt,{variant:"outline",className:"flex-1",onClick:o,children:"Keep Current"}),e.jsx(zt,{className:"flex-1",onClick:i,children:"Match Video"})]})]})})},N0=[{id:"default",name:"Default",description:"White text on dark background"},{id:"modern",name:"Modern",description:"Clean, minimal style"},{id:"bold",name:"Bold",description:"Large, impactful text"},{id:"cinematic",name:"Cinematic",description:"Film-style captions"},{id:"minimal",name:"Minimal",description:"Subtle, understated"}],C0=()=>{const t=Ct(b=>b.getSpeechToTextEngine),s=F(b=>b.addSubtitle),a=F(b=>b.applySubtitleStylePreset),[r,n]=l.useState(!1),[i,o]=l.useState(null),[c,d]=l.useState("en-US"),[u,p]=l.useState("default"),[m,x]=l.useState([]),[h,f]=l.useState(null),v=l.useMemo(()=>Vl.isSupported(),[]),A=l.useMemo(()=>Vl.getSupportedLanguages(),[]),g=l.useCallback(async()=>{f(null),x([]),n(!0);try{const b=await t();b.setOptions({language:c}),b.onProgress(j=>{o(j)}),b.onSegment(j=>{x(y=>[...y,j])}),await b.startLiveTranscription()}catch(b){f(b instanceof Error?b.message:"Failed to start transcription"),n(!1)}},[t,c]),k=l.useCallback(async()=>{const b=await t(),j=b.stopTranscription();n(!1),o(null),j.success&&j.segments.length>0&&(b.segmentsToSubtitles(j.segments).forEach(w=>{s(w)}),u!=="default"&&await a(u))},[t,s,a,u]),N=l.useCallback(async()=>{if(m.length===0)return;(await t()).segmentsToSubtitles(m).forEach(y=>{s(y)}),u!=="default"&&await a(u),x([])},[t,s,a,m,u]);return v?e.jsxs("div",{className:"space-y-4 w-full min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Rr,{size:16,className:"text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Auto-Caption"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Generate captions from speech"})]})]}),e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jx,{size:14,className:"text-text-secondary"}),e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Language"})]}),e.jsxs(ot,{value:c,onValueChange:d,disabled:r,children:[e.jsx(lt,{className:"w-auto min-w-[100px] bg-background-secondary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:A.map(b=>e.jsx(ge,{value:b.code,children:b.name},b.code))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Caption Style"}),e.jsxs(ot,{value:u,onValueChange:p,disabled:r,children:[e.jsx(lt,{className:"w-auto min-w-[100px] bg-background-secondary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:N0.map(b=>e.jsx(ge,{value:b.id,children:b.name},b.id))})]})]})]}),h&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[e.jsx(Ba,{size:14,className:"text-red-400"}),e.jsx("span",{className:"text-[10px] text-red-400",children:h})]}),r&&i&&e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2 h-2 bg-red-500 rounded-full animate-pulse"}),e.jsx("span",{className:"text-[10px] text-red-400",children:"Recording"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Segments Found"}),e.jsx("span",{className:"text-[10px] text-text-primary font-mono",children:i.segmentsFound})]})]}),m.length>0&&!r&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[10px] text-text-secondary",children:[m.length," caption",m.length!==1?"s":""," ","detected"]}),e.jsx("button",{onClick:N,className:"px-2 py-1 text-[10px] bg-primary text-white rounded hover:bg-primary/80 transition-colors",children:"Add to Timeline"})]}),e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1",children:m.map((b,j)=>e.jsxs("div",{className:"p-2 bg-background-secondary rounded text-[10px] text-text-primary",children:[e.jsxs("span",{className:"text-text-muted font-mono",children:["[",b.startTime.toFixed(1),"s -"," ",b.endTime.toFixed(1),"s]"]}),e.jsx("span",{className:"ml-2",children:b.text})]},j))})]}),e.jsx("div",{className:"flex gap-2",children:r?e.jsxs("button",{onClick:k,className:"flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors",children:[e.jsx(Jd,{size:16}),e.jsx("span",{className:"text-[11px] font-medium",children:"Stop Recording"})]}):e.jsxs("button",{onClick:g,className:"flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors",children:[e.jsx(Rr,{size:16}),e.jsx("span",{className:"text-[11px] font-medium",children:"Start Recording"})]})}),e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Speak clearly into your microphone. Captions will be generated in real-time."})]}):e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-status-warning",children:[e.jsx(Ba,{size:16}),e.jsx("span",{className:"text-[11px] font-medium",children:"Browser Not Supported"})]}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Auto-captions require Chrome or Edge browser with Speech Recognition API support."})]})};async function yn(t,s,a,r={}){const n=r.headers??{},i=`/api/proxy/${t}${s}`;return fetch(i,{...r,headers:{"x-proxy-api-key":a,...n}})}const S0=[{id:"piper",label:"Piper (Free)",description:"Built-in open-source TTS"},{id:"elevenlabs",label:"ElevenLabs",description:"Premium AI voices"}],yo=[{model_id:"eleven_v3",name:"Eleven v3",description:"Latest ElevenLabs model",can_do_text_to_speech:!0,languages:[]}],fu=[{id:"amy",name:"Amy",gender:"female",language:"en-US"},{id:"ryan",name:"Ryan",gender:"male",language:"en-US"}],zc=`You are a professional voice director transforming text into expressive, emotionally rich scripts for ElevenLabs v3 TTS. Your goal is to turn narration into performance. + +Analyze the input for speaker intent, emotional arc, subtext, physical state, relationship dynamics, pacing needs, and environmental context. + +Use the 4-Layer System: Delivery (HOW), Tone (emotional color), Texture (voice quality), Subtext (what's beneath). Layer 1-3 tags per emotional beat. + +Available tags include: [authoritatively], [hesitantly], [breathlessly], [whispered], [softly], [sighs], [chuckles], [laughs], [sobs], [gasps], [pause:200ms], and many more. + +Rules: Do not alter original text. Do not over-tag. Do not use conflicting tags. Output ONLY enhanced text with tags, no explanations.`;function A0(t){const{provider:s,hasElevenLabsKey:a,settingsOpen:r,elevenLabsModel:n,defaultLlmProvider:i}=t,{cachedElevenLabsVoices:o,cachedElevenLabsModels:c,setCachedElevenLabsVoices:d,setCachedElevenLabsModels:u}=Fa(),[p,m]=l.useState([]),[x,h]=l.useState([]),[f,v]=l.useState(!1),[A,g]=l.useState(!1),k=l.useRef(null),N=l.useRef(r),b=l.useCallback(()=>(k.current&&k.current.abort(),k.current=new AbortController,k.current.signal),[]),j=l.useCallback(async C=>{if(c){h(c);return}if(!Mr()){h(yo);return}const M=await jn("elevenlabs");if(!M){h(yo);return}g(!0);try{const z=await yn("elevenlabs","/models",M,{signal:C});if(!z.ok)throw new Error("Failed to fetch models");const L=await z.json(),O=(Array.isArray(L)?L:[]).filter(G=>G.can_do_text_to_speech!==!1);u(O),h(O)}catch(z){if(z instanceof DOMException&&z.name==="AbortError")return;h(yo)}finally{g(!1)}},[c,u]),y=l.useCallback(async C=>{if(o){m(o);return}if(!Mr())return;const M=await jn("elevenlabs");if(M){v(!0);try{const z=await yn("elevenlabs","/voices",M,{signal:C});if(!z.ok)throw new Error("Failed to fetch voices");const B=(await z.json()).voices??[];d(B),m(B)}catch(z){if(z instanceof DOMException&&z.name==="AbortError")return}finally{v(!1)}}},[o,d]);l.useEffect(()=>{if(s==="elevenlabs"&&a){const C=b();p.length===0&&y(C),x.length===0&&j(C)}},[s,a,p.length,x.length,y,j,b]),l.useEffect(()=>{if(N.current&&!r&&s==="elevenlabs"&&a&&Mr()){const C=b();p.length===0&&y(C),x.length===0&&j(C)}N.current=r},[r,s,a,p.length,x.length,y,j,b]),l.useEffect(()=>()=>{k.current&&k.current.abort()},[]),l.useEffect(()=>{k.current&&(k.current.abort(),k.current=null)},[s]);const w=l.useCallback(async(C,M,z,L)=>{const B=await fetch(`${Em}/tts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:C,voice:M,speed:z}),signal:L});if(!B.ok){if(B.status===429)throw new Error("Rate limit reached. Please wait a minute. Free service is limited to 10 req/min.");const O=await B.json().catch(()=>({}));throw new Error(O.detail||O.error||"Failed to generate speech")}return B.blob()},[]),S=l.useCallback(async(C,M,z)=>{if(!Mr())throw new Error("Session locked. Unlock in Settings > API Keys first.");const L=await jn("elevenlabs");if(!L)throw new Error("ElevenLabs API key not found. Add it in Settings > API Keys.");const B=await yn("elevenlabs",`/text-to-speech/${M}`,L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:C,model_id:n,voice_settings:{stability:.5,similarity_boost:.75}}),signal:z});if(!B.ok){const O=await B.json().catch(()=>({})),G=O.detail??O.message??`ElevenLabs error (${B.status})`;throw new Error(String(G))}return B.blob()},[n]),T=l.useCallback(async(C,M)=>{const z=i;if(!Mr())throw new Error("Session locked. Unlock in Settings > API Keys to use text enhancement.");const L=await jn(z);if(!L)throw new Error(`${z==="openai"?"OpenAI":"Anthropic"} API key not found. Add it in Settings > API Keys.`);if(z==="anthropic"){const V=await yn("anthropic","/messages",L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:"claude-sonnet-4-20250514",max_tokens:2048,system:zc,messages:[{role:"user",content:C}]}),signal:M});if(!V.ok){const se=await V.json().catch(()=>({}));throw new Error(se.error?String(se.error):`Anthropic error (${V.status})`)}return(await V.json()).content?.[0]?.text??C}const B=await yn("openai","/chat/completions",L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-4o-mini",messages:[{role:"system",content:zc},{role:"user",content:C}],max_tokens:2048}),signal:M});if(!B.ok){const P=(await B.json().catch(()=>({}))).error;throw new Error(P?String(P.message??P):`OpenAI error (${B.status})`)}return(await B.json()).choices?.[0]?.message?.content??C},[i]);return{allVoices:p,allModels:x,isLoadingVoices:f,isLoadingModels:A,generateWithElevenLabs:S,generateWithPiper:w,enhanceViaLlm:T}}const Ea=un((t,s)=>({generatedAudio:null,isAudioSaved:!1,audioUrl:null,setGeneratedAudio:a=>{const r=s().audioUrl;if(r&&URL.revokeObjectURL(r),!a){t({generatedAudio:null,isAudioSaved:!1,audioUrl:null});return}const n=URL.createObjectURL(a);t({generatedAudio:a,isAudioSaved:!1,audioUrl:n})},markAudioSaved:()=>t({isAudioSaved:!0}),clearAudio:()=>{const a=s().audioUrl;a&&URL.revokeObjectURL(a),t({generatedAudio:null,isAudioSaved:!1,audioUrl:null})}}));function T0(t){const{provider:s,selectedVoice:a,text:r,speed:n,enhanceText:i,enhancedPreview:o,allVoices:c,favoriteVoices:d,generateWithElevenLabs:u,generateWithPiper:p,enhanceViaLlm:m,setText:x,setError:h,setEnhancedPreview:f}=t,v=F(pe=>pe.importMedia),A=F(pe=>pe.project),g=Ea(pe=>pe.generatedAudio),k=Ea(pe=>pe.isAudioSaved),N=Ea(pe=>pe.audioUrl),b=Ea(pe=>pe.setGeneratedAudio),j=Ea(pe=>pe.markAudioSaved),y=Ea(pe=>pe.clearAudio),[w,S]=l.useState(!1),[T,C]=l.useState(!1),[M,z]=l.useState(!1),[L,B]=l.useState(null),O=l.useRef(null),G=l.useRef(null),V=g!==null&&!k;l.useEffect(()=>{if(!V)return;const pe=fe=>{fe.preventDefault()};return window.addEventListener("beforeunload",pe),()=>window.removeEventListener("beforeunload",pe)},[V]),l.useEffect(()=>{O.current&&N&&(O.current.src=N)},[N]),l.useEffect(()=>()=>{O.current&&O.current.pause(),G.current&&G.current.abort()},[]);const P=l.useCallback(pe=>{pe?b(pe):y()},[b,y]),_=l.useCallback(()=>{if(s==="piper")return fu.find(We=>We.id===a)?.name??"TTS";const pe=d.find(We=>We.voiceId===a);if(pe)return pe.name;const fe=c.find(We=>We.voice_id===a);return fe?fe.name:"TTS"},[s,a,d,c]),se=l.useCallback(async()=>{if(!r.trim()){h("Please enter some text");return}G.current?.abort();const pe=new AbortController;G.current=pe,z(!0),h(null);try{const fe=await m(r.trim(),pe.signal);f(fe)}catch(fe){if(fe instanceof DOMException&&fe.name==="AbortError")return;h(fe instanceof Error?fe.message:"Failed to enhance text")}finally{z(!1)}},[r,m,h,f]),R=l.useCallback(async()=>{if(!r.trim()&&!o){h("Please enter some text");return}G.current?.abort();const pe=new AbortController;G.current=pe,S(!0),h(null);try{const fe=i&&o?o:r.trim(),We=s==="elevenlabs"?await u(fe,a,pe.signal):await p(fe,a,n,pe.signal);if(b(We),O.current){const Ze=Ea.getState().audioUrl;Ze&&(O.current.src=Ze)}}catch(fe){if(fe instanceof DOMException&&fe.name==="AbortError")return;h(fe instanceof Error?fe.message:"Failed to generate speech")}finally{S(!1)}},[r,o,i,a,n,s,p,u,h,b]),U=l.useCallback(()=>{!O.current||!N||(T?(O.current.pause(),C(!1)):(O.current.play(),C(!0)))},[T,N]),D=l.useCallback(()=>{C(!1)},[]),X=l.useCallback(async()=>{if(!g||!A)return null;const pe=_(),fe=Date.now(),We=`${pe}_${fe}.wav`,Ze=new File([g],We,{type:"audio/wav"}),at=await v(Ze);if(!at.success||!at.actionId){const de=typeof at.error=="string"?at.error:"Failed to import audio";throw new Error(de)}return at.actionId},[g,A,_,v]),K=l.useCallback(async()=>{if(!(!g||!A)){S(!0),h(null),B(null);try{await X(),y(),x(""),B("Saved to Media Assets"),setTimeout(()=>B(null),3e3)}catch(pe){h(pe instanceof Error?pe.message:"Failed to save to media")}finally{S(!1)}}},[g,A,X,h,y,x]),ue=l.useCallback(async()=>{if(!(!g||!A)){S(!0),h(null);try{const pe=await X();if(!pe)return;const{addClipToNewTrack:fe}=F.getState();await fe(pe),y(),x("")}catch(pe){h(pe instanceof Error?pe.message:"Failed to add to timeline")}finally{S(!1)}}},[g,A,X,x,h,y]),Te=l.useCallback(()=>{if(!g)return;j();const pe=_(),fe=Date.now(),We=`${pe}_${fe}.wav`,Ze=URL.createObjectURL(g),at=document.createElement("a");at.href=Ze,at.download=We,at.click(),URL.revokeObjectURL(Ze)},[g,_,j]);return{isGenerating:w,isPlaying:T,isEnhancing:M,generatedAudio:g,hasUnsavedAudio:V,successMsg:L,audioRef:O,getSelectedVoiceName:_,handleEnhance:se,generateSpeech:R,togglePlayback:U,handleAudioEnded:D,saveToMedia:K,addToTimeline:ue,downloadAudio:Te,setGeneratedAudio:P}}const M0=({provider:t,selectedVoice:s,onSelectVoice:a,allVoices:r,isLoadingVoices:n})=>{const{favoriteVoices:i,addFavoriteVoice:o,removeFavoriteVoice:c,openSettings:d}=Fa(),[u,p]=l.useState(""),[m,x]=l.useState(!1),[h,f]=l.useState(null),v=l.useRef(null),A=l.useCallback(b=>i.some(j=>j.voiceId===b),[i]),g=l.useCallback(b=>{A(b.voice_id)?c(b.voice_id):o({voiceId:b.voice_id,name:b.name,previewUrl:b.preview_url})},[A,o,c]),k=l.useCallback((b,j)=>{if(!b)return;if(v.current&&h===j){v.current.pause(),v.current=null,f(null);return}v.current&&(v.current.pause(),v.current=null),f(j??null);const y=new Audio;y.crossOrigin="anonymous",v.current=y,y.onended=()=>{v.current=null,f(null)},y.onerror=()=>{v.current=null,f(null)},y.src=b,y.play().catch(()=>{v.current=null,f(null)})},[h]),N=l.useMemo(()=>r.filter(b=>{if(!u.trim())return!0;const j=u.toLowerCase();return b.name.toLowerCase().includes(j)||b.category?.toLowerCase().includes(j)||Object.values(b.labels||{}).some(y=>y.toLowerCase().includes(j))}),[r,u]);return t==="piper"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Voice"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:fu.map(b=>e.jsxs("button",{onClick:()=>a(b.id),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[10px] transition-colors ${s===b.id?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary border border-border"}`,children:[e.jsx(hl,{size:10}),e.jsx("span",{children:b.name}),e.jsx("span",{className:"text-[8px] opacity-70",children:b.gender==="female"?"F":"M"})]},b.id))})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Voice"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("span",{className:"text-[9px] text-text-muted flex items-center gap-1",children:[e.jsx(Ys,{size:9,className:"text-amber-400 fill-amber-400"})," Favorites"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(b=>e.jsxs("button",{onClick:()=>a(b.voiceId),className:`flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] transition-colors ${s===b.voiceId?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary border border-border"}`,children:[e.jsx(Ys,{size:8,className:"text-amber-400 fill-amber-400"}),e.jsx("span",{children:b.name}),b.previewUrl&&e.jsx("button",{onClick:j=>{j.stopPropagation(),k(b.previewUrl,b.voiceId)},className:"ml-0.5 opacity-60 hover:opacity-100",title:"Preview voice",children:h===b.voiceId?e.jsx(dr,{size:8}):e.jsx(As,{size:8})})]},b.voiceId))})]}),e.jsxs("button",{onClick:()=>x(!m),className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-lg text-[10px] border border-dashed border-border text-text-muted hover:text-text-primary hover:border-primary/50 transition-colors",children:[e.jsx(la,{size:10}),m?"Hide voice browser":"Browse & search voices",e.jsx(qt,{size:10,className:`transition-transform ${m?"rotate-180":""}`})]}),m&&e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border bg-background-secondary",children:[e.jsx(la,{size:12,className:"text-text-muted shrink-0"}),e.jsx("input",{type:"text",value:u,onChange:b=>p(b.target.value),placeholder:"Search by name, accent, gender...",className:"flex-1 bg-transparent text-[10px] text-text-primary placeholder:text-text-muted focus:outline-none",autoFocus:!0}),n&&e.jsx(ds,{size:12,className:"animate-spin text-text-muted"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto",children:N.length===0?e.jsx("div",{className:"p-3 text-center text-[10px] text-text-muted",children:n?"Loading voices...":r.length===0?e.jsxs("button",{onClick:()=>d("api-keys"),className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-amber-500/15 border border-amber-500/30 text-amber-400 hover:bg-amber-500/25 transition-colors font-medium",children:[e.jsx(Da,{size:12}),"Unlock session to browse voices"]}):"No voices match your search"}):N.map(b=>{const j=b.labels?.gender??"",y=b.labels?.accent??"",w=s===b.voice_id,S=A(b.voice_id);return e.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 cursor-pointer transition-colors ${w?"bg-primary/10 border-l-2 border-primary":"hover:bg-background-tertiary border-l-2 border-transparent"}`,onClick:()=>a(b.voice_id),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-primary truncate",children:b.name}),b.category==="cloned"&&e.jsx("span",{className:"text-[8px] px-1 py-0.5 rounded bg-purple-500/20 text-purple-400",children:"Cloned"})]}),e.jsx("div",{className:"text-[8px] text-text-muted",children:[j,y,b.category].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.preview_url&&e.jsx("button",{onClick:T=>{T.stopPropagation(),k(b.preview_url,b.voice_id)},className:"p-1 rounded hover:bg-background-elevated text-text-muted hover:text-text-primary transition-colors",title:"Preview",children:h===b.voice_id?e.jsx(dr,{size:10}):e.jsx(As,{size:10})}),e.jsx("button",{onClick:T=>{T.stopPropagation(),g(b)},className:`p-1 rounded hover:bg-background-elevated transition-colors ${S?"text-amber-400":"text-text-muted hover:text-amber-400"}`,title:S?"Remove from favorites":"Add to favorites",children:S?e.jsx(Ys,{size:10,className:"fill-current"}):e.jsx(au,{size:10})})]})]},b.voice_id)})}),e.jsxs("div",{className:"px-2 py-1 border-t border-border bg-background-secondary text-[8px] text-text-muted text-center",children:[N.length," of ",r.length," voices"]})]})]})]})},E0=({allModels:t,isLoadingModels:s})=>{const{elevenLabsModel:a,setElevenLabsModel:r,favoriteModels:n,addFavoriteModel:i,removeFavoriteModel:o}=Fa(),[c,d]=l.useState(!1),u=l.useCallback(x=>n.some(h=>h.modelId===x),[n]),p=l.useCallback(x=>{u(x.model_id)?o(x.model_id):i({modelId:x.model_id,name:x.name})},[u,i,o]),m=l.useCallback(()=>{const x=t.find(f=>f.model_id===a);if(x)return x.name;const h=n.find(f=>f.modelId===a);return h?h.name:a},[a,t,n]);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Model"}),n.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("span",{className:"text-[9px] text-text-muted flex items-center gap-1",children:[e.jsx(Ys,{size:9,className:"text-amber-400 fill-amber-400"})," Favorite Models"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(x=>e.jsxs("button",{onClick:()=>r(x.modelId),className:`flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] transition-colors ${a===x.modelId?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary border border-border"}`,children:[e.jsx(Ys,{size:8,className:"text-amber-400 fill-amber-400"}),e.jsx("span",{children:x.name})]},x.modelId))})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex-1 h-8 px-2 rounded-lg border border-border bg-background-tertiary text-[10px] text-text-primary flex items-center justify-between cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>d(!c),children:[e.jsx("span",{className:"truncate",children:s?"Loading models...":m()}),e.jsx(qt,{size:12,className:`shrink-0 text-text-muted transition-transform ${c?"rotate-180":""}`})]})}),c&&e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"max-h-48 overflow-y-auto",children:t.length===0?e.jsx("div",{className:"p-3 text-center text-[10px] text-text-muted",children:s?"Loading models...":"No models available"}):t.map(x=>{const h=a===x.model_id,f=u(x.model_id),v=x.languages?.length??0;return e.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 cursor-pointer transition-colors ${h?"bg-primary/10 border-l-2 border-primary":"hover:bg-background-tertiary border-l-2 border-transparent"}`,onClick:()=>{r(x.model_id),d(!1)},children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-[10px] font-medium text-text-primary truncate",children:x.name})}),e.jsxs("div",{className:"text-[8px] text-text-muted truncate",children:[x.description?x.description.length>80?x.description.slice(0,80)+"...":x.description:"",v>0&&` · ${v} languages`]})]}),e.jsx("button",{onClick:A=>{A.stopPropagation(),p(x)},className:`p-1 rounded hover:bg-background-elevated transition-colors shrink-0 ${f?"text-amber-400":"text-text-muted hover:text-amber-400"}`,title:f?"Remove from favorites":"Add to favorites",children:f?e.jsx(Ys,{size:10,className:"fill-current"}):e.jsx(au,{size:10})})]},x.model_id)})}),e.jsxs("div",{className:"px-2 py-1 border-t border-border bg-background-secondary text-[8px] text-text-muted text-center",children:[t.length," models available"]})]})]})},R0=({enhancedPreview:t,onUpdate:s,onDiscard:a})=>e.jsxs("div",{className:"p-2 bg-amber-500/5 border border-amber-500/20 rounded-lg space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gs,{size:9,className:"text-amber-400"}),e.jsx("span",{className:"text-[9px] font-medium text-amber-400",children:"Enhanced — edit below then Generate"})]}),e.jsx("button",{onClick:a,className:"text-[9px] text-text-muted hover:text-red-400 transition-colors",children:"Discard"})]}),e.jsx("textarea",{value:t,onChange:r=>s(r.target.value),className:"w-full h-24 px-2 py-1.5 text-[10px] bg-background-tertiary rounded-md border border-amber-500/20 focus:border-amber-500/50 focus:outline-none resize-none text-text-primary leading-relaxed"})]}),P0=({generatedAudio:t,voiceName:s,isPlaying:a,isGenerating:r,onTogglePlayback:n,onSaveToMedia:i,onAddToTimeline:o,onDownload:c})=>e.jsxs("div",{className:"p-3 bg-background-tertiary rounded-lg border border-border space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(Ts,{size:14,className:"text-primary"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-medium text-text-primary",children:[s," Voice"]}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:[(t.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("button",{onClick:n,className:"w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white hover:opacity-90 transition-opacity",children:a?e.jsx(dr,{size:14}):e.jsx(As,{size:14,className:"ml-0.5"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:i,disabled:r,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-primary text-white rounded-lg text-[10px] font-medium hover:opacity-90 transition-opacity disabled:opacity-50",children:[e.jsx(Rx,{size:12}),"Save to Media"]}),e.jsx("button",{onClick:o,disabled:r,className:"px-3 py-2 bg-background-secondary border border-border rounded-lg text-[10px] text-text-secondary hover:text-text-primary transition-colors",title:"Add to Timeline",children:e.jsx(cs,{size:12})}),e.jsx("button",{onClick:c,className:"px-3 py-2 bg-background-secondary border border-border rounded-lg text-[10px] text-text-secondary hover:text-text-primary transition-colors",title:"Download",children:e.jsx(nl,{size:12})})]})]}),z0=()=>{const{defaultTtsProvider:t,defaultLlmProvider:s,openSettings:a,settingsOpen:r,configuredServices:n,elevenLabsModel:i,favoriteVoices:o}=Fa(),c=n.includes("elevenlabs"),d=t==="elevenlabs"&&c?"elevenlabs":"piper",[u,p]=l.useState(d),[m,x]=l.useState(""),[h,f]=l.useState(d==="elevenlabs"&&o.length>0?o[0].voiceId:"amy"),[v,A]=l.useState(1),[g,k]=l.useState(null),[N,b]=l.useState(!1),[j,y]=l.useState(null),{allVoices:w,allModels:S,isLoadingVoices:T,isLoadingModels:C,generateWithElevenLabs:M,generateWithPiper:z,enhanceViaLlm:L}=A0({provider:u,hasElevenLabsKey:c,settingsOpen:r,elevenLabsModel:i,defaultLlmProvider:s}),{isGenerating:B,isPlaying:O,isEnhancing:G,generatedAudio:V,hasUnsavedAudio:P,successMsg:_,audioRef:se,getSelectedVoiceName:R,handleEnhance:U,generateSpeech:D,togglePlayback:X,handleAudioEnded:K,saveToMedia:ue,addToTimeline:Te,downloadAudio:pe,setGeneratedAudio:fe}=T0({provider:u,selectedVoice:h,text:m,speed:v,enhanceText:N,enhancedPreview:j,allVoices:w,favoriteVoices:o,generateWithElevenLabs:M,generateWithPiper:z,enhanceViaLlm:L,setText:x,setError:k,setEnhancedPreview:y}),We=()=>{const Ne=S.find(Me=>Me.model_id===i);return Ne?Ne.name:i},Ze=l.useCallback(()=>{P&&Fe.warning("Unsaved audio discarded","Save to media or download next time to keep it.")},[P]),at=l.useCallback(Ne=>{Ne!==u&&(Ze(),p(Ne),f(Ne==="elevenlabs"?o.length>0?o[0].voiceId:"":"amy"),fe(null))},[u,Ze,o,fe]),de=m.length,Ce=5e3;return e.jsxs("div",{className:"space-y-3 w-full min-w-0 max-w-full",children:[e.jsx("audio",{ref:se,onEnded:K,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-between p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{size:16,className:"text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Text to Speech"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"AI voice generation"})]})]}),e.jsx("button",{onClick:()=>a("api-keys"),className:"p-1.5 rounded-md hover:bg-background-tertiary text-text-muted hover:text-text-primary transition-colors",title:"API Key Settings",children:e.jsx(Da,{size:14})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Provider"}),e.jsx("div",{className:"flex gap-1.5",children:S0.map(Ne=>{const Me=Ne.id==="elevenlabs"&&!c;return e.jsx("button",{onClick:()=>{if(Me){a("api-keys");return}at(Ne.id)},className:`flex-1 px-2 py-1.5 rounded-lg text-[10px] transition-colors ${u===Ne.id?"bg-primary text-white font-medium":Me?"bg-background-tertiary text-text-muted border border-border opacity-60 cursor-default":"bg-background-tertiary text-text-secondary hover:text-text-primary border border-border"}`,title:Me?"Add ElevenLabs API key in Settings":Ne.description,children:Ne.label},Ne.id)})})]}),u==="elevenlabs"&&c&&e.jsx(E0,{allModels:S,isLoadingModels:C}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Text"}),e.jsx("textarea",{value:m,onChange:Ne=>{x(Ne.target.value),y(null)},placeholder:"Enter the text you want to convert to speech...",className:"w-full h-24 px-3 py-2 text-[11px] bg-background-tertiary rounded-lg border border-border focus:border-primary focus:outline-none resize-none",maxLength:Ce}),e.jsxs("div",{className:"flex items-center justify-between",children:[u==="elevenlabs"?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(oa,{checked:N,onCheckedChange:b,className:"scale-75 origin-left"}),e.jsxs("label",{className:"text-[9px] text-text-muted flex items-center gap-1 cursor-pointer",onClick:()=>b(!N),children:[e.jsx(gs,{size:10,className:N?"text-amber-400":""}),"Enhance for TTS"]})]}):e.jsx("div",{}),e.jsxs("span",{className:`text-[9px] ${de>Ce*.9?"text-red-400":"text-text-muted"}`,children:[de,"/",Ce]})]}),j&&N&&e.jsx(R0,{enhancedPreview:j,onUpdate:y,onDiscard:()=>y(null)})]}),e.jsx(M0,{provider:u,selectedVoice:h,onSelectVoice:f,allVoices:w,isLoadingVoices:T}),u==="piper"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Speed"}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:[v.toFixed(1),"x"]})]}),e.jsx(st,{min:.5,max:2,step:.1,value:[v],onValueChange:Ne=>A(Ne[0])}),e.jsxs("div",{className:"flex justify-between text-[8px] text-text-muted",children:[e.jsx("span",{children:"0.5x"}),e.jsx("span",{children:"1.0x"}),e.jsx("span",{children:"2.0x"})]})]}),g&&e.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded-lg flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-[10px] text-red-400",children:g}),(g.includes("API key")||g.includes("Session locked")||g.includes("Unlock"))&&e.jsx("button",{onClick:()=>a("api-keys"),className:"shrink-0 px-2 py-1 rounded text-[9px] font-medium bg-red-500/20 text-red-300 hover:bg-red-500/30 transition-colors",children:"Open Settings"})]}),_&&e.jsx("div",{className:"p-2 bg-green-500/10 border border-green-500/30 rounded-lg",children:e.jsx("p",{className:"text-[10px] text-green-400",children:_})}),N&&u==="elevenlabs"&&!j&&e.jsx("button",{onClick:U,disabled:G||!m.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-amber-500 text-white rounded-lg text-[11px] font-medium transition-all hover:bg-amber-600 disabled:opacity-50 disabled:cursor-not-allowed",children:G?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"})," Enhancing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{size:14})," Enhance Text"]})}),e.jsx("button",{onClick:D,disabled:B||!m.trim()||u==="elevenlabs"&&!h||N&&u==="elevenlabs"&&!j,className:"w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg text-[11px] font-medium transition-all hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed",children:B?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ts,{size:14})," Generate Speech"]})}),P&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[e.jsx(ra,{size:12,className:"text-amber-400 shrink-0"}),e.jsx("p",{className:"text-[9px] text-amber-400",children:"Unsaved audio — save to media, add to timeline, or download to keep it."})]}),V&&e.jsx(P0,{generatedAudio:V,voiceName:R(),isPlaying:O,isGenerating:B,onTogglePlayback:X,onSaveToMedia:ue,onAddToTimeline:Te,onDownload:pe}),e.jsxs("p",{className:"text-[9px] text-text-muted text-center",children:["Powered by ",u==="elevenlabs"?"ElevenLabs":"Piper TTS",u==="elevenlabs"&&` · ${We()}`]})]})},D0={cinematic:lr,vintage:cl,mood:Zd,color:za,stylized:cr},I0=({preset:t,isApplied:s,onApply:a})=>{const[r,n]=l.useState(!1);return e.jsxs("button",{onClick:a,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),className:`relative w-full p-3 rounded-lg border transition-all text-left ${s?"border-primary bg-primary/10":"border-border bg-background-tertiary hover:border-primary/50"}`,children:[e.jsx("div",{className:"flex items-start justify-between",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:t.name}),s&&e.jsx(is,{size:12,className:"text-primary"})]}),e.jsx("p",{className:"text-[9px] text-text-muted mt-0.5",children:t.description})]})}),e.jsxs("div",{className:"mt-2 flex gap-1 flex-wrap",children:[t.effects.slice(0,3).map((i,o)=>e.jsx("span",{className:"px-1.5 py-0.5 text-[8px] bg-background-secondary rounded text-text-muted",children:i.type},o)),t.effects.length>3&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] bg-background-secondary rounded text-text-muted",children:["+",t.effects.length-3]})]}),r&&!s&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background-tertiary/80 rounded-lg",children:e.jsx("span",{className:"text-[10px] text-primary font-medium",children:"Click to Apply"})})]})},B0=({clipId:t})=>{const s=vt(v=>v.getSelectedClipIds()),a=F(v=>v.addVideoEffect),r=F(v=>v.getVideoEffects),n=F(v=>v.removeVideoEffect),[i,o]=l.useState("cinematic"),[c,d]=l.useState(null),[u,p]=l.useState(100),m=t||s[0],x=l.useMemo(()=>_f(i),[i]),h=l.useCallback(v=>{if(!m)return;r(m).forEach(g=>{n(m,g.id)}),v.effects.forEach(g=>{a(m,g.type,g.params)}),d(v.id),Fe.success("Filter Applied",`${v.name} preset applied`)},[m,a,r,n]),f=l.useCallback(()=>{if(!m)return;r(m).forEach(A=>{n(m,A.id)}),d(null),Fe.info("Effects Cleared")},[m,r,n]);return m?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(za,{size:16,className:"text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Filter Presets"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"One-click color grades"})]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-1",children:cc.map(v=>{const A=D0[v.id]||za;return e.jsxs("button",{onClick:()=>o(v.id),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] whitespace-nowrap transition-colors ${i===v.id?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:[e.jsx(A,{size:12}),v.name]},v.id)})}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:x.map(v=>e.jsx(I0,{preset:v,isApplied:c===v.id,onApply:()=>h(v)},v.id))}),c&&e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Intensity"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[u,"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[u],onValueChange:v=>p(v[0])}),e.jsx("button",{onClick:f,className:"w-full py-2 text-[10px] text-red-400 hover:text-red-300 bg-red-500/10 rounded-lg transition-colors",children:"Remove All Effects"})]}),e.jsxs("p",{className:"text-[9px] text-text-muted text-center",children:[lu.length," presets across ",cc.length," ","categories"]})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(za,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Select a video clip to apply filters"})]})},F0=({sound:t,isPlaying:s,onPlay:a,onStop:r,onAdd:n})=>{const i=o=>{if(o<60)return`${o.toFixed(1)}s`;const c=Math.floor(o/60),d=Math.floor(o%60);return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs("div",{className:"p-2 rounded-lg border border-border bg-background-tertiary hover:border-primary/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:s?r:a,className:`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${s?"bg-primary text-white":"bg-background-secondary hover:bg-primary/20"}`,children:s?e.jsx(dr,{size:14}):e.jsx(As,{size:14,className:"ml-0.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10px] font-medium text-text-primary truncate",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-text-muted",children:[e.jsx(Ia,{size:10}),e.jsx("span",{children:i(t.duration)})]}),t.bpm&&e.jsxs("span",{className:"text-[9px] text-text-muted",children:[t.bpm," BPM"]})]})]}),e.jsx("button",{onClick:n,className:"p-1.5 rounded-md bg-primary/20 hover:bg-primary text-primary hover:text-white transition-colors",title:"Add to timeline",children:e.jsx(cs,{size:14})})]}),t.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:t.tags.slice(0,3).map(o=>e.jsx("span",{className:"px-1.5 py-0.5 text-[8px] bg-background-secondary text-text-muted rounded",children:o},o))})]})},L0=()=>{const t=Ct(S=>S.getSoundLibraryEngine),s=F(S=>S.importMedia),a=F(S=>S.project),[r,n]=l.useState("music"),[i,o]=l.useState("all"),[c,d]=l.useState("all"),[u,p]=l.useState([]),[m,x]=l.useState(""),[h,f]=l.useState(null),[v,A]=l.useState([]),[g,k]=l.useState([]);l.useEffect(()=>{let S=!1;return(async()=>{const C=await t();S||(A(C.getMusic()),k(C.getSFX()))})(),()=>{S=!0}},[t]);const N=l.useMemo(()=>{let S=r==="music"?v:g;if(S.length===0)return[];if(r==="music"&&i!=="all"&&(S=S.filter(T=>T.subcategory===i)),r==="sfx"&&c!=="all"&&(S=S.filter(T=>T.subcategory===c)),u.length>0&&(S=S.filter(T=>T.mood?.some(C=>u.includes(C)))),m){const T=m.toLowerCase();S=S.filter(C=>C.name.toLowerCase().includes(T)||C.tags.some(M=>M.toLowerCase().includes(T)))}return S},[v,g,r,i,c,u,m]),b=l.useCallback(async S=>{const T=await t();h===S.id?(T.stopPreview(),f(null)):(T.stopPreview(),f(S.id),await T.previewSound(S))},[t,h]),j=l.useCallback(async()=>{(await t()).stopPreview(),f(null)},[t]),y=l.useCallback(async S=>{if(!a)return;const C=(await t()).getSoundBlob(S.id);if(!C){console.error("[MusicLibrary] Failed to get sound blob for:",S.id);return}const M=new File([C],`${S.name}.wav`,{type:"audio/wav"}),z=await s(M);if(!z.success||!z.actionId){console.error("[MusicLibrary] Failed to import sound:",z.error);return}const L=z.actionId,{addClipToNewTrack:B}=F.getState();await B(L)},[a,t,s]),w=l.useCallback(S=>{p(T=>T.includes(S)?T.filter(C=>C!==S):[...T,S])},[]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Ps,{size:16,className:"text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Music & SFX"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Royalty-free sounds"})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs("button",{onClick:()=>n("music"),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[10px] transition-colors ${r==="music"?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:[e.jsx(Ps,{size:12}),"Music"]}),e.jsxs("button",{onClick:()=>n("sfx"),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[10px] transition-colors ${r==="sfx"?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:[e.jsx(ks,{size:12}),"Sound FX"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(la,{size:14,className:"absolute left-2 top-1/2 -translate-y-1/2 text-text-muted z-10"}),e.jsx(ts,{type:"text",placeholder:"Search sounds...",value:m,onChange:S=>x(S.target.value),className:"pl-8 text-[10px] bg-background-secondary border-border h-8"})]}),r==="music"&&e.jsxs("div",{className:"flex gap-1 overflow-x-auto pb-1",children:[e.jsx("button",{onClick:()=>o("all"),className:`px-2 py-1 rounded text-[9px] whitespace-nowrap transition-colors ${i==="all"?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,children:"All"}),Rf.map(S=>e.jsx("button",{onClick:()=>o(S.id),className:`px-2 py-1 rounded text-[9px] whitespace-nowrap transition-colors ${i===S.id?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,children:S.name},S.id))]}),r==="sfx"&&e.jsxs("div",{className:"flex gap-1 overflow-x-auto pb-1",children:[e.jsx("button",{onClick:()=>d("all"),className:`px-2 py-1 rounded text-[9px] whitespace-nowrap transition-colors ${c==="all"?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,children:"All"}),Pf.map(S=>e.jsx("button",{onClick:()=>d(S.id),className:`px-2 py-1 rounded text-[9px] whitespace-nowrap transition-colors ${c===S.id?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,children:S.name},S.id))]}),r==="music"&&e.jsx("div",{className:"flex flex-wrap gap-1",children:zf.slice(0,6).map(S=>e.jsx("button",{onClick:()=>w(S.id),className:`px-2 py-0.5 rounded-full text-[8px] transition-colors ${u.includes(S.id)?"bg-primary text-white":"bg-background-secondary text-text-muted hover:text-text-primary"}`,children:S.name},S.id))}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:N.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx(Ts,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No sounds found"}),e.jsx("p",{className:"text-[9px] text-text-muted mt-1",children:"Try adjusting filters"})]}):N.map(S=>e.jsx(F0,{sound:S,isPlaying:h===S.id,onPlay:()=>b(S),onStop:j,onAdd:()=>y(S)},S.id))}),e.jsxs("p",{className:"text-[9px] text-text-muted text-center",children:[N.length," ",r==="music"?"tracks":"effects"," available"]})]})},$0=({isOpen:t,onClose:s})=>{const{project:a}=F(),r=Ct(S=>S.getTemplateEngine),n=Ct(S=>S.getGraphicsEngine),[i,o]=l.useState(""),[c,d]=l.useState(""),[u,p]=l.useState("custom"),[m,x]=l.useState(""),[h,f]=l.useState(""),[v,A]=l.useState("cloud"),[g,k]=l.useState(!1),[N,b]=l.useState(null),[j,y]=l.useState(!1),w=l.useCallback(async()=>{if(!i.trim()){b("Template name is required");return}if(!c.trim()){b("Description is required");return}k(!0),b(null);try{const S=await r(),T=n();await S.initialize();const C=m.split(",").map(B=>B.trim()).filter(Boolean),M=[],L={...S.createFromProject(a,{name:i.trim(),description:c.trim(),category:u,placeholders:M,tags:C}),author:h.trim()||"Anonymous"};if(T){const B=T.getAllShapeClips(),O=T.getAllSVGClips(),G=T.getAllStickerClips();(B.length>0||O.length>0||G.length>0)&&(L.timeline.graphics={shapes:B,svgs:O,stickers:G})}if(v==="cloud"){const B=await kn.uploadTemplate(L);if(!B.success)throw new Error(B.error||"Failed to upload to cloud")}else await S.saveTemplate(L);y(!0),setTimeout(()=>{s(),y(!1),o(""),d(""),x(""),f(""),p("custom")},1500)}catch(S){b(S instanceof Error?S.message:"Failed to save template")}finally{k(!1)}},[i,c,u,m,h,v,a,r,n,s]);return t?e.jsx(ur,{open:!0,onOpenChange:S=>!S&&s(),children:e.jsxs(mr,{className:"max-w-lg p-0 gap-0 bg-background border-border overflow-hidden",children:[e.jsx(pr,{className:"p-4 border-b border-border space-y-0",children:e.jsx(xr,{className:"text-lg font-semibold text-text-primary",children:"Save as Template"})}),e.jsxs("div",{className:"p-4 space-y-4 max-h-[70vh] overflow-y-auto",children:[j&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 border border-green-500/30 rounded-lg",children:[e.jsx(is,{size:16,className:"text-green-400"}),e.jsx("span",{className:"text-sm text-green-400",children:"Template saved successfully!"})]}),N&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:[e.jsx(Ba,{size:16,className:"text-red-400"}),e.jsx("span",{className:"text-sm text-red-400",children:N})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(kt,{className:"text-xs font-medium text-text-secondary",children:["Template Name ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx(ts,{type:"text",value:i,onChange:S=>o(S.target.value),placeholder:"My Awesome Template",className:"bg-background-secondary border-border text-text-primary",maxLength:50}),e.jsxs("p",{className:"text-[10px] text-text-muted",children:[i.length,"/50 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(kt,{className:"text-xs font-medium text-text-secondary",children:["Description ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("textarea",{value:c,onChange:S=>d(S.target.value),placeholder:"Describe what this template is for and how to use it...",className:"w-full px-3 py-2 text-sm bg-background-secondary border border-border rounded-lg text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none",rows:4,maxLength:500}),e.jsxs("p",{className:"text-[10px] text-text-muted",children:[c.length,"/500 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-xs font-medium text-text-secondary",children:"Category"}),e.jsxs(ot,{value:u,onValueChange:S=>p(S),children:[e.jsx(lt,{className:"w-full bg-background-secondary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:fl.map(S=>e.jsx(ge,{value:S.id,children:S.name},S.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-xs font-medium text-text-secondary",children:"Tags (comma-separated)"}),e.jsx(ts,{type:"text",value:m,onChange:S=>x(S.target.value),placeholder:"intro, animated, youtube",className:"bg-background-secondary border-border text-text-primary"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-xs font-medium text-text-secondary",children:"Author Name"}),e.jsx(ts,{type:"text",value:h,onChange:S=>f(S.target.value),placeholder:"Your name or username",className:"bg-background-secondary border-border text-text-primary"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-xs font-medium text-text-secondary",children:"Save Location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{onClick:()=>A("cloud"),className:`flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ${v==="cloud"?"border-primary bg-primary/10 text-primary":"border-border bg-background-secondary text-text-secondary hover:border-primary/50"}`,children:[e.jsx(Xd,{size:16}),e.jsx("span",{className:"text-sm font-medium",children:"Cloud"})]}),e.jsxs("button",{onClick:()=>A("local"),className:`flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ${v==="local"?"border-primary bg-primary/10 text-primary":"border-border bg-background-secondary text-text-secondary hover:border-primary/50"}`,children:[e.jsx(qd,{size:16}),e.jsx("span",{className:"text-sm font-medium",children:"Local"})]})]}),e.jsx("p",{className:"text-[10px] text-text-muted",children:v==="cloud"?"Saved to cloud and accessible from any device":"Saved locally in your browser storage"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 p-4 border-t border-border",children:[e.jsx(zt,{variant:"ghost",onClick:s,disabled:g,children:"Cancel"}),e.jsx(zt,{onClick:w,disabled:g||!i.trim()||!c.trim(),children:g?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ya,{size:16}),"Save Template"]})})]})]})}):null},O0=({placeholder:t,value:s,onChange:a,onClear:r})=>{const[n,i]=l.useState(s?.value||t.defaultValue||"");l.useEffect(()=>{s?.value!==void 0&&i(s.value)},[s?.value]);const o=l.useCallback(u=>{i(u),a({type:"text",value:u})},[a]),c=s?.value!==void 0&&s.value!==t.defaultValue,d=t.constraints?.maxLength||500;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hs,{size:12,className:"text-primary"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:t.label}),t.required&&e.jsx("span",{className:"text-red-400 text-[10px]",children:"*"})]}),c&&e.jsx("button",{onClick:r,className:"p-1 text-text-muted hover:text-text-primary",title:"Reset to default",children:e.jsx(pn,{size:10})})]}),t.description&&e.jsx("p",{className:"text-[9px] text-text-muted",children:t.description}),e.jsx("textarea",{value:n,onChange:u=>o(u.target.value),maxLength:d,rows:Math.min(4,Math.ceil((n.length||20)/40)),className:"w-full px-2 py-1.5 text-[11px] text-text-primary bg-background-tertiary border border-border rounded-lg focus:border-primary focus:outline-none resize-none",placeholder:t.defaultValue||"Enter text..."}),e.jsx("div",{className:"flex justify-between text-[9px] text-text-muted",children:e.jsxs("span",{children:[n.length," / ",d," characters"]})})]})},_0=({placeholder:t,value:s,onChange:a,onClear:r})=>{const n=F(m=>m.project),[i,o]=l.useState(s?.value||""),c=t.constraints?.mediaTypes||["video","image"],d=l.useMemo(()=>n.mediaLibrary.items.filter(m=>!!(c.includes("video")&&m.type==="video"||c.includes("image")&&m.type==="image"||c.includes("audio")&&m.type==="audio")),[n.mediaLibrary.items,c]),u=l.useCallback(m=>{o(m),n.mediaLibrary.items.find(h=>h.id===m)&&a({type:"media",value:m})},[a,n.mediaLibrary.items]),p=s?.value!==void 0;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c.includes("video")?e.jsx(zs,{size:12,className:"text-green-400"}):e.jsx(va,{size:12,className:"text-primary"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:t.label}),t.required&&e.jsx("span",{className:"text-red-400 text-[10px]",children:"*"})]}),p&&e.jsx("button",{onClick:r,className:"p-1 text-text-muted hover:text-text-primary",title:"Reset",children:e.jsx(pn,{size:10})})]}),t.description&&e.jsx("p",{className:"text-[9px] text-text-muted",children:t.description}),d.length===0?e.jsxs("div",{className:"p-4 border border-dashed border-border rounded-lg text-center",children:[e.jsx(ya,{size:16,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No media available"}),e.jsx("p",{className:"text-[9px] text-text-muted mt-1",children:"Import media to use here"})]}):e.jsx("div",{className:"grid grid-cols-3 gap-2 max-h-32 overflow-y-auto",children:d.map(m=>e.jsxs("button",{onClick:()=>u(m.id),className:`relative aspect-video rounded overflow-hidden border-2 transition-all ${i===m.id?"border-primary ring-1 ring-primary":"border-transparent hover:border-text-muted"}`,children:[m.thumbnailUrl?e.jsx("img",{src:m.thumbnailUrl,alt:m.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full bg-background-secondary flex items-center justify-center",children:m.type==="video"?e.jsx(zs,{size:14,className:"text-text-muted"}):e.jsx(va,{size:14,className:"text-text-muted"})}),i===m.id&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 bg-primary rounded-full flex items-center justify-center",children:e.jsx(is,{size:10,className:"text-white"})})]},m.id))})]})},V0=({placeholder:t,value:s,onChange:a,onClear:r})=>{const[n,i]=l.useState(s?.value||t.defaultValue||"");l.useEffect(()=>{s?.value!==void 0&&i(s.value)},[s?.value]);const o=l.useCallback(d=>{i(d),a({type:"subtitle",value:d})},[a]),c=s?.value!==void 0&&s.value!==t.defaultValue;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ax,{size:12,className:"text-yellow-400"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:t.label}),t.required&&e.jsx("span",{className:"text-red-400 text-[10px]",children:"*"})]}),c&&e.jsx("button",{onClick:r,className:"p-1 text-text-muted hover:text-text-primary",title:"Reset to default",children:e.jsx(pn,{size:10})})]}),t.description&&e.jsx("p",{className:"text-[9px] text-text-muted",children:t.description}),e.jsx("input",{type:"text",value:n,onChange:d=>o(d.target.value),className:"w-full px-2 py-1.5 text-[11px] text-text-primary bg-background-tertiary border border-border rounded-lg focus:border-primary focus:outline-none",placeholder:t.defaultValue||"Enter subtitle text..."})]})},U0=({template:t,values:s,onChange:a,onApply:r})=>{const n=l.useMemo(()=>t?.placeholders??[],[t]),i=l.useCallback((x,h)=>{a({...s,[x]:h})},[s,a]),o=l.useCallback(x=>{const h={...s};delete h[x],a(h)},[s,a]),c=l.useCallback(()=>{a({})},[a]),d=Object.keys(s).length>0,u=l.useMemo(()=>n.filter(x=>x.required&&!s[x.id]?.value&&!x.defaultValue),[n,s]),p=u.length===0,m=l.useCallback(x=>{const h={placeholder:x,value:s[x.id],onChange:f=>i(x.id,f),onClear:()=>o(x.id)};switch(x.type){case"text":return e.jsx(O0,{...h},x.id);case"media":return e.jsx(_0,{...h},x.id);case"subtitle":return e.jsx(V0,{...h},x.id);default:return null}},[s,i,o]);return t?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dn,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Template Variables"}),e.jsx("span",{className:"text-[9px] text-text-muted bg-background-tertiary px-1.5 py-0.5 rounded",children:n.length})]}),d&&e.jsxs("button",{onClick:c,className:"flex items-center gap-1 text-[10px] text-text-muted hover:text-text-primary",children:[e.jsx(Ns,{size:10}),"Reset All"]})]}),n.length===0?e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-[10px] text-text-muted",children:"This template has no editable variables"})}):e.jsx("div",{className:"space-y-4",children:n.map(x=>e.jsx("div",{className:"p-3 bg-background-tertiary rounded-lg border border-border",children:m(x)},x.id))}),u.length>0&&e.jsx("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:e.jsxs("p",{className:"text-[10px] text-amber-400",children:["Fill in required fields:"," ",u.map(x=>x.label).join(", ")]})}),r&&e.jsx("button",{onClick:r,disabled:!p,className:`w-full py-2 rounded-lg text-[11px] font-medium transition-all ${p?"bg-primary text-white hover:bg-primary/90":"bg-background-tertiary text-text-muted cursor-not-allowed"}`,children:"Apply Template"})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(Dn,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Select a template to edit variables"})]})},gu={"social-media":Hh,youtube:zs,tiktok:Zr,instagram:Zr,business:Rm,personal:hl,slideshow:Kx,"intro-outro":As,"lower-third":Xi,custom:zx},K0=({template:t,isSelected:s,onSelect:a,onApply:r})=>{const n=gu[t.category]||sn;return e.jsxs("div",{onClick:a,className:`relative p-3 rounded-lg border cursor-pointer transition-all w-full max-w-full box-border ${s?"border-primary bg-primary/10 ring-1 ring-primary":"border-border bg-background-tertiary hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items-start gap-3 w-full",children:[e.jsx("div",{className:`w-10 h-10 shrink-0 rounded-lg flex items-center justify-center ${s?"bg-primary text-white":"bg-background-secondary"}`,children:e.jsx(n,{size:18})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary truncate",children:t.name}),t.id.startsWith("builtin-")&&e.jsx("span",{className:"px-1.5 py-0.5 text-[8px] bg-status-info/20 text-status-info rounded shrink-0",children:"Built-in"}),t.source==="cloud"&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] bg-primary/20 text-primary rounded flex items-center gap-1 shrink-0",children:[e.jsx(Xd,{size:8}),"Cloud"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-text-muted",children:[e.jsx(Os,{size:10}),e.jsxs("span",{children:[t.placeholderCount," placeholders"]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-text-muted",children:[e.jsx(Ia,{size:10}),e.jsxs("span",{children:[t.duration,"s"]})]})]})]})]}),s&&e.jsx("button",{onClick:i=>{i.stopPropagation(),r()},className:"mt-3 w-full py-1.5 text-[10px] font-medium bg-primary text-white rounded-md hover:bg-primary/90 transition-colors",children:"Use This Template"})]})},Y0=({onTemplateApplied:t})=>{const s=Ct(C=>C.getTemplateEngine),a=Ct(C=>C.getTitleEngine),r=F(C=>C.loadProject),[n,i]=l.useState("all"),[o,c]=l.useState([]),[d,u]=l.useState(null),[p,m]=l.useState(!0),[x,h]=l.useState(null),[f,v]=l.useState(!1),[A,g]=l.useState(null),[k,N]=l.useState({}),[b,j]=l.useState(!1);l.useEffect(()=>{(async()=>{m(!0);try{const M=await s();await M.initialize();const z=await M.listTemplates(),L=await kn.listTemplates(),B=[...z.map(G=>({...G,source:"local"})),...L.map(G=>({...G,source:"cloud"}))],O=Array.from(new Map(B.map(G=>[G.id,G])).values());c(O)}catch(M){console.error("Failed to load templates:",M)}finally{m(!1)}})()},[s]);const y=l.useMemo(()=>n==="all"?o:o.filter(C=>C.category===n),[o,n]),w=l.useCallback(async C=>{u(C),h(null);const M=await s(),z=o.find(B=>B.id===C);let L=await M.loadTemplate(C);!L&&z?.source==="cloud"&&(L=await kn.getTemplate(C)),L&&(g(L),N({}),L.placeholders.length>0?j(!0):j(!1))},[s,o]),S=l.useCallback(()=>{j(!1),g(null),N({})},[]),T=l.useCallback(async()=>{if(!d)return;const C=await s(),M=a();h(null);try{let z=A;if(!z){const G=o.find(V=>V.id===d);z=await C.loadTemplate(d),!z&&G?.source==="cloud"&&(z=await kn.getTemplate(d))}if(!z){h("Template not found");return}const{project:L,missingPlaceholders:B,textClips:O}=C.applyTemplate(z,k);if(B.length>0&&h(`Missing required: ${B.join(", ")}`),r(L),M&&O.length>0)for(const G of O){const P=z.placeholders.find(R=>R.id===G.placeholderId)?.label||"Text",_=L.timeline.tracks.find(R=>R.clips.some(U=>U.id===G.id)),se=_?.clips.find(R=>R.id===G.id);_&&se&&M.createTextClip({id:G.id,trackId:_.id,text:G.text,startTime:se.startTime,duration:se.duration,style:{fontFamily:"Inter",fontSize:P.toLowerCase().includes("title")?32:48,fontWeight:600,fontStyle:"normal",color:"#ffffff",textAlign:"center",verticalAlign:"middle",letterSpacing:0,lineHeight:1.2},transform:se.transform,animation:{preset:"fade",params:{easing:"ease-out"},inDuration:.5,outDuration:.3}})}j(!1),g(null),N({}),t?.()}catch(z){h(z instanceof Error?z.message:"Failed to apply template")}},[d,s,a,r,t,A,k,o]);return p?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-primary border-t-transparent"})}):b&&A?e.jsxs("div",{className:"space-y-4 w-full min-w-0 max-w-full",children:[e.jsxs("button",{onClick:S,className:"flex items-center gap-1.5 text-[10px] text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(dl,{size:12}),e.jsx("span",{children:"Back to Templates"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Dn,{size:16,className:"text-primary"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:A.name}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Configure template variables"})]})]}),x&&e.jsx("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:e.jsx("p",{className:"text-[10px] text-red-400",children:x})}),e.jsx(U0,{template:A,values:k,onChange:N,onApply:T})]}):e.jsxs("div",{className:"space-y-4 w-full min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(sn,{size:16,className:"text-primary shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Templates"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Start with a pre-made project"})]})]}),e.jsxs("div",{className:"flex gap-1 overflow-x-auto pb-1 -mx-1 px-1",children:[e.jsx("button",{onClick:()=>i("all"),className:`shrink-0 px-3 py-1.5 rounded-lg text-[10px] whitespace-nowrap transition-colors ${n==="all"?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:"All"}),fl.map(C=>{const M=gu[C.id]||sn;return e.jsxs("button",{onClick:()=>i(C.id),className:`shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] whitespace-nowrap transition-colors ${n===C.id?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:[e.jsx(M,{size:12}),C.name]},C.id)})]}),x&&e.jsx("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:e.jsx("p",{className:"text-[10px] text-red-400",children:x})}),e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto overflow-x-hidden",children:y.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sn,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No templates in this category"})]}):y.map(C=>e.jsx(K0,{template:C,isSelected:d===C.id,onSelect:()=>w(C.id),onApply:T},C.id))}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsxs("button",{onClick:()=>v(!0),className:"w-full flex items-center justify-center gap-2 py-2 text-[10px] text-text-secondary hover:text-text-primary bg-background-tertiary rounded-lg transition-colors",children:[e.jsx(cs,{size:12}),e.jsx("span",{children:"Save Current Project as Template"})]})}),e.jsxs("p",{className:"text-[9px] text-text-muted text-center",children:[o.length," templates available"]}),e.jsx($0,{isOpen:f,onClose:()=>{v(!1),(async()=>{m(!0);try{const M=await s();await M.initialize();const z=await M.listTemplates(),L=await kn.listTemplates(),B=[...z.map(G=>({...G,source:"local"})),...L.map(G=>({...G,source:"cloud"}))],O=Array.from(new Map(B.map(G=>[G.id,G])).values());c(O)}catch(M){console.error("Failed to load templates:",M)}finally{m(!1)}})()}})]})},X0=({angle:t,isActive:s,onSelect:a,onRename:r,onRemove:n,onOffsetChange:i})=>{const[o,c]=l.useState(!1),[d,u]=l.useState(t.name),p=()=>{r(d),c(!1)};return e.jsxs("div",{className:`p-2 rounded-lg border transition-colors cursor-pointer ${s?"bg-primary/20 border-primary":"bg-background-tertiary border-border hover:border-primary/50"}`,onClick:a,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:t.color}}),o?e.jsx("input",{type:"text",value:d,onChange:m=>u(m.target.value),onBlur:p,onKeyDown:m=>m.key==="Enter"&&p(),onClick:m=>m.stopPropagation(),className:"flex-1 px-1 py-0.5 text-[10px] bg-background-secondary rounded border border-primary focus:outline-none",autoFocus:!0}):e.jsx("span",{className:"flex-1 text-[10px] font-medium text-text-primary",onDoubleClick:m=>{m.stopPropagation(),c(!0)},children:t.name}),s&&e.jsx(is,{size:12,className:"text-primary"}),e.jsx("button",{onClick:m=>{m.stopPropagation(),n()},className:"p-1 text-text-muted hover:text-red-400 transition-colors",children:e.jsx($t,{size:10})})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[e.jsx("span",{className:"text-[8px] text-text-muted",children:"Offset:"}),e.jsx("input",{type:"number",value:t.offset.toFixed(2),onChange:m=>i(parseFloat(m.target.value)||0),onClick:m=>m.stopPropagation(),className:"w-16 px-1 py-0.5 text-[8px] bg-background-secondary rounded border border-border focus:border-primary focus:outline-none",step:"0.1"}),e.jsx("span",{className:"text-[8px] text-text-muted",children:"sec"})]})]})},G0=({group:t,isExpanded:s,onToggle:a,onSelectAngle:r,onRemoveAngle:n,onRenameAngle:i,onOffsetChange:o,onSync:c,onDelete:d})=>e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:a,className:"w-full flex items-center gap-2 p-2 bg-background-tertiary hover:bg-background-secondary transition-colors",children:[s?e.jsx(qt,{size:12,className:"text-text-muted"}):e.jsx(bs,{size:12,className:"text-text-muted"}),e.jsx(cl,{size:12,className:"text-primary"}),e.jsx("span",{className:"flex-1 text-left text-[10px] font-medium text-text-primary",children:t.name}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[t.angles.length," angles"]})]}),s&&e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.angles.map(u=>e.jsx(X0,{angle:u,isActive:u.id===t.activeAngleId,onSelect:()=>r(u.id),onRename:p=>i(u.id,p),onRemove:()=>n(u.id),onOffsetChange:p=>o(u.id,p)},u.id))}),e.jsxs("div",{className:"flex gap-1 pt-2 border-t border-border",children:[e.jsxs("button",{onClick:c,className:"flex-1 flex items-center justify-center gap-1 py-1.5 text-[9px] text-text-secondary hover:text-text-primary bg-background-tertiary rounded transition-colors",children:[e.jsx(rh,{size:10}),"Sync Audio"]}),e.jsx("button",{onClick:d,className:"flex items-center justify-center gap-1 px-2 py-1.5 text-[9px] text-red-400 hover:bg-red-400/10 rounded transition-colors",children:e.jsx($t,{size:10})})]})]})]}),H0=()=>{const t=F(N=>N.project),s=Ct(N=>N.getMultiCamEngine),[a,r]=l.useState(new Set),[n,i]=l.useState([]),[o,c]=l.useState(null);l.useEffect(()=>{let N=!1;return(async()=>{const j=await s();N||c(j)})(),()=>{N=!0}},[s]);const d=l.useMemo(()=>o?.getAllGroups()||[],[o,t.modifiedAt]),u=l.useMemo(()=>{const N=[];for(const b of t.timeline.tracks)if(b.type==="video"||b.type==="image")for(const j of b.clips)N.push({id:j.id,name:`Clip ${j.id.slice(-6)}`,trackName:b.name||`Track ${b.id.slice(-4)}`});return N},[t]),p=N=>{r(b=>{const j=new Set(b);return j.has(N)?j.delete(N):j.add(N),j})},m=l.useCallback(()=>{if(!o||n.length<2)return;const N=o.createGroup(`Multi-Cam ${d.length+1}`,n);r(b=>new Set([...b,N.id])),i([]),F.setState(b=>({project:{...b.project,modifiedAt:Date.now()}}))},[o,n,d.length]),x=l.useCallback((N,b)=>{o&&(o.setActiveAngle(N,b),F.setState(j=>({project:{...j.project,modifiedAt:Date.now()}})))},[o]),h=l.useCallback((N,b)=>{o&&(o.removeAngle(N,b),F.setState(j=>({project:{...j.project,modifiedAt:Date.now()}})))},[o]),f=l.useCallback((N,b,j)=>{o&&(o.renameAngle(N,b,j),F.setState(y=>({project:{...y.project,modifiedAt:Date.now()}})))},[o]),v=l.useCallback((N,b,j)=>{o&&(o.setAngleOffset(N,b,j),F.setState(y=>({project:{...y.project,modifiedAt:Date.now()}})))},[o]),A=l.useCallback(async N=>{},[o]),g=l.useCallback(N=>{o&&(o.deleteGroup(N),r(b=>{const j=new Set(b);return j.delete(N),j}),F.setState(b=>({project:{...b.project,modifiedAt:Date.now()}})))},[o]),k=N=>{i(b=>b.includes(N)?b.filter(j=>j!==N):[...b,N])};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(zs,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Multi-Camera Editing"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Sync and switch between camera angles"})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Camera Groups"}),d.map(N=>e.jsx(G0,{group:N,isExpanded:a.has(N.id),onToggle:()=>p(N.id),onSelectAngle:b=>x(N.id,b),onRemoveAngle:b=>h(N.id,b),onRenameAngle:(b,j)=>f(N.id,b,j),onOffsetChange:(b,j)=>v(N.id,b,j),onSync:()=>A(N.id),onDelete:()=>g(N.id)},N.id))]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Create New Group"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Select 2+ video clips to create a multi-camera group"}),u.length===0?e.jsxs("div",{className:"text-center py-4",children:[e.jsx(zs,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Import video clips to use multi-camera editing"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1",children:u.map(N=>e.jsxs("button",{onClick:()=>k(N.id),className:`w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors ${n.includes(N.id)?"bg-primary/20 border border-primary":"bg-background-tertiary border border-transparent hover:border-primary/30"}`,children:[e.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center ${n.includes(N.id)?"bg-primary border-primary":"border-border"}`,children:n.includes(N.id)&&e.jsx(is,{size:10,className:"text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[10px] text-text-primary",children:N.name}),e.jsxs("span",{className:"text-[8px] text-text-muted ml-1",children:["(",N.trackName,")"]})]})]},N.id))}),e.jsxs("button",{onClick:m,disabled:n.length<2,className:`w-full flex items-center justify-center gap-2 py-2 text-[10px] rounded-lg transition-colors ${n.length>=2?"bg-primary text-white hover:bg-primary/90":"bg-background-tertiary text-text-muted cursor-not-allowed"}`,children:[e.jsx(cs,{size:12}),"Create Group (",n.length," selected)"]})]})]}),e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Switch angles during playback to create cuts"})]})},Kr=({icon:t,title:s,description:a,iconColor:r,iconBg:n,activeBorder:i,activeBg:o,activeRing:c,isActive:d,onClick:u})=>e.jsx("button",{onClick:u,className:`w-full min-w-0 p-3 rounded-xl border text-left transition-all group ${d?`${i} ${o} ring-1 ${c}`:"border-border bg-background-tertiary hover:border-border-strong hover:bg-background-elevated"}`,children:e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 shrink-0 rounded-lg flex items-center justify-center transition-colors ${d?n:"bg-background-secondary group-hover:bg-background-tertiary"}`,children:e.jsx(t,{size:20,className:d?r:"text-text-secondary group-hover:text-text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[12px] font-semibold text-text-primary truncate",children:s}),e.jsx(bs,{size:14,className:`shrink-0 transition-transform ${d?"rotate-90 text-text-primary":"text-text-muted group-hover:text-text-secondary"}`})]}),e.jsx("p",{className:"text-[10px] text-text-muted mt-0.5 truncate",children:a})]})]})}),xi=({title:t,icon:s,children:a})=>e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx(s,{size:12,className:"text-text-muted shrink-0"}),e.jsx("span",{className:"text-[10px] font-semibold text-text-muted uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"space-y-1.5 min-w-0",children:a})]}),W0=()=>{const[t,s]=l.useState(null),a=Ea(o=>o.generatedAudio!==null&&!o.isAudioSaved),r=l.useCallback(o=>{t==="tts"&&o!=="tts"&&a&&Fe.warning("Unsaved audio discarded","Save to media or download next time to keep it."),s(o)},[t,a]),n=o=>{r(t===o?null:o)},i=()=>{switch(t){case"templates":return e.jsx(Y0,{});case"captions":return e.jsx(C0,{});case"tts":return e.jsx(z0,{});case"filters":return e.jsx(B0,{});case"music":return e.jsx(L0,{});case"multicam":return e.jsx(H0,{});default:return null}};return t?e.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto w-full min-w-0",children:[e.jsxs("button",{onClick:()=>r(null),className:"flex items-center gap-2 px-4 py-3 text-text-secondary hover:text-text-primary transition-colors border-b border-border bg-background-secondary shrink-0",children:[e.jsx(bs,{size:14,className:"rotate-180"}),e.jsx("span",{className:"text-[11px] font-medium",children:"Back to AI Tools"})]}),e.jsx(ia,{className:"flex-1 w-full",children:e.jsx("div",{className:"p-4 w-full min-w-0 overflow-hidden",children:i()})})]}):e.jsx(ia,{className:"flex-1 w-full",children:e.jsxs("div",{className:"p-4 space-y-6 min-w-0",children:[e.jsxs("div",{className:"text-center pb-2",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-2xl bg-gradient-to-br from-primary/20 to-primary/5 mb-3",children:e.jsx(cr,{size:24,className:"text-primary"})}),e.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"AI-Powered Tools"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-1",children:"Automate your editing with intelligent features"})]}),e.jsxs(xi,{title:"Content Generation",icon:cr,children:[e.jsx(Kr,{icon:Rr,title:"Text to Speech",description:"Generate natural voiceovers from text",iconColor:"text-blue-400",iconBg:"bg-blue-500/20",activeBorder:"border-blue-500/50",activeBg:"bg-blue-500/10",activeRing:"ring-blue-500/30",isActive:t==="tts",onClick:()=>n("tts")}),e.jsx(Kr,{icon:Xi,title:"Auto Captions",description:"Automatically generate subtitles from audio",iconColor:"text-purple-400",iconBg:"bg-purple-500/20",activeBorder:"border-purple-500/50",activeBg:"bg-purple-500/10",activeRing:"ring-purple-500/30",isActive:t==="captions",onClick:()=>n("captions")})]}),e.jsxs(xi,{title:"Templates & Presets",icon:Cx,children:[e.jsx(Kr,{icon:Os,title:"Project Templates",description:"Start with pre-built project structures",iconColor:"text-green-400",iconBg:"bg-green-500/20",activeBorder:"border-green-500/50",activeBg:"bg-green-500/10",activeRing:"ring-green-500/30",isActive:t==="templates",onClick:()=>n("templates")}),e.jsx(Kr,{icon:za,title:"Filter Presets",description:"Apply cinematic color grades instantly",iconColor:"text-orange-400",iconBg:"bg-orange-500/20",activeBorder:"border-orange-500/50",activeBg:"bg-orange-500/10",activeRing:"ring-orange-500/30",isActive:t==="filters",onClick:()=>n("filters")})]}),e.jsx(xi,{title:"Media Library",icon:Ts,children:e.jsx(Kr,{icon:Ps,title:"Music & Sound Effects",description:"Browse royalty-free audio for your projects",iconColor:"text-pink-400",iconBg:"bg-pink-500/20",activeBorder:"border-pink-500/50",activeBg:"bg-pink-500/10",activeRing:"ring-pink-500/30",isActive:t==="music",onClick:()=>n("music")})}),e.jsx(xi,{title:"Tools",icon:zs,children:e.jsx(Kr,{icon:zs,title:"Multi-Camera Editing",description:"Sync and switch between multiple angles",iconColor:"text-cyan-400",iconBg:"bg-cyan-500/20",activeBorder:"border-cyan-500/50",activeBg:"bg-cyan-500/10",activeRing:"ring-cyan-500/30",isActive:t==="multicam",onClick:()=>n("multicam")})}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"More AI features coming soon — image generation, auto-edit, and more"})})]})})},Sn=t=>(t.controls||[]).reduce((s,a)=>(s[a.id]=a.defaultValue,s),{}),Ei=(t,s)=>{const a=Sn(t);for(const r of t.controls||[]){const n=s?.[r.id];(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(a[r.id]=n)}return a},bu=({template:t,values:s,onChange:a,disabled:r=!1,className:n})=>!t.controls||t.controls.length===0?null:e.jsx("div",{className:n||"space-y-3",children:t.controls.map(i=>{const o=s[i.id]??i.defaultValue;if(i.type==="number")return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("label",{className:"text-[11px] font-medium text-text-primary",children:i.label}),e.jsx("span",{className:"rounded-full bg-background-tertiary px-2 py-0.5 text-[10px] text-text-secondary",children:o})]}),e.jsx("input",{type:"range",min:i.min??0,max:i.max??100,step:i.step??1,value:Number(o),disabled:r,onChange:c=>a(i.id,Number(c.target.value)),className:"w-full accent-[var(--color-primary,#22c55e)] disabled:cursor-not-allowed disabled:opacity-60"})]},i.id);if(i.type==="toggle")return e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("label",{className:"text-[11px] font-medium text-text-primary",children:i.label}),e.jsx("button",{type:"button",disabled:r,onClick:()=>a(i.id,!o),className:`inline-flex h-7 w-12 items-center rounded-full px-1 transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${o?"justify-end bg-primary":"justify-start bg-background-tertiary"}`,children:e.jsx("span",{className:"h-5 w-5 rounded-full bg-white shadow-sm"})})]},i.id);if(i.type==="select"){const c=i.options||[],d=Math.max(0,c.findIndex(u=>u.value===o));return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-medium text-text-primary",children:i.label}),e.jsx("select",{value:`${d}`,disabled:r,onChange:u=>{const p=c[Number(u.target.value)];p&&a(i.id,p.value)},className:"h-10 w-full rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60",children:c.map((u,p)=>e.jsx("option",{value:`${p}`,children:u.label},u.label))})]},i.id)}return i.type==="color"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-medium text-text-primary",children:i.label}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color",value:String(o),disabled:r,onChange:c=>a(i.id,c.target.value),className:"h-10 w-12 rounded-lg border border-border bg-transparent disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("input",{type:"text",value:String(o),disabled:r,onChange:c=>a(i.id,c.target.value),className:"h-10 flex-1 rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary placeholder:text-text-muted focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"})]})]},i.id):e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-medium text-text-primary",children:i.label}),e.jsx("input",{type:"text",value:String(o),disabled:r,onChange:c=>a(i.id,c.target.value),className:"h-10 w-full rounded-xl border border-border bg-background-tertiary px-3 text-xs text-text-primary placeholder:text-text-muted focus:border-primary/50 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"})]},i.id)})}),q0=t=>t.replace(/-/g," "),Q0=()=>{const t=F(M=>M.project),s=F(M=>M.getClip),a=F(M=>M.getMediaItem),r=F(M=>M.getEditingTemplates),n=F(M=>M.applyEditingTemplate),i=vt(M=>M.getSelectedClipIds),[o,c]=l.useState(""),[d,u]=l.useState("all"),[p,m]=l.useState(null),[x,h]=l.useState(null),[f,v]=l.useState({}),A=i(),g=l.useMemo(()=>r(),[r]),k=l.useMemo(()=>A.length!==1?null:s(A[0])||null,[s,A,t.modifiedAt]),N=l.useMemo(()=>k&&t.timeline.tracks.find(M=>M.clips.some(z=>z.id===k.id))||null,[t.timeline.tracks,k]),b=N?.type==="image"?"image":N?.type==="video"?"video":null,j=k?a(k.mediaId):void 0,y=k?.metadata?.appliedTemplates||[];l.useEffect(()=>{if(!p)return;const M=g.find(z=>z.id===p);!M||f[p]||v(z=>({...z,[p]:Sn(M)}))},[f,p,g]);const w=l.useMemo(()=>g.filter(M=>{if(b&&M.supportedTargets&&!M.supportedTargets.includes(b)||d!=="all"&&M.category!==d)return!1;if(!o.trim())return!0;const z=o.trim().toLowerCase();return M.name.toLowerCase().includes(z)||M.description.toLowerCase().includes(z)||M.tags.some(L=>L.toLowerCase().includes(z))}),[o,d,b,g]),S=M=>{m(z=>z===M.id?null:M.id),f[M.id]||v(z=>({...z,[M.id]:Sn(M)}))},T=(M,z,L)=>{v(B=>({...B,[M]:{...B[M]||{},[z]:L}}))},C=async M=>{if(!k||!b){Fe.warning("Select a clip","Recipes apply to one selected video or image clip.");return}h(M.id);try{if(!n(M.id,k.id,f[M.id]||Sn(M))){Fe.error("Could not apply recipe","This recipe could not be applied to the current clip.");return}Fe.success("Recipe applied",`${M.name} was added to ${j?.name||"the selected clip"}.`)}finally{h(null)}};return!k||!b?e.jsxs("div",{className:"h-full flex-1 min-h-0 flex flex-col items-center justify-center p-6 text-center space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-background-tertiary border border-border shadow-inner text-text-muted",children:e.jsx(gs,{size:24})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-text-primary",children:"Select a clip first"}),e.jsx("p",{className:"mt-1.5 text-xs text-text-muted max-w-[240px] leading-relaxed mx-auto",children:"Choose a video or image in the timeline to apply clip-scoped recipes, looks, and caption treatments."})]})]}):e.jsxs("div",{className:"flex flex-col flex-1 min-h-0 h-full bg-background-secondary overflow-y-auto",children:[e.jsxs("div",{className:"p-4 border-b border-border bg-background-secondary/80 backdrop-blur sticky top-0 z-10 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 bg-background-tertiary rounded-xl p-2 pr-3 border border-border",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-background-elevated flex items-center justify-center border border-border shrink-0",children:b==="video"?e.jsx("span",{className:"text-primary/70 text-[10px]",children:"VIDEO"}):e.jsx("span",{className:"text-primary/70 text-[10px]",children:"IMAGE"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold text-text-primary truncate",title:j?.name||k.id,children:j?.name||"Selected Clip"}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:[k.duration.toFixed(1),"s • ",y.length," recipes applied"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(la,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-muted"}),e.jsx("input",{type:"text",value:o,onChange:M=>c(M.target.value),placeholder:"Search recipes...",className:"w-full h-9 pl-9 pr-3 rounded-lg border border-border bg-background-tertiary text-xs text-text-primary placeholder:text-text-muted outline-none focus:border-primary/50 transition-colors"})]})]}),e.jsx("div",{className:"px-4 py-3 border-b border-border/50 bg-background-secondary",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("button",{onClick:()=>u("all"),className:`px-3 py-1.5 text-[10px] font-bold rounded-full transition-colors ${d==="all"?"bg-text-primary text-black":"bg-background-tertiary text-text-muted hover:text-text-primary hover:bg-background-elevated border border-border/50"}`,children:"ALL"}),mg.map(M=>e.jsx("button",{onClick:()=>u(M.id),className:`px-3 py-1.5 text-[10px] font-bold rounded-full uppercase transition-colors ${d===M.id?"bg-text-primary text-black":"bg-background-tertiary text-text-muted hover:text-text-primary hover:bg-background-elevated border border-border/50"}`,children:M.name},M.id))]})}),e.jsx("div",{className:"flex-1 p-4 space-y-3",children:w.length===0?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-text-secondary text-sm font-medium",children:"No recipes match"}),e.jsx("p",{className:"mt-2 text-xs text-text-muted",children:"Try a different search or category."})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3",children:w.map(M=>{const z=f[M.id]||Sn(M),L=y.filter(O=>O.templateId===M.id).length,B=p===M.id;return e.jsxs("div",{className:"rounded-xl border border-border bg-background-tertiary/50 transition-all hover:bg-background-tertiary overflow-hidden group shadow-sm hover:border-primary/30",children:[e.jsx("div",{className:"p-3",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-background-elevated border border-border/60 flex items-center justify-center shrink-0 shadow-inner group-hover:border-primary/30 transition-colors",children:e.jsx(cr,{size:18,className:`${L>0?"text-primary":"text-text-muted"}`})}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"truncate text-xs font-bold text-text-primary leading-tight",children:M.name}),L>0&&e.jsxs("span",{className:"shrink-0 flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[9px] font-bold text-primary ring-1 ring-primary/20",children:[e.jsx(Pm,{size:10}),L,"x"]})]}),e.jsx("p",{className:"mt-0.5 text-[10px] text-text-muted line-clamp-2 leading-relaxed",children:M.description})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2.5",children:[e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-text-muted font-medium",children:q0(M.category)}),e.jsxs("div",{className:"flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[M.controls&&M.controls.length>0&&e.jsxs("button",{onClick:()=>S(M),className:`h-6 px-2 text-[10px] font-medium rounded transition-colors flex items-center gap-1.5 ${B?"bg-primary/20 text-primary border border-primary/30":"bg-background-secondary border border-border hover:text-text-primary text-text-secondary"}`,children:[e.jsx(nf,{size:10}),"Edit"]}),e.jsx("button",{onClick:()=>void C(M),disabled:x!==null,className:"h-6 px-3 bg-primary text-black text-[10px] font-bold rounded transition-colors hover:bg-primary/80 disabled:opacity-50",children:x===M.id?"Applying":"Apply"})]})]})]})]})}),B&&M.controls&&M.controls.length>0&&e.jsx("div",{className:"px-3 pb-4 pt-1 bg-background-tertiary border-t border-border/50",children:e.jsx("div",{className:"space-y-3 pt-3",children:e.jsx(bu,{template:M,values:z,onChange:(O,G)=>T(M.id,O,G)})})})]},M.id)})})})]})},J0=()=>{const t=Ct(f=>f.getTemplateEngine),[s,a]=l.useState([]),[r,n]=l.useState(""),[i,o]=l.useState("all"),[c,d]=l.useState(!0),[u,p]=l.useState(null);l.useEffect(()=>{let f=!1;return(async()=>{const A=await t();await A.initialize();const g=await A.listTemplates();f||(a(g),d(!1))})(),()=>{f=!0}},[t]);const m=l.useMemo(()=>{let f=s;if(i!=="all"&&(f=f.filter(v=>v.category===i)),r.trim()){const v=r.toLowerCase();f=f.filter(A=>A.name.toLowerCase().includes(v))}return f},[s,i,r]),x=l.useCallback(async f=>{if(!(F.getState().project.timeline.tracks.length>0&&!window.confirm("Applying a template will replace your current project. Continue?"))){p(f);try{const A=await t(),g=await A.loadTemplate(f);if(!g)return;const k=A.applyTemplate(g,{});F.setState(()=>({project:{...k.project,modifiedAt:Date.now()}}))}finally{p(null)}}},[t]),h=f=>{const v=Math.floor(f/60),A=Math.round(f%60);return v>0?`${v}:${A.toString().padStart(2,"0")}`:`${A}s`};return c?e.jsx("div",{className:"flex items-center justify-center py-12 text-text-muted text-xs",children:"Loading templates..."}):e.jsxs("div",{className:"px-5 py-4 space-y-3 flex-1 min-h-0 h-full overflow-y-auto bg-background-secondary",children:[e.jsxs("div",{className:"relative",children:[e.jsx(la,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"}),e.jsx("input",{type:"text",placeholder:"Search templates...",value:r,onChange:f=>n(f.target.value),className:"w-full pl-8 pr-3 py-2 text-xs bg-background-secondary border border-border rounded-lg text-text-primary placeholder:text-text-muted focus:outline-none focus:border-primary/50"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx("button",{onClick:()=>o("all"),className:`px-2.5 py-1 text-[10px] rounded-full border transition-colors ${i==="all"?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-muted hover:border-primary/50"}`,children:"All"}),fl.slice(0,6).map(f=>e.jsx("button",{onClick:()=>o(f.id),className:`px-2.5 py-1 text-[10px] rounded-full border transition-colors ${i===f.id?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-muted hover:border-primary/50"}`,children:f.name},f.id))]}),m.length===0?e.jsx("div",{className:"text-center py-8 text-text-muted text-xs",children:"No templates found"}):e.jsx("div",{className:"grid grid-cols-2 gap-2",children:m.map(f=>e.jsxs("button",{onClick:()=>x(f.id),disabled:u!==null,className:"group relative flex flex-col p-3 bg-background-tertiary border border-border rounded-lg hover:border-primary/50 transition-all text-left disabled:opacity-50",children:[e.jsx("div",{className:"w-full aspect-video bg-background-secondary rounded mb-2 flex items-center justify-center",children:f.thumbnailUrl?e.jsx("img",{src:f.thumbnailUrl,alt:f.name,className:"w-full h-full object-cover rounded"}):e.jsx(vh,{size:20,className:"text-text-muted"})}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary truncate w-full",children:f.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-[9px] text-text-muted capitalize",children:f.category.replace("-"," ")}),e.jsxs("span",{className:"flex items-center gap-0.5 text-[9px] text-text-muted",children:[e.jsx(Ia,{size:8}),h(f.duration)]})]}),u===f.id&&e.jsx("div",{className:"absolute inset-0 bg-background-primary/80 rounded-lg flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] text-primary",children:"Applying..."})})]},f.id))})]})},Yt=(t,s,a)=>t+(s-t)*a,Dc=[{type:"brightness",label:"Brightness",description:"Lift midtones and highlights",category:"Basic",previewStyle:t=>({filter:`brightness(${Yt(.9,1.6,t)})`})},{type:"contrast",label:"Contrast",description:"Punchier shadows and highlights",category:"Basic",previewStyle:t=>({filter:`contrast(${Yt(.8,1.8,t)})`})},{type:"saturation",label:"Saturation",description:"Boost or mute color intensity",category:"Basic",previewStyle:t=>({filter:`saturate(${Yt(.5,2,t)})`})},{type:"temperature",label:"Temperature",description:"Warm / cool color shift",category:"Color",previewStyle:t=>({filter:`sepia(${Yt(0,.6,t)}) hue-rotate(${Yt(-12,12,t)}deg)`})},{type:"tint",label:"Tint",description:"Magenta / green color shift",category:"Color",previewStyle:t=>({filter:`hue-rotate(${Yt(0,60,t)}deg)`})},{type:"hue",label:"Hue",description:"Rotate the color wheel",category:"Color",previewStyle:t=>({filter:`hue-rotate(${Yt(0,360,t)}deg)`})},{type:"blur",label:"Blur",description:"Soft gaussian defocus",category:"Blur",previewStyle:t=>({filter:`blur(${Yt(0,6,t)}px)`})},{type:"motion-blur",label:"Motion Blur",description:"Directional smear",category:"Blur",previewStyle:t=>({filter:`blur(${Yt(0,3,t)}px)`,transform:`translateX(${Yt(0,6,t)}px)`})},{type:"radial-blur",label:"Radial Blur",description:"Zoom-style radial motion",category:"Blur",previewStyle:t=>({filter:`blur(${Yt(0,4,t)}px)`,transform:`scale(${Yt(1,1.12,t)})`})},{type:"sharpen",label:"Sharpen",description:"Unsharp-mask edge enhance",category:"Creative",previewStyle:t=>({filter:`contrast(${Yt(1,1.4,t)}) brightness(${Yt(1,1.05,t)})`})},{type:"vignette",label:"Vignette",description:"Darkened edges for focus",category:"Creative",previewStyle:t=>({boxShadow:`inset 0 0 ${Yt(0,50,t)}px ${Yt(0,25,t)}px rgba(0,0,0,0.65)`})},{type:"grain",label:"Film Grain",description:"Analog film texture",category:"Creative",previewStyle:t=>({filter:`contrast(${Yt(1,1.1,t)})`,opacity:Yt(1,.92,t)})},{type:"shadow",label:"Drop Shadow",description:"Cast a soft shadow",category:"Stylize",previewStyle:t=>({filter:`drop-shadow(${Yt(0,4,t)}px ${Yt(0,4,t)}px ${Yt(0,8,t)}px rgba(0,0,0,0.6))`})},{type:"glow",label:"Glow",description:"Bright outer halo",category:"Stylize",previewStyle:t=>({filter:`brightness(${Yt(1,1.15,t)}) drop-shadow(0 0 ${Yt(0,12,t)}px var(--accent))`})},{type:"chromatic-aberration",label:"Chromatic Aberration",description:"RGB-channel split offset",category:"Stylize",previewStyle:t=>({filter:`hue-rotate(${Yt(0,6,t)}deg)`,textShadow:`${Yt(0,2,t)}px 0 red, ${Yt(0,-2,t)}px 0 cyan`})}],Z0=["Basic","Color","Blur","Creative","Stylize"],Es=(t,s,a)=>e.jsx("div",{className:"absolute inset-0 overflow-hidden",style:s,children:t?e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full",style:{background:`linear-gradient(135deg, ${a}, oklch(0.45 0.12 200))`}})}),Ic=[{type:"crossfade",label:"Crossfade",description:"Smooth opacity blend",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{opacity:1-t},"oklch(0.55 0.14 295)"),Es(s,{opacity:t},"oklch(0.72 0.16 162)")]})},{type:"dipToBlack",label:"Dip to Black",description:"Fade through black",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{opacity:t<.5?1-t*2:0},"oklch(0.55 0.14 295)"),Es(s,{opacity:t>=.5?(t-.5)*2:0},"oklch(0.72 0.16 162)"),e.jsx("div",{className:"absolute inset-0 bg-black pointer-events-none",style:{opacity:t<.5?t*2:(1-t)*2}})]})},{type:"dipToWhite",label:"Dip to White",description:"Fade through white",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{opacity:t<.5?1-t*2:0},"oklch(0.55 0.14 295)"),Es(s,{opacity:t>=.5?(t-.5)*2:0},"oklch(0.72 0.16 162)"),e.jsx("div",{className:"absolute inset-0 bg-white pointer-events-none",style:{opacity:t<.5?t*2:(1-t)*2}})]})},{type:"wipe",label:"Wipe",description:"Hard edge sweeps across",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{clipPath:`inset(0 ${t*100}% 0 0)`},"oklch(0.55 0.14 295)"),Es(s,{clipPath:`inset(0 0 0 ${(1-t)*100}%)`},"oklch(0.72 0.16 162)")]})},{type:"slide",label:"Slide",description:"New clip slides in",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{transform:`translateX(${-t*100}%)`},"oklch(0.55 0.14 295)"),Es(s,{transform:`translateX(${(1-t)*100}%)`},"oklch(0.72 0.16 162)")]})},{type:"push",label:"Push",description:"Outgoing clip is shoved off",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{transform:`translateX(${-t*100}%)`},"oklch(0.55 0.14 295)"),Es(s,{transform:`translateX(${(1-t)*100}%)`},"oklch(0.72 0.16 162)")]})},{type:"zoom",label:"Zoom",description:"Scale up and dissolve",renderPreview:(t,s)=>e.jsxs(e.Fragment,{children:[Es(s,{transform:`scale(${1+t*1.5})`,opacity:1-t},"oklch(0.55 0.14 295)"),Es(s,{transform:`scale(${1.5-t*.5})`,opacity:t},"oklch(0.72 0.16 162)")]})}],Jo="application/x-openreel-effect",Zo="application/x-openreel-transition",_i=1800,eb=({def:t,thumbUrl:s,onApply:a})=>{const[r,n]=l.useState(0),[i,o]=l.useState(!1),c=_e.useRef(null),d=_e.useRef(0);_e.useEffect(()=>{if(!i){c.current&&cancelAnimationFrame(c.current),n(0);return}d.current=performance.now();const m=x=>{const f=(x-d.current)%_i/_i,v=f<.5?f*2:(1-f)*2;n(v),c.current=requestAnimationFrame(m)};return c.current=requestAnimationFrame(m),()=>{c.current&&cancelAnimationFrame(c.current)}},[i]);const u=t.previewStyle(r),p=l.useCallback(m=>{m.dataTransfer.effectAllowed="copy";const x=JSON.stringify({effectType:t.type});m.dataTransfer.setData(Jo,x),m.dataTransfer.setData("text/plain",`effect:${t.type}`)},[t.type]);return e.jsxs("button",{draggable:!0,onDragStart:p,onDoubleClick:a,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:"Drag onto a clip to apply • double-click to apply to selected clip",className:"group relative flex flex-col items-stretch rounded-lg border border-border bg-bg-2 overflow-hidden text-left cursor-grab active:cursor-grabbing hover:border-accent transition-colors",children:[e.jsxs("div",{className:"relative aspect-video bg-bg-3 overflow-hidden",children:[s?e.jsx("img",{src:s,alt:"",className:"absolute inset-0 w-full h-full object-cover",style:u,draggable:!1}):e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(135deg, oklch(0.55 0.14 295), oklch(0.72 0.16 162))",...u}}),e.jsx("span",{className:"absolute bottom-1 right-1 text-[8.5px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-black/55 text-white/85 backdrop-blur-sm",children:t.category})]}),e.jsxs("div",{className:"px-2 py-1.5 border-t border-border",children:[e.jsx("div",{className:"text-[10.5px] font-medium text-fg leading-tight",children:t.label}),e.jsx("div",{className:"text-[9.5px] text-fg-muted leading-tight mt-0.5 line-clamp-1",children:t.description})]})]})},tb=({def:t,thumbUrl:s})=>{const[a,r]=l.useState(0),[n,i]=l.useState(!1),o=_e.useRef(null),c=_e.useRef(0);_e.useEffect(()=>{if(!n){o.current&&cancelAnimationFrame(o.current),r(0);return}c.current=performance.now();const u=p=>{const m=(p-c.current)%_i;r(m/_i),o.current=requestAnimationFrame(u)};return o.current=requestAnimationFrame(u),()=>{o.current&&cancelAnimationFrame(o.current)}},[n]);const d=l.useCallback(u=>{u.dataTransfer.effectAllowed="copy";const p=JSON.stringify({transitionType:t.type});u.dataTransfer.setData(Zo,p),u.dataTransfer.setData("text/plain",`transition:${t.type}`)},[t.type]);return e.jsxs("button",{draggable:!0,onDragStart:d,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:"Drag onto a clip's edge (or between two clips) to apply",className:"group relative flex flex-col items-stretch rounded-lg border border-border bg-bg-2 overflow-hidden text-left cursor-grab active:cursor-grabbing hover:border-accent transition-colors",children:[e.jsx("div",{className:"relative aspect-video bg-bg-3 overflow-hidden",children:t.renderPreview(a,s)}),e.jsxs("div",{className:"px-2 py-1.5 border-t border-border",children:[e.jsx("div",{className:"text-[10.5px] font-medium text-fg leading-tight",children:t.label}),e.jsx("div",{className:"text-[9.5px] text-fg-muted leading-tight mt-0.5 line-clamp-1",children:t.description})]})]})},yu=()=>{const t=F(a=>a.project),s=vt(a=>a.getSelectedClipIds);return l.useMemo(()=>{const a=s(),r=t.timeline.tracks,n=t.mediaLibrary.items,i=c=>{for(const d of r){const u=d.clips.find(p=>p.id===c);if(u){const p=n.find(m=>m.id===u.mediaId);if(p?.thumbnailUrl)return p.thumbnailUrl}}return null};for(const c of a){const d=i(c);if(d)return d}for(const c of r)for(const d of c.clips){const u=n.find(p=>p.id===d.mediaId);if(u?.thumbnailUrl)return u.thumbnailUrl}return n.find(c=>c.thumbnailUrl)?.thumbnailUrl??null},[t,s])},sb=()=>{const t=yu(),s=vt(c=>c.getSelectedClipIds),a=F(c=>c.addVideoEffect),[r,n]=l.useState(""),i=l.useMemo(()=>{const c=r.trim().toLowerCase();return c?Dc.filter(d=>d.label.toLowerCase().includes(c)||d.description.toLowerCase().includes(c)||d.category.toLowerCase().includes(c)):Dc},[r]),o=l.useCallback(c=>{const d=s();if(d.length===0){Fe.warning("No clip selected","Drag the effect onto a clip in the timeline, or select a clip and double-click.");return}for(const u of d)a(u,c);Fe.success("Effect applied",`${c} added to ${d.length} clip${d.length>1?"s":""}`)},[s,a]);return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("div",{className:"px-3 pt-3 pb-2 shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(la,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-muted"}),e.jsx(ts,{type:"text",value:r,onChange:c=>n(c.target.value),placeholder:"Search effects",className:"pl-8 h-8 text-[11px] bg-bg-2 border-border"})]})}),e.jsx(ia,{className:"flex-1 min-h-0",children:e.jsxs("div",{className:"px-3 pb-3 space-y-3",children:[Z0.map(c=>{const d=i.filter(u=>u.category===c);return d.length===0?null:e.jsxs("section",{children:[e.jsx("div",{className:"text-[9.5px] uppercase tracking-wider text-fg-muted mb-1.5",children:c}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:d.map(u=>e.jsx(eb,{def:u,thumbUrl:t,onApply:()=>o(u.type)},u.type))})]},c)}),i.length===0&&e.jsxs("div",{className:"text-center text-[10.5px] text-fg-muted py-6",children:['No effects match "',r,'".']})]})})]})},ab=()=>{const t=yu(),[s,a]=l.useState(""),r=l.useMemo(()=>{const n=s.trim().toLowerCase();return n?Ic.filter(i=>i.label.toLowerCase().includes(n)||i.description.toLowerCase().includes(n)):Ic},[s]);return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("div",{className:"px-3 pt-3 pb-2 shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(la,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-muted"}),e.jsx(ts,{type:"text",value:s,onChange:n=>a(n.target.value),placeholder:"Search transitions",className:"pl-8 h-8 text-[11px] bg-bg-2 border-border"})]})}),e.jsx(ia,{className:"flex-1 min-h-0",children:e.jsxs("div",{className:"px-3 pb-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:r.map(n=>e.jsx(tb,{def:n,thumbUrl:t},n.type))}),r.length===0&&e.jsxs("div",{className:"text-center text-[10.5px] text-fg-muted py-6",children:['No transitions match "',s,'".']})]})})]})},rb="/api/file-stream-upload";async function nb(t,s={}){const a=new FormData;return a.append("file",t),a.append("uploadPath",s.uploadPath??"openreel"),s.fileName&&a.append("fileName",s.fileName),zm(rb,a)}const ib=[{id:xs.SEEDREAM,name:"Seedream 5 Lite",description:"High-quality image-to-image with aspect ratio and quality control. Up to 4K output.",badge:"4K"},{id:xs.Z_IMAGE,name:"Z-Image",description:"Text-to-image generation. Source image is used as inspiration only.",badge:"Text→Image"},{id:xs.NANO_BANANA2,name:"Nano Banana 2",description:"Versatile generation with wide aspect ratio support and flexible resolution.",badge:"Versatile"},{id:xs.FLUX2,name:"Flux 2 Pro",description:"Professional image-to-image with up to 8 reference images and 2K output.",badge:"Pro"},{id:xs.GROK,name:"Grok Imagine",description:"Style and composition transfer with optional prompt guidance.",badge:"Style"},{id:xs.QWEN,name:"Qwen",description:"Fine-grained control over image transformation strength and quality.",badge:"Control"}];function ob({onSelect:t}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-text-muted",children:"Select a model to generate a new image from your source."}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:ib.map(s=>e.jsxs("button",{onClick:()=>t(s.id),className:"flex items-start gap-3 rounded-lg border border-border bg-background-elevated p-3 text-left hover:border-primary hover:bg-primary/5 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:s.name}),s.badge&&e.jsx("span",{className:"rounded px-1.5 py-0.5 text-[10px] font-medium bg-primary/15 text-primary",children:s.badge})]}),e.jsx("p",{className:"mt-0.5 text-xs text-text-muted leading-relaxed",children:s.description})]}),e.jsx("svg",{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-text-muted",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M9 18l6-6-6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]},s.id))})]})}const yl=[{value:"1:1",label:"1:1 Square"},{value:"4:3",label:"4:3 Landscape"},{value:"3:4",label:"3:4 Portrait"},{value:"16:9",label:"16:9 Wide"},{value:"9:16",label:"9:16 Story"},{value:"2:3",label:"2:3 Portrait"},{value:"3:2",label:"3:2 Landscape"},{value:"21:9",label:"21:9 Cinematic"}],lb=[{value:"auto",label:"Auto"},...yl,{value:"1:4",label:"1:4 Tall"},{value:"4:1",label:"4:1 Wide"},{value:"1:8",label:"1:8 Very Tall"},{value:"8:1",label:"8:1 Very Wide"},{value:"4:5",label:"4:5 Portrait"},{value:"5:4",label:"5:4 Landscape"}],cb=[{value:"1:1",label:"1:1 Square"},{value:"4:3",label:"4:3 Landscape"},{value:"3:4",label:"3:4 Portrait"},{value:"16:9",label:"16:9 Wide"},{value:"9:16",label:"9:16 Story"}];function db({value:t,onChange:s,onSubmit:a,isLoading:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt *"}),e.jsx("textarea",{value:t.prompt,onChange:n=>s({...t,prompt:n.target.value}),placeholder:"Describe the image you want to generate…",maxLength:3e3,rows:4,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[t.prompt.length,"/3000"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Aspect Ratio"}),e.jsxs(ot,{value:t.aspect_ratio,onValueChange:n=>s({...t,aspect_ratio:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsx(dt,{children:yl.map(n=>e.jsx(ge,{value:n.value,children:n.label},n.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Quality"}),e.jsxs(ot,{value:t.quality,onValueChange:n=>s({...t,quality:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"basic",children:"Basic (2K)"}),e.jsx(ge,{value:"high",children:"High (4K)"})]})]})]})]}),e.jsx(zt,{onClick:a,disabled:r||!t.prompt.trim(),className:"w-full",children:r?"Generating…":"Generate with Seedream"})]})}function ub({value:t,onChange:s,onSubmit:a,isLoading:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30 text-xs text-yellow-400",children:"Z-Image is text-to-image — the source image is used as inspiration only, not as a direct reference."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt *"}),e.jsx("textarea",{value:t.prompt,onChange:n=>s({...t,prompt:n.target.value}),placeholder:"Describe the image you want to generate…",maxLength:1e3,rows:4,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[t.prompt.length,"/1000"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Aspect Ratio"}),e.jsxs(ot,{value:t.aspect_ratio,onValueChange:n=>s({...t,aspect_ratio:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsx(dt,{children:cb.map(n=>e.jsx(ge,{value:n.value,children:n.label},n.value))})]})]}),e.jsx(zt,{onClick:a,disabled:r||!t.prompt.trim(),className:"w-full",children:r?"Generating…":"Generate with Z-Image"})]})}function mb({value:t,onChange:s,onSubmit:a,isLoading:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt *"}),e.jsx("textarea",{value:t.prompt,onChange:n=>s({...t,prompt:n.target.value}),placeholder:"Describe the image you want to generate…",maxLength:2e3,rows:4,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[t.prompt.length,"/2000"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Aspect Ratio"}),e.jsxs(ot,{value:t.aspect_ratio??"1:1",onValueChange:n=>s({...t,aspect_ratio:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsx(dt,{children:lb.map(n=>e.jsx(ge,{value:n.value,children:n.label},n.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Resolution"}),e.jsxs(ot,{value:t.resolution??"2K",onValueChange:n=>s({...t,resolution:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"1K",children:"1K"}),e.jsx(ge,{value:"2K",children:"2K"}),e.jsx(ge,{value:"4K",children:"4K"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Format"}),e.jsxs(ot,{value:t.output_format??"png",onValueChange:n=>s({...t,output_format:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"png",children:"PNG"}),e.jsx(ge,{value:"jpg",children:"JPG"})]})]})]})]}),e.jsx(zt,{onClick:a,disabled:r||!t.prompt.trim(),className:"w-full",children:r?"Generating…":"Generate with Nano Banana 2"})]})}function pb({value:t,onChange:s,onSubmit:a,isLoading:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt *"}),e.jsx("textarea",{value:t.prompt,onChange:n=>s({...t,prompt:n.target.value}),placeholder:"Describe the image you want to generate…",maxLength:2e3,rows:4,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[t.prompt.length,"/2000"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Aspect Ratio"}),e.jsxs(ot,{value:t.aspect_ratio,onValueChange:n=>s({...t,aspect_ratio:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsx(dt,{children:yl.map(n=>e.jsx(ge,{value:n.value,children:n.label},n.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Resolution"}),e.jsxs(ot,{value:t.resolution,onValueChange:n=>s({...t,resolution:n}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"1K",children:"1K"}),e.jsx(ge,{value:"2K",children:"2K"})]})]})]})]}),e.jsx(zt,{onClick:a,disabled:r||!t.prompt.trim(),className:"w-full",children:r?"Generating…":"Generate with Flux 2"})]})}function xb({value:t,onChange:s,onSubmit:a,isLoading:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"p-2 rounded-lg bg-blue-500/10 border border-blue-500/30 text-xs text-blue-400",children:"Grok Imagine uses the source image as a reference for style and composition. An optional prompt can guide the transformation."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt (optional)"}),e.jsx("textarea",{value:t.prompt??"",onChange:n=>s({...t,prompt:n.target.value||void 0}),placeholder:"Optional: describe what you want to change or emphasize…",maxLength:1e3,rows:3,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[(t.prompt??"").length,"/1000"]})]}),e.jsx(zt,{onClick:a,disabled:r,className:"w-full",children:r?"Generating…":"Generate with Grok Imagine"})]})}function hb({value:t,onChange:s,onSubmit:a,isLoading:r}){const n=t.strength??.8;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Prompt *"}),e.jsx("textarea",{value:t.prompt,onChange:i=>s({...t,prompt:i.target.value}),placeholder:"Describe the image you want to generate…",maxLength:2e3,rows:4,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"}),e.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[t.prompt.length,"/2000"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-medium text-text-secondary",children:["Strength — ",n.toFixed(1),e.jsx("span",{className:"ml-2 text-text-muted font-normal",children:"(0 = preserve original, 1 = full remake)"})]}),e.jsx("input",{type:"range",min:0,max:1,step:.05,value:n,onChange:i=>s({...t,strength:parseFloat(i.target.value)}),className:"w-full accent-primary"}),e.jsxs("div",{className:"flex justify-between text-[10px] text-text-muted",children:[e.jsx("span",{children:"Preserve"}),e.jsx("span",{children:"Remake"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Format"}),e.jsxs(ot,{value:t.output_format??"png",onValueChange:i=>s({...t,output_format:i}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"png",children:"PNG"}),e.jsx(ge,{value:"jpeg",children:"JPEG"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Acceleration"}),e.jsxs(ot,{value:t.acceleration??"regular",onValueChange:i=>s({...t,acceleration:i}),children:[e.jsx(lt,{className:"h-8 text-sm",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"none",children:"None (best quality)"}),e.jsx(ge,{value:"regular",children:"Regular"}),e.jsx(ge,{value:"high",children:"High (fastest)"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Negative Prompt (optional)"}),e.jsx("textarea",{value:t.negative_prompt??"",onChange:i=>s({...t,negative_prompt:i.target.value||void 0}),placeholder:"Describe what you don't want in the result…",maxLength:500,rows:2,className:"w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"})]}),e.jsx(zt,{onClick:a,disabled:r||!t.prompt.trim(),className:"w-full",children:r?"Generating…":"Generate with Qwen"})]})}function Bc(){return{prompt:"",image_urls:[],aspect_ratio:"1:1",quality:"basic"}}function Fc(){return{prompt:"",aspect_ratio:"1:1"}}function Lc(){return{prompt:"",aspect_ratio:"1:1",resolution:"2K",output_format:"png"}}function $c(){return{prompt:"",input_urls:[],aspect_ratio:"1:1",resolution:"1K"}}function Oc(){return{image_urls:[]}}function _c(t){return{prompt:"",image_url:t,strength:.8,output_format:"png",acceleration:"regular"}}function fb({open:t,onClose:s,sourceFile:a,previewUrl:r}){const[n,i]=l.useState("pick"),[o,c]=l.useState(null),[d,u]=l.useState(""),p=l.useRef(null),{project:m,addPlaceholderMedia:x}=F(),{addTask:h}=kd(),[f,v]=l.useState(Bc),[A,g]=l.useState(Fc),[k,N]=l.useState(Lc),[b,j]=l.useState($c),[y,w]=l.useState(Oc),[S,T]=l.useState(()=>_c("")),C=l.useCallback(()=>{p.current?.abort(),i("pick"),c(null),u(""),v(Bc()),g(Fc()),N(Lc()),j($c()),w(Oc()),T(_c("")),s()},[s]),M=l.useCallback(O=>{c(O),i("form")},[]),z=l.useCallback(()=>{i("pick"),c(null)},[]),L=l.useCallback(async()=>{if(!o||!m)return;i("submitting"),u("");const O=new AbortController;p.current=O;try{let G="";if(o!==xs.Z_IMAGE){const K=await nb(a);if(O.signal.aborted)return;if(console.log("[KieAI] upload response:",K),G=K.fileUrl||K.downloadUrl||K.url||"",!G)throw new Error("Upload succeeded but returned no file URL. Check console for response.")}if(O.signal.aborted)return;let P;switch(o){case xs.SEEDREAM:P={...f,image_urls:[G]};break;case xs.Z_IMAGE:P=A;break;case xs.NANO_BANANA2:P={...k,image_input:[G]};break;case xs.FLUX2:P={...b,input_urls:[G]};break;case xs.GROK:P={...y,image_urls:[G]};break;case xs.QWEN:P={...S,image_url:G};break;default:throw new Error("Unknown model")}console.log("[KieAI] createTask payload:",{model:o,input:P});const _=await Dm(o,P);if(O.signal.aborted)return;const U=`${a.name.replace(/\.[^.]+$/,"")}_kieai.png`,D=Nd();x({id:D,name:U,type:"image",fileHandle:null,blob:null,metadata:{duration:0,width:0,height:0,frameRate:0,codec:"",sampleRate:0,channels:0,fileSize:0},thumbnailUrl:r,waveformData:null,isPlaceholder:!0,isPending:!0,kieaiTaskId:_}),h({taskId:_,mediaId:D,projectId:m.id,type:"image",suggestedName:U,createdAt:Date.now()}),C()}catch(G){if(G instanceof Error&&G.name==="AbortError")return;u(G instanceof Error?G.message:String(G)),i("error")}},[o,m,a,r,f,A,k,b,y,S,x,h,C]),B=o?o.split("/")[0].replace(/-/g," ").replace(/\b\w/g,O=>O.toUpperCase()):"";return e.jsx(ur,{open:t,onOpenChange:O=>{O||C()},children:e.jsxs(mr,{className:"max-w-md",children:[e.jsx(pr,{children:e.jsxs(xr,{children:[n==="pick"&&"Create with KieAI",n==="form"&&`${B}`,n==="submitting"&&"Submitting…",n==="error"&&"Submission Failed"]})}),e.jsxs("div",{className:"mt-2 max-h-[70vh] overflow-y-auto pr-1",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2 rounded-lg border border-border bg-background-elevated p-2",children:[r?e.jsx("img",{src:r,alt:"Source",className:"h-10 w-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"h-10 w-10 rounded bg-background-tertiary flex items-center justify-center flex-shrink-0",children:e.jsxs("svg",{className:"h-5 w-5 text-text-muted",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("path",{d:"m3 9 4-4 4 4 4-4 4 4"}),e.jsx("circle",{cx:"8.5",cy:"14.5",r:"1.5"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-xs font-medium text-text-primary",children:a.name}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Source image"})]})]}),n==="pick"&&e.jsx(ob,{onSelect:M}),n==="form"&&o===xs.SEEDREAM&&e.jsx(db,{value:f,onChange:v,onSubmit:L,isLoading:!1}),n==="form"&&o===xs.Z_IMAGE&&e.jsx(ub,{value:A,onChange:g,onSubmit:L,isLoading:!1}),n==="form"&&o===xs.NANO_BANANA2&&e.jsx(mb,{value:k,onChange:N,onSubmit:L,isLoading:!1}),n==="form"&&o===xs.FLUX2&&e.jsx(pb,{value:b,onChange:j,onSubmit:L,isLoading:!1}),n==="form"&&o===xs.GROK&&e.jsx(xb,{value:y,onChange:w,onSubmit:L,isLoading:!1}),n==="form"&&o===xs.QWEN&&e.jsx(hb,{value:S,onChange:T,onSubmit:L,isLoading:!1}),n==="submitting"&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx("div",{className:"mx-auto h-10 w-10 animate-spin rounded-full border-4 border-border border-t-primary"}),e.jsx("p",{className:"text-sm text-text-secondary",children:"Uploading & submitting task…"}),e.jsx(zt,{variant:"outline",size:"sm",onClick:()=>{p.current?.abort(),C()},children:"Cancel"})]}),n==="error"&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400",children:d}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(zt,{variant:"outline",className:"flex-1",onClick:C,children:"Close"}),e.jsx(zt,{className:"flex-1",onClick:()=>i("form"),children:"Try Again"})]})]})]}),n==="form"&&e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx("button",{onClick:z,className:"text-xs text-text-muted hover:text-text-primary transition-colors",children:"← Back to model selection"})})]})})}const Vc=t=>{const s=Math.floor(t/60),a=Math.floor(t%60);return`${s.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`},Uc=[{value:"media",label:"Media",description:"Import footage, audio, and stills."},{value:"text",label:"Text",description:"Add title presets and caption elements."},{value:"graphics",label:"Graphics",description:"Create shapes, arrows, and SVG overlays."},{value:"effects",label:"Effects",description:"Drag effects onto a clip to apply them."},{value:"transitions",label:"Transitions",description:"Drag transitions onto a clip's edge."},{value:"ai",label:"AI Generate",description:"Generate clips, captions, and assisted edits."},{value:"recipes",label:"Recipes",description:"Apply clip-scoped looks, overlays, and text stacks."},{value:"templates",label:"Project Templates",description:"Load full-project starter layouts and presets."}],gb={media:zs,text:Hs,graphics:mn,effects:ks,transitions:Zh,ai:gs,recipes:cr,templates:eh},bb=({item:t,isSelected:s,viewMode:a,onSelect:r,onDelete:n,onReplace:i,onDragStart:o,onAddToTimeline:c,onKieAI:d,onRetryKieAI:u})=>{const[p,m]=l.useState(!1),h=(()=>{switch(t.type){case"video":return lr;case"audio":return Ps;case"image":return va;default:return lr}})(),f=()=>t.metadata?.width&&t.metadata?.height?`${t.metadata.width}×${t.metadata.height}`:null,v=b=>b?b<1024?`${b} B`:b<1024*1024?`${(b/1024).toFixed(1)} KB`:`${(b/(1024*1024)).toFixed(1)} MB`:null,A=t.type==="audio"||t.type==="image"?"text-primary/50":"text-status-info/50",g=t.kieaiError?"border-red-500 ring-1 ring-red-500/50 shadow-[0_0_10px_rgba(239,68,68,0.3)]":t.isPending?"border-purple-500 ring-1 ring-purple-500/50 shadow-[0_0_10px_rgba(168,85,247,0.3)]":t.isPlaceholder?"border-yellow-500 ring-1 ring-yellow-500/50 shadow-[0_0_10px_rgba(234,179,8,0.3)]":s?"border-primary ring-1 ring-primary/50 shadow-[0_0_10px_rgba(34,197,94,0.2)]":"border-border hover:border-text-secondary",k=e.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-[1px] flex items-center justify-center gap-2 animate-in fade-in duration-200",children:t.kieaiError?e.jsx("button",{onClick:b=>{b.stopPropagation(),u?.()},title:"Generation failed — click to retry",className:"p-2 bg-red-500/20 rounded-full hover:bg-red-500/40 backdrop-blur-sm transition-colors",children:e.jsx(na,{size:14,className:"text-red-400"})}):t.isPending?e.jsx("div",{title:"KieAI generation in progress…",className:"p-2",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-purple-400 border-t-transparent"})}):t.isPlaceholder?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:b=>{b.stopPropagation(),i()},title:"Replace asset",className:"p-2 bg-yellow-500/20 rounded-full hover:bg-yellow-500/40 backdrop-blur-sm transition-colors",children:e.jsx(na,{size:14,className:"text-yellow-500"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),n()},title:"Delete",className:"p-2 bg-red-500/20 rounded-full hover:bg-red-500/40 backdrop-blur-sm transition-colors",children:e.jsx($t,{size:14,className:"text-red-400"})})]}):e.jsxs(e.Fragment,{children:[t.type==="image"&&d&&e.jsx("button",{onClick:b=>{b.stopPropagation(),d()},title:"Create with KieAI",className:"p-2 bg-purple-500/20 rounded-full hover:bg-purple-500/40 backdrop-blur-sm transition-colors",children:e.jsx(gs,{size:14,className:"text-purple-300"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),c()},title:"Add to timeline",className:"p-2 bg-primary/20 rounded-full hover:bg-primary/40 backdrop-blur-sm transition-colors",children:e.jsx(cs,{size:14,className:"text-primary"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),n()},title:"Delete",className:"p-2 bg-red-500/20 rounded-full hover:bg-red-500/40 backdrop-blur-sm transition-colors",children:e.jsx($t,{size:14,className:"text-red-400"})})]})});if(a==="list")return e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{draggable:!0,onDragStart:o,onClick:r,onDoubleClick:b=>{b.stopPropagation(),c()},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),className:`flex items-center gap-3 px-2 py-1.5 rounded-lg border-2 cursor-pointer transition-all group ${g}`,children:[e.jsxs("div",{className:"w-12 h-8 rounded bg-background-tertiary relative overflow-hidden flex-shrink-0",children:[t.thumbnailUrl?e.jsx("img",{src:t.thumbnailUrl,alt:t.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(h,{size:14,className:A})}),t.kieaiError&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-red-500/10",children:e.jsx(ra,{size:12,className:"text-red-400"})}),!t.kieaiError&&t.isPending&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-purple-500/10",children:e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-purple-400 border-t-transparent"})}),!t.kieaiError&&!t.isPending&&t.isPlaceholder&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-yellow-500/10",children:e.jsx(ra,{size:12,className:"text-yellow-500/70"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:`text-[11px] truncate font-medium ${s?"text-primary":"text-text-primary"}`,title:t.name,children:t.name}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] text-text-muted",children:[t.metadata?.duration&&e.jsx("span",{children:Vc(t.metadata.duration)}),t.metadata?.duration&&f()&&e.jsx("span",{children:"•"}),f()&&e.jsx("span",{children:f()}),(t.metadata?.duration||f())&&v(t.metadata?.fileSize)&&e.jsx("span",{children:"•"}),v(t.metadata?.fileSize)&&e.jsx("span",{children:v(t.metadata?.fileSize)})]})]}),p&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:t.kieaiError?e.jsx("button",{onClick:b=>{b.stopPropagation(),u?.()},title:"Retry generation",className:"p-1 bg-red-500/20 rounded hover:bg-red-500/40 transition-colors",children:e.jsx(na,{size:12,className:"text-red-400"})}):t.isPending?e.jsx("div",{className:"p-1",title:"Generating…",children:e.jsx("div",{className:"h-3 w-3 animate-spin rounded-full border-2 border-purple-400 border-t-transparent"})}):t.isPlaceholder?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:b=>{b.stopPropagation(),i()},title:"Replace asset",className:"p-1 bg-yellow-500/20 rounded hover:bg-yellow-500/40 transition-colors",children:e.jsx(na,{size:12,className:"text-yellow-500"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),n()},title:"Delete",className:"p-1 bg-red-500/20 rounded hover:bg-red-500/40 transition-colors",children:e.jsx($t,{size:12,className:"text-red-400"})})]}):e.jsxs(e.Fragment,{children:[t.type==="image"&&d&&e.jsx("button",{onClick:b=>{b.stopPropagation(),d()},title:"Create with KieAI",className:"p-1 bg-purple-500/20 rounded hover:bg-purple-500/40 transition-colors",children:e.jsx(gs,{size:12,className:"text-purple-300"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),c()},title:"Add to timeline",className:"p-1 bg-primary/20 rounded hover:bg-primary/40 transition-colors",children:e.jsx(cs,{size:12,className:"text-primary"})}),e.jsx("button",{onClick:b=>{b.stopPropagation(),n()},title:"Delete",className:"p-1 bg-red-500/20 rounded hover:bg-red-500/40 transition-colors",children:e.jsx($t,{size:12,className:"text-red-400"})})]})}),s&&e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full shadow-[0_0_8px_#22c55e] flex-shrink-0"})]})}),e.jsxs(En,{children:[t.type==="image"&&d&&e.jsxs(rs,{onClick:d,children:[e.jsx(gs,{size:13,className:"mr-2 text-primary"}),"Create with KieAI"]}),e.jsxs(rs,{onClick:b=>{b.stopPropagation?.(),c()},children:[e.jsx(cs,{size:13,className:"mr-2"}),"Add to Timeline"]}),e.jsxs(rs,{onClick:b=>{b.stopPropagation?.(),n()},className:"text-red-400 focus:text-red-400",children:[e.jsx($t,{size:13,className:"mr-2"}),"Delete"]})]})]});const N=a==="small"?16:24;return e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{draggable:!0,onDragStart:o,onClick:r,onDoubleClick:b=>{b.stopPropagation(),c()},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),className:`aspect-video bg-background-tertiary rounded-lg border-2 relative group cursor-pointer transition-all overflow-hidden shadow-sm ${g}`,children:[t.thumbnailUrl?e.jsx("img",{src:t.thumbnailUrl,alt:t.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background-tertiary",children:e.jsx(h,{size:N,className:A})}),t.type==="audio"&&e.jsx("div",{className:"absolute top-1/2 left-0 right-0 h-4 flex items-center gap-px px-2 -translate-y-1/2",children:[...Array(10)].map((b,j)=>e.jsx("div",{className:"flex-1 bg-primary/30 rounded-full",style:{height:`${Math.random()*100}%`}},j))}),t.kieaiError&&e.jsxs("div",{className:"absolute top-1 left-1 px-1.5 py-0.5 bg-red-500 rounded text-[8px] text-white font-bold flex items-center gap-1",children:[e.jsx(ra,{size:8}),"Failed"]}),!t.kieaiError&&t.isPending&&e.jsxs("div",{className:"absolute top-1 left-1 px-1.5 py-0.5 bg-purple-500 rounded text-[8px] text-white font-bold flex items-center gap-1",children:[e.jsx("div",{className:"h-2 w-2 animate-spin rounded-full border border-white border-t-transparent"}),"AI"]}),!t.kieaiError&&!t.isPending&&t.isPlaceholder&&e.jsxs("div",{className:"absolute top-1 left-1 px-1.5 py-0.5 bg-yellow-500 rounded text-[8px] text-black font-bold flex items-center gap-1",children:[e.jsx(ra,{size:10}),"Missing"]}),t.metadata?.duration&&e.jsx("div",{className:"absolute bottom-1 right-1 px-1.5 py-0.5 bg-black/70 rounded text-[9px] text-white font-mono",children:Vc(t.metadata.duration)}),t.kieaiError&&!p&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-red-500/10",children:e.jsx(ra,{size:a==="small"?20:32,className:"text-red-400/60"})}),!t.kieaiError&&t.isPending&&!p&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-purple-500/10",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-purple-400 border-t-transparent"})}),!t.kieaiError&&!t.isPending&&t.isPlaceholder&&!p&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-yellow-500/10",children:e.jsx(ra,{size:a==="small"?20:32,className:"text-yellow-500/50"})}),p&&k,s&&e.jsx("div",{className:"absolute top-1 right-1 w-2 h-2 bg-primary rounded-full shadow-[0_0_8px_#22c55e]"})]}),e.jsxs("div",{className:"mt-1.5 px-0.5",children:[e.jsx("div",{className:`text-[10px] truncate font-medium ${s?"text-primary":"text-text-primary"}`,title:t.name,children:t.name}),a==="large"&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] text-text-muted mt-0.5",children:[f()&&e.jsx("span",{children:f()}),f()&&v(t.metadata?.fileSize)&&e.jsx("span",{children:"•"}),v(t.metadata?.fileSize)&&e.jsx("span",{children:v(t.metadata?.fileSize)})]})]})]})}),e.jsxs(En,{children:[t.type==="image"&&d&&e.jsxs(rs,{onClick:d,children:[e.jsx(gs,{size:13,className:"mr-2 text-primary"}),"Create with KieAI"]}),e.jsxs(rs,{onClick:()=>c(),children:[e.jsx(cs,{size:13,className:"mr-2"}),"Add to Timeline"]}),e.jsxs(rs,{onClick:()=>n(),className:"text-red-400 focus:text-red-400",children:[e.jsx($t,{size:13,className:"mr-2"}),"Delete"]})]})]})},yb=({onImport:t})=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-background-tertiary border border-border flex items-center justify-center mb-4 shadow-inner",children:e.jsx(ya,{size:24,className:"text-text-muted"})}),e.jsx("p",{className:"text-sm text-text-secondary mb-2 font-medium",children:"No media imported"}),e.jsx("p",{className:"text-xs text-text-muted mb-6",children:"Drag files here or click to import"}),e.jsx("button",{onClick:t,className:"px-4 py-2 bg-background-elevated hover:bg-background-tertiary border border-border text-text-primary text-xs font-medium rounded-lg transition-all hover:border-primary/50",children:"Import Media"})]}),vb=({message:t})=>e.jsxs("div",{className:"absolute inset-0 bg-background-secondary/90 backdrop-blur-sm flex flex-col items-center justify-center z-50",children:[e.jsx("div",{className:"w-10 h-10 border-2 border-primary border-t-transparent rounded-full animate-spin mb-3"}),e.jsx("p",{className:"text-sm text-text-secondary",children:t})]}),jb=()=>{const t=l.useRef(null),[s,a]=l.useState(""),[r,n]=l.useState("media"),i=Ea(ae=>ae.generatedAudio!==null&&!ae.isAudioSaved),o=l.useCallback(ae=>{r==="ai"&&ae!=="ai"&&i&&Fe.warning("Unsaved audio discarded","Save to media or download next time to keep it."),n(ae)},[r,i]),[c,d]=l.useState(!1),[u,p]=l.useState(!1),[m,x]=l.useState(""),[h,f]=l.useState(!1),[v,A]=l.useState(!1),[g,k]=l.useState(null),[N,b]=l.useState("large"),[j,y]=l.useState(null),[w,S]=l.useState("all"),[T,C]=l.useState(null),{project:M,importMedia:z,deleteMedia:L,replaceMediaAsset:B,updateSettings:O,setKieAIItemState:G}=F(),V=M.mediaLibrary.items,{retryTask:P}=kd(),{select:_,isSelected:se,startDrag:R}=vt(),U=V.filter(ae=>ae.isPlaceholder).length,D=V.filter(ae=>{const W=ae.name.toLowerCase().includes(s.toLowerCase()),Q=h?ae.isPlaceholder:!0;return W&&Q}),X=l.useCallback(async ae=>{if(!ae||ae.length===0)return;p(!0);const W=Array.from(ae);try{for(let Q=0;Q{ae.preventDefault(),d(!1);const W=ae.dataTransfer.files,Q="getAsFileSystemHandle"in DataTransferItem.prototype?Array.from(ae.dataTransfer.items).filter(be=>be.kind==="file").map(async be=>{try{const Oe=await be.getAsFileSystemHandle();if(Oe.kind==="file"){const Ue=Oe,Le=await Ue.getFile();await Ul(Le.name,Le.size,Ue)}}catch{}}):[];await Promise.all(Q),X(W)},[X]),ue=l.useCallback(ae=>{ae.preventDefault(),d(!0)},[]),Te=l.useCallback(()=>{d(!1)},[]),pe=l.useCallback(ae=>{_({type:"clip",id:ae})},[_]),fe=l.useCallback(async ae=>{await L(ae)},[L]),We=l.useCallback(async ae=>{const W=document.createElement("input");W.type="file",W.accept="video/*,audio/*,image/*",W.onchange=async Q=>{const be=Q.target.files?.[0];if(be){p(!0),x("Replacing asset...");try{await B(ae,be)}catch(Oe){console.error("Asset replacement failed:",Oe)}finally{p(!1),x("")}}},W.click()},[B]),Ze=l.useCallback(async()=>{if(!("showDirectoryPicker"in window)){Fe.error("Folder picker not supported","Please relink assets individually using the refresh button on each missing asset.");return}let ae;try{ae=await window.showDirectoryPicker()}catch{return}const{project:W}=F.getState(),Q=W.mediaLibrary.items.filter(Le=>Le.isPlaceholder);if(Q.length===0)return;try{await Im(W.id,ae)}catch{}const be=new Map,Oe=ae.entries();for await(const[,Le]of Oe)if(Le.kind==="file"){const Ye=Le,Ke=await Ye.getFile();be.set(`${Ke.name.toLowerCase()}:${Ke.size}`,{file:Ke,handle:Ye})}p(!0);let Ue=0;for(const Le of Q){const Ye=Le.sourceFile?`${Le.sourceFile.name.toLowerCase()}:${Le.sourceFile.size}`:null,Ke=Ye?be.get(Ye):null;if(Ke){x(`Relinking ${Le.name}…`);try{try{await Ul(Ke.file.name,Ke.file.size,Ke.handle)}catch{}await B(Le.id,Ke.file,ae.name),Ue++}catch(mt){console.error(`[AssetsPanel] Failed to relink ${Le.name}:`,mt)}}}p(!1),x(""),Ue>0?Fe.success(`Relinked ${Ue} of ${Q.length} asset${Q.length!==1?"s":""}`):Fe.error("No matches found","None of the files in the selected folder matched the missing assets by filename.")},[B]),at=l.useCallback((ae,W)=>{ae.dataTransfer.setData("application/json",JSON.stringify({mediaId:W.id})),ae.dataTransfer.effectAllowed="copy",R("media",{mediaId:W.id,mediaType:W.type})},[R]),de=l.useCallback(async ae=>{const{addClipToNewTrack:W}=F.getState();await W(ae.id)},[]),Ce=l.useCallback(async()=>{if(!g)return;await O({width:g.videoWidth,height:g.videoHeight});const ae=g.itemToAdd;A(!1),k(null),await de(ae)},[g,O,de]),Ne=l.useCallback(async()=>{if(!g)return;const ae=g.itemToAdd;A(!1),k(null),await de(ae)},[g,de]),Me=l.useCallback(async ae=>{const{project:W}=F.getState();if(!W.timeline.tracks.some(Oe=>Oe.clips.length>0)&&ae.type==="video"&&ae.metadata?.width&&ae.metadata?.height){const Oe=ae.metadata.width,Ue=ae.metadata.height,Le=W.settings.width,Ye=W.settings.height;if(Oe!==Le||Ue!==Ye){k({videoWidth:Oe,videoHeight:Ue,itemToAdd:ae}),A(!0);return}}await de(ae)},[de]),qe=l.useCallback(()=>{t.current?.click()},[]),nt=l.useCallback(async ae=>{y(ae.id);try{const{width:W,height:Q}=M.settings,be=await w0(ae,W,Q),Oe=new File([be],`${ae.name}_${W}x${Q}.png`,{type:"image/png"}),Ue=await z(Oe);if(Ue.success&&Ue.actionId){const{addClipToNewTrack:Le}=F.getState();await Le(Ue.actionId)}}catch(W){console.error("Failed to generate background:",W)}finally{y(null)}},[z,M.settings]),rt=j0.filter(ae=>w==="all"||ae.category===w),Pe=l.useCallback(async ae=>{try{const W=await Bm(ae.id);if(!W){Fe.error("Asset not found","Cannot load the image data for this asset.");return}const Q=W.type||(ae.name.match(/\.png$/i)?"image/png":"image/jpeg"),be=new File([W],ae.name,{type:Q});C({file:be,previewUrl:ae.thumbnailUrl})}catch(W){console.error("[KieAI] Failed to load media blob:",W),Fe.error("Failed to open KieAI",W instanceof Error?W.message:"Unknown error")}},[]),Ie=l.useCallback(ae=>{ae.kieaiTaskId&&(G(ae.id,!0,!1),P(ae.kieaiTaskId))},[P,G]),Ee=ae=>{switch(ae){case"media":return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70",children:[e.jsxs("div",{className:"px-4 pt-3 pb-3 flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(la,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-muted z-10"}),e.jsx(ts,{type:"text",value:s,onChange:W=>a(W.target.value),placeholder:"Search media",className:"pl-9 text-xs bg-background-tertiary border-border text-text-primary h-9"})]}),e.jsx("div",{className:"flex items-center bg-background-tertiary border border-border rounded-lg p-0.5",children:[{mode:"large",icon:Cd,title:"Large icons"},{mode:"small",icon:Fx,title:"Small icons"},{mode:"list",icon:ih,title:"List view"}].map(({mode:W,icon:Q,title:be})=>e.jsx("button",{onClick:()=>b(W),title:be,className:`p-1.5 rounded transition-colors ${N===W?"bg-background-elevated text-text-primary":"text-text-muted hover:text-text-secondary"}`,children:e.jsx(Q,{size:13})},W))})]}),U>0&&e.jsxs("div",{className:"px-4 pb-3 space-y-2",children:[e.jsxs("button",{onClick:()=>f(!h),className:`w-full px-3 py-2 rounded-lg border text-xs font-medium transition-all flex items-center justify-between ${h?"bg-yellow-500/10 border-yellow-500 text-yellow-500":"bg-background-tertiary border-border text-text-secondary hover:border-yellow-500/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{size:14}),e.jsx("span",{children:"Show Only Missing Assets"})]}),e.jsx("div",{className:"px-2 py-0.5 rounded-full bg-yellow-500 text-black text-[10px] font-bold",children:U})]}),e.jsxs("button",{onClick:Ze,className:"w-full px-3 py-2 rounded-lg border border-yellow-500/40 bg-yellow-500/5 text-yellow-500 text-xs font-medium transition-all hover:bg-yellow-500/15 flex items-center gap-2",children:[e.jsx(na,{size:14}),e.jsx("span",{children:"Relink from Folder…"})]})]}),e.jsx(ia,{className:`min-h-0 flex-1 ${c?"bg-primary/5":""}`,onDrop:K,onDragOver:ue,onDragLeave:Te,children:e.jsxs("div",{className:"px-4 pb-4 relative",children:[D.length===0?e.jsx(yb,{onImport:qe}):e.jsxs("div",{className:N==="list"?"flex flex-col gap-1.5":N==="small"?"grid grid-cols-3 gap-2":"grid grid-cols-2 gap-3",children:[D.map(W=>e.jsx(bb,{item:W,isSelected:se(W.id),viewMode:N,onSelect:()=>pe(W.id),onDelete:()=>fe(W.id),onReplace:()=>We(W.id),onDragStart:Q=>at(Q,W),onAddToTimeline:()=>Me(W),onKieAI:W.type==="image"&&!W.isPending&&!W.kieaiError?()=>Pe(W):void 0,onRetryKieAI:W.kieaiError&&W.kieaiTaskId?()=>Ie(W):void 0},W.id)),N==="list"?e.jsxs("button",{onClick:qe,className:"flex items-center gap-3 px-2 py-1.5 rounded-lg border-2 border-dashed border-border hover:border-text-secondary cursor-pointer transition-all group",children:[e.jsx("div",{className:"w-12 h-8 rounded bg-background-tertiary flex items-center justify-center flex-shrink-0",children:e.jsx(ya,{size:14,className:"text-text-muted group-hover:text-text-secondary transition-colors"})}),e.jsx("span",{className:"text-[11px] text-text-muted group-hover:text-text-secondary transition-colors font-medium",children:"Add media"})]}):e.jsx("div",{className:"flex flex-col",children:e.jsx("button",{onClick:qe,className:"aspect-video bg-background-tertiary rounded-lg border-2 border-dashed border-border hover:border-text-secondary relative flex items-center justify-center cursor-pointer transition-all overflow-hidden shadow-sm group",children:e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsx(ya,{size:N==="small"?16:20,className:"text-text-muted group-hover:text-text-secondary transition-colors"}),e.jsx("span",{className:"text-[10px] text-text-muted group-hover:text-text-secondary transition-colors",children:"Add media"})]})})})]}),c&&e.jsx("div",{className:"absolute inset-4 border-2 border-dashed border-primary rounded-xl flex items-center justify-center bg-primary/5 pointer-events-none z-50 backdrop-blur-sm",children:e.jsx("div",{className:"text-primary text-sm font-bold bg-background-secondary px-4 py-2 rounded-full shadow-lg",children:"Drop files to import"})})]})})]});case"graphics":return e.jsx("div",{className:"min-h-0 flex-1 border-t border-border/70",children:e.jsx(ia,{className:"min-h-0 flex-1",children:e.jsxs("div",{className:"px-4 py-4",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("h4",{className:"text-xs font-medium text-text-secondary flex items-center gap-1.5",children:[e.jsx(za,{size:12}),"Backgrounds"]})}),e.jsx("div",{className:"flex gap-1.5 mb-3 flex-wrap",children:["all","solid","gradient","mesh","pattern"].map(W=>e.jsx("button",{onClick:()=>S(W),className:`px-2.5 py-1 text-[10px] rounded-md transition-all ${w===W?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-secondary"}`,children:W.charAt(0).toUpperCase()+W.slice(1)},W))}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:rt.map(W=>e.jsxs("button",{onClick:()=>nt(W),disabled:j!==null,className:"aspect-square rounded-lg border border-border hover:border-primary/50 transition-all overflow-hidden relative group disabled:opacity-50",title:W.name,style:{background:W.thumbnail},children:[j===W.id&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-all flex items-center justify-center opacity-0 group-hover:opacity-100",children:e.jsx(cs,{size:16,className:"text-white"})}),e.jsx("span",{className:"absolute bottom-0 left-0 right-0 text-[8px] text-white bg-black/60 py-0.5 px-1 truncate opacity-0 group-hover:opacity-100 transition-opacity",children:W.name})]},W.id))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h4",{className:"text-xs font-medium text-text-secondary mb-3",children:"Shapes"}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[{type:"rectangle",icon:Gs,label:"Rectangle"},{type:"circle",icon:or,label:"Circle"},{type:"triangle",icon:iu,label:"Triangle"},{type:"star",icon:Ys,label:"Star"},{type:"arrow",icon:Pr,label:"Arrow"},{type:"polygon",icon:Qd,label:"Polygon"}].map(W=>e.jsxs("button",{onClick:async()=>{const Q=F.getState(),{createShapeClip:be,addTrack:Oe}=Q,Ue=Q.project.timeline.tracks;await Oe("graphics",0);const Ye=F.getState().project.timeline.tracks.find(Ke=>Ke.type==="graphics"&&!Ue.some(mt=>mt.id===Ke.id));Ye&&be(Ye.id,0,W.type)},className:"aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group",title:W.label,children:[e.jsx(W.icon,{size:20,className:"text-text-secondary group-hover:text-primary transition-colors"}),e.jsx("span",{className:"text-[9px] text-text-muted group-hover:text-text-secondary",children:W.label})]},W.type))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h4",{className:"text-xs font-medium text-text-secondary mb-3",children:"3D Objects"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{type:"mesh-cube",label:"Cube",icon:"□"},{type:"mesh-sphere",label:"Sphere",icon:"○"},{type:"mesh-torus",label:"Torus",icon:"◯"},{type:"mesh-cone",label:"Cone",icon:"△"},{type:"mesh-cylinder",label:"Cylinder",icon:"▯"},{type:"mesh-icosahedron",label:"Icosahedron",icon:"◆"}].map(W=>e.jsxs("button",{onClick:async()=>{const Q=F.getState(),{createShapeClip:be,addTrack:Oe,updateClipRotate3D:Ue}=Q,Le=Q.project.timeline.tracks;await Oe("graphics",0);const Ke=F.getState().project.timeline.tracks.find(mt=>mt.type==="graphics"&&!Le.some(Ge=>Ge.id===mt.id));if(Ke){const mt=be(Ke.id,0,W.type);mt&&Ue(mt.id,{x:-18,y:28,z:0})}},className:"aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group",title:W.label,children:[e.jsx("span",{className:"text-2xl text-text-secondary group-hover:text-primary transition-colors leading-none",children:W.icon}),e.jsx("span",{className:"text-[9px] text-text-muted group-hover:text-text-secondary",children:W.label})]},W.type))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h4",{className:"text-xs font-medium text-text-secondary mb-3",children:"SVG Import"}),e.jsxs("button",{onClick:()=>{const W=document.createElement("input");W.type="file",W.accept=".svg",W.onchange=async Q=>{const be=Q.target.files?.[0];if(be){const Oe=await be.text(),Ue=F.getState(),{importSVG:Le,addTrack:Ye}=Ue,Ke=Ue.project.timeline.tracks;await Ye("graphics",0);const Ge=F.getState().project.timeline.tracks.find(gt=>gt.type==="graphics"&&!Ke.some(Ft=>Ft.id===gt.id));Ge&&Le(Oe,Ge.id,0)}},W.click()},className:"w-full py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center gap-2 group",children:[e.jsx(Ki,{size:16,className:"text-text-secondary group-hover:text-primary transition-colors"}),e.jsx("span",{className:"text-xs text-text-secondary group-hover:text-text-primary",children:"Import SVG File"})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h4",{className:"text-xs font-medium text-text-secondary mb-3",children:"Stickers & Emojis"}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:["😀","🎉","❤️","⭐","🔥","👍","🎬","🎵"].map((W,Q)=>e.jsx("button",{onClick:async()=>{const be=F.getState(),{createStickerClip:Oe,addTrack:Ue}=be,{stickerLibrary:Le}=await zi(async()=>{const{stickerLibrary:Ge}=await import("./index-C7tVZKMU.js");return{stickerLibrary:Ge}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])),Ye=be.project.timeline.tracks;await Ue("graphics",0);const mt=F.getState().project.timeline.tracks.find(Ge=>Ge.type==="graphics"&&!Ye.some(gt=>gt.id===Ge.id));if(mt){const Ge={id:`emoji-${Q}`,emoji:W,name:W,category:"emojis"},gt=Le.createEmojiClip(Ge,mt.id,0,5);Oe(gt)}},className:"aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex items-center justify-center text-xl cursor-pointer",children:W},Q))})]})]})})});case"text":return e.jsx("div",{className:"min-h-0 flex-1 border-t border-border/70",children:e.jsx(ia,{className:"min-h-0 flex-1",children:e.jsxs("div",{className:"px-4 py-4 space-y-3",children:[e.jsxs("button",{onClick:async()=>{const W=F.getState(),{createTextClip:Q,addTrack:be}=W,Oe=W.project.timeline.tracks;await be("text",0);const Le=F.getState().project.timeline.tracks.find(Ye=>Ye.type==="text"&&!Oe.some(Ke=>Ke.id===Ye.id));Le&&Q(Le.id,0,"New Title")},className:"w-full py-4 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-center",children:[e.jsx("span",{className:"text-lg font-bold text-text-primary",children:"Add Title"}),e.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Click to add text to timeline"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{name:"Heading",text:"Heading",style:{fontSize:72,fontWeight:700,textAlign:"center",verticalAlign:"middle"}},{name:"Subtitle",text:"Subtitle text",style:{fontSize:36,fontWeight:400,textAlign:"center",verticalAlign:"middle"}},{name:"Lower Third",text:"Name Here",style:{fontSize:32,fontWeight:600,textAlign:"left",verticalAlign:"bottom",backgroundColor:"rgba(0, 0, 0, 0.7)"}},{name:"Caption",text:"Caption text here",style:{fontSize:24,fontWeight:400,textAlign:"center",verticalAlign:"bottom",shadowColor:"rgba(0, 0, 0, 0.8)",shadowBlur:4,shadowOffsetX:1,shadowOffsetY:1}}].map(W=>e.jsx("button",{onClick:async()=>{const Q=F.getState(),{createTextClip:be,addTrack:Oe}=Q,Ue=Q.project.timeline.tracks;await Oe("text",0);const Ye=F.getState().project.timeline.tracks.find(Ke=>Ke.type==="text"&&!Ue.some(mt=>mt.id===Ke.id));Ye&&be(Ye.id,0,W.text,5,W.style)},className:"py-3 bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-xs text-text-secondary hover:text-text-primary",children:W.name},W.name))})]})})});case"effects":return e.jsx("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70 bg-bg-1",children:e.jsx(sb,{})});case"transitions":return e.jsx("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70 bg-bg-1",children:e.jsx(ab,{})});case"ai":return e.jsx("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70 bg-background-secondary content-area-fix",children:e.jsx(W0,{})});case"recipes":return e.jsx("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70 bg-background-secondary content-area-fix",children:e.jsx(Q0,{})});case"templates":return e.jsx("div",{className:"flex min-h-0 flex-1 flex-col border-t border-border/70 bg-background-secondary content-area-fix",children:e.jsx(J0,{})});default:return null}};return e.jsxs("div",{"data-tour":"assets",className:"w-full min-w-0 bg-bg-1 flex flex-col h-full relative",children:[e.jsx("div",{className:"flex items-stretch gap-0.5 px-2 pt-2 pb-1 border-b border-border bg-bg-1 overflow-x-auto scrollbar-none shrink-0",children:Uc.map(ae=>{const W=gb[ae.value],Q=r===ae.value;return e.jsxs("button",{onClick:()=>o(ae.value),title:ae.description,className:`group flex flex-col items-center justify-center gap-1 px-2 py-1.5 rounded-md min-w-[50px] shrink-0 text-[10.5px] font-medium tracking-tight transition-colors ${Q?"text-accent":"text-fg-3 hover:text-fg hover:bg-hover"}`,children:[e.jsx("span",{className:`w-7 h-7 grid place-items-center rounded-md transition-colors ${Q?"bg-accent-soft text-accent":"text-fg-2 group-hover:text-fg"}`,children:e.jsx(W,{size:17,strokeWidth:1.6})}),e.jsx("span",{className:Q?"text-accent":"",children:ae.label})]},ae.value)})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0 h-full bg-bg-1 relative",children:[u&&e.jsx(vb,{message:m||"Importing media..."}),e.jsxs("div",{className:"px-3 py-2 flex items-center justify-between border-b border-border shrink-0",children:[e.jsx("p",{className:"text-[11px] text-fg-muted line-clamp-1",children:Uc.find(ae=>ae.value===r)?.description}),r==="media"&&e.jsxs("button",{onClick:qe,title:"Import media",className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-accent text-accent-fg font-semibold text-[11.5px] hover:bg-accent-strong transition-colors",children:[e.jsx(cs,{size:12}),e.jsx("span",{children:"Import"})]})]}),e.jsx("input",{ref:t,type:"file",multiple:!0,accept:"video/*,audio/*,image/*",onChange:ae=>X(ae.target.files),className:"hidden"}),e.jsx("div",{className:"flex-1 min-h-0 relative flex flex-col overflow-hidden",children:Ee(r)})]}),g&&e.jsx(k0,{isOpen:v,videoWidth:g.videoWidth,videoHeight:g.videoHeight,currentWidth:M.settings.width,currentHeight:M.settings.height,onConfirm:Ce,onCancel:Ne}),T&&e.jsx(fb,{open:!0,onClose:()=>C(null),sourceFile:T.file,previewUrl:T.previewUrl})]})},qa={MIN:10,DEFAULT:50,MAX:500},Et=un()(Ld((t,s)=>({playheadPosition:0,playbackState:"stopped",playbackLockedReason:null,playbackRate:1,pixelsPerSecond:qa.DEFAULT,scrollX:0,scrollY:0,viewportWidth:800,viewportHeight:400,trackHeight:80,trackHeights:{},loopEnabled:!1,loopStart:0,loopEnd:0,isScrubbing:!1,scrubPosition:null,expandedTracks:new Set,expandedClipKeyframes:new Set,keyframeEditMode:!1,play:()=>{s().playbackLockedReason||t({playbackState:"playing"})},pause:()=>{t({playbackState:"paused"})},stop:()=>{t({playbackState:"stopped"})},togglePlayback:()=>{const{playbackLockedReason:a,playbackState:r}=s();a||t(r==="playing"?{playbackState:"paused"}:{playbackState:"playing"})},lockPlayback:a=>{t({playbackLockedReason:a??"Applying effect"})},unlockPlayback:()=>{t({playbackLockedReason:null})},setPlaybackRate:a=>{t({playbackRate:Math.max(.1,Math.min(4,a))})},setPlayheadPosition:a=>{t({playheadPosition:Math.max(0,a)})},seekTo:a=>{const r=Math.max(0,a);t({playheadPosition:r})},seekRelative:a=>{const{playheadPosition:r}=s(),n=Math.max(0,r+a);t({playheadPosition:n})},seekToStart:()=>{t({playheadPosition:0})},seekToEnd:a=>{t({playheadPosition:a})},startScrubbing:a=>{t({isScrubbing:!0,scrubPosition:a,playheadPosition:a})},updateScrubPosition:a=>{const{isScrubbing:r}=s();if(r){const n=Math.max(0,a);t({scrubPosition:n,playheadPosition:n})}},endScrubbing:()=>{const{scrubPosition:a}=s();t({isScrubbing:!1,scrubPosition:null,playheadPosition:a??s().playheadPosition})},zoomIn:()=>{const{pixelsPerSecond:a}=s(),r=Math.min(a*1.5,qa.MAX);t({pixelsPerSecond:r})},zoomOut:()=>{const{pixelsPerSecond:a}=s(),r=Math.max(a/1.5,qa.MIN);t({pixelsPerSecond:r})},setZoom:a=>{const r=Math.max(qa.MIN,Math.min(qa.MAX,a));t({pixelsPerSecond:r})},zoomToFit:a=>{const{viewportWidth:r}=s();if(a>0){const n=Math.max(qa.MIN,Math.min(qa.MAX,(r-100)/a));t({pixelsPerSecond:n,scrollX:0})}},resetZoom:()=>{t({pixelsPerSecond:qa.DEFAULT,scrollX:0})},setScrollX:a=>{t({scrollX:Math.max(0,a)})},setScrollY:a=>{t({scrollY:Math.max(0,a)})},scrollToPlayhead:()=>{const{playheadPosition:a,pixelsPerSecond:r,viewportWidth:n,scrollX:i}=s(),o=a*r;if(oi+n){const c=Math.max(0,o-n/2);t({scrollX:c})}},setViewportDimensions:(a,r)=>{t({viewportWidth:a,viewportHeight:r})},setTrackHeight:a=>{t({trackHeight:Math.max(40,Math.min(200,a))})},setTrackHeightById:(a,r)=>{const n=Math.max(40,Math.min(200,r));t(i=>({trackHeights:{...i.trackHeights,[a]:n}}))},getTrackHeight:a=>{const{trackHeights:r,trackHeight:n}=s();return r[a]??n},setLoopEnabled:a=>{t({loopEnabled:a})},setLoopRange:(a,r)=>{a{const{pixelsPerSecond:r}=s();return a*r},pixelsToTime:a=>{const{pixelsPerSecond:r}=s();return a/r},getVisibleTimeRange:()=>{const{scrollX:a,viewportWidth:r,pixelsPerSecond:n}=s();return{start:a/n,end:(a+r)/n}},isTimeVisible:a=>{const{start:r,end:n}=s().getVisibleTimeRange();return a>=r&&a<=n},toggleTrackExpanded:a=>{t(r=>{const n=new Set(r.expandedTracks);return n.has(a)?n.delete(a):n.add(a),{expandedTracks:n}})},setTrackExpanded:(a,r)=>{t(n=>{const i=new Set(n.expandedTracks);return r?i.add(a):i.delete(a),{expandedTracks:i}})},isTrackExpanded:a=>s().expandedTracks.has(a),toggleClipKeyframesExpanded:a=>{t(r=>{const n=new Set(r.expandedClipKeyframes);return n.has(a)?n.delete(a):n.add(a),{expandedClipKeyframes:n}})},setClipKeyframesExpanded:(a,r)=>{t(n=>{const i=new Set(n.expandedClipKeyframes);return r?i.add(a):i.delete(a),{expandedClipKeyframes:i}})},isClipKeyframesExpanded:a=>s().expandedClipKeyframes.has(a),setKeyframeEditMode:a=>{t({keyframeEditMode:a})}}))),wb={maxFrames:100,maxSizeBytes:500*1024*1024,preloadAhead:30,preloadBehind:10};class tn{videoEngine=null;videoEffectsEngine=null;transitionEngine=null;canvas=null;ctx=null;initialized=!1;renderStats={lastRenderTime:0,avgRenderTime:0,framesRendered:0,renderErrors:0};renderTimes=[];maxRenderTimeSamples=60;pendingRender=null;lastRenderedTime=-1;DEBOUNCE_THRESHOLD=.001;frameCache=new Map;cacheConfig;cacheStats={hits:0,misses:0};totalCacheSizeBytes=0;isPreloading=!1;preloadAbortController=null;constructor(s={}){this.cacheConfig={...wb,...s}}async initialize(){if(this.initialized)return;const s=Ct.getState();if(!s.initialized)throw new Error("EngineStore must be initialized before RenderBridge");if(this.videoEngine=s.videoEngine,!this.videoEngine)throw new Error("VideoEngine not available in EngineStore");const a=F.getState().project,{width:r,height:n}=a.settings;this.videoEffectsEngine=Fm(r,n),this.transitionEngine=Lm(r,n),this.initialized=!0}setCanvas(s){this.canvas=s,s?this.ctx=s.getContext("2d"):this.ctx=null}getCanvas(){return this.canvas}async renderFrame(s){if(!this.initialized||!this.videoEngine)return null;const a=performance.now();try{const r=F.getState().project,n=await this.videoEngine.renderFrame(r,s);this.canvas&&this.ctx&&n&&this.drawFrameToCanvas(n);const i=performance.now()-a;return this.updateRenderStats(i),Ct.setState({currentFrame:n}),this.lastRenderedTime=s,n}catch(r){return this.renderStats.renderErrors++,console.error("RenderBridge: Frame render error:",r),null}}renderFrameDebounced(s){this.pendingRender!==null&&cancelAnimationFrame(this.pendingRender),!(Math.abs(s-this.lastRenderedTime){this.pendingRender=null,this.renderFrame(s).catch(a=>{console.error("[RenderBridge] Frame render failed:",a)})}))}async renderCurrentFrame(){const s=Et.getState().playheadPosition;return this.renderFrame(s)}async applyEffects(s,a){if(!this.videoEffectsEngine)return s;const r=this.filterEnabledEffects(a);return r.length===0?s:(await this.videoEffectsEngine.applyEffects(s,r)).image}filterEnabledEffects(s){return s.filter(a=>a.enabled)}getEffectApplicationOrder(s){return this.filterEnabledEffects(s).map(a=>a.id)}async applyClipEffects(s,a){const r=F.getState().project;for(const n of r.timeline.tracks){const i=n.clips.find(o=>o.id===a);if(i&&i.effects&&i.effects.length>0)return this.applyEffects(s,i.effects)}return s}hasEffectsEngine(){return this.videoEffectsEngine!==null}getVideoEffectsEngine(){return this.videoEffectsEngine}findTransitionAtTime(s,a){if(!this.transitionEngine)return null;for(const r of s.transitions){const n=s.clips.find(o=>o.id===r.clipAId),i=s.clips.find(o=>o.id===r.clipBId);if(!(!n||!i)&&this.transitionEngine.isTimeInTransition(r,n,a)){const o=this.transitionEngine.calculateTransitionProgress(r,n,a);return{transition:r,clipA:n,clipB:i,progress:o}}}return null}async renderTransition(s,a,r,n){if(!this.transitionEngine)return null;try{return(await this.transitionEngine.renderTransition(s,a,r,n)).frame}catch(i){return console.error("RenderBridge: Transition render error:",i),null}}isTimeInTransition(s,a){return this.findTransitionAtTime(s,a)!==null}getTransitionEngine(){return this.transitionEngine}hasTransitionEngine(){return this.transitionEngine!==null}getClipLocalTime(s,a){const r=a-s.startTime;return s.inPoint+r}drawFrameToCanvas(s){if(!this.canvas||!this.ctx)return;const{width:a,height:r}=this.canvas;this.ctx.clearRect(0,0,a,r);const n=s.width/s.height,i=a/r;let o,c,d,u;n>i?(o=a,c=a/n,d=0,u=(r-c)/2):(c=r,o=r*n,d=(a-o)/2,u=0),this.ctx.drawImage(s.image,d,u,o,c)}updateRenderStats(s){this.renderStats.lastRenderTime=s,this.renderStats.framesRendered++,this.renderTimes.push(s),this.renderTimes.length>this.maxRenderTimeSamples&&this.renderTimes.shift();const a=this.renderTimes.reduce((r,n)=>r+n,0);this.renderStats.avgRenderTime=a/this.renderTimes.length}getRenderStats(){return{...this.renderStats}}clearCanvas(){this.canvas&&this.ctx&&this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}resizeCanvas(){if(!this.canvas)return;const s=F.getState().project,{width:a,height:r}=s.settings;(this.canvas.width!==a||this.canvas.height!==r)&&(this.canvas.width=a,this.canvas.height=r)}isInitialized(){return this.initialized}static getCacheKey(s,a=30){return`frame:${(Math.round(s*a)/a).toFixed(4)}`}getCachedFrame(s){const a=this.frameCache.get(s);return a?(a.lastAccessed=Date.now(),this.cacheStats.hits++,a.frame):(this.cacheStats.misses++,null)}hasFrame(s){return this.frameCache.has(s)}cacheFrame(s,a){const r=a.width*a.height*4;if(this.evictIfNeeded(r),r>this.cacheConfig.maxSizeBytes){console.warn("RenderBridge: Frame too large to cache:",r,"bytes");return}if(this.frameCache.has(s)){const n=this.frameCache.get(s);this.totalCacheSizeBytes-=n.sizeBytes}this.frameCache.set(s,{frame:a,key:s,sizeBytes:r,lastAccessed:Date.now()}),this.totalCacheSizeBytes+=r}removeFrame(s){const a=this.frameCache.get(s);return a?(a.frame.image&&typeof a.frame.image.close=="function"&&a.frame.image.close(),this.totalCacheSizeBytes-=a.sizeBytes,this.frameCache.delete(s)):!1}evictIfNeeded(s){for(;this.frameCache.size>=this.cacheConfig.maxFrames;)this.evictOldest();for(;this.totalCacheSizeBytes+s>this.cacheConfig.maxSizeBytes&&this.frameCache.size>0;)this.evictOldest()}evictOldest(){let s="",a=1/0;for(const[r,n]of this.frameCache.entries())n.lastAccessed=o;p-=i){const m=tn.getCacheKey(p,r);this.frameCache.has(m)||u.push(p)}for(const p of u){if(n.aborted)break;try{const m=await this.videoEngine.renderFrame(d,p);if(m&&!n.aborted){const x=tn.getCacheKey(p,r);this.cacheFrame(x,m)}}catch(m){console.warn("RenderBridge: Preload frame error:",m)}}}finally{this.isPreloading=!1}}getPreloadRange(s,a,r=30){const n=1/r,i=Math.max(0,s-this.cacheConfig.preloadBehind*n),o=Math.min(a,s+this.cacheConfig.preloadAhead*n),c=[];for(let d=i;d<=o;d+=n){const u=tn.getCacheKey(d,r);this.frameCache.has(u)||c.push(d)}return{startTime:i,endTime:o,missingFrames:c}}cancelPreload(){this.preloadAbortController&&(this.preloadAbortController.abort(),this.preloadAbortController=null),this.isPreloading=!1}isPreloadingFrames(){return this.isPreloading}clearCache(){for(const s of this.frameCache.values())s.frame.image&&typeof s.frame.image.close=="function"&&s.frame.image.close();this.frameCache.clear(),this.totalCacheSizeBytes=0,this.cacheStats={hits:0,misses:0}}getCacheStats(){const s=this.cacheStats.hits+this.cacheStats.misses;return{entries:this.frameCache.size,sizeBytes:this.totalCacheSizeBytes,hitRate:s>0?this.cacheStats.hits/s:0,maxSizeBytes:this.cacheConfig.maxSizeBytes,hits:this.cacheStats.hits,misses:this.cacheStats.misses}}getCacheConfig(){return{...this.cacheConfig}}updateCacheConfig(s){this.cacheConfig={...this.cacheConfig,...s},this.evictIfNeeded(0)}async applyColorAdjustments(s,a){if(!this.videoEffectsEngine)return s;const r=[];return a.brightness!==void 0&&a.brightness!==0&&r.push({id:"color-brightness",type:"brightness",params:{value:a.brightness},enabled:!0}),a.contrast!==void 0&&a.contrast!==1&&r.push({id:"color-contrast",type:"contrast",params:{value:a.contrast},enabled:!0}),a.saturation!==void 0&&a.saturation!==1&&r.push({id:"color-saturation",type:"saturation",params:{value:a.saturation},enabled:!0}),a.temperature!==void 0&&a.temperature!==0&&r.push({id:"color-temperature",type:"temperature",params:{value:a.temperature},enabled:!0}),a.tint!==void 0&&a.tint!==0&&r.push({id:"color-tint",type:"tint",params:{value:a.tint},enabled:!0}),(a.shadows!==void 0&&a.shadows!==0||a.midtones!==void 0&&a.midtones!==0||a.highlights!==void 0&&a.highlights!==0)&&r.push({id:"color-tonal",type:"tonal",params:{shadows:a.shadows??0,midtones:a.midtones??0,highlights:a.highlights??0},enabled:!0}),r.length===0?s:(await this.videoEffectsEngine.applyEffects(s,r)).image}hasColorAdjustments(s){return s.brightness!==void 0&&s.brightness!==0||s.contrast!==void 0&&s.contrast!==1||s.saturation!==void 0&&s.saturation!==1||s.temperature!==void 0&&s.temperature!==0||s.tint!==void 0&&s.tint!==0||s.shadows!==void 0&&s.shadows!==0||s.midtones!==void 0&&s.midtones!==0||s.highlights!==void 0&&s.highlights!==0}getDefaultColorAdjustments(){return{brightness:0,contrast:1,saturation:1,temperature:0,tint:0,shadows:0,midtones:0,highlights:0}}dispose(){this.pendingRender!==null&&(cancelAnimationFrame(this.pendingRender),this.pendingRender=null),this.cancelPreload(),this.clearCache(),this.clearCanvas(),this.transitionEngine&&(this.transitionEngine.dispose(),this.transitionEngine=null),this.canvas=null,this.ctx=null,this.videoEngine=null,this.videoEffectsEngine=null,this.initialized=!1,this.lastRenderedTime=-1,this.renderTimes=[],this.renderStats={lastRenderTime:0,avgRenderTime:0,framesRendered:0,renderErrors:0}}}let nn=null;function el(){return nn||(nn=new tn),nn}async function kb(){const t=el();return await t.initialize(),t}function Nb(){nn&&(nn.dispose(),nn=null)}const Ks={position:{x:0,y:0},scale:{x:1,y:1},rotation:0,opacity:1,anchor:{x:.5,y:.5},borderRadius:0,fitMode:"contain"},hi=t=>{const s=Math.floor(t/60),a=Math.floor(t%60),r=Math.floor(t%1*100);return`${s.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`},Kc=new Map,fi=new Map,Cb="/fonts/helvetiker_regular.typeface.json",Sb="/fonts/helvetiker_bold.typeface.json";function Ab(t,s){let a=t.replace("#","");if(a.length===3&&(a=a.split("").map(p=>p+p).join("")),a.length!==6)return t;const r=parseInt(a.slice(0,2),16),n=parseInt(a.slice(2,4),16),i=parseInt(a.slice(4,6),16),o=Math.max(0,1-s),c=Math.round(r*o),d=Math.round(n*o),u=Math.round(i*o);return`#${c.toString(16).padStart(2,"0")}${d.toString(16).padStart(2,"0")}${u.toString(16).padStart(2,"0")}`}function Tb(t){const s=t.style.fontWeight;return s==="bold"||typeof s=="number"&&s>=600?Sb:Cb}function Mb(t,s){const a=Kc.get(t);if(a)return a;if(!fi.has(t)){const r=new Tp,n=new Promise((i,o)=>{r.load(t,c=>{Kc.set(t,c),fi.delete(t),s&&s(),i(c)},void 0,c=>{fi.delete(t),o(c)})});fi.set(t,n),n.catch(()=>{})}}const Eb={normal:ga,multiply:ac,screen:Si,overlay:ga,darken:ga,lighten:Si,"color-dodge":Si,"color-burn":ac,"hard-light":ga,"soft-light":ga,difference:sc,exclusion:sc,hue:ga,saturation:ga,color:ga,luminosity:ga};class vu{scene;camera;renderer;_canvas;constructor(s,a){this._canvas=document.createElement("canvas"),this._canvas.width=s,this._canvas.height=a,this.renderer=new $d({canvas:this._canvas,alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),this.renderer.setSize(s,a),this.renderer.setClearColor(0,0),this.scene=new Od;const r=s/a,n=a;this.camera=new _d(-n*r/2,n*r/2,n/2,-n/2,.1,2e3),this.camera.position.z=1e3;const i=new gp(16777215,.7);this.scene.add(i);const o=new bp(16777215,.6);o.position.set(.5,1,1).normalize().multiplyScalar(500),this.scene.add(o)}_onFontReady=null;setFontReadyCallback(s){this._onFontReady=s}resize(s,a){this._canvas.width=s,this._canvas.height=a,this.renderer.setSize(s,a);const r=s/a,n=a;this.camera.left=-n*r/2,this.camera.right=n*r/2,this.camera.top=n/2,this.camera.bottom=-n/2,this.camera.updateProjectionMatrix()}createTextTexture(s,a,r){const n=document.createElement("canvas");n.width=a,n.height=r;const i=n.getContext("2d");i.clearRect(0,0,a,r);const o=s.style,c=typeof o.fontWeight=="number"?o.fontWeight:o.fontWeight==="bold"?700:400;i.font=`${o.fontStyle} ${c} ${o.fontSize}px "${o.fontFamily}"`,i.fillStyle=o.color,i.textAlign=o.textAlign,i.textBaseline="middle",o.shadowColor&&o.shadowBlur&&(i.shadowColor=o.shadowColor,i.shadowBlur=o.shadowBlur,i.shadowOffsetX=o.shadowOffsetX||0,i.shadowOffsetY=o.shadowOffsetY||0),o.strokeColor&&o.strokeWidth&&(i.strokeStyle=o.strokeColor,i.lineWidth=o.strokeWidth);const d=s.text.split(` +`),u=o.fontSize*o.lineHeight;d.forEach((m,x)=>{const h=r/2+(x-(d.length-1)/2)*u;o.strokeColor&&o.strokeWidth&&i.strokeText(m,a/2,h),i.fillText(m,a/2,h)});const p=new tc(n);return p.needsUpdate=!0,p}applyTransform(s,a,r,n){const i=(a.position.x-.5)*r,o=-(a.position.y-.5)*n;s.position.set(i,o,0),s.scale.set(a.scale.x,a.scale.y,1),s.rotation.z=a.rotation*Math.PI/180,a.rotate3d&&(s.rotation.x=a.rotate3d.x*Math.PI/180,s.rotation.y=a.rotate3d.y*Math.PI/180,s.rotation.z+=a.rotate3d.z*Math.PI/180),a.perspective&&(this.camera.position.z=a.perspective,this.camera.updateProjectionMatrix())}applyBlendMode(s,a,r){s.blending=Eb[a]||ga,s.opacity=(r??100)/100,s.transparent=!0}renderTextClip(s,a,r){if(s.text3d?.enabled){const d=Tb(s),u=Mb(d,()=>{this._onFontReady&&this._onFontReady()});if(u){const p=this.buildText3DMesh(s,u,a,r);if(p)return p}}const n=this.createTextTexture(s,a,r),i=new kr({map:n,transparent:!0,opacity:s.transform.opacity,side:si});this.applyBlendMode(i,s.blendMode||"normal",s.blendOpacity??100);const o=new ai(a,r),c=new Ga(o,i);return this.applyTransform(c,s.transform,a,r),c}buildText3DMesh(s,a,r,n){try{const i=s.text3d,o=s.style.fontSize,c=Math.max(1,i.depth),d=i.bevelThickness>0||i.bevelSize>0,u=s.text.split(` +`),p=o*s.style.lineHeight,m=new yp;return u.forEach((x,h)=>{if(!x)return;const f=new vp(x,{font:a,size:o,depth:c,curveSegments:4,bevelEnabled:d,bevelThickness:i.bevelThickness,bevelSize:i.bevelSize,bevelSegments:Math.max(1,i.bevelSegments),bevelOffset:0});f.computeBoundingBox();const v=f.boundingBox,A=v?v.max.x-v.min.x:0;let g=0;s.style.textAlign==="center"?g=-A/2:s.style.textAlign==="right"&&(g=-A),f.translate(g,-h*p+(u.length-1)*p/2,-c/2);const k=i.frontColor??s.style.color,N=i.sideColor??Ab(k,.6);let b,j;i.material==="physical"?(b=new co({color:new Vr(k),metalness:i.metalness??.4,roughness:i.roughness??.45}),j=new co({color:new Vr(N),metalness:i.metalness??.4,roughness:i.roughness??.45})):(b=new kr({color:new Vr(k)}),j=new kr({color:new Vr(N)}));const y=new Ga(f,[b,j]);m.add(y)}),this.applyTransform(m,s.transform,r,n),m.traverse(x=>{if(x instanceof Ga){const h=Array.isArray(x.material)?x.material:[x.material];for(const f of h)f.transparent=!0,f.opacity=s.transform.opacity}}),m}catch(i){return console.error("[ThreeJSLayerRenderer] 3D text build failed:",i),null}}createCanvasTexture(s,a,r){const n=document.createElement("canvas");n.width=a,n.height=r;const i=n.getContext("2d");s(i);const o=new tc(n);return o.needsUpdate=!0,o}buildShape3DMesh(s,a,r){const{shapeType:n,style:i,transform:o}=s,c=Math.min(a,r)*.15;let d;switch(n){case"mesh-cube":d=new Sp(c,c,c);break;case"mesh-sphere":d=new Cp(c/2,32,32);break;case"mesh-torus":d=new Np(c/2,c/6,16,48);break;case"mesh-cone":d=new kp(c/2,c,32);break;case"mesh-cylinder":d=new wp(c/2,c/2,c,32);break;case"mesh-icosahedron":d=new jp(c/2,0);break;default:return null}const u=i.fill?.color??"#3b82f6",p=i.material3d,x=(p?.kind??"physical")==="physical"?new co({color:new Vr(u),metalness:p?.metalness??.3,roughness:p?.roughness??.5,transparent:!0,opacity:o.opacity}):new kr({color:new Vr(u),transparent:!0,opacity:o.opacity}),h=new Ga(d,x);return this.applyTransform(h,o,a,r),h}renderShapeClip(s,a,r){const{shapeType:n,style:i,transform:o}=s;if(n.startsWith("mesh-"))return this.buildShape3DMesh(s,a,r);const c=this.createCanvasTexture(m=>{const x=o.position.x*a,h=o.position.y*r;m.translate(x,h),m.scale(o.scale.x,o.scale.y),i.shadow?.blur&&i.shadow.blur>0&&(m.shadowColor=i.shadow.color||"#000000",m.shadowBlur=i.shadow.blur,m.shadowOffsetX=i.shadow.offsetX||0,m.shadowOffsetY=i.shadow.offsetY||0);const f=Math.min(a,r),v=f*.15,A=v/2,g=f/1080;switch(m.fillStyle=i.fill?.color||"#3b82f6",m.strokeStyle=i.stroke?.color||"#1d4ed8",m.lineWidth=(i.stroke?.width||2)*g,i.stroke?.dashArray&&i.stroke.dashArray.length>0&&m.setLineDash(i.stroke.dashArray),m.beginPath(),n){case"rectangle":{const k=i.cornerRadius||0;k>0?m.roundRect(-A,-A,v,v,Math.min(k,A)):m.rect(-A,-A,v,v);break}case"circle":case"ellipse":{m.ellipse(0,0,A,A,0,0,Math.PI*2);break}case"triangle":{m.moveTo(0,-A),m.lineTo(A,A),m.lineTo(-A,A),m.closePath();break}case"star":{const k=A,N=A*.4,b=5;for(let j=0;j0&&m.stroke()},a,r),d=new kr({map:c,transparent:!0,opacity:o.opacity,side:si});this.applyBlendMode(d,s.blendMode||"normal",s.blendOpacity??100);const u=new ai(a,r),p=new Ga(u,d);return this.applyTransform(p,o,a,r),p}renderSVGClip(s,a,r){const{svgContent:n,transform:i,viewBox:o}=s,c=this.createCanvasTexture(m=>{const x=new Image,h=new Blob([n],{type:"image/svg+xml"});if(x.src=URL.createObjectURL(h),x.complete&&x.naturalWidth>0){const f=i.position.x*a,v=i.position.y*r;m.translate(f,v),m.scale(i.scale.x,i.scale.y);const A=o?.width||200,g=o?.height||200;m.drawImage(x,-A/2,-g/2,A,g)}URL.revokeObjectURL(x.src)},a,r),d=new kr({map:c,transparent:!0,opacity:i.opacity,side:si});this.applyBlendMode(d,s.blendMode||"normal",s.blendOpacity??100);const u=new ai(a,r),p=new Ga(u,d);return this.applyTransform(p,i,a,r),p}renderStickerClip(s,a,r){const{imageUrl:n,transform:i}=s,o=this.createCanvasTexture(p=>{const m=new Image;if(m.src=n,m.complete&&m.naturalWidth>0){const x=i.position.x*a,h=i.position.y*r;p.translate(x,h),p.scale(i.scale.x,i.scale.y),p.drawImage(m,-m.naturalWidth/2,-m.naturalHeight/2,m.naturalWidth,m.naturalHeight)}},a,r),c=new kr({map:o,transparent:!0,opacity:i.opacity,side:si});this.applyBlendMode(c,s.blendMode||"normal",s.blendOpacity??100);const d=new ai(a,r),u=new Ga(d,c);return this.applyTransform(u,i,a,r),u}render(){return this.renderer.render(this.scene,this.camera),this._canvas}clear(){for(;this.scene.children.length>0;){const s=this.scene.children[0];this.scene.remove(s),s instanceof Ga&&(s.geometry.dispose(),s.material instanceof Ap&&s.material.dispose())}this.renderer.clear()}dispose(){this.clear(),this.renderer.dispose()}getScene(){return this.scene}get canvas(){return this._canvas}}let Yc=0,ls=null;const Yr=new $m,Xc={opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0},Mn=(t,s)=>{const{type:a,speed:r,intensity:n,loop:i,startTime:o,animationDuration:c}=t,d=o??0;if(s0){const x=d+c;if(s>x)return Xc}const u=s-d,p=i?u*r%1:Math.min(u*r,1),m=p*Math.PI*2;switch(a){case"pulse":return{opacity:1,scale:1+Math.sin(m)*.1*n,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"shake":{const x=Math.sin(m*5)*.02*n,h=Math.cos(m*5)*.02*n;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:x,offsetY:h,rotation:0}}case"bounce":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.abs(Math.sin(m))*-.05*n,rotation:0};case"float":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.sin(m)*.03*n,rotation:0};case"spin":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:p*360*n};case"flash":return{opacity:.5+Math.abs(Math.sin(m))*.5,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"heartbeat":{const x=p*4;let h=1;return x<1?h=1+.15*n*Math.sin(x*Math.PI):x<2&&(h=1+.1*n*Math.sin((x-1)*Math.PI)),{opacity:1,scale:h,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"swing":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(m)*15*n};case"wobble":{const x=Math.sin(m*3)*5*n;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:Math.sin(m)*.02*n,offsetY:0,rotation:x}}case"jello":{const x=1+Math.sin(m*2)*.1*n,h=1-Math.sin(m*2)*.1*n;return{opacity:1,scale:1,scaleX:x,scaleY:h,offsetX:0,offsetY:0,rotation:0}}case"rubber-band":{const x=1+Math.sin(m)*.2*n,h=1-Math.sin(m)*.1*n;return{opacity:1,scale:1,scaleX:x,scaleY:h,offsetX:0,offsetY:0,rotation:0}}case"tada":{const x=Math.sin(m*4)*10*n;return{opacity:1,scale:1+Math.sin(m*2)*.1*n,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:x}}case"vibrate":{const x=(Math.random()-.5)*.02*n,h=(Math.random()-.5)*.02*n;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:x,offsetY:h,rotation:0}}case"flicker":return{opacity:Math.random()>.1?1:.3,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"glow":{const x=1+Math.sin(m)*.05*n;return{opacity:.8+Math.sin(m)*.2,scale:x,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"breathe":return{opacity:1,scale:1+Math.sin(m*.5)*.08*n,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"wave":{const x=Math.sin(m+s*2)*.03*n,h=Math.sin(m)*5*n;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:x,rotation:h}}case"tilt":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(m*.5)*10*n};case"zoom-pulse":return{opacity:1,scale:1+Math.sin(m)*.15*n,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"focus-zoom":{const x=t.focusPoint||{x:.5,y:.5},h=t.zoomScale||1.5,f=t.holdDuration||.3,v=.3,A=1-f-v;let g=1,k=0,N=0;if(p{if(!s||s.length===0)return t;const r={...t},n=s.filter(p=>p.property==="position.x"),i=s.filter(p=>p.property==="position.y"),o=s.filter(p=>p.property==="scale.x"),c=s.filter(p=>p.property==="scale.y"),d=s.filter(p=>p.property==="rotation"),u=s.filter(p=>p.property==="opacity");if(n.length>0){const{value:p}=Yr.getValueAtTime(n,a);typeof p=="number"&&(r.position={...r.position,x:p})}if(i.length>0){const{value:p}=Yr.getValueAtTime(i,a);typeof p=="number"&&(r.position={...r.position,y:p})}if(o.length>0){const{value:p}=Yr.getValueAtTime(o,a);typeof p=="number"&&(r.scale={...r.scale,x:p})}if(c.length>0){const{value:p}=Yr.getValueAtTime(c,a);typeof p=="number"&&(r.scale={...r.scale,y:p})}if(d.length>0){const{value:p}=Yr.getValueAtTime(d,a);typeof p=="number"&&(r.rotation=p)}if(u.length>0){const{value:p}=Yr.getValueAtTime(u,a);typeof p=="number"&&(r.opacity=p)}return r},gi=new Map,Rb=async(t,s)=>{const a=`${s}px "${t}"`;if(!gi.has(a)){const r=document.fonts.load(a).then(()=>{});gi.set(a,r),setTimeout(()=>gi.delete(a),3e4)}try{await Promise.race([gi.get(a),new Promise(r=>setTimeout(r,100))])}catch{}},Ri=(t,s,a,r,n)=>{const i=n-s.startTime,o=Om.getAnimatedState(s,i);let{opacity:c,transform:d,style:u,visibleText:p,characterStates:m}=o;if(c<=0||p.length===0)return;if(s.emphasisAnimation&&s.emphasisAnimation.type!=="none"){const y=Mn(s.emphasisAnimation,i);c=c*y.opacity,d={...d,scale:{x:d.scale.x*y.scale*y.scaleX,y:d.scale.y*y.scale*y.scaleY},position:{x:d.position.x+y.offsetX,y:d.position.y+y.offsetY},rotation:d.rotation+y.rotation}}const x=d.rotate3d&&(d.rotate3d.x!==0||d.rotate3d.y!==0),h=s.blendMode&&s.blendMode!=="normal",f=s.text3d?.enabled===!0;if(x||h||f){ls||(ls=new vu(a,r)),(ls.canvas.width!==a||ls.canvas.height!==r)&&ls.resize(a,r),ls.clear();const y={...s,text:p,style:u,transform:{...d,opacity:c}},w=ls.renderTextClip(y,a,r);if(w){ls.getScene().add(w);const S=ls.render();t.drawImage(S,0,0)}return}Rb(u.fontFamily,u.fontSize),t.save();const v=d.position.x*a,A=d.position.y*r;t.translate(v,A),t.rotate(d.rotation*Math.PI/180),t.scale(d.scale.x,d.scale.y),t.globalAlpha=c;const g=typeof u.fontWeight=="number"?u.fontWeight:u.fontWeight==="bold"?700:400;t.font=`${u.fontStyle} ${g} ${u.fontSize}px "${u.fontFamily}"`,t.textAlign=u.textAlign,t.textBaseline="middle",u.shadowColor&&u.shadowBlur&&(t.shadowColor=u.shadowColor,t.shadowBlur=u.shadowBlur,t.shadowOffsetX=u.shadowOffsetX||0,t.shadowOffsetY=u.shadowOffsetY||0);const k=p.split(` +`),N=u.fontSize*u.lineHeight,b=k.length*N;let j=-b/2+N/2;if(u.verticalAlign==="top"?j=0:u.verticalAlign==="bottom"&&(j=-b),m&&m.length>0){let y=0;for(let w=0;wt.filter(a=>{const r=a.startTime+a.duration;return s>=a.startTime&&st.filter(a=>{const r=a.startTime+a.duration;return s>=a.startTime&&s{vl=t},Pb=(t,s,a,r,n)=>{const c=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("svg");if(!c)return t;const d=n?.minX??0,u=n?.minY??0,p=n?.width??s,m=n?.height??a,x=r/s*p,h=r/a*m,f=s+r*2,v=a+r*2;return c.setAttribute("width",String(f)),c.setAttribute("height",String(v)),c.setAttribute("viewBox",`${d-x} ${u-h} ${p+x*2} ${m+h*2}`),c.setAttribute("overflow","visible"),new XMLSerializer().serializeToString(c)},zb=(t,s,a,r,n)=>{const{imageUrl:i,transform:o,keyframes:c}=s,d=n-s.startTime,u=c&&c.length>0?ir(o,c,d):o;t.save();const p=u.position.x*a,m=u.position.y*r;t.translate(p,m),t.rotate(u.rotation*Math.PI/180),t.globalAlpha=u.opacity;let x=Gc.get(i);if(x||(x=new Image,x.onload=()=>vl?.(),x.src=i,Gc.set(i,x)),x.complete&&x.naturalHeight!==0){const h=x.naturalWidth,f=x.naturalHeight,v=u.scale.x,A=u.scale.y,g=u.anchor?.x??.5,k=u.anchor?.y??.5;if(u.crop){const N=u.crop.x*h,b=u.crop.y*f,j=u.crop.width*h,y=u.crop.height*f;t.drawImage(x,N,b,j,y,-j*v*g,-y*A*k,j*v,y*A)}else t.drawImage(x,-h*v*g,-f*A*k,h*v,f*A)}t.restore()},Db=(t,s,a,r,n)=>{const{svgContent:i,viewBox:o,colorStyle:c,entryAnimation:d,exitAnimation:u}=s,p=n-s.startTime;let m=s.transform;s.keyframes&&s.keyframes.length>0&&(m=ir(s.transform,s.keyframes,p)),t.save();const x=Math.round(m.position.x*a),h=Math.round(m.position.y*r);let f={x:m.scale.x,y:m.scale.y},v=m.opacity,A=0,g=0;const k=s.duration;let N=null,b=0;if(d&&p1,D);f={x:f.x*X,y:f.y*X};break;case"flip-horizontal":f={x:f.x*Math.cos(P*Math.PI),y:f.y},v*=Math.abs(Math.cos(P*Math.PI/2));break;case"flip-vertical":f={x:f.x,y:f.y*Math.cos(P*Math.PI)},v*=Math.abs(Math.cos(P*Math.PI/2));break}}if(u&&p>k-u.duration){const V=k-u.duration,_=(p-V)/u.duration;switch(u.type){case"fade":v*=1-_;break;case"scale":const se=1-_;f={x:f.x*se,y:f.y*se};break;case"slide-left":A=-_*a;break;case"slide-right":A=_*a;break;case"slide-up":g=-_*r;break;case"slide-down":g=_*r;break;case"rotate":t.rotate(_*Math.PI*2),v*=1-_;break;case"bounce":const R=1-(_<.5?2*_*_:1-Math.pow(-2*_+2,2)/2);f={x:f.x*R,y:f.y*R},v*=1-_;break;case"pop":const U=_<.5?1-_*.2:1-_*2.2;f={x:f.x*Math.max(0,U),y:f.y*Math.max(0,U)};break;case"draw":b=1-_,v*=Math.max(0,1-_*2);break;case"wipe-left":N={x:(o?.width||200)*_,y:0,width:(o?.width||200)*(1-_),height:o?.height||200};break;case"wipe-right":N={x:0,y:0,width:(o?.width||200)*(1-_),height:o?.height||200};break;case"wipe-up":N={x:0,y:0,width:o?.width||200,height:(o?.height||200)*(1-_)};break;case"wipe-down":N={x:0,y:(o?.height||200)*_,width:o?.width||200,height:(o?.height||200)*(1-_)};break;case"reveal-center":N={x:(o?.width||200)*_*.5,y:(o?.height||200)*_*.5,width:(o?.width||200)*(1-_),height:(o?.height||200)*(1-_)};break;case"reveal-edges":N={x:(o?.width||200)*(1-_)*.5,y:(o?.height||200)*(1-_)*.5,width:(o?.width||200)*_,height:(o?.height||200)*_};break;case"elastic":const D=1-(_<.5?4*_*_*_:1-Math.pow(-2*_+2,3)/2);f={x:f.x*Math.max(0,D),y:f.y*Math.max(0,D)};break;case"flip-horizontal":f={x:f.x*Math.cos((1-_)*Math.PI+Math.PI),y:f.y},v*=Math.abs(Math.cos((1-_)*Math.PI/2));break;case"flip-vertical":f={x:f.x,y:f.y*Math.cos((1-_)*Math.PI+Math.PI)},v*=Math.abs(Math.cos((1-_)*Math.PI/2));break}}t.translate(x+Math.round(A),h+Math.round(g)),t.rotate(m.rotation*Math.PI/180),t.scale(f.x,f.y),t.globalAlpha=v;const j=o?.width||200,y=o?.height||200,w=j/y,S=Math.max(Math.abs(f.x),Math.abs(f.y),1),T=Math.ceil(S*2)/2;let C,M;w>1?(C=Math.ceil(a*T),M=Math.ceil(C/w)):(M=Math.ceil(r*T),C=Math.ceil(M*w));const z=16,L=C+z*2,B=M+z*2,O=`${s.id}_${C}x${M}`;let G=Xr.get(O);if(!G){const V=Pb(i,C,M,z,o?{minX:o.minX,minY:o.minY,width:j,height:y}:void 0);G=new Image;const P=new Blob([V],{type:"image/svg+xml"});if(G.onload=()=>vl?.(),G.src=URL.createObjectURL(P),Xr.set(O,G),Xr.size>50){const _=Xr.keys().next().value;if(_){const se=Xr.get(_);se?.src?.startsWith("blob:")&&URL.revokeObjectURL(se.src),Xr.delete(_)}}}if(G.complete&&G.naturalWidth>0){const V=C/T,P=M/T,_=z/T,se=c&&c.colorMode&&c.colorMode!=="none"||b>0&&b<1;if(N&&(t.save(),t.beginPath(),t.rect(-V/2+N.x/j*V,-P/2+N.y/y*P,N.width/j*V,N.height/y*P),t.clip()),se){const R=document.createElement("canvas");R.width=L,R.height=B;const U=R.getContext("2d");if(U){if(U.drawImage(G,0,0,L,B),c&&c.colorMode&&c.colorMode!=="none"&&(c.colorMode==="tint"||c.colorMode==="replace")&&(U.globalCompositeOperation="source-in",U.fillStyle=c.tintColor||"#ffffff",U.globalAlpha=c.tintOpacity??1,U.fillRect(0,0,L,B)),b>0&&b<1){const D=Math.max(C,M)*4,X=D*(1-b);U.globalCompositeOperation="destination-in",U.strokeStyle="#000",U.lineWidth=Math.max(C,M),U.setLineDash([D]),U.lineDashOffset=X,U.strokeRect(z,z,C,M),U.setLineDash([])}t.drawImage(R,-(V/2+_),-(P/2+_),V+_*2,P+_*2)}}else t.drawImage(G,-(V/2+_),-(P/2+_),V+_*2,P+_*2);N&&t.restore()}t.restore()},Ib=(t,s,a,r)=>{const{shapeType:n,style:i,transform:o}=s;t.save();const c=o.position.x*a,d=o.position.y*r;t.translate(c,d),t.rotate(o.rotation*Math.PI/180),t.scale(o.scale.x,o.scale.y),t.globalAlpha=o.opacity,i.shadow?.blur&&i.shadow.blur>0&&(t.shadowColor=i.shadow.color||"#000000",t.shadowBlur=i.shadow.blur,t.shadowOffsetX=i.shadow.offsetX||0,t.shadowOffsetY=i.shadow.offsetY||0);const u=Math.min(a,r),p=u*.15,m=p/2,x=u/1080;switch(t.fillStyle=i.fill?.color||"#3b82f6",t.strokeStyle=i.stroke?.color||"#1d4ed8",t.lineWidth=(i.stroke?.width||2)*x,i.stroke?.dashArray&&i.stroke.dashArray.length>0&&t.setLineDash(i.stroke.dashArray),t.beginPath(),n){case"rectangle":{const h=i.cornerRadius||0;h>0?t.roundRect(-m,-m,p,p,Math.min(h,m)):t.rect(-m,-m,p,p);break}case"circle":case"ellipse":{t.ellipse(0,0,m,m,0,0,Math.PI*2);break}case"triangle":{t.moveTo(0,-m),t.lineTo(m,m),t.lineTo(-m,m),t.closePath();break}case"star":{const h=i.points||5,f=(i.innerRadius||.5)*m;for(let v=0;v0&&(t.globalAlpha=o.opacity*(i.stroke?.opacity??1),t.stroke()),t.restore()},Gr=(t,s,a,r,n)=>{const i=n-s.startTime;let o=s.transform;s.keyframes&&s.keyframes.length>0&&(o=ir(s.transform,s.keyframes,i));let c={...s,transform:o};if(s.emphasisAnimation&&s.emphasisAnimation.type!=="none"){const m=Mn(s.emphasisAnimation,i);c={...c,transform:{...o,opacity:o.opacity*m.opacity,scale:{x:o.scale.x*m.scale*m.scaleX,y:o.scale.y*m.scale*m.scaleY},position:{x:o.position.x+m.offsetX,y:o.position.y+m.offsetY},rotation:o.rotation+m.rotation}}}const d=c.transform.rotate3d&&(c.transform.rotate3d.x!==0||c.transform.rotate3d.y!==0),u=c.blendMode&&c.blendMode!=="normal",p=c.type==="shape"&&c.shapeType.startsWith("mesh-");if(d||u||p){ls||(ls=new vu(a,r)),(ls.canvas.width!==a||ls.canvas.height!==r)&&ls.resize(a,r),ls.clear();let m=null;if(c.type==="svg"?m=ls.renderSVGClip(c,a,r):c.type==="sticker"||c.type==="emoji"?m=ls.renderStickerClip(c,a,r):m=ls.renderShapeClip(c,a,r),m){ls.getScene().add(m);const x=ls.render();t.drawImage(x,0,0)}return}c.type==="svg"?Db(t,c,a,r,n):c.type==="sticker"||c.type==="emoji"?zb(t,c,a,r,n):Ib(t,c,a,r)},Ja=(t,s)=>t.filter(a=>s>=a.startTime&&s{const{text:i,animationStyle:o,words:c}=s;if(!i||i.trim().length===0)return;const d=o&&o!=="none"&&c&&c.length>0,u=n??s.startTime;d?Fb(t,s,a,r,u):Bb(t,s,a,r)},Bb=(t,s,a,r)=>{const{text:n,style:i}=s;t.save();const o=i?.fontSize||24,c=i?.fontFamily||"Inter",d=i?.color||"#ffffff",u=i?.backgroundColor||"rgba(0, 0, 0, 0.7)",p=i?.position||"bottom";t.font=`bold ${o}px "${c}"`,t.textAlign="center",t.textBaseline="middle";const m=n.split(` +`),x=o*1.3,h=m.length*x;let f;p==="top"?f=o*2:p==="center"?f=r/2-h/2:f=r-o*2-h;for(let v=0;v{const i=lg(s,n);if(!i.visible||i.segments.length===0)return;t.save();const o=s.style,c=o?.fontSize||24,d=o?.fontFamily||"Inter",u=o?.color||"#ffffff",p=o?.backgroundColor||"rgba(0, 0, 0, 0.7)",m=o?.position||"bottom";t.font=`bold ${c}px "${d}"`,t.textBaseline="middle";const x=c*1.3;let h;m==="top"?h=c*2+x/2:m==="center"?h=r/2:h=r-c*2-x/2;const f=i.segments.map(N=>N.text).join(" "),v=t.measureText(f).width,A=v+30,g=x+10;t.fillStyle=p,t.fillRect(a/2-A/2,h-g/2,A,g);let k=a/2-v/2;for(const N of i.segments){const b=t.measureText(N.text+" ").width;t.save(),t.globalAlpha=N.opacity;const j=k+t.measureText(N.text).width/2,y=h+N.offsetY;t.translate(j,y),t.scale(N.scale,N.scale),t.translate(-j,-y);const w=Lb(N,u,o?.highlightColor);t.fillStyle=w,t.textAlign="left",t.fillText(N.text,k,h+N.offsetY),t.restore(),k+=b}t.restore()},Lb=(t,s,a)=>{if(t.color)return t.color.startsWith("linear-gradient")?a||"#ffff00":t.color==="transparent"?"rgba(0,0,0,0)":t.color;switch(t.style){case"highlighted":case"active":return a||"#ffff00";case"hidden":return"rgba(0,0,0,0)";default:return s}},Ta=(t,s,a,r,n)=>{const i={...Ks,...a,position:{x:a?.position?.x??Ks.position.x,y:a?.position?.y??Ks.position.y},scale:{x:a?.scale?.x??Ks.scale.x,y:a?.scale?.y??Ks.scale.y},anchor:{x:a?.anchor?.x??Ks.anchor.x,y:a?.anchor?.y??Ks.anchor.y}};t.save(),t.globalAlpha=i.opacity??1;const o=r/2,c=n/2;t.translate(o+i.position.x,c+i.position.y),t.rotate(i.rotation*Math.PI/180),t.scale(i.scale.x,i.scale.y);let d,u;s instanceof HTMLVideoElement?(d=s.videoWidth||r,u=s.videoHeight||n):(d="width"in s?s.width:r,u="height"in s?s.height:n);const p=d/u,m=r/n,x=!i.fitMode||i.fitMode==="none"?"contain":i.fitMode;let h,f;x==="stretch"?(h=r,f=n):x==="cover"?p>m?(f=n,h=n*p):(h=r,f=r/p):p>m?(h=r,f=r/p):(f=n,h=n*p);const v=-h*i.anchor.x,A=-f*i.anchor.y,g=i.borderRadius||0;if(g>0){t.beginPath();const k=Math.min(g,h/2,f/2);t.roundRect(v,A,h,f,k),t.clip()}if(i.crop){const k=i.crop.x*d,N=i.crop.y*u,b=i.crop.width*d,j=i.crop.height*u,y=b/j;let w,S;y>m?(w=r,S=r/y):(S=n,w=n*y);const T=-w*i.anchor.x,C=-S*i.anchor.y;t.drawImage(s,k,N,b,j,T,C,w,S)}else t.drawImage(s,v,A,h,f);t.restore()},Tr=async(t,s)=>{try{let a=s;const r=an();if(r&&r.isInitialized()&&r.getSettings(t).enabled)try{const m=await r.processFrame(t,a,a.width,a.height);m&&m.width>0&&m.height>0&&(a=m)}catch{}const n=Sd();if(!n.isInitialized())return a;const o=n.getEffects(t),c=n.getColorGrading(t),d=Date.now();if(d-Yc>5e3&&(Yc=d),o.filter(p=>p.enabled).length>0)try{const p=await n.processEffects(t,a);p.image&&p.image.width>0&&p.image.height>0&&(a=p.image)}catch{}if(Object.keys(c).length>0)try{const p=await n.processColorGrading(t,a);p.image&&p.image.width>0&&p.image.height>0&&(a=p.image)}catch{}return a}catch{return s}},vo=(t,s)=>{try{const a=Bn();if(!a.isInitialized())return null;const r=s.filter(n=>n.type==="video"||n.type==="image");for(const n of r){const i=a.getTransitionsForTrack(n.id);for(const o of i){const c=n.clips.find(u=>u.id===o.clipAId),d=n.clips.find(u=>u.id===o.clipBId);if(!(!c||!d)&&a.isTimeInTransition(o,c,t)){const u=a.calculateProgress(o,c,t);return{clipA:{id:c.id,startTime:c.startTime,duration:c.duration,mediaId:c.mediaId,inPoint:c.inPoint},clipB:{id:d.id,startTime:d.startTime,duration:d.duration,mediaId:d.mediaId,inPoint:d.inPoint},transitionId:o.id,progress:u}}}}return null}catch{return null}},$b=async(t,s,a)=>{try{const r=Bn();if(!r.isInitialized())return t.progress<.5?s:a;const n=r.getTransition(t.transitionId);if(!n)return t.progress<.5?s:a;const i=await r.renderTransition(s,a,n,t.progress);return i&&i.frame&&i.frame.width>0&&i.frame.height>0?i.frame:t.progress<.5?s:a}catch{return t.progress<.5?s:a}},Wc=async(t,s,a)=>{try{const r=Bn();if(!r.isInitialized())return t.progress<.5?s:a;const n=r.getTransition(t.transitionId);if(!n)return t.progress<.5?s:a;const i=await r.renderTransitionToCanvas(s,a,n,t.progress);return i&&i.width>0&&i.height>0?i:t.progress<.5?s:a}catch{return t.progress<.5?s:a}},Ob=[{label:"Free",value:null},{label:"9:16",value:9/16},{label:"16:9",value:16/9},{label:"1:1",value:1},{label:"4:3",value:4/3},{label:"3:4",value:3/4}],_b=({clip:t,videoSrc:s,mediaType:a,currentTime:r,canvasWidth:n,canvasHeight:i,onCropChange:o,onComplete:c,onCancel:d})=>{const u=l.useRef(null),p=l.useRef(null),m=l.useRef(null),x=t.transform.crop||{x:0,y:0,width:1,height:1},[h,f]=l.useState(x),[v,A]=l.useState(!1),[g,k]=l.useState(null),[N,b]=l.useState({x:0,y:0}),[j,y]=l.useState(x),[w,S]=l.useState(null),[T,C]=l.useState({width:0,height:0}),[M,z]=l.useState(!0);l.useEffect(()=>{if(z(!0),a==="image"){const R=m.current;if(!R)return;const U=()=>{R.naturalWidth>0&&R.naturalHeight>0&&(C({width:R.naturalWidth,height:R.naturalHeight}),z(!1))},D=()=>{console.error("[CropModeView] Image load error"),z(!1)};return R.addEventListener("load",U),R.addEventListener("error",D),R.src=s,()=>{R.removeEventListener("load",U),R.removeEventListener("error",D)}}else{const R=p.current;if(!R)return;const U=()=>{R.videoWidth>0&&R.videoHeight>0&&(C({width:R.videoWidth,height:R.videoHeight}),z(!1))},D=()=>{console.error("[CropModeView] Video load error"),z(!1)};return R.addEventListener("loadedmetadata",U),R.addEventListener("error",D),R.src=s,R.currentTime=r,()=>{R.removeEventListener("loadedmetadata",U),R.removeEventListener("error",D)}}},[s,r,a]);const L=(R,U)=>{R.preventDefault(),R.stopPropagation(),A(!0),k(U),b({x:R.clientX,y:R.clientY}),y(h)},B=R=>{if(!v||!g||!u.current)return;const U=(R.clientX-N.x)/(T.width*G),D=(R.clientY-N.y)/(T.height*G);let X={...j};if(g==="center")X.x=Math.max(0,Math.min(1-j.width,j.x+U)),X.y=Math.max(0,Math.min(1-j.height,j.y+D));else if(g==="nw"){const K=-j.x,ue=j.width-.05,Te=-j.y,pe=j.height-.05,fe=Math.max(K,Math.min(U,ue)),We=Math.max(Te,Math.min(D,pe));if(w){const Ze=(fe+We)/2;X.x=j.x+Ze,X.y=j.y+Ze,X.width=j.width-Ze,X.height=j.height-Ze}else X.x=j.x+fe,X.y=j.y+We,X.width=j.width-fe,X.height=j.height-We}else if(g==="ne"){const K=-j.y,ue=j.height-.05,Te=Math.max(K,Math.min(D,ue));if(w){const pe=(-U+Te)/2;X.y=j.y+pe,X.width=j.width-pe,X.height=j.height-pe}else X.y=j.y+Te,X.width=Math.min(1-j.x,j.width+U),X.height=j.height-Te}else if(g==="sw"){const K=-j.x,ue=j.width-.05,Te=Math.max(K,Math.min(U,ue));if(w){const pe=(Te-D)/2;X.x=j.x+pe,X.width=j.width-pe,X.height=j.height-pe}else X.x=j.x+Te,X.width=j.width-Te,X.height=Math.min(1-j.y,j.height+D)}else if(g==="se")if(w){const K=(U+D)/2;X.width=Math.min(1-j.x,Math.max(.1,j.width+K)),X.height=Math.min(1-j.y,Math.max(.1,j.height+K))}else X.width=Math.min(1-j.x,Math.max(.1,j.width+U)),X.height=Math.min(1-j.y,Math.max(.1,j.height+D));else if(g==="n"){const K=-j.y,ue=j.height-.05,Te=Math.max(K,Math.min(D,ue));X.y=j.y+Te,X.height=j.height-Te}else if(g==="s")X.height=Math.min(1-j.y,Math.max(.1,j.height+D));else if(g==="w"){const K=-j.x,ue=j.width-.05,Te=Math.max(K,Math.min(U,ue));X.x=j.x+Te,X.width=j.width-Te}else g==="e"&&(X.width=Math.min(1-j.x,Math.max(.1,j.width+U)));X.width=Math.max(.05,Math.min(1,X.width)),X.height=Math.max(.05,Math.min(1,X.height)),X.x=Math.max(0,Math.min(1-X.width,X.x)),X.y=Math.max(0,Math.min(1-X.height,X.y)),f(X)},O=T.width>0&&n>0&&i>0?(()=>{const R=T.width/T.height,U=n/i;let D,X;return R>U?(D=n,X=n/R):(X=i,D=i*R),{width:D,height:X}})():{width:n,height:i},G=T.width>0?O.width/T.width:1,V=T.width>0?{x:h.x*T.width*G,y:h.y*T.height*G,width:h.width*T.width*G,height:h.height*T.height*G}:{x:0,y:0,width:0,height:0},P=()=>{v&&g&&o(h),A(!1),k(null)};l.useEffect(()=>{if(v)return window.addEventListener("mousemove",B),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",B),window.removeEventListener("mouseup",P)}},[v,g,N,j,w,T,G]);const _=R=>{if(S(R),R){const U=h.width/h.height;let D;if(U>R){const X=h.height*R;D={...h,x:h.x+(h.width-X)/2,width:X}}else{const X=h.width/R;D={...h,y:h.y+(h.height-X)/2,height:X}}f(D),o(D)}},se=()=>{const R={x:0,y:0,width:1,height:1};f(R),S(null),o(R)};return e.jsxs("div",{className:"absolute inset-0 z-10 bg-background-secondary flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-background border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Crop Video"}),e.jsx("div",{className:"flex items-center gap-1",children:Ob.map(R=>e.jsx("button",{onClick:()=>_(R.value),disabled:M,className:`px-2.5 py-1 text-xs rounded transition-colors ${w===R.value?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:bg-background-secondary"}`,children:R.label},R.label))}),e.jsx("button",{onClick:se,disabled:M,className:"p-1 text-text-muted hover:bg-background-secondary rounded transition-colors",title:"Reset crop",children:e.jsx(zr,{size:14})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:d,className:"px-3 py-1.5 text-xs bg-background-tertiary hover:bg-background-secondary text-text-primary rounded transition-colors flex items-center gap-1.5",children:[e.jsx(Ls,{size:14}),"Cancel"]}),e.jsxs("button",{onClick:()=>{o(h),c()},disabled:M,className:"px-3 py-1.5 text-xs bg-primary hover:bg-primary/90 text-black font-medium rounded transition-colors flex items-center gap-1.5",children:[e.jsx(is,{size:14}),"Apply"]})]})]}),e.jsxs("div",{className:"flex-1 flex items-center justify-center p-4 overflow-hidden relative",children:[M&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background-secondary",children:e.jsx("div",{className:"text-text-muted text-sm",children:"Loading video..."})}),e.jsxs("div",{ref:u,className:"relative",style:{width:O.width,height:O.height,opacity:M?0:1},children:[a==="image"?e.jsx("img",{ref:m,className:"w-full h-full",style:{objectFit:"contain"},alt:"Crop preview"}):e.jsx("video",{ref:p,className:"w-full h-full",style:{objectFit:"contain"},muted:!0,playsInline:!0,preload:"metadata"}),!M&&T.width>0&&e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"absolute inset-0 pointer-events-none",width:O.width,height:O.height,children:[e.jsx("defs",{children:e.jsxs("mask",{id:"crop-mask",children:[e.jsx("rect",{x:"0",y:"0",width:O.width,height:O.height,fill:"white"}),e.jsx("rect",{x:V.x,y:V.y,width:V.width,height:V.height,fill:"black"})]})}),e.jsx("rect",{x:"0",y:"0",width:O.width,height:O.height,fill:"black",opacity:"0.6",mask:"url(#crop-mask)"})]}),e.jsxs("div",{className:"absolute border-2 border-white pointer-events-auto cursor-move",style:{left:V.x,top:V.y,width:V.width,height:V.height},onMouseDown:R=>L(R,"center"),children:[e.jsxs("svg",{className:"absolute inset-0 pointer-events-none",width:"100%",height:"100%",children:[e.jsx("line",{x1:"33.33%",y1:"0",x2:"33.33%",y2:"100%",stroke:"white",strokeWidth:"1",opacity:"0.5"}),e.jsx("line",{x1:"66.66%",y1:"0",x2:"66.66%",y2:"100%",stroke:"white",strokeWidth:"1",opacity:"0.5"}),e.jsx("line",{x1:"0",y1:"33.33%",x2:"100%",y2:"33.33%",stroke:"white",strokeWidth:"1",opacity:"0.5"}),e.jsx("line",{x1:"0",y1:"66.66%",x2:"100%",y2:"66.66%",stroke:"white",strokeWidth:"1",opacity:"0.5"})]}),["nw","ne","sw","se"].map(R=>e.jsx("div",{className:"absolute w-4 h-4 bg-white border-2 border-gray-800 rounded-sm cursor-nwse-resize pointer-events-auto hover:bg-primary transition-colors",style:{top:R.includes("n")?-8:void 0,bottom:R.includes("s")?-8:void 0,left:R.includes("w")?-8:void 0,right:R.includes("e")?-8:void 0},onMouseDown:U=>L(U,R)},R)),e.jsx("div",{className:"absolute w-16 h-4 bg-white border-2 border-gray-800 rounded-sm cursor-ns-resize pointer-events-auto hover:bg-primary transition-colors -top-2 left-1/2 -translate-x-1/2",onMouseDown:R=>L(R,"n")}),e.jsx("div",{className:"absolute w-16 h-4 bg-white border-2 border-gray-800 rounded-sm cursor-ns-resize pointer-events-auto hover:bg-primary transition-colors -bottom-2 left-1/2 -translate-x-1/2",onMouseDown:R=>L(R,"s")}),e.jsx("div",{className:"absolute w-4 h-16 bg-white border-2 border-gray-800 rounded-sm cursor-ew-resize pointer-events-auto hover:bg-primary transition-colors -left-2 top-1/2 -translate-y-1/2",onMouseDown:R=>L(R,"w")}),e.jsx("div",{className:"absolute w-4 h-16 bg-white border-2 border-gray-800 rounded-sm cursor-ew-resize pointer-events-auto hover:bg-primary transition-colors -right-2 top-1/2 -translate-y-1/2",onMouseDown:R=>L(R,"e")})]})]})]})]})]})},Vb=({points:t,canvasWidth:s,canvasHeight:a,selectedPoint:r,hoveredPoint:n,disabled:i,onPointSelect:o,onPointHover:c,onPointMove:d,onPointRemove:u,onControlPointMove:p})=>{const[m,x]=l.useState(null),h=l.useRef(null),f=l.useCallback((k,N,b,j,y)=>{i||(k.preventDefault(),k.stopPropagation(),x({type:N,pointIndex:b,startX:k.clientX,startY:k.clientY,initialX:j,initialY:y}),N==="point"&&o(b))},[i,o]),v=l.useCallback(k=>{if(!m)return;const N=k.clientX-m.startX,b=k.clientY-m.startY,j=m.initialX+N,y=m.initialY+b;m.type==="point"?d(m.pointIndex,j,y):p(m.pointIndex,m.type,j,y)},[m,d,p]),A=l.useCallback(()=>{x(null)},[]);l.useEffect(()=>{if(m)return window.addEventListener("mousemove",v),window.addEventListener("mouseup",A),()=>{window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",A)}},[m,v,A]);const g=l.useCallback((k,N)=>{k.preventDefault(),t.length>2&&u(N)},[t.length,u]);return e.jsx("g",{ref:h,children:t.map((k,N)=>{const b=r===N,j=n===N,y=b&&k.controlPoints;return e.jsxs("g",{children:[y&&k.controlPoints&&e.jsxs(e.Fragment,{children:[e.jsx("line",{x1:k.controlPoints.cp1.x,y1:k.controlPoints.cp1.y,x2:k.screenX,y2:k.screenY,stroke:"#a855f7",strokeWidth:"1",opacity:"0.6"}),e.jsx("line",{x1:k.screenX,y1:k.screenY,x2:k.controlPoints.cp2.x,y2:k.controlPoints.cp2.y,stroke:"#a855f7",strokeWidth:"1",opacity:"0.6"}),e.jsx("circle",{cx:k.controlPoints.cp1.x,cy:k.controlPoints.cp1.y,r:"5",fill:"#a855f7",stroke:"white",strokeWidth:"1",className:"cursor-move pointer-events-auto",onMouseDown:w=>f(w,"cp1",N,k.controlPoints.cp1.x,k.controlPoints.cp1.y)}),e.jsx("circle",{cx:k.controlPoints.cp2.x,cy:k.controlPoints.cp2.y,r:"5",fill:"#a855f7",stroke:"white",strokeWidth:"1",className:"cursor-move pointer-events-auto",onMouseDown:w=>f(w,"cp2",N,k.controlPoints.cp2.x,k.controlPoints.cp2.y)})]}),e.jsxs("g",{transform:`translate(${k.screenX}, ${k.screenY}) rotate(45)`,className:"pointer-events-auto cursor-move",onMouseDown:w=>f(w,"point",N,k.screenX,k.screenY),onMouseEnter:()=>c(N),onMouseLeave:()=>c(null),onContextMenu:w=>g(w,N),children:[e.jsx("rect",{x:"-7",y:"-7",width:"14",height:"14",fill:b?"#22d3ee":j?"#67e8f9":"white",stroke:b?"white":"#22d3ee",strokeWidth:"2",rx:"2"}),N===0&&e.jsx("text",{transform:"rotate(-45)",x:"0",y:"4",textAnchor:"middle",fill:b?"white":"#22d3ee",fontSize:"8",fontWeight:"bold",className:"pointer-events-none select-none",children:"S"}),N===t.length-1&&N!==0&&e.jsx("text",{transform:"rotate(-45)",x:"0",y:"4",textAnchor:"middle",fill:b?"white":"#22d3ee",fontSize:"8",fontWeight:"bold",className:"pointer-events-none select-none",children:"E"})]})]},`point-${N}`)})})},Ub=({config:t,canvasWidth:s,canvasHeight:a,currentTime:r,clipDuration:n,onPointMove:i,onPointAdd:o,onPointRemove:c,onControlPointMove:d,disabled:u=!1})=>{const[p,m]=l.useState(null),[x,h]=l.useState(null),f=l.useMemo(()=>t.points.map(N=>({...N,screenX:s/2+N.x,screenY:a/2+N.y,controlPoints:N.controlPoints?{cp1:{x:s/2+N.controlPoints.cp1.x,y:a/2+N.controlPoints.cp1.y},cp2:{x:s/2+N.controlPoints.cp2.x,y:a/2+N.controlPoints.cp2.y}}:void 0})),[t.points,s,a]),v=l.useMemo(()=>{if(f.length<2)return"";const N=f.map(b=>({x:b.screenX,y:b.screenY,time:b.time,controlPoints:b.controlPoints}));return _m(N)},[f]),A=l.useMemo(()=>{if(t.points.length===0||n<=0)return null;const N=r/n,b=[...f].sort((j,y)=>j.time-y.time);if(N<=b[0].time)return{x:b[0].screenX,y:b[0].screenY};if(N>=b[b.length-1].time){const j=b[b.length-1];return{x:j.screenX,y:j.screenY}}for(let j=0;j=b[j].time&&N<=b[j+1].time){const y=b[j],w=b[j+1],S=w.time-y.time,T=S>0?(N-y.time)/S:0;return y.controlPoints&&w.controlPoints?Kb({x:y.screenX,y:y.screenY},y.controlPoints.cp2,w.controlPoints.cp1,{x:w.screenX,y:w.screenY},T):{x:y.screenX+(w.screenX-y.screenX)*T,y:y.screenY+(w.screenY-y.screenY)*T}}return null},[f,r,n,t.points.length]),g=l.useCallback(N=>{if(u)return;const b=N.currentTarget.closest("svg");if(!b)return;const j=b.getBoundingClientRect(),y=N.clientX-j.left,w=N.clientY-j.top,S=y-s/2,T=w-a/2;let C=.5;if(f.length>=2){let M=1/0,z=.5;for(let L=0;L{m(b=>b===N?null:N)},[]);return!t.enabled||!t.showPath?null:e.jsxs("svg",{className:"absolute inset-0 pointer-events-none",width:s,height:a,style:{overflow:"visible"},children:[e.jsx("defs",{children:e.jsx("marker",{id:"motion-path-arrow",markerWidth:"6",markerHeight:"6",refX:"3",refY:"3",orient:"auto",markerUnits:"strokeWidth",children:e.jsx("path",{d:"M0,0 L6,3 L0,6 Z",fill:"#22d3ee"})})}),v&&e.jsxs(e.Fragment,{children:[e.jsx("path",{d:v,fill:"none",stroke:"#22d3ee",strokeWidth:"2",strokeDasharray:"6 3",opacity:"0.8",className:"pointer-events-auto cursor-crosshair",onClick:g}),e.jsx("path",{d:v,fill:"none",stroke:"transparent",strokeWidth:"16",className:"pointer-events-auto cursor-crosshair",onClick:g})]}),e.jsx(Vb,{points:f,canvasWidth:s,canvasHeight:a,selectedPoint:p,hoveredPoint:x,disabled:u,onPointSelect:k,onPointHover:h,onPointMove:(N,b,j)=>{const y=b-s/2,w=j-a/2;i(N,y,w)},onPointRemove:c,onControlPointMove:(N,b,j,y)=>{const w=j-s/2,S=y-a/2;d(N,b,w,S)}}),A&&e.jsxs("g",{transform:`translate(${A.x}, ${A.y})`,children:[e.jsx("circle",{r:"8",fill:"#22d3ee",opacity:"0.3"}),e.jsx("circle",{r:"5",fill:"#22d3ee"}),e.jsx("circle",{r:"3",fill:"white"})]}),f.map((N,b)=>e.jsxs("text",{x:N.screenX+12,y:N.screenY-12,fill:"white",fontSize:"10",fontFamily:"system-ui",className:"pointer-events-none select-none",children:[(N.time*100).toFixed(0),"%"]},`label-${b}`))]})};function Kb(t,s,a,r,n){const i=1-n,o=i*i,c=o*i,d=n*n,u=d*n;return{x:c*t.x+3*o*n*s.x+3*i*d*a.x+u*r.x,y:c*t.y+3*o*n*s.y+3*i*d*a.y+u*r.y}}const Yb=({effects:t,width:s,height:a,currentTime:r,isPlaying:n})=>{const i=l.useRef(null),o=l.useRef(null),c=l.useRef(null),d=l.useRef(null),u=l.useRef(null),p=l.useRef(null),m=l.useRef(r),x=l.useRef(performance.now()),h=l.useRef(0),f=l.useRef(0),v=l.useRef(n),[A,g]=_e.useState(!1),k=l.useMemo(()=>ol(),[]);l.useEffect(()=>{m.current=r},[r]),l.useEffect(()=>{k.setCanvasSize(s,a)},[k,s,a]);const N=l.useRef(new Set);l.useEffect(()=>{const w=new Set(t.map(T=>T.id)),S=N.current;for(const T of t)k.getEffect(T.id)?S.has(T.id)||k.updateEffect(T.id,T.config):k.addEffect(T);for(const T of S)w.has(T)||k.removeEffect(T);N.current=w},[t,k]),l.useEffect(()=>{if(!i.current||s<=0||a<=0)return;const w=new Od;c.current=w;const S=new _d(0,s,a,0,.1,1e3);S.position.z=100,d.current=S;const T=new $d({alpha:!0,antialias:!0,premultipliedAlpha:!1});T.setSize(s,a,!1),T.setPixelRatio(Math.min(window.devicePixelRatio,2)),T.setClearColor(0,0),T.domElement.style.width="100%",T.domElement.style.height="100%",T.domElement.style.objectFit="contain",T.domElement.style.position="absolute",T.domElement.style.top="0",T.domElement.style.left="0",i.current.appendChild(T.domElement),o.current=T;const C=new Mp,M=new Float32Array(1e4*3),z=new Float32Array(1e4*3),L=new Float32Array(1e4),B=new Float32Array(1e4);C.setAttribute("position",new ri(M,3)),C.setAttribute("color",new ri(z,3)),C.setAttribute("size",new ri(L,1)),C.setAttribute("alpha",new ri(B,1)),u.current=C;const O=new Ep({size:12,vertexColors:!0,transparent:!0,opacity:1,blending:Si,depthWrite:!1,sizeAttenuation:!1}),G=new Rp(C,O);return w.add(G),g(!0),()=>{g(!1),C.dispose(),O.dispose(),T.dispose(),i.current&&T.domElement&&i.current.removeChild(T.domElement)}},[s,a]);const b=l.useCallback(w=>{const S=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(w);if(S)return{r:parseInt(S[1],16)/255,g:parseInt(S[2],16)/255,b:parseInt(S[3],16)/255};const T=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i.exec(w);return T?{r:parseInt(T[1],10)/255,g:parseInt(T[2],10)/255,b:parseInt(T[3],10)/255}:{r:1,g:1,b:1}},[]),j=l.useCallback(w=>{if(!u.current)return;const S=u.current.attributes.position.array,T=u.current.attributes.color.array,C=u.current.attributes.size.array,M=Math.min(w.length,1e4);for(let z=0;z{!o.current||!c.current||!d.current||o.current.render(c.current,d.current)},[]);return l.useEffect(()=>{v.current=n},[n]),l.useEffect(()=>{if(A)if(n){h.current=performance.now(),f.current=m.current,x.current=performance.now();const w=()=>{if(!v.current)return;const S=performance.now(),T=S-x.current;x.current=S;const C=T/1e3,M=(S-h.current)/1e3,z=f.current+M;k.update(z,C);const L=k.getParticles();j(L),y(),p.current=requestAnimationFrame(w)};return p.current=requestAnimationFrame(w),()=>{p.current&&(cancelAnimationFrame(p.current),p.current=null)}}else{k.update(r,1/30);const w=k.getParticles();j(w),y()}},[n,A,r,k,j,y,t]),l.useEffect(()=>{d.current&&(d.current.left=0,d.current.right=s,d.current.top=a,d.current.bottom=0,d.current.updateProjectionMatrix()),o.current&&o.current.setSize(s,a,!1)},[s,a]),e.jsx("div",{ref:i,className:"absolute inset-0 pointer-events-none w-full h-full",style:{zIndex:50}})};let Xb=0;const ju=un((t,s)=>({tasks:new Map,isProcessing:!1,currentTaskId:null,addTask:(a,r)=>{const n=`task-${++Xb}-${Date.now()}`,i={id:n,clipId:a,type:r,progress:0,status:"queued",message:"Waiting to start..."};return t(o=>{const c=new Map(o.tasks);return c.set(n,i),{tasks:c,isProcessing:!0,currentTaskId:o.currentTaskId||n}}),n},updateTaskProgress:(a,r,n)=>{t(i=>{const o=i.tasks.get(a);if(!o)return i;const c=new Map(i.tasks);return c.set(a,{...o,progress:Math.min(100,Math.max(0,r)),status:"processing",message:n||o.message,startedAt:o.startedAt||Date.now()}),{tasks:c}})},completeTask:a=>{t(r=>{const n=r.tasks.get(a);if(!n)return r;const i=new Map(r.tasks);i.set(a,{...n,progress:100,status:"completed",message:"Complete",completedAt:Date.now()});const o=Array.from(i.values()).some(d=>d.status==="queued"||d.status==="processing"),c=o&&Array.from(i.values()).find(d=>d.status==="queued")?.id||null;return{tasks:i,isProcessing:o,currentTaskId:c}})},failTask:(a,r)=>{t(n=>{const i=n.tasks.get(a);if(!i)return n;const o=new Map(n.tasks);o.set(a,{...i,status:"failed",message:"Failed",error:r,completedAt:Date.now()});const c=Array.from(o.values()).some(d=>d.status==="queued"||d.status==="processing");return{tasks:o,isProcessing:c,currentTaskId:c&&Array.from(o.values()).find(d=>d.status==="queued")?.id||null}})},removeTask:a=>{t(r=>{const n=new Map(r.tasks);n.delete(a);const i=Array.from(n.values()).some(o=>o.status==="queued"||o.status==="processing");return{tasks:n,isProcessing:i,currentTaskId:i?r.currentTaskId:null}})},getTasksForClip:a=>Array.from(s().tasks.values()).filter(r=>r.clipId===a),hasActiveProcessing:()=>Array.from(s().tasks.values()).some(a=>a.status==="queued"||a.status==="processing"),getOverallProgress:()=>{const a=Array.from(s().tasks.values()),r=a.filter(o=>o.status!=="completed"&&o.status!=="failed");if(r.length===0)return{total:0,completed:0,progress:100};const i=r.reduce((o,c)=>o+c.progress,0)/r.length;return{total:r.length,completed:a.filter(o=>o.status==="completed").length,progress:Math.round(i)}},clearCompleted:()=>{t(a=>{const r=new Map(a.tasks);for(const[n,i]of r)(i.status==="completed"||i.status==="failed")&&r.delete(n);return{tasks:r}})}})),Gb={"background-removal":"Background Removal","auto-reframe":"Auto Reframe","color-grading":"Color Grading",effects:"Video Effects"},Hb=({task:t})=>{const s=()=>{switch(t.status){case"queued":return e.jsx(Ia,{size:14,className:"text-text-muted"});case"processing":return e.jsx(ds,{size:14,className:"text-blue-400 animate-spin"});case"completed":return e.jsx(ul,{size:14,className:"text-green-400"});case"failed":return e.jsx(Vm,{size:14,className:"text-red-400"})}},a=()=>{switch(t.status){case"queued":return"text-text-muted";case"processing":return"text-blue-400";case"completed":return"text-green-400";case"failed":return"text-red-400"}};return e.jsxs("div",{className:"flex items-center gap-3 p-2 bg-black/20 rounded",children:[s(),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-text-primary truncate",children:Gb[t.type]}),e.jsx("span",{className:`text-[10px] ${a()}`,children:t.status==="processing"?`${t.progress}%`:t.status})]}),t.status==="processing"&&e.jsxs("div",{className:"mt-1",children:[e.jsx(Ad,{value:t.progress,className:"h-1 bg-black/30"}),e.jsx("p",{className:"text-[9px] text-text-muted mt-0.5 truncate",children:t.message})]}),t.status==="failed"&&t.error&&e.jsx("p",{className:"text-[9px] text-red-400 mt-0.5 truncate",children:t.error})]})]})},Wb=()=>{const{tasks:t,isProcessing:s,getOverallProgress:a}=ju(),n=Array.from(t.values()).filter(o=>o.status==="queued"||o.status==="processing");if(!s||n.length===0)return null;const{progress:i}=a();return e.jsx("div",{className:"absolute inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-background-secondary/95 rounded-xl p-6 max-w-sm w-full mx-4 shadow-2xl border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-500/20 flex items-center justify-center",children:e.jsx(ds,{size:20,className:"text-blue-400 animate-spin"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Processing Effects"}),e.jsxs("p",{className:"text-xs text-text-muted",children:[n.length," task",n.length!==1?"s":""," in progress"]})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Overall Progress"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[i,"%"]})]}),e.jsx(Ad,{value:i,className:"h-2 bg-black/30"})]}),e.jsx(ia,{className:"max-h-48",children:e.jsx("div",{className:"space-y-2",children:n.map(o=>e.jsx(Hb,{task:o},o.id))})}),e.jsx("p",{className:"text-[10px] text-text-muted text-center mt-4",children:"Please wait while effects are being applied..."})]})})},wu=t=>{const s=an();if(s?.isInitialized()&&s.getSettings(t).enabled)return!0;const a=Sd();return a.isInitialized()?a.getEffects(t).some(r=>r.enabled)?!0:Object.keys(a.getColorGrading(t)).length>0:!1},qb=async(t,s,a)=>{const r=wu(t);if(!a&&!r)return{frame:s,cleanup:()=>{}};let n=null,i=null;try{return n=await createImageBitmap(s),r?(i=await Tr(t,n),i===n?{frame:n,cleanup:()=>{n?.close()}}:{frame:i,cleanup:()=>{i?.close(),n?.close()}}):{frame:n,cleanup:()=>{n?.close()}}}catch{return i?.close(),n?.close(),{frame:s,cleanup:()=>{}}}},jo=(t,s,a,r,n,i,o)=>Hm(t,s,a,{canvasWidth:r,canvasHeight:n,sourceWidth:i,sourceHeight:o}),Qb=(t,s,a,r,n)=>{const i=!t||t==="none"?"contain":t;if(i==="stretch"||s<=0||a<=0||r<=0||n<=0)return{x:1,y:1};const o=s/a,c=r/n;let d,u;return i==="cover"?o>c?(u=n,d=n*o):(d=r,u=r/o):o>c?(d=r,u=r/o):(u=n,d=n*o),{x:d/r,y:u/n}},Jb=async(t,s,a,r)=>{try{if(!t.getDevice()||s.length===0)return null;t.beginFrame();const i=[];for(let c=0;ct.some(s=>s.behindSubject),wo=async(t,s,a)=>{try{return await createImageBitmap(t.canvas,0,0,s,a)}catch{return null}},Zb=async(t,s,a,r)=>{if(!s)return;const n=Td();if(n.isInitialized())try{const i=await n.getPersonMask(s);if(!i)return;const o=new OffscreenCanvas(a,r),c=o.getContext("2d");if(!c)return;c.drawImage(s,0,0,a,r);const d=new OffscreenCanvas(i.width,i.height),u=d.getContext("2d");if(!u)return;u.putImageData(i.mask,0,0),c.globalCompositeOperation="destination-in",c.drawImage(d,0,0,a,r),t.drawImage(o,0,0)}catch{}},ko=async(t,s,a,r,n,i)=>{Ri(t,s,a,r,n),s.behindSubject&&await Zb(t,i,a,r)},ey=()=>{const t=l.useRef(null),s=l.useRef(null),a=l.useRef(null),r=l.useRef(null),n=l.useRef(null),i=l.useRef(!1),o=l.useRef(null),c=l.useRef(null),d=l.useRef(null),u=l.useRef(null),p=l.useRef(0),m=l.useRef(null),x=l.useRef(0),h=l.useRef(null),f=l.useRef(null),v=l.useRef(null),A=l.useRef(null),g=l.useRef(!1),k=l.useRef(null),N=l.useRef(null),b=l.useRef(null),j=l.useRef(new Map),y=l.useRef(new Map),w=(E,I)=>`${E}:${I??0}`,S=async(E,I,J=0)=>{try{const{getFFmpegFallback:H}=await zi(async()=>{const{getFFmpegFallback:ee}=await import("./index-Dws9LQij.js").then(le=>le.eB);return{getFFmpegFallback:ee}},__vite__mapDeps([1,2,3,4,5])),ke=await(await H().extractAudioAsWav(I,J)).arrayBuffer();return await E.decodeAudioData(ke)}catch{}if(J===0)try{const H=await I.arrayBuffer();return await E.decodeAudioData(H)}catch{return null}return null},T=l.useCallback(E=>JSON.stringify(E.map(I=>({id:I.id,type:I.type,enabled:I.enabled,params:I.params,metadata:I.metadata}))),[]),C=l.useCallback(async(E,I,J)=>{const H=lo(J.filter(Re=>Re.enabled)),{profileAwareNoiseEffects:q,realtimeEffects:re}=Kl(H);if(q.length===0)return{audioBuffer:E,effects:re};const ke=`${I}:profile-denoise:${T(q)}`,ee=y.current.get(ke);if(ee)return{audioBuffer:ee,effects:re};const le=await Um();let ne=E;for(const Re of q){const oe=Re.params;oe.profile&&(ne=await le.applyNoiseReductionWithProfileData(ne,oe.profile,oe.reduction??.5,oe.focus??"balanced",oe.threshold??-40))}return y.current.set(ke,ne),{audioBuffer:ne,effects:re}},[T]),M=l.useCallback(E=>Km(E,{tracks:ye.current}),[]),z=l.useCallback(E=>Ym(E,{tracks:ye.current}),[]),L=l.useRef(null),B=l.useRef(!1),[O,G]=l.useState(!1),[V,P]=l.useState(!1),[_,se]=l.useState({width:0,height:0}),[R,U]=l.useState({width:0,height:0}),[D,X]=l.useState("none"),[K,ue]=l.useState(!1),[Te,pe]=l.useState(!1),[fe,We]=l.useState(1),[Ze,at]=l.useState(!1),de=[{label:"50%",value:.5},{label:"75%",value:.75},{label:"100%",value:1},{label:"125%",value:1.25},{label:"150%",value:1.5},{label:"200%",value:2}],Ce=Oi(E=>E.isDark),Ne=l.useRef(Ce?"#000000":"#ffffff");l.useEffect(()=>{const E=typeof window<"u"?getComputedStyle(document.documentElement).getPropertyValue("--screen-bg").trim():"";Ne.current=E||(Ce?"#000000":"#ffffff")},[Ce]);const[Me,qe]=l.useState("none"),[nt,rt]=l.useState(null),[Pe,Ie]=l.useState(!0),Ee=l.useRef(null),ae=l.useRef(null),W=l.useRef(null),Q=l.useRef(!1),be=l.useRef(0),Oe=32,Ue=l.useRef(0),Le=16,[Ye,Ke]=l.useState(null),[mt,Ge]=l.useState(null),gt=l.useRef(null),Ft=l.useRef(new Map),Qe=l.useCallback(E=>{const{video:I,url:J}=E;I.pause(),I.removeAttribute("src"),I.onloadedmetadata=null,I.onerror=null,I.load(),URL.revokeObjectURL(J)},[]),Ds=l.useCallback(()=>{let E="",I=1/0;for(const[H,q]of Ft.current.entries())q.lastUsed{d.current&&(clearTimeout(d.current),d.current=null),u.current?.(null),u.current=null,p.current+=1},[]),Dt=l.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),Cs();for(const E of Ft.current.values())Qe(E);Ft.current.clear()},[Cs,Qe]),us=l.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{Dt()},350)},[Dt]),Ws=l.useRef(new Map);l.useEffect(()=>{const E=t.current;if(!E)return;const I=new ResizeObserver(J=>{for(const H of J){const{width:q,height:re}=H.contentRect;se({width:q,height:re}),q>0&&re>0&&(c.current=new OffscreenCanvas(q,re),h.current=c.current.getContext("2d"))}});return I.observe(E),()=>I.disconnect()},[]),l.useEffect(()=>{const E=a.current;if(!E)return;const I=new ResizeObserver(J=>{for(const H of J){const{width:q,height:re}=H.contentRect;U({width:q,height:re})}});return I.observe(E),()=>I.disconnect()},[]);const Qt=F(E=>E.project),Lt=F(E=>E.getMediaItem),ca=Ct(E=>E.getTitleEngine),ms=l.useMemo(()=>ca()?.getAllTextClips()||[],[ca,Qt.modifiedAt]),da=Ct(E=>E.getGraphicsEngine),ss=l.useMemo(()=>{const E=da(),I=E?.getAllShapeClips()||[],J=E?.getAllSVGClips()||[],H=E?.getAllStickerClips()||[];return[...I,...J,...H]},[da,Qt.modifiedAt]),ps=l.useMemo(()=>Qt.timeline.subtitles||[],[Qt.timeline.subtitles]),Ss=F(E=>E.updateClipTransform),qs=F(E=>E.updateTextTransform),ua=F(E=>E.updateShapeTransform),He=Qt.timeline.tracks,$=Qt.settings,ve=l.useMemo(()=>{if(R.width<=0||R.height<=0)return{width:0,height:0};const E=$.width/$.height,I=24,J=Math.max(1,R.width-I*2),H=Math.max(1,R.height-I*2);let q=J,re=q/E;return re>H&&(re=H,q=re*E),{width:q*fe,height:re*fe}},[$.height,$.width,R,fe]),ye=l.useRef(He);l.useEffect(()=>{ye.current=He},[He]);const we=l.useRef(ms);l.useEffect(()=>{we.current=ms},[ms]);const Y=l.useRef(ss);l.useEffect(()=>{Y.current=ss},[ss]);const je=l.useRef(ps);l.useEffect(()=>{je.current=ps},[ps]);const Se=l.useRef(!1),Ae=vt(E=>E.selectedItems),Be=vt(E=>E.cropMode),jt=vt(E=>E.cropClipId),Gt=vt(E=>E.setCropMode),Kt=vt(E=>E.exportState),ja=vt(E=>E.motionPathMode),ma=vt(E=>E.motionPathClipId),Dr=vt(E=>E.select),{playheadPosition:wt,playbackState:kl,playbackLockedReason:On,playbackRate:Hi,isScrubbing:Wi,pause:Qs,togglePlayback:Lu,seekTo:Nl,seekRelative:_n,setPlayheadPosition:Js}=Et();l.useEffect(()=>{Se.current=Wi},[Wi]);const Jt=kl==="playing",Ir=_e.useMemo(()=>{if(!ja||!ma)return null;for(const E of Qt.timeline.tracks){const I=E.clips.find(J=>J.id===ma);if(I)return I}return null},[ja,ma,Qt.timeline.tracks]),[Cl,Br]=_e.useState(null);_e.useEffect(()=>{Br(Ir?{clipId:Ir.id,enabled:!0,pathType:"bezier",points:[],showPath:!0,autoOrient:!1,alignOrigin:[.5,.5]}:null)},[Ir]);const $u=_e.useCallback((E,I,J)=>{Br(H=>{if(!H)return H;const q=[...H.points];return q[E]={...q[E],x:I,y:J},{...H,points:q}})},[]),Ou=_e.useCallback(E=>{Br(I=>{if(!I)return I;const J=[...I.points,E].sort((H,q)=>H.time-q.time);return{...I,points:J}})},[]),_u=_e.useCallback(E=>{Br(I=>{if(!I)return I;const J=I.points.filter((H,q)=>q!==E);return{...I,points:J}})},[]),Vu=_e.useCallback((E,I,J,H)=>{Br(q=>{if(!q)return q;const re=[...q.points],ke=re[E];return ke.controlPoints||(ke.controlPoints={cp1:{x:0,y:0},cp2:{x:0,y:0}}),ke.controlPoints[I]={x:J,y:H},{...q,points:re}})},[]),Fr=_e.useMemo(()=>ol(),[]),[Uu,Ku]=_e.useState(()=>Fr.getChangeVersion());_e.useEffect(()=>Fr.onEffectsChange(()=>{Ku(Fr.getChangeVersion())}),[Fr]);const Sl=_e.useMemo(()=>Fr.getAllEffects(),[Fr,Uu]),Ms=_e.useMemo(()=>{const E=Qt.timeline.tracks;let I=0;for(const J of E)for(const H of J.clips){const q=H.startTime+H.duration;q>I&&(I=q)}for(const J of ms){const H=J.startTime+J.duration;H>I&&(I=H)}for(const J of ss){const H=J.startTime+J.duration;H>I&&(I=H)}return I},[Qt.timeline.tracks,ms,ss]);l.useEffect(()=>{if(i.current)return;const E=el();t.current&&E.setCanvas(t.current),i.current=!0,P(!0)},[]),l.useEffect(()=>()=>{for(const E of Ws.current.values())E.input[Symbol.dispose]?.();Ws.current.clear(),Dt(),f.current&&(f.current.pause(),f.current.removeAttribute("src"),f.current.load(),f.current=null),v.current&&(URL.revokeObjectURL(v.current),v.current=null),A.current=null},[Dt]),_e.useLayoutEffect(()=>{const E=t.current;E&&(E.width!==$.width||E.height!==$.height)&&(E.width=$.width,E.height=$.height)},[$.width,$.height]),l.useEffect(()=>{V&&t.current&&el().setCanvas(t.current)},[V]),l.useEffect(()=>B.current||!t.current?void 0:((async()=>{try{const I=t.current;if(!I)return;const H=await Xm.getInstance().createRenderer({canvas:I,width:$.width,height:$.height,preferredRenderer:Gm()?"webgpu":"canvas2d"});L.current=H,B.current=!0,X(H.type),H.onDeviceLost(()=>{console.warn("[Preview] GPU device lost, attempting recovery..."),H.recreateDevice().then(q=>{q||(console.error("[Preview] Failed to recover GPU device"),X("canvas2d"))})})}catch(I){console.warn("[Preview] Failed to initialize GPU renderer:",I),X("canvas2d")}})(),()=>{L.current&&(L.current.destroy(),L.current=null,B.current=!1)}),[]),l.useEffect(()=>{if(L.current&&t.current){const E=t.current;(E.width!==$.width||E.height!==$.height)&&L.current.resize($.width,$.height)}},[$.width,$.height]);const qi=l.useRef(Hi),Lr=l.useRef(wt),Is=l.useRef(new Map),hn=l.useRef(new Map);l.useEffect(()=>{qi.current=Hi},[Hi]),l.useEffect(()=>{Jt||(Lr.current=wt)},[Jt,wt]);const hr=l.useCallback(()=>{const E=Is.current;for(const[,I]of E)I.input[Symbol.dispose]?.();Is.current=new Map;for(const[,I]of hn.current)I.close();hn.current=new Map},[]),$r=l.useCallback(()=>{if(k.current){try{k.current.stop()}catch{}k.current.disconnect(),k.current=null}b.current&&(b.current.stopScheduler(),b.current.stopAllClips())},[]);l.useEffect(()=>{N.current&&(N.current.gain.value=O?0:1),b.current&&b.current.setPreviewMuted(O)},[O]);const Zs=l.useCallback(async(E,I,J,H,q,re,ke,ee="all",le=null)=>{const ne=I.map((ce,ie)=>({track:ce,originalIndex:ie})).filter(({track:ce})=>(ce.type==="video"||ce.type==="image")&&!ce.hidden).map(({originalIndex:ce})=>ce),Re=ne.length>0?Math.min(...ne):1/0,oe=ne.length>0?Math.max(...ne):-1,me=I.map((ce,ie)=>({track:ce,originalIndex:ie})).filter(({track:ce})=>(ce.type==="text"||ce.type==="graphics")&&!ce.hidden).filter(({originalIndex:ce})=>ee==="below-video"?ce>oe:ee==="above-video"?ceie.originalIndex-ce.originalIndex);for(const{track:ce}of me)if(ce.type==="graphics"){const ie=J.filter(Z=>Z.trackId===ce.id);for(const Z of ie)Gr(E,Z,re,ke,q)}else if(ce.type==="text"){const ie=H.filter(Z=>Z.trackId===ce.id);for(const Z of ie)await ko(E,Z,re,ke,q,le)}},[]),Yu=l.useCallback(async E=>{const J=ye.current.filter(ke=>ke.type==="audio"&&!ke.hidden);b.current||(b.current=Nn());const H=b.current;H.setPreviewMuted(O);const q=ba(),re=[];for(const ke of J)if(H.createTrack({trackId:ke.id,volume:1,pan:0,muted:ke.muted||!1,solo:ke.solo||!1,effects:[]}),!ke.muted)for(const ee of ke.clips){const le=ee.startTime+ee.duration;if(E>=ee.startTime&&EVe.enabled),ce=await C(oe,Re,me);H.updateTrackEffects(ke.id,ce.effects);const ie=E-ee.startTime,Z=q.isReverse(ee.id);let xe=(ee.inPoint||0)+ie;Z&&(xe=oe.duration-xe,xe=Math.max(0,xe)),re.push({clipId:ee.id,trackId:ke.id,audioBuffer:ce.audioBuffer,startTime:ee.startTime,endTime:le,mediaOffset:xe,volume:ee.volume??1,volumeAutomation:z(ee),pan:0,effects:ce.effects,speed:ee.speed??1})}}re.length>0&&(await H.resume(),H.scheduleClips(re))},[Lt,C,M,z,O]),Vn=l.useCallback(async()=>{const E=ye.current,I=E.filter(ke=>ke.type==="audio"&&!ke.hidden),J=E.filter(ke=>(ke.type==="video"||ke.type==="image")&&!ke.hidden);b.current||(b.current=Nn());const q=b.current.getAudioContext(),re=[...I,...J];for(const ke of re)for(const ee of ke.clips){const le=w(ee.mediaId,ee.audioTrackIndex);let ne=j.current.get(le);if(!ne){const Re=Lt(ee.mediaId);if(!Re?.blob)continue;try{ne=await S(q,Re.blob,ee.audioTrackIndex??0),ne&&j.current.set(le,ne)}catch{ne=null}}if(ne){const Re=M(ee).filter(oe=>oe.enabled);if(Re.length>0)try{await C(ne,le,Re)}catch(oe){console.warn(`[Preview] Failed to pre-process audio effects for clip ${ee.id}:`,oe)}}}},[Lt,C,M]),Un=l.useCallback(E=>{const J=ye.current.filter(q=>(q.type==="audio"||q.type==="video")&&!q.hidden&&!q.muted),H=[];for(const q of J)for(const re of q.clips){const ke=re.startTime+re.duration;if(ke<=E||re.startTime>E+1)continue;const ee=j.current.get(w(re.mediaId,re.audioTrackIndex));if(!ee)continue;const le=M(re).filter(ce=>ce.enabled),ne=lo(le),{profileAwareNoiseEffects:Re,realtimeEffects:oe}=Kl(ne);let ze=ee,me=ne;if(Re.length>0){const ce=`${w(re.mediaId,re.audioTrackIndex)}:profile-denoise:${T(Re)}`,ie=y.current.get(ce);ie&&(ze=ie,me=oe)}H.push({clipId:re.id,trackId:q.id,audioBuffer:ze,startTime:re.startTime,endTime:ke,mediaOffset:re.inPoint||0,volume:re.volume??1,volumeAutomation:z(re),pan:0,effects:me,speed:re.speed??1})}return H},[T,M,z]),Kn=l.useCallback(async(E,I,J,H)=>{const q=Lt(E.mediaId);if(!q?.blob)return null;const re=Ma(),ke=re.hasStabilized(E.id)?re.getStabilizedBlob(E.id):q.blob;if(q.type==="image")try{return await createImageBitmap(q.blob)}catch{return null}const ee=++p.current,le=()=>ee!==p.current;return m.current&&(clearTimeout(m.current),m.current=null),d.current&&(clearTimeout(d.current),d.current=null),u.current?.(null),u.current=null,new Promise(ne=>{u.current=ne,d.current=setTimeout(async()=>{if(d.current=null,u.current=null,le()){ne(null);return}try{const Re=I-E.startTime,ze=ba().getSourceTimeAtPlaybackTime(E.id,Re),me=re.hasStabilized(E.id),ce=me?ze:(E.inPoint||0)+ze,ie=me?`${E.mediaId}:stabilized`:E.mediaId;let Z=Ft.current.get(ie);if(!Z){const yt=URL.createObjectURL(ke),ut=document.createElement("video");if(ut.src=yt,ut.muted=!0,ut.playsInline=!0,ut.preload="metadata",ut.crossOrigin="anonymous",await new Promise((De,ft)=>{const Wt=setTimeout(()=>ft(new Error("Video load timeout")),1e4);ut.onloadedmetadata=()=>{clearTimeout(Wt),De()},ut.onerror=()=>{clearTimeout(Wt),ft(new Error("Video load failed"))}}),le()){Qe({video:ut,url:yt}),ne(null);return}for(Z={video:ut,url:yt,lastUsed:Date.now()},Ft.current.set(ie,Z);Ft.current.size>2;)Ds()}Z.lastUsed=Date.now();const{video:xe}=Z,Ve=Math.max(0,Math.min(ce,xe.duration-.001)),Mt=Ve<=0&&xe.duration>.002?.001:Ve;if((Math.abs(xe.currentTime-Mt)>.01||xe.readyState{let ut=!1,De=null;const ft=()=>{ut||(ut=!0,De&&clearTimeout(De),xe.removeEventListener("seeked",ft),yt())};xe.addEventListener("seeked",ft),De=setTimeout(()=>{ut||(ut=!0,xe.removeEventListener("seeked",ft),yt())},250)})),le()){ne(null);return}if(await new Promise(yt=>{if(!("requestVideoFrameCallback"in xe)){yt();return}let ut=!1,De=null;const ft=()=>{ut||(ut=!0,De&&clearTimeout(De),yt())};xe.requestVideoFrameCallback(ft),De=setTimeout(ft,300)}),le()){ne(null);return}if(await new Promise(yt=>{if(xe.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){yt();return}let ut=!1,De=null;const ft=()=>{ut||(ut=!0,De&&clearTimeout(De),xe.removeEventListener("loadeddata",ft),xe.removeEventListener("canplay",ft),yt())};xe.addEventListener("loadeddata",ft),xe.addEventListener("canplay",ft),De=setTimeout(ft,250)}),le()){ne(null);return}const St=document.createElement("canvas");St.width=J,St.height=H;const bt=St.getContext("2d");if(!bt){ne(null);return}const Bt=xe.videoWidth/xe.videoHeight,Ot=J/H;let te=J,$e=H,xt=0,Je=0;Bt>Ot?($e=J/Bt,Je=(H-$e)/2):(te=H*Bt,xt=(J-te)/2),bt.fillStyle=Ne.current,bt.fillRect(0,0,J,H),bt.drawImage(xe,xt,Je,te,$e);const _t=await createImageBitmap(St);if(le()){_t.close(),ne(null);return}us(),ne(_t)}catch{const Re=Ft.current.get(E.mediaId);Re&&(Qe(Re),Ft.current.delete(E.mediaId)),us(),ne(null)}},50)})},[Ds,Lt,Qe,us]),ea=l.useCallback(async E=>{const I=t.current;if(!I)return!1;(I.width===0||I.height===0)&&(I.width=$.width,I.height=$.height);const J=I.getContext("2d");if(!J)return!1;(!c.current||c.current.width!==I.width||c.current.height!==I.height)&&(c.current=new OffscreenCanvas(I.width,I.height),h.current=c.current.getContext("2d"));const H=h.current;if(!H)return!1;const q=He.filter(oe=>(oe.type==="video"||oe.type==="image")&&!oe.hidden);let re=!1,ke=!0;const ee=Aa(ss,E),le=Qa(ms,E),ne=vo(E,He);if(ne)try{const oe=await Kn(ne.clipA,E,I.width,I.height),ze=await Kn(ne.clipB,E,I.width,I.height);if(oe&&ze){const me=await Tr(ne.clipA.id,oe),ce=await Tr(ne.clipB.id,ze),ie=me.width>0&&me.height>0?me:oe,Z=ce.width>0&&ce.height>0?ce:ze,xe=await $b(ne,ie,Z);xe&&xe.width>0&&xe.height>0&&(ke&&(H.fillStyle=Ne.current,H.fillRect(0,0,I.width,I.height),ke=!1),await Zs(H,He,ee,le,E,I.width,I.height,"below-video"),H.drawImage(xe,0,0),await Zs(H,He,ee,le,E,I.width,I.height,"above-video",Hr(le)?xe:null),me!==oe&&me.close(),ce!==ze&&ce.close(),oe.close(),ze.close(),xe.close(),re=!0)}else if(oe){const me=await Tr(ne.clipA.id,oe),ce=me.width>0&&me.height>0?me:oe;ke&&(H.fillStyle=Ne.current,H.fillRect(0,0,I.width,I.height),ke=!1),await Zs(H,He,ee,le,E,I.width,I.height,"below-video"),H.drawImage(ce,0,0),await Zs(H,He,ee,le,E,I.width,I.height,"above-video",Hr(le)?ce:null),me!==oe&&me.close(),oe.close(),re=!0}else if(ze){const me=await Tr(ne.clipB.id,ze),ce=me.width>0&&me.height>0?me:ze;ke&&(H.fillStyle=Ne.current,H.fillRect(0,0,I.width,I.height),ke=!1),await Zs(H,He,ee,le,E,I.width,I.height,"below-video"),H.drawImage(ce,0,0),await Zs(H,He,ee,le,E,I.width,I.height,"above-video",Hr(le)?ce:null),me!==ze&&me.close(),ze.close(),re=!0}}catch(oe){console.warn("[Preview] Transition render failed:",oe)}if(!re){const oe=q.some(ie=>ie.clips.some(Z=>E>=Z.startTime&&E0||le.length>0)&&(H.fillStyle=oe?"#000000":Ce?"#0f0f11":"#ffffff",H.fillRect(0,0,I.width,I.height),ke=!1);const ze=He.map((ie,Z)=>({track:ie,originalIndex:Z})).filter(({track:ie})=>(ie.type==="video"||ie.type==="image"||ie.type==="text"||ie.type==="graphics")&&!ie.hidden).sort((ie,Z)=>Z.originalIndex-ie.originalIndex);let me=null;const ce=Hr(le);for(const{track:ie}of ze)if(ie.type==="video"||ie.type==="image")for(const Z of ie.clips){const xe=Z.startTime,Ve=Z.startTime+Z.duration;if(E>=xe&&E0&&xt.height>0?(Ta(H,xt,$e,I.width,I.height),re=!0):(Ta(H,Mt,$e,I.width,I.height),re=!0)}catch{Ta(H,Mt,$e,I.width,I.height),re=!0}finally{xt&&xt!==Mt&&xt.close()}ce&&(me?.close(),me=await wo(H,I.width,I.height)),Mt.close()}}}else if(ie.type==="graphics"){const Z=ee.filter(xe=>xe.trackId===ie.id);for(const xe of Z)Gr(H,xe,I.width,I.height,E),re=!0}else if(ie.type==="text"){const Z=le.filter(xe=>xe.trackId===ie.id);for(const xe of Z)await ko(H,xe,I.width,I.height,E,me),re=!0}me?.close()}const Re=Ja(ps,E);if(Re.length>0&&H)for(const oe of Re)Za(H,oe,I.width,I.height,E);return re&&c.current&&(J.clearRect(0,0,I.width,I.height),J.drawImage(c.current,0,0)),re},[He,Lt,Kn,$.width,$.height,ms,ss,ps,Zs,Ce]),Al=l.useRef(ea);l.useEffect(()=>{Al.current=ea},[ea]);const Tl=l.useRef(Jt);l.useEffect(()=>{Tl.current=Jt},[Jt]);const Ml=l.useRef(wt);l.useEffect(()=>{Ml.current=wt},[wt]),l.useEffect(()=>(Hc(()=>{Tl.current||Al.current(Ml.current)}),()=>Hc(null)),[]);const El=l.useCallback(E=>{const I=t.current;if(!I)return;(I.width===0||I.height===0)&&(I.width=$.width,I.height=$.height);const J=I.getContext("2d");if(!J)return;const H=Ce?"#0f0f11":"#ffffff",q=Ce?"#52525b":"#a1a1aa",re=Ce?"#ffffff":"#18181b",ke=Ce?"#a1a1aa":"#71717a",ee=Aa(ss,E),le=Qa(ms,E),Re=He.filter(Z=>(Z.type==="video"||Z.type==="image")&&!Z.hidden).some(Z=>Z.clips.some(xe=>E>=xe.startTime&&E({track:Z,originalIndex:xe})).filter(({track:Z})=>(Z.type==="video"||Z.type==="image"||Z.type==="text"||Z.type==="graphics")&&!Z.hidden).sort((Z,xe)=>xe.originalIndex-Z.originalIndex);for(const{track:Z}of ze)if(Z.type==="video"||Z.type==="image")for(const xe of Z.clips){const Ve=xe.startTime,Mt=xe.startTime+xe.duration;if(E>=Ve&&EVe.trackId===Z.id);for(const Ve of xe)Gr(J,Ve,I.width,I.height,E),oe=!0}else if(Z.type==="text"){const xe=le.filter(Ve=>Ve.trackId===Z.id);for(const Ve of xe)Ri(J,Ve,I.width,I.height,E),oe=!0}const me=Ja(ps,E);for(const Z of me)Za(J,Z,I.width,I.height,E);const ie=He.filter(Z=>Z.type==="audio"&&!Z.hidden).some(Z=>Z.clips.some(xe=>E>=xe.startTime&&E{const I=He,J=I.filter(le=>le.type==="video"&&!le.hidden),H=[],q=ba();for(const le of J)for(const ne of le.clips)if(ne.startTime+ne.duration>E){const Re=Lt(ne.mediaId);if(Re?.blob&&Re.type==="video"){const oe=q.getClipSpeed(ne.id),ze=q.isReverse(ne.id);if(oe!==1||ze||wu(ne.id))return{canUse:!1,clips:[]};H.push({clip:ne,mediaItem:Re})}}if(I.some(le=>(le.type==="audio"||le.type==="video")&&!le.hidden&&le.clips.some(ne=>ne.startTime+ne.duration<=E?!1:lo(M(ne)).some(Re=>Re.enabled))))return{canUse:!1,clips:[]};if(H.length===0)return{canUse:!1,clips:[]};H.sort((le,ne)=>le.clip.startTime-ne.clip.startTime);for(let le=0;lele.type==="image"&&!le.hidden),ee=[];return ke.forEach(le=>{const ne=I.indexOf(le);for(const Re of le.clips)ee.push({clip:Re,trackIndex:ne})}),{canUse:!0,clips:H,imageClips:ee}},[He,Lt,ms,ss,M]),Pl=l.useCallback(async(E,I,J,H)=>{const q=t.current;if(!q||E.length===0)return H(),()=>{};const re=q.getContext("2d");if(!re)return H(),()=>{};g.current=!0;const ke=new Map;for(const{clip:te}of I){const $e=Lt(te.mediaId);if($e?.type==="image"&&$e.blob)try{const xt=await createImageBitmap($e.blob);ke.set(te.id,xt)}catch(xt){console.warn(`Failed to cache image bitmap for ${te.id}:`,xt)}}try{await Vn()}catch(te){console.warn("[Preview] Audio warmup failed:",te)}const ee=new Map,le=new Map,ne=(te,$e)=>{const _t=Ma().hasStabilized(te.id)?`stabilized:${te.id}`:te.mediaId,yt=le.get(_t);if(yt)return yt;const ut=ee.get(_t)?.video;if(ut&&ut.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA||!$e.blob)return Promise.resolve();const De=Ma(),ft=De.hasStabilized(te.id),Wt=ft?De.getStabilizedBlob(te.id):$e.blob,Vt=ft?`stabilized:${te.id}`:te.mediaId,xa=URL.createObjectURL(Wt),as=document.createElement("video");as.src=xa,as.muted=!0,as.playsInline=!0,as.preload="auto",ee.set(Vt,{video:as,url:xa});const Ca=new Promise(Wn=>{let Xa=!1;const os=()=>{Xa||(Xa=!0,as.onloadedmetadata=null,as.onloadeddata=null,as.oncanplay=null,as.onerror=null,le.delete(Vt),Wn())};as.onloadeddata=os,as.oncanplay=os,as.onloadedmetadata=()=>{as.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&os()},as.onerror=os,as.load(),setTimeout(os,1200)});return le.set(Vt,Ca),Ca},Re=E.find(({clip:te})=>J>=te.startTime&&J{});const oe=ti();oe.setDuration(Ms),oe.seek(J),b.current||(b.current=Nn());const ze=b.current;ze.setPreviewMuted(O);const me=He.filter(te=>(te.type==="audio"||te.type==="video")&&!te.hidden);for(const te of me)ze.createTrack({trackId:te.id,volume:1,pan:0,muted:te.muted||!1,solo:te.solo||!1,effects:[]});await ze.resume(),ze.seekTo(J),await oe.play(),ze.startScheduler(Un);let ce=!0,ie=null,Z=null;const xe=te=>{for(const{clip:$e,mediaItem:xt}of E)if(te>=$e.startTime&&te<$e.startTime+$e.duration)return{clip:$e,mediaItem:xt};return null},Ve=te=>{const $e=[...E].sort((Je,_t)=>Je.clip.startTime-_t.clip.startTime),xt=$e.findIndex(({clip:Je})=>Je.id===te);return xt>=0?$e[xt+1]??null:null},Mt=te=>E.find(({clip:$e})=>$e.id===te)??null,St=async(te,$e=300)=>{te.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA||await new Promise(xt=>{let Je=!1,_t=null;const yt=()=>{Je||(Je=!0,_t&&clearTimeout(_t),te.removeEventListener("loadeddata",yt),te.removeEventListener("canplay",yt),xt())};te.addEventListener("loadeddata",yt),te.addEventListener("canplay",yt),_t=setTimeout(yt,$e)})},bt=async(te,$e,xt)=>{const Je=ba(),_t=Math.max(0,Math.min($e.duration,xt-$e.startTime)),yt=Je.getSourceTimeAtPlaybackTime($e.id,_t),ut=Math.max($e.inPoint,Math.min($e.outPoint,$e.inPoint+yt)),ft=Ma().hasStabilized($e.id)?ut-$e.inPoint:ut;let Wt=te.readyState.1?(Wt=!0,await new Promise(Vt=>{let xa=!1,as=null;const Ca=()=>{xa||(xa=!0,as&&clearTimeout(as),te.removeEventListener("seeked",Ca),Vt())};te.addEventListener("seeked",Ca),as=setTimeout(Ca,250),te.currentTime=ft})):te.readyState{if(!ce||!g.current)return;const te=oe.currentTime;if(te>=Ms){Ot(),Js(0),Lr.current=0,H();return}if(!oe.isPlaying){Ot(),Se.current||H();return}const $e=vo(te,ye.current);if($e){const et=Mt($e.clipA.id),Ht=Mt($e.clipB.id);if(et&&Ht){if(await Promise.all([ne(et.clip,et.mediaItem),ne(Ht.clip,Ht.mediaItem)]),!ce||!g.current)return;const _s=Ma().hasStabilized(et.clip.id)?`stabilized:${et.clip.id}`:et.clip.mediaId,Xe=Ma().hasStabilized(Ht.clip.id)?`stabilized:${Ht.clip.id}`:Ht.clip.mediaId,At=ee.get(_s)?.video,Nt=ee.get(Xe)?.video;if(At&&Nt){if(await Promise.all([bt(At,et.clip,te),bt(Nt,Ht.clip,te)]),!ce||!g.current)return;At.paused&&At.play().catch(()=>{}),Nt.paused&&Nt.play().catch(()=>{});const Ut=await Wc($e,At,Nt);if(!ce||!g.current)return;re.fillStyle=Ne.current,re.fillRect(0,0,q.width,q.height),re.drawImage(Ut,0,0,q.width,q.height);const Rt=Aa(Y.current,te),tt=Qa(we.current,te);(Rt.length>0||tt.length>0)&&await Zs(re,ye.current,Rt,tt,te,q.width,q.height,"all");const It=Ja(ps,te);for(const Pt of It)Za(re,Pt,q.width,q.height,te);const it=performance.now();it-Ue.current>=Le&&(Ue.current=it,Js(te)),ie=requestAnimationFrame(()=>{Bt()});return}}}const xt=xe(te);if(!xt){re.fillStyle=Ne.current,re.fillRect(0,0,q.width,q.height);const et=[...I].sort((Nt,Ut)=>Ut.trackIndex-Nt.trackIndex);for(const{clip:Nt}of et)if(te>=Nt.startTime&&te{for(const it of ye.current){const Pt=it.clips.find(Tt=>Tt.id===Nt.id);if(Pt)return Pt}return Nt})(),tt=te-Nt.startTime,It=ir(Rt.transform||Ks,Rt.keyframes,tt);Ta(re,Ut,It,q.width,q.height)}}const Ht=Aa(Y.current,te),_s=Qa(we.current,te);(Ht.length>0||_s.length>0)&&await Zs(re,ye.current,Ht,_s,te,q.width,q.height,"all");const Xe=Ja(ps,te);for(const Nt of Xe)Za(re,Nt,q.width,q.height,te);const At=performance.now();At-Ue.current>=Le&&(Ue.current=At,Js(te)),ie=requestAnimationFrame(()=>{Bt()});return}const{clip:Je,mediaItem:_t}=xt,De=Ma().hasStabilized(Je.id)?`stabilized:${Je.id}`:Je.mediaId,ft=ee.get(De);if(!ft){if(await ne(Je,_t),!ce||!g.current)return;const et=performance.now();et-Ue.current>=Le&&(Ue.current=et,Js(te)),ie=requestAnimationFrame(()=>{Bt()});return}const{video:Wt}=ft;Z!==Je.id&&(Z=Je.id);const Vt=(()=>{for(const et of ye.current){const Ht=et.clips.find(_s=>_s.id===Je.id);if(Ht)return Ht}return Je})(),xa=te-Vt.startTime,Ca=ba().getSourceTimeAtPlaybackTime(Vt.id,xa),Wn=Math.max(Vt.inPoint,Math.min(Vt.outPoint,Vt.inPoint+Ca));if(await bt(Wt,Vt,te),!ce||!g.current)return;if(Wt.paused&&Wt.play().catch(()=>{}),Vt.startTime+Vt.duration-te<=1){const et=Ve(Vt.id);et&&ne(et.clip,et.mediaItem).catch(()=>{})}let os=ir(Vt.transform||Ks,Vt.keyframes,xa);if(Vt.emphasisAnimation&&Vt.emphasisAnimation.type!=="none"){const et=Mn(Vt.emphasisAnimation,xa);os={...os,opacity:os.opacity*et.opacity,scale:{x:os.scale.x*et.scale*et.scaleX,y:os.scale.y*et.scale*et.scaleY},position:{x:os.position.x+et.offsetX*q.width,y:os.position.y+et.offsetY*q.height},rotation:os.rotation+et.rotation}}re.fillStyle=Ne.current,re.fillRect(0,0,q.width,q.height);const _r=[...I].sort((et,Ht)=>Ht.trackIndex-et.trackIndex);for(const{clip:et}of _r)if(te>=et.startTime&&te{for(const Nt of ye.current){const Ut=Nt.clips.find(Rt=>Rt.id===et.id);if(Ut)return Ut}return et})(),Xe=te-et.startTime,At=ir(_s.transform||Ks,_s.keyframes,Xe);Ta(re,Ht,At,q.width,q.height)}}const ro=Y.current,qn=Aa(ro,te),gr=Qa(we.current,te),Qn=an(),Jn=Qn?.isInitialized()&&Qn.getSettings(Je.id).enabled;let Sa=Wt;if(Jn)try{const et=await createImageBitmap(Wt),Ht=await Tr(Je.id,et);if(!ce||!g.current){Ht!==et&&Ht.close(),et.close();return}Ht!==et&&et.close(),Sa=Ht}catch{Sa=Wt}let no=os;const Zn=Ma();Vt.stabilization?.enabled&&Vt.stabilization.analyzed&&!Zn.hasStabilized(Vt.id)&&(no=jo(Vt,os,Wn,q.width,q.height,Wt.videoWidth,Wt.videoHeight)),Ta(re,Sa,no,q.width,q.height),Sa!==Wt&&Sa instanceof ImageBitmap&&Sa.close();const br=Hr(gr)?await wo(re,q.width,q.height):null;(qn.length>0||gr.length>0)&&await Zs(re,ye.current,qn,gr,te,q.width,q.height,"all",br),br?.close();const ei=Ja(ps,te);for(const et of ei)Za(re,et,q.width,q.height,te);const bn=performance.now();bn-Ue.current>=Le&&(Ue.current=bn,Js(te)),ie=requestAnimationFrame(()=>{Bt()})},Ot=()=>{ce=!1,g.current=!1,ie&&cancelAnimationFrame(ie);for(const[,te]of ee)Qe(te);ee.clear();for(const[,te]of ke)te.close();ke.clear(),f.current=null,A.current=null,oe.stop(),ze.stopScheduler()};return ie=requestAnimationFrame(()=>{Bt()}),Ot},[Ms,ps,Lt,Un,O,Vn,Qe,Zs,Js,He]);l.useEffect(()=>{const E=t.current;if(!E)return;if((E.width===0||E.height===0)&&(E.width=$.width,E.height=$.height),!Jt){n.current&&(cancelAnimationFrame(n.current),n.current=null),hr(),$r();return}if(Ms<=0){Qs();return}let I=!0,J=null;const H=Lr.current,q=me=>{const ce=ye.current,ie=[];return ce.forEach((Z,xe)=>{if((Z.type==="video"||Z.type==="image")&&!Z.hidden)for(const Ve of Z.clips)me>=Ve.startTime&&meZ.trackIndex-xe.trackIndex)},re=async(me,ce)=>{const ie=Lt(me.mediaId);if(!ie?.blob||ie.type==="image")return null;try{const Z=await zi(()=>import("./index-DjtrfS0G.js"),[]),{Input:xe,ALL_FORMATS:Ve,BlobSource:Mt,CanvasSink:St}=Z,bt=new xe({source:new Mt(ie.blob),formats:Ve}),Bt=await bt.getPrimaryVideoTrack();if(!Bt||!await Bt.canDecode())return bt[Symbol.dispose]?.(),null;const te=new St(Bt,{poolSize:3});return{input:bt,sink:te,mediaId:me.mediaId,clipId:me.id,trackIndex:ce}}catch(Z){return console.error(`[Preview] Failed to init resources for clip ${me.id}:`,Z),null}},ke=async()=>{const ce=ye.current.filter(ie=>ie.type==="image"&&!ie.hidden);for(const ie of ce)for(const Z of ie.clips){if(hn.current.has(Z.id))continue;const xe=Lt(Z.mediaId);if(xe?.type==="image"&&xe.blob)try{const Ve=await createImageBitmap(xe.blob);hn.current.set(Z.id,Ve)}catch(Ve){console.warn(`[Preview] Failed to pre-cache image clip ${Z.id}:`,Ve)}}},ee=async()=>{const me=q(H),ce=Qa(we.current,H),ie=Aa(Y.current,H),xe=ye.current.filter(De=>De.type==="audio"&&!De.hidden).some(De=>De.clips.some(ft=>H>=ft.startTime&&H0||ce.length>0||ie.length>0||xe)&&Ms<=0){Qs();return}ke().catch(De=>{console.warn("[Preview] Image warmup failed:",De)});for(const{clip:De,trackIndex:ft}of me)if(!Is.current.has(De.id)){const Wt=await re(De,ft);Wt&&Is.current.set(De.id,Wt)}const St=ce.length>0||ie.length>0;if(Is.current.size===0&&!St&&!xe&&Ms<=0){Qs();return}try{await Vn()}catch(De){console.warn("[Preview] Audio warmup failed:",De)}b.current||(b.current=Nn());const bt=b.current;bt.setPreviewMuted(O);const Bt=ye.current.filter(De=>(De.type==="audio"||De.type==="video")&&!De.hidden);for(const De of Bt)bt.createTrack({trackId:De.id,volume:1,pan:0,muted:De.muted||!1,solo:De.solo||!1,effects:[]});await bt.resume();const Ot=E.getContext("2d");if(!Ot){console.error("[Preview] Failed to get 2D context"),Qs();return}(!c.current||c.current.width!==E.width||c.current.height!==E.height)&&(c.current=new OffscreenCanvas(E.width,E.height),h.current=c.current.getContext("2d"));const te=h.current;if(!te){console.error("[Preview] Failed to get offscreen 2D context"),Qs();return}const $e=ti();$e.setDuration(Ms),$e.seek(H),bt.seekTo(H),await $e.play(),bt.startScheduler(Un);const xt=1e3/30;let Je=performance.now(),_t=0,yt=!1;const ut=async()=>{if(!I){hr(),$e.pause();return}if(yt)return;yt=!0;const De=$e.currentTime;try{if(De>=Ms){yt=!1,hr(),$r(),$e.stop(),Js(0),Lr.current=0,Qs();return}if(!$e.isPlaying){yt=!1,hr(),$r(),Se.current||Qs();return}const ft=q(De),Wt=Qa(we.current,De),Vt=Aa(Y.current,De),as=ye.current.filter(Xe=>Xe.type==="audio"&&!Xe.hidden).some(Xe=>Xe.clips.some(At=>De>=At.startTime&&De0||Wt.length>0||Vt.length>0||as)){const Xe=le(De),At=ne(De),Nt=Re(De),Ut=oe(De),Rt=[Xe,At,Nt,Ut].filter(It=>It!==null&&It0?Math.min(...Rt):null;if(tt!==null){$e.seek(tt),bt.seekTo(tt),yt=!1,n.current=requestAnimationFrame(ut);return}else{yt=!1,hr(),$r(),Se.current||($e.stop(),Js(0),Lr.current=0,Qs());return}}for(const{clip:Xe,trackIndex:At}of ft)if(!Is.current.has(Xe.id)){const Nt=await re(Xe,At);Nt&&Is.current.set(Xe.id,Nt)}const Xa=vo(De,ye.current),os=Aa(Y.current,De),_r=Qa(we.current,De);if(Xa){const Xe=ye.current,At=Rt=>{for(let tt=0;ttit.id===Rt);if(It)return{clip:It,trackIndex:tt}}return null},Nt=At(Xa.clipA.id),Ut=At(Xa.clipB.id);if(Nt&&Ut){for(const it of[Nt,Ut])if(!Is.current.has(it.clip.id)){const Pt=await re(it.clip,it.trackIndex);Pt&&Is.current.set(it.clip.id,Pt)}const Rt=async it=>{const Pt=Is.current.get(it.id);if(!Pt)return null;const Tt=ba(),Zt=De-it.startTime,sa=Tt.getSourceTimeAtPlaybackTime(it.id,Zt),yr=Math.max(it.inPoint,Math.min(it.outPoint,(it.inPoint||0)+sa));try{const Bs=await Pt.sink.getCanvas(yr);return Bs?.canvas?Bs.canvas:null}catch(Bs){return console.warn(`[Preview] Transition decode failed for clip ${it.id}:`,Bs),null}},[tt,It]=await Promise.all([Rt(Nt.clip),Rt(Ut.clip)]);if(tt&&It)try{const it=await Wc(Xa,tt,It);te.fillStyle=Ne.current,te.fillRect(0,0,E.width,E.height),te.drawImage(it,0,0,E.width,E.height);for(const Bs of os)Gr(te,Bs,E.width,E.height,De);for(const Bs of _r)Ri(te,Bs,E.width,E.height,De);const Pt=Ja(je.current,De);for(const Bs of Pt)Za(te,Bs,E.width,E.height,De);Ot.drawImage(c.current,0,0),_t++,$e.reportVideoTime(De);const Tt=performance.now();Tt-Ue.current>=Le&&(Ue.current=Tt,Js(De));const Zt=Tt-Je,sa=xt/qi.current,yr=Math.max(0,sa-Zt);Je=Tt,yt=!1,I&&(yr>0?setTimeout(()=>{I&&(n.current=requestAnimationFrame(ut))},yr):n.current=requestAnimationFrame(ut));return}catch(it){console.warn("[Preview] Transition render failed, falling back to normal compositing:",it)}}}const ro=new Set(ft.map(Xe=>Xe.clip.id));for(const[Xe,At]of Is.current)ro.has(Xe)||(At.input[Symbol.dispose]?.(),Is.current.delete(Xe));const qn=[...ft].sort((Xe,At)=>At.trackIndex-Xe.trackIndex),gr=Hr(_r),Qn=L.current?.type==="webgpu"&&!gr,Jn=[],Sa=[];for(const{clip:Xe,track:At}of qn){if(!I)continue;const Nt=De-Xe.startTime;let Ut=ir(Xe.transform||Ks,Xe.keyframes,Nt);if(Xe.emphasisAnimation&&Xe.emphasisAnimation.type!=="none"){const Rt=Mn(Xe.emphasisAnimation,Nt);Ut={...Ut,opacity:Ut.opacity*Rt.opacity,scale:{x:Ut.scale.x*Rt.scale*Rt.scaleX,y:Ut.scale.y*Rt.scale*Rt.scaleY},position:{x:Ut.position.x+Rt.offsetX*E.width,y:Ut.position.y+Rt.offsetY*E.height},rotation:Ut.rotation+Rt.rotation}}if(At.type==="image"){const Rt=hn.current.get(Xe.id);Rt&&Jn.push({clip:Xe,transform:Ut,frame:Rt});continue}Sa.push((async()=>{const Rt=Is.current.get(Xe.id);if(!Rt)return null;const It=ba().getSourceTimeAtPlaybackTime(Xe.id,Nt),it=Math.max(Xe.inPoint,Math.min(Xe.outPoint,(Xe.inPoint||0)+It));try{const Pt=await Rt.sink.getCanvas(it);if(!I)return null;if(Pt?.canvas){const Tt=await qb(Xe.id,Pt.canvas,Qn),Zt=jo(Xe,Ut,it,E.width,E.height,Tt.frame.width,Tt.frame.height);return{clip:Xe,transform:Zt,frame:Tt.frame,cleanup:Tt.cleanup}}}catch(Pt){if((Pt instanceof Error?Pt.message:String(Pt)).includes("disposed")||!I)return null;console.warn(`[Preview] Failed to get frame for clip ${Xe.id}:`,Pt)}return null})())}const Zn=(await Promise.all(Sa)).filter(Xe=>Xe!==null),br=[...Jn,...Zn];if(br.length>0||Wt.length>0||Vt.length>0){te.fillStyle=Ne.current,te.fillRect(0,0,E.width,E.height);const Xe=ye.current,At=new Map;Xe.forEach((tt,It)=>{if((tt.type==="video"||tt.type==="image")&&!tt.hidden)for(const it of tt.clips)At.set(it.id,It)});const Nt=Xe.map((tt,It)=>({track:tt,originalIndex:It})).filter(({track:tt})=>(tt.type==="video"||tt.type==="image"||tt.type==="text"||tt.type==="graphics")&&!tt.hidden).sort((tt,It)=>It.originalIndex-tt.originalIndex);if(L.current&&L.current.type==="webgpu"&&!gr){const tt=[],It=[];for(const{track:it,originalIndex:Pt}of Nt)if(it.type==="video"){const Tt=br.filter(Zt=>At.get(Zt.clip.id)===Pt);for(const{transform:Zt,frame:sa}of Tt)sa instanceof ImageBitmap&&tt.push({bitmap:sa,transform:Zt})}else if(it.type==="image"){const Tt=br.filter(Zt=>At.get(Zt.clip.id)===Pt);for(const{transform:Zt,frame:sa}of Tt)Ta(te,sa,Zt,E.width,E.height)}else if(it.type==="graphics"){const Tt=os.filter(Zt=>Zt.trackId===it.id);for(const Zt of Tt)Gr(te,Zt,E.width,E.height,De)}else if(it.type==="text"){const Tt=_r.filter(Zt=>Zt.trackId===it.id);for(const Zt of Tt){const sa=new OffscreenCanvas(E.width,E.height),yr=sa.getContext("2d");if(yr){Ri(yr,Zt,E.width,E.height,De);const Bs=await createImageBitmap(sa);It.push(Bs),tt.push({bitmap:Bs,transform:{...Ks,opacity:1,scale:{x:1,y:1},position:{x:0,y:0},anchor:{x:0,y:0}}})}}}if(tt.length>0){const it=await Jb(L.current,tt,E.width,E.height);if(it)te.drawImage(it,0,0,E.width,E.height),it.close();else for(const Pt of tt)Ta(te,Pt.bitmap,Pt.transform,E.width,E.height)}for(const it of It)it.close()}else{let tt=null;for(const{track:It,originalIndex:it}of Nt)if(It.type==="video"||It.type==="image"){const Pt=br.filter(Tt=>At.get(Tt.clip.id)===it);for(const{transform:Tt,frame:Zt}of Pt)Ta(te,Zt,Tt,E.width,E.height),gr&&(tt?.close(),tt=await wo(te,E.width,E.height))}else if(It.type==="graphics"){const Pt=os.filter(Tt=>Tt.trackId===It.id);for(const Tt of Pt)Gr(te,Tt,E.width,E.height,De)}else if(It.type==="text"){const Pt=_r.filter(Tt=>Tt.trackId===It.id);for(const Tt of Pt)await ko(te,Tt,E.width,E.height,De,tt)}tt?.close()}for(const tt of Zn)tt.cleanup();const Rt=Ja(je.current,De);for(const tt of Rt)Za(te,tt,E.width,E.height,De);Ot.drawImage(c.current,0,0);try{o.current?.close(),o.current=await createImageBitmap(c.current)}catch{}}else if(o.current){te.drawImage(o.current,0,0,E.width,E.height);const Xe=Ja(je.current,De);for(const At of Xe)Za(te,At,E.width,E.height,De);Ot.drawImage(c.current,0,0)}_t++,$e.reportVideoTime(De);const ei=performance.now();ei-Ue.current>=Le&&(Ue.current=ei,Js(De));const bn=performance.now(),et=bn-Je,Ht=xt/qi.current,_s=Math.max(0,Ht-et);Je=bn,yt=!1,I&&(_s>0?setTimeout(()=>{I&&(n.current=requestAnimationFrame(ut))},_s):n.current=requestAnimationFrame(ut))}catch(ft){yt=!1,console.error("[Preview] Multi-track frame error:",ft),hr(),Qs()}};n.current=requestAnimationFrame(ut)},le=me=>{const ie=ye.current.filter(xe=>(xe.type==="video"||xe.type==="image")&&!xe.hidden);let Z=null;for(const xe of ie)for(const Ve of xe.clips)Ve.startTime>me&&(Z===null||Ve.startTime{const ce=we.current;let ie=null;for(const Z of ce)Z.startTime>me&&(ie===null||Z.startTime{const ce=Y.current;let ie=null;for(const Z of ce)Z.startTime>me&&(ie===null||Z.startTime{const ie=ye.current.filter(xe=>xe.type==="audio"&&!xe.hidden);let Z=null;for(const xe of ie)for(const Ve of xe.clips)Ve.startTime>me&&(Z===null||Ve.startTime{const me=Rl(H);if(me.canUse&&me.clips.length>0)try{return J=await Pl(me.clips,me.imageClips||[],H,()=>Qs()),J}catch(ce){console.warn("[Preview] Native video playback failed, falling back to MediaBunny:",ce)}await ee()})().catch(me=>{console.error("[Preview] startPlayback error:",me)}),()=>{I=!1,g.current=!1;const me=ti();(me.isPlaying||me.isPaused)&&(Lr.current=me.currentTime),J&&(J(),J=null),n.current&&(cancelAnimationFrame(n.current),n.current=null),f.current&&(f.current.pause(),f.current.removeAttribute("src"),f.current.load(),f.current=null),v.current&&(URL.revokeObjectURL(v.current),v.current=null),me.pause(),$r()}},[Jt,Rl,Pl,Ms,Js,Qs,Lt,hr,$r,Yu,Vn,Un,O,$.width,$.height]);const Qi=l.useRef(Qt.modifiedAt),zl=l.useRef(wt),fr=l.useRef(null),Ji=l.useRef(!1),Yn=l.useRef(null);l.useEffect(()=>{if(Jt)return;if(Q.current){Qi.current=Qt.modifiedAt;return}if(!t.current)return;const I=wt!==zl.current,J=Qt.modifiedAt!==Qi.current;Qi.current=Qt.modifiedAt,zl.current=wt;const H=x.current;(Math.abs(wt-H)>1||wt{if(Ji.current){Yn.current=ke;return}Ji.current=!0;try{await ea(ke)||El(ke)}finally{Ji.current=!1;const ee=Yn.current;ee!==null&&ee!==ke?(Yn.current=null,re(ee)):Yn.current=null}};return I?re(wt):J&&(fr.current&&clearTimeout(fr.current),fr.current=setTimeout(()=>{fr.current=null,re(wt)},150)),()=>{fr.current&&(clearTimeout(fr.current),fr.current=null)}},[wt,Jt,Wi,ea,El,Dt,Qt.modifiedAt,Ce]);const[Dl,Xu]=l.useState(0);l.useEffect(()=>{const E=()=>{y.current.clear(),b.current&&b.current.seekTo(ti().currentTime),Xu(I=>I+1)};return window.addEventListener("openreel:preview-invalidate",E),()=>window.removeEventListener("openreel:preview-invalidate",E)},[]),l.useEffect(()=>{Jt||Dl===0||!t.current||ea(wt)},[Dl,Jt,ea,wt]);const Zi=l.useMemo(()=>Ae.find(I=>I.type==="clip")?.id||null,[Ae]),wa=l.useMemo(()=>{if(!Zi)return null;for(const E of He){const I=E.clips.find(J=>J.id===Zi);if(I)return I}return null},[Zi,He]),$a=l.useMemo(()=>{const E=He.filter(I=>(I.type==="video"||I.type==="image")&&!I.hidden);for(const I of E)for(const J of I.clips){const H=J.startTime,q=J.startTime+J.duration;if(wt>=H&&wtAe.find(I=>I.type==="text-clip")?.id||null,[Ae]),fn=l.useMemo(()=>eo&&ms.find(E=>E.id===eo)||null,[eo,ms]),pa=fn,ta=l.useMemo(()=>{const E=wa||$a;if(!E||!t.current||!r.current)return null;const I=t.current,H=r.current.getBoundingClientRect(),q=I.getBoundingClientRect(),re=E.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,opacity:1,anchor:{x:.5,y:.5}},ke=Ye?{...re,position:Ye.position,scale:Ye.scale}:re,ee=$.width,le=$.height,ne=ee/le,Re=q.width/q.height;let oe,ze,me=0,ce=0;Re>ne?(ze=q.height,oe=ze*ne,me=(q.width-oe)/2):(oe=q.width,ze=oe/ne,ce=(q.height-ze)/2);const ie=oe/ee,Z=!re.fitMode||re.fitMode==="none"?"contain":re.fitMode,xe=Lt(E.mediaId),Ve=xe?.metadata?.width??ee,Mt=xe?.metadata?.height??le;let St,bt;if(Z==="stretch")St=ee,bt=le;else if(Z==="cover"){const ut=Ve/Mt;ut>ne?(bt=le,St=le*ut):(St=ee,bt=ee/ut)}else{const ut=Ve/Mt;ut>ne?(St=ee,bt=ee/ut):(bt=le,St=le*ut)}const Bt=St*ke.scale.x*ie,Ot=bt*ke.scale.y*ie,te=ke.position.x*ie,$e=ke.position.y*ie,xt=q.left-H.left+me,Je=q.top-H.top+ce,_t=xt+oe/2+te,yt=Je+ze/2+$e;return{x:_t-Bt/2,y:yt-Ot/2,width:Bt,height:Ot,centerX:_t,centerY:yt,displayScale:ie}},[wa,$a,$.width,$.height,_,Ye,Lt]),ka=l.useMemo(()=>{if(!fn||!t.current||!r.current)return null;const E=t.current,J=r.current.getBoundingClientRect(),H=E.getBoundingClientRect(),{transform:q,style:re,text:ke}=fn,ee=$.width,le=$.height,ne=ee/le,Re=H.width/H.height;let oe,ze,me=0,ce=0;Re>ne?(ze=H.height,oe=ze*ne,me=(H.width-oe)/2):(oe=H.width,ze=oe/ne,ce=(H.height-ze)/2);const ie=oe/ee,Z=ke.split(` +`),xe=re.fontSize*re.lineHeight,Ve=Z.length*xe,St=re.fontSize*Math.max(...Z.map(_t=>_t.length))*.6*q.scale.x*ie,bt=Ve*q.scale.y*ie,Bt=q.position.x*ee*ie,Ot=q.position.y*le*ie,te=H.left-J.left+me,$e=H.top-J.top+ce,xt=te+Bt,Je=$e+Ot;return{x:xt-St/2,y:Je-bt/2,width:St,height:bt,centerX:xt,centerY:Je,displayScale:ie,isTextClip:!0}},[fn,$.width,$.height,_]),Xn=l.useMemo(()=>Ae.find(I=>I.type==="shape-clip")?.id||null,[Ae]),Oa=l.useMemo(()=>Xn&&ss.find(E=>E.id===Xn)||null,[Xn,ss]),Na=Oa,[Il,to]=l.useState(null),Gn=l.useMemo(()=>Aa(ss,wt),[ss,wt]),_a=l.useMemo(()=>{if(!Oa||!t.current||!r.current)return null;const E=t.current,J=r.current.getBoundingClientRect(),H=E.getBoundingClientRect(),{transform:q}=Oa,re=$.width,ke=$.height,ee=re/ke,le=H.width/H.height;let ne,Re,oe=0,ze=0;le>ee?(Re=H.height,ne=Re*ee,oe=(H.width-ne)/2):(ne=H.width,Re=ne/ee,ze=(H.height-Re)/2);const me=ne/re;let ce,ie;if(Oa.type==="svg"){const te=Oa,$e=te.viewBox?.width||200,xt=te.viewBox?.height||200,Je=$e/xt;Je>1?(ce=re,ie=re/Je):(ie=ke,ce=ke*Je)}else ce=200,ie=200;const Z=ce*q.scale.x*me,xe=ie*q.scale.y*me,Ve=q.position.x*re*me,Mt=q.position.y*ke*me,St=H.left-J.left+oe,bt=H.top-J.top+ze,Bt=St+Ve,Ot=bt+Mt;return{x:Bt-Z/2,y:Ot-xe/2,width:Z,height:xe,centerX:Bt,centerY:Ot,displayScale:me,isShapeClip:!0}},[Oa,$.width,$.height,_]),so=l.useCallback(E=>{if(!t.current||!r.current)return null;const I=t.current,H=r.current.getBoundingClientRect(),q=I.getBoundingClientRect(),{transform:re}=E,ke=$.width,ee=$.height,le=ke/ee,ne=q.width/q.height;let Re,oe,ze=0,me=0;ne>le?(oe=q.height,Re=oe*le,ze=(q.width-Re)/2):(Re=q.width,oe=Re/le,me=(q.height-oe)/2);const ce=Re/ke;let ie,Z;if(E.type==="svg"){const $e=E,xt=$e.viewBox?.width||200,Je=$e.viewBox?.height||200,_t=xt/Je;_t>1?(ie=ke,Z=ke/_t):(Z=ee,ie=ee*_t)}else ie=200,Z=200;const xe=ie*re.scale.x*ce,Ve=Z*re.scale.y*ce,Mt=re.position.x*ke*ce,St=re.position.y*ee*ce,bt=q.left-H.left+ze,Bt=q.top-H.top+me,Ot=bt+Mt,te=Bt+St;return{x:Ot-xe/2,y:te-Ve/2,width:xe,height:Ve,centerX:Ot,centerY:te}},[$.width,$.height]),Hn=l.useCallback((E,I)=>{if(!r.current)return null;const J=r.current.getBoundingClientRect(),H=E-J.left,q=I-J.top;for(let re=Gn.length-1;re>=0;re--){const ke=Gn[re],ee=so(ke);if(ee&&H>=ee.x&&H<=ee.x+ee.width&&q>=ee.y&&q<=ee.y+ee.height)return ke}return null},[Gn,so]),ao=l.useMemo(()=>Ae.find(I=>I.type==="subtitle")?.id||null,[Ae]),Va=l.useMemo(()=>ao&&ps.find(E=>E.id===ao)||null,[ao,ps]),Or=l.useMemo(()=>{if(!Va||!t.current||!r.current||wt=Va.endTime)return null;const E=t.current,J=r.current.getBoundingClientRect(),H=E.getBoundingClientRect(),q=Va.style?.fontSize||24,re=Va.style?.position||"bottom",ke=Va.text.split(` +`),ee=q*1.3,le=ke.length*ee,ne=$.width,Re=$.height,oe=ne/Re,ze=H.width/H.height;let me,ce,ie=0,Z=0;ze>oe?(ce=H.height,me=ce*oe,ie=(H.width-me)/2):(me=H.width,ce=me/oe,Z=(H.height-ce)/2);const xe=me/ne;let Ve;re==="top"?Ve=q*2:re==="center"?Ve=Re/2-le/2:Ve=Re-q*2-le;const Mt=ne*.8*xe,St=le*xe,bt=H.left-J.left+ie,Bt=H.top-J.top+Z,Ot=bt+me/2,te=Bt+Ve*xe;return{x:Ot-Mt/2,y:te,width:Mt,height:St,centerX:Ot,centerY:te+St/2,displayScale:xe}},[Va,$.width,$.height,_,wt]),Ua=l.useCallback((E,I)=>{E.stopPropagation(),E.preventDefault();const J=wa||$a;if(!J)return;const H=J.transform||{position:{x:0,y:0},scale:{x:1,y:1}};Q.current=!0,qe("resize"),rt(I),Ee.current={x:E.clientX,y:E.clientY,transform:{x:H.position.x,y:H.position.y,scaleX:H.scale.x,scaleY:H.scale.y}}},[wa,$a]),Gu=l.useCallback(E=>{E.stopPropagation(),E.preventDefault();const I=wa||$a;if(!I)return;const J=I.transform||{position:{x:0,y:0},scale:{x:1,y:1}};Q.current=!0,qe("move"),Ee.current={x:E.clientX,y:E.clientY,transform:{x:J.position.x,y:J.position.y,scaleX:J.scale.x,scaleY:J.scale.y}}},[wa,$a]),Hu=l.useCallback(E=>{if(E.stopPropagation(),E.preventDefault(),!pa)return;const{transform:I}=pa;Q.current=!0,qe("move"),Ge("text-clip"),gt.current=pa.id,Ee.current={x:E.clientX,y:E.clientY,transform:{x:I.position.x,y:I.position.y,scaleX:I.scale.x,scaleY:I.scale.y}}},[pa]),Ka=l.useCallback((E,I)=>{if(E.stopPropagation(),E.preventDefault(),!pa)return;const{transform:J}=pa;Q.current=!0,qe("resize"),rt(I),Ge("text-clip"),gt.current=pa.id,Ee.current={x:E.clientX,y:E.clientY,transform:{x:J.position.x,y:J.position.y,scaleX:J.scale.x,scaleY:J.scale.y}}},[pa]),Wu=l.useCallback(E=>{if(E.stopPropagation(),E.preventDefault(),!Na)return;const{transform:I}=Na;Q.current=!0,qe("move"),Ge("shape-clip"),gt.current=Na.id,Ee.current={x:E.clientX,y:E.clientY,transform:{x:I.position.x,y:I.position.y,scaleX:I.scale.x,scaleY:I.scale.y}}},[Na]),Ya=l.useCallback((E,I)=>{if(E.stopPropagation(),E.preventDefault(),!Na)return;const{transform:J}=Na;Q.current=!0,qe("resize"),rt(I),Ge("shape-clip"),gt.current=Na.id,Ee.current={x:E.clientX,y:E.clientY,transform:{x:J.position.x,y:J.position.y,scaleX:J.scale.x,scaleY:J.scale.y}}},[Na]),qu=l.useCallback(E=>{if(Me!=="none"){to(null);return}const I=Hn(E.clientX,E.clientY);to(I?I.id:null)},[Me,Hn]),Qu=l.useCallback(E=>{if(Me!=="none")return;const I=Hn(E.clientX,E.clientY);I&&(Dr({type:"shape-clip",id:I.id}),E.stopPropagation())},[Me,Hn,Dr]),Ju=l.useCallback(E=>{if(Me==="none"||!Ee.current)return;if(mt==="text-clip"&&ka&&pa){const ee=E.clientX-Ee.current.x,le=E.clientY-Ee.current.y,{displayScale:ne}=ka;let Re={};if(Me==="move"){const oe=Ee.current.transform.x+ee/ne/$.width,ze=Ee.current.transform.y+le/ne/$.height;Re={position:{x:oe,y:ze}}}else if(Me==="resize"&&nt){const oe=Ee.current.transform;let ze=oe.scaleX,me=oe.scaleY;const ce=ee/ne/100,ie=le/ne/100;switch(nt){case"e":case"se":case"ne":ze=Math.max(.1,oe.scaleX+ce),Pe&&(me=ze);break;case"w":case"sw":case"nw":ze=Math.max(.1,oe.scaleX-ce),Pe&&(me=ze);break;case"s":me=Math.max(.1,oe.scaleY+ie),Pe&&(ze=me);break;case"n":me=Math.max(.1,oe.scaleY-ie),Pe&&(ze=me);break}Re={position:{x:oe.x,y:oe.y},scale:{x:ze,y:me}}}W.current||(W.current=requestAnimationFrame(()=>{const oe=performance.now();oe-be.current>=Oe&>.current&&(be.current=oe,qs(gt.current,Re)),W.current=null}));return}if(mt==="shape-clip"&&_a&&Na){const ee=E.clientX-Ee.current.x,le=E.clientY-Ee.current.y,{displayScale:ne}=_a;let Re={};if(Me==="move"){const oe=Ee.current.transform.x+ee/ne/$.width,ze=Ee.current.transform.y+le/ne/$.height;Re={position:{x:oe,y:ze}}}else if(Me==="resize"&&nt){const oe=Ee.current.transform;let ze=oe.scaleX,me=oe.scaleY;const ce=ee/ne/100,ie=le/ne/100;switch(nt){case"e":case"se":case"ne":ze=Math.max(.1,oe.scaleX+ce),Pe&&(me=ze);break;case"w":case"sw":case"nw":ze=Math.max(.1,oe.scaleX-ce),Pe&&(me=ze);break;case"s":me=Math.max(.1,oe.scaleY+ie),Pe&&(ze=me);break;case"n":me=Math.max(.1,oe.scaleY-ie),Pe&&(ze=me);break}Re={position:{x:oe.x,y:oe.y},scale:{x:ze,y:me}}}W.current||(W.current=requestAnimationFrame(()=>{const oe=performance.now();oe-be.current>=Oe&>.current&&(be.current=oe,ua(gt.current,Re)),W.current=null}));return}if(!ta)return;const I=wa||$a;if(!I)return;const J=E.clientX-Ee.current.x,H=E.clientY-Ee.current.y,{displayScale:q}=ta;let re={};if(Me==="move"){const ee=Ee.current.transform.x+J/q,le=Ee.current.transform.y+H/q;re={position:{x:ee,y:le}}}else if(Me==="resize"&&nt){const ee=Ee.current.transform;let le=ee.scaleX,ne=ee.scaleY,Re=ee.x,oe=ee.y;const ze=ta.width/q/Math.max(.001,ee.scaleX),me=ta.height/q/Math.max(.001,ee.scaleY),ce=J/q/(ze/2),ie=H/q/(me/2);switch(nt){case"e":le=Math.max(.1,ee.scaleX+ce),Pe&&(ne=le);break;case"w":le=Math.max(.1,ee.scaleX-ce),Pe&&(ne=le),Re=ee.x+J/q/2;break;case"s":ne=Math.max(.1,ee.scaleY+ie),Pe&&(le=ne);break;case"n":ne=Math.max(.1,ee.scaleY-ie),Pe&&(le=ne),oe=ee.y+H/q/2;break;case"se":if(Pe){const Z=(ce+ie)/2;le=Math.max(.1,ee.scaleX+Z),ne=le}else le=Math.max(.1,ee.scaleX+ce),ne=Math.max(.1,ee.scaleY+ie);break;case"sw":if(Pe){const Z=(-ce+ie)/2;le=Math.max(.1,ee.scaleX+Z),ne=le}else le=Math.max(.1,ee.scaleX-ce),ne=Math.max(.1,ee.scaleY+ie);Re=ee.x+J/q/2;break;case"ne":if(Pe){const Z=(ce-ie)/2;le=Math.max(.1,ee.scaleX+Z),ne=le}else le=Math.max(.1,ee.scaleX+ce),ne=Math.max(.1,ee.scaleY-ie);oe=ee.y+H/q/2;break;case"nw":if(Pe){const Z=(-ce-ie)/2;le=Math.max(.1,ee.scaleX+Z),ne=le}else le=Math.max(.1,ee.scaleX-ce),ne=Math.max(.1,ee.scaleY-ie);Re=ee.x+J/q/2,oe=ee.y+H/q/2;break}re={position:{x:Re,y:oe},scale:{x:le,y:ne}}}ae.current={clipId:I.id,transform:re};const ke=I.transform||{position:{x:0,y:0},scale:{x:1,y:1}};Ke({position:re.position||ke.position,scale:re.scale||ke.scale}),W.current||(W.current=requestAnimationFrame(()=>{const ee=performance.now();ae.current&&ee-be.current>=Oe&&(be.current=ee,Ss(ae.current.clipId,ae.current.transform)),W.current=null}))},[Me,nt,ta,wa,$a,Ss,$.width,$.height,Pe,mt,ka,pa,qs]),Zu=l.useCallback(()=>{ae.current&&(Ss(ae.current.clipId,ae.current.transform),ae.current=null),Ge(null),gt.current=null,W.current&&(cancelAnimationFrame(W.current),W.current=null);const E=Q.current;Q.current=!1,qe("none"),rt(null),Ee.current=null,Ke(null),E&&ea(wt)},[Ss,ea,wt]),em=l.useCallback(E=>{jt&&Ss(jt,{crop:E})},[jt,Ss]),tm=l.useCallback(()=>{Gt(!1)},[Gt]),sm=l.useCallback(()=>{Gt(!1)},[Gt]);l.useEffect(()=>{if(Me!=="none"){const E=()=>{ae.current&&(Ss(ae.current.clipId,ae.current.transform),ae.current=null),W.current&&(cancelAnimationFrame(W.current),W.current=null);const I=Q.current;Q.current=!1,qe("none"),rt(null),Ee.current=null,Ke(null),I&&ea(wt)};return window.addEventListener("mouseup",E),()=>window.removeEventListener("mouseup",E)}},[Me,ea,wt,Ss]);const am=l.useCallback(E=>{const I=E.currentTarget.getBoundingClientRect(),J=E.clientX-I.left,q=Math.max(0,Math.min(1,J/I.width))*(Ms||10);Nl(q)},[Ms,Nl]),rm=l.useCallback(()=>{_n(-5)},[_n]),nm=l.useCallback(()=>{_n(5)},[_n]),im=l.useCallback(()=>{const E=s.current;E&&(document.fullscreenElement?document.exitFullscreen().then(()=>{pe(!1)}).catch(I=>{console.error("Error exiting fullscreen:",I)}):(We(1),E.requestFullscreen().then(()=>{pe(!0)}).catch(I=>{console.error("Error entering fullscreen:",I)})))},[]),om=l.useCallback(()=>{We(1),ue(E=>!E)},[]);l.useEffect(()=>{const E=()=>{pe(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",E),()=>document.removeEventListener("fullscreenchange",E)},[]);const lm=Ms>0?wt/Ms*100:0,cm=!Jt&&wa&&ta,dm=!Jt&&fn&&ka,um=!Jt&&Oa&&_a,mm=!Jt&&Va&&Or,gn=l.useMemo(()=>{if(!Be||!jt)return null;for(const E of He){const I=E.clips.find(J=>J.id===jt);if(I)return I}return null},[Be,jt,He]),Bl=l.useMemo(()=>{if(!Be||!jt||!gn)return null;const E=Lt(gn.mediaId);if(!E)return null;let I=null;return E.blob?I=URL.createObjectURL(E.blob):E.originalUrl&&(I=E.originalUrl),I?{src:I,type:E.type}:null},[Be,jt,gn,Lt]),Fl=Bl?.src??null,pm=Bl?.type??"video",xm=Be&&jt&&gn&&Fl;return e.jsxs("div",{ref:s,"data-tour":"preview",className:"w-full h-full min-h-0 min-w-0 bg-stage-bg flex flex-col relative group overflow-hidden",children:[!K&&!Te&&e.jsxs("div",{className:"flex items-center px-3.5 py-2 border-b border-border bg-bg-1 gap-2.5 min-h-[38px] shrink-0",children:[e.jsx("h2",{className:"text-[13px] font-semibold tracking-tight text-fg m-0",children:"Player"}),e.jsx("div",{className:"ml-auto flex items-center gap-1",children:e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent",title:"Live preview"})})]}),xm&&e.jsx(_b,{clip:gn,videoSrc:Fl,mediaType:pm,currentTime:wt,canvasWidth:_.width,canvasHeight:_.height,onCropChange:em,onComplete:tm,onCancel:sm}),e.jsx("div",{ref:a,className:`flex-1 min-h-0 min-w-0 relative flex items-center justify-center bg-stage-bg transition-all duration-300 ${K||Te?"p-0":"p-4"} ${fe>1?"overflow-auto":""}`,onMouseMove:Me!=="none"?Ju:void 0,onMouseUp:Zu,children:e.jsxs("div",{ref:r,className:`relative bg-[var(--screen-bg)] overflow-visible transition-all duration-300 ${K||Te?"rounded-none ring-0 shadow-none":Ce?"shadow-2xl rounded-xl ring-1 ring-border shadow-[0_0_50px_rgba(0,0,0,0.5)]":"rounded-xl ring-1 ring-border shadow-[0_10px_40px_rgba(0,0,0,0.1)]"}`,style:K||Te?{width:"100%",height:"100%",maxWidth:"none"}:{width:`${ve.width}px`,height:`${ve.height}px`,maxWidth:"100%",maxHeight:"100%"},onMouseMove:Jt?void 0:qu,onClick:Jt?void 0:Qu,onMouseLeave:()=>to(null),children:[e.jsx("canvas",{ref:t,width:$.width,height:$.height,className:"w-full h-full object-contain bg-[var(--screen-bg)]",style:{cursor:Il&&!Jt?"pointer":"default"}}),e.jsx(Wb,{}),ja&&Cl&&Ir&&e.jsx("div",{className:"absolute inset-0 pointer-events-auto z-30",children:e.jsx(Ub,{config:Cl,canvasWidth:$.width,canvasHeight:$.height,currentTime:wt-Ir.startTime,clipDuration:Ir.duration,onPointMove:$u,onPointAdd:Ou,onPointRemove:_u,onControlPointMove:Vu,disabled:Jt})}),Sl.length>0&&e.jsx("div",{className:"absolute inset-0 pointer-events-none z-20",children:e.jsx(Yb,{effects:Sl,width:$.width,height:$.height,currentTime:wt,isPlaying:Jt})}),Kt.isExporting&&e.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-background-secondary/95 rounded-xl p-6 max-w-sm w-full mx-4 shadow-2xl border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(ds,{size:20,className:"text-primary animate-spin"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Exporting Video"}),e.jsx("p",{className:"text-xs text-text-muted",children:Kt.phase||"Preparing..."})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Export Progress"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[Math.round(Kt.progress),"%"]})]}),e.jsx("div",{className:"h-2 bg-black/30 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-primary to-primary-hover transition-all duration-300",style:{width:`${Kt.progress}%`}})})]}),e.jsx("p",{className:"text-[10px] text-text-muted text-center",children:"Please wait while your video is being exported..."})]})}),!Be&&cm&&ta&&e.jsxs("div",{className:"absolute pointer-events-none",style:{left:ta.x,top:ta.y,width:ta.width,height:ta.height},children:[e.jsx("div",{className:"absolute inset-0 border-2 border-primary pointer-events-none"}),e.jsx("div",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-primary/80 rounded-full flex items-center justify-center cursor-move pointer-events-auto hover:bg-primary transition-colors",onMouseDown:Gu,title:"Drag to move",children:e.jsx(rn,{size:14,className:"text-white"})}),e.jsx("button",{className:`absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 text-[10px] rounded pointer-events-auto transition-colors ${Pe?"bg-primary text-white":"bg-background-tertiary text-text-secondary border border-border hover:bg-background-elevated"}`,onClick:()=>Ie(!Pe),title:Pe?"Unlock aspect ratio":"Lock aspect ratio",children:Pe?"🔒 Locked":"🔓 Free"}),e.jsx("div",{className:"absolute -left-2 -top-2 w-4 h-4 bg-white border-2 border-primary rounded-sm cursor-nw-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"nw")}),e.jsx("div",{className:"absolute -right-2 -top-2 w-4 h-4 bg-white border-2 border-primary rounded-sm cursor-ne-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"ne")}),e.jsx("div",{className:"absolute -left-2 -bottom-2 w-4 h-4 bg-white border-2 border-primary rounded-sm cursor-sw-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"sw")}),e.jsx("div",{className:"absolute -right-2 -bottom-2 w-4 h-4 bg-white border-2 border-primary rounded-sm cursor-se-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"se")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -top-2 w-6 h-4 bg-white border-2 border-primary rounded-sm cursor-n-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"n")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -bottom-2 w-6 h-4 bg-white border-2 border-primary rounded-sm cursor-s-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"s")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -left-2 w-4 h-6 bg-white border-2 border-primary rounded-sm cursor-w-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"w")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -right-2 w-4 h-6 bg-white border-2 border-primary rounded-sm cursor-e-resize pointer-events-auto hover:bg-primary hover:border-white transition-colors",onMouseDown:E=>Ua(E,"e")})]}),dm&&ka&&e.jsxs("div",{className:"absolute pointer-events-none",style:{left:ka.x,top:ka.y,width:ka.width,height:ka.height},children:[e.jsx("div",{className:"absolute inset-0 border-2 border-cyan-500 pointer-events-none"}),e.jsx("div",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-cyan-500/80 rounded-full flex items-center justify-center cursor-move pointer-events-auto hover:bg-cyan-500 transition-colors",onMouseDown:Hu,title:"Drag to move text",children:e.jsx(rn,{size:14,className:"text-white"})}),e.jsx("button",{className:`absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 text-[10px] rounded pointer-events-auto transition-colors ${Pe?"bg-cyan-500 text-white":"bg-background-tertiary text-text-secondary border border-border hover:bg-background-elevated"}`,onClick:()=>Ie(!Pe),title:Pe?"Unlock aspect ratio":"Lock aspect ratio",children:Pe?"🔒 Locked":"🔓 Free"}),e.jsx("div",{className:"absolute -left-2 -top-2 w-4 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-nw-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"nw")}),e.jsx("div",{className:"absolute -right-2 -top-2 w-4 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-ne-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"ne")}),e.jsx("div",{className:"absolute -left-2 -bottom-2 w-4 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-sw-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"sw")}),e.jsx("div",{className:"absolute -right-2 -bottom-2 w-4 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-se-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"se")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -top-2 w-6 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-n-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"n")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -bottom-2 w-6 h-4 bg-white border-2 border-cyan-500 rounded-sm cursor-s-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"s")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -left-2 w-4 h-6 bg-white border-2 border-cyan-500 rounded-sm cursor-w-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"w")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -right-2 w-4 h-6 bg-white border-2 border-cyan-500 rounded-sm cursor-e-resize pointer-events-auto hover:bg-cyan-500 hover:border-white transition-colors",onMouseDown:E=>Ka(E,"e")})]}),um&&_a&&e.jsxs("div",{className:"absolute pointer-events-none",style:{left:_a.x,top:_a.y,width:_a.width,height:_a.height},children:[Oa.type!=="svg"&&e.jsx("div",{className:"absolute inset-0 border-2 border-green-500 pointer-events-none"}),e.jsx("div",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 bg-green-500/80 rounded-full flex items-center justify-center cursor-move pointer-events-auto hover:bg-green-500 transition-colors",onMouseDown:Wu,title:"Drag to move shape",children:e.jsx(rn,{size:14,className:"text-white"})}),e.jsx("button",{className:`absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 text-[10px] rounded pointer-events-auto transition-colors ${Pe?"bg-green-500 text-white":"bg-background-tertiary text-text-secondary border border-border hover:bg-background-elevated"}`,onClick:()=>Ie(!Pe),title:Pe?"Unlock aspect ratio":"Lock aspect ratio",children:Pe?"🔒 Locked":"🔓 Free"}),e.jsx("div",{className:"absolute -left-2 -top-2 w-4 h-4 bg-white border-2 border-green-500 rounded-sm cursor-nw-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"nw")}),e.jsx("div",{className:"absolute -right-2 -top-2 w-4 h-4 bg-white border-2 border-green-500 rounded-sm cursor-ne-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"ne")}),e.jsx("div",{className:"absolute -left-2 -bottom-2 w-4 h-4 bg-white border-2 border-green-500 rounded-sm cursor-sw-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"sw")}),e.jsx("div",{className:"absolute -right-2 -bottom-2 w-4 h-4 bg-white border-2 border-green-500 rounded-sm cursor-se-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"se")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -top-2 w-6 h-4 bg-white border-2 border-green-500 rounded-sm cursor-n-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"n")}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 -bottom-2 w-6 h-4 bg-white border-2 border-green-500 rounded-sm cursor-s-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"s")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -left-2 w-4 h-6 bg-white border-2 border-green-500 rounded-sm cursor-w-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"w")}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 -right-2 w-4 h-6 bg-white border-2 border-green-500 rounded-sm cursor-e-resize pointer-events-auto hover:bg-green-500 hover:border-white transition-colors",onMouseDown:E=>Ya(E,"e")})]}),mm&&Or&&e.jsxs("div",{className:"absolute pointer-events-none",style:{left:Or.x,top:Or.y,width:Or.width,height:Or.height},children:[e.jsx("div",{className:"absolute inset-0 border-2 border-yellow-500 rounded-lg pointer-events-none animate-pulse"}),e.jsx("div",{className:"absolute -top-6 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-yellow-500 rounded text-[10px] font-medium text-black whitespace-nowrap",children:"Subtitle Selected - Edit in Inspector"})]}),!Be&&!Jt&&Gn.map(E=>{if(E.type==="svg"||E.id===Xn||E.id!==Il)return null;const I=so(E);return I?e.jsxs("div",{className:"absolute pointer-events-none z-10",style:{left:I.x,top:I.y,width:I.width,height:I.height},children:[e.jsx("div",{className:"absolute inset-0 border-2 border-dashed border-white/80 rounded-sm"}),e.jsx("div",{"aria-hidden":"true",className:"absolute -top-6 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-black/70 rounded text-[10px] text-white whitespace-nowrap",children:"Click to select"})]},E.id):null})]})}),e.jsxs("div",{className:`border-t border-border transition-all duration-300 ${K||Te?"absolute bottom-0 left-0 right-0 z-50 bg-bg-1 backdrop-blur-sm":"z-20 bg-bg-1"}`,children:[e.jsx("div",{className:"h-1.5 bg-bg-2 cursor-pointer group hover:h-2.5 transition-all relative",onClick:am,children:e.jsx("div",{className:"h-full bg-accent relative pointer-events-none shadow-glow",style:{width:`${lm}%`},children:e.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full shadow-md opacity-0 group-hover:opacity-100 transition-opacity transform scale-0 group-hover:scale-100 duration-100 border border-black/20"})})}),e.jsxs("div",{className:"h-12 px-4 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-[11px] tabular-nums tracking-tight",children:[e.jsx("span",{className:"text-accent font-semibold",children:hi(wt)}),e.jsx("span",{className:"text-fg-3 mx-1",children:"/"}),e.jsx("span",{className:"text-fg-3",children:hi(Qt.timeline.duration||0)})]}),D!=="none"&&e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${D==="webgpu"?"bg-green-500/20 text-green-400":"bg-gray-500/20 text-gray-400"}`,title:`Rendering with ${D.toUpperCase()}`,children:D.toUpperCase()})]}),e.jsxs("div",{className:"flex items-center gap-1 mx-auto",children:[e.jsx("button",{onClick:rm,title:"Skip back 5s",className:"w-7 h-7 grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(tf,{size:13})}),e.jsx("button",{onClick:()=>{Lu()},disabled:!!On,title:On??(Jt?"Pause":"Play"),className:`w-8 h-8 rounded-full flex items-center justify-center transition-all ${On?"bg-bg-2 text-fg-muted cursor-not-allowed":"text-fg hover:bg-hover"}`,children:Jt?e.jsx(dr,{size:18,fill:"currentColor"}):On?e.jsx(ds,{size:18,className:"animate-spin"}):e.jsx(As,{size:18,fill:"currentColor",className:"ml-0.5"})}),e.jsx("button",{onClick:nm,title:"Skip forward 5s",className:"w-7 h-7 grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors",children:e.jsx(af,{size:13})})]}),e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("button",{onClick:()=>G(!O),className:`w-7 h-7 grid place-items-center rounded-md transition-colors ${O?"text-status-error":"text-fg-2 hover:text-fg hover:bg-hover"}`,title:O?"Unmute":"Mute",children:O?e.jsx($i,{size:14}):e.jsx(Ts,{size:14})}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>at(!Ze),className:"px-2 py-0.5 rounded border border-border text-[10.5px] font-medium text-fg-2 hover:bg-hover hover:text-fg transition-colors",title:"Preview Zoom",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ou,{size:11}),e.jsxs("span",{children:[Math.round(fe*100),"%"]})]})}),Ze&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>at(!1)}),e.jsx("div",{className:"absolute bottom-full mb-1 left-1/2 -translate-x-1/2 bg-bg-elev border border-border rounded-md shadow-md py-1 z-50 min-w-[80px]",children:de.map(E=>e.jsx("button",{onClick:()=>{We(E.value),at(!1)},className:`w-full px-3 py-1.5 text-[11px] font-mono text-left hover:bg-hover transition-colors ${fe===E.value?"text-accent":"text-fg-2"}`,children:E.label},E.value))})]})]}),e.jsx("button",{onClick:im,title:Te?"Exit Full Screen":"Full Screen",className:`w-7 h-7 grid place-items-center rounded-md transition-colors ${Te?"bg-accent-soft text-accent":"text-fg-2 hover:text-fg hover:bg-hover"}`,children:e.jsx(Er,{size:14})}),e.jsx("button",{onClick:om,title:K?"Restore Size":"Maximize Preview",className:`w-7 h-7 grid place-items-center rounded-md transition-colors ${K?"bg-accent-soft text-accent":"text-fg-2 hover:text-fg hover:bg-hover"}`,children:K?e.jsx(ml,{size:14}):e.jsx(zr,{size:14})})]})]})]})]})},ty=["balanced","speech","whiteNoise","music","heavy","wind","hum"],bi=[{type:"lowshelf",frequency:60,gain:0,q:.707},{type:"peaking",frequency:250,gain:0,q:1.4},{type:"peaking",frequency:1e3,gain:0,q:1.4},{type:"peaking",frequency:4e3,gain:0,q:1.4},{type:"highshelf",frequency:16e3,gain:0,q:.707}],ns={threshold:-40,reduction:.5,attack:10,release:100,focus:"balanced"},sy=t=>{if(!t||typeof t!="object")return!1;const s=t,a=(r,n)=>typeof r=="number"&&Number.isInteger(r)&&r>0&&(r&r-1)===0&&r/2===n;return Array.isArray(s.frequencyBins)&&s.frequencyBins.length>0&&s.frequencyBins.every(r=>typeof r=="number"&&Number.isFinite(r))&&Array.isArray(s.magnitudes)&&s.magnitudes.every(r=>typeof r=="number"&&Number.isFinite(r))&&s.frequencyBins.length===s.magnitudes.length&&(s.standardDeviations===void 0||Array.isArray(s.standardDeviations)&&s.standardDeviations.length===s.magnitudes.length&&s.standardDeviations.every(r=>typeof r=="number"&&Number.isFinite(r)))&&typeof s.sampleRate=="number"&&Number.isFinite(s.sampleRate)&&(s.fftSize===void 0||a(s.fftSize,s.magnitudes.length))};function ku(t){return{type:["lowshelf","highshelf","peaking","lowpass","highpass","notch"].includes(t.type)?t.type:"peaking",frequency:Math.max(20,Math.min(2e4,t.frequency??1e3)),gain:Math.max(-24,Math.min(24,t.gain??0)),q:Math.max(.1,Math.min(18,t.q??1))}}function Nu(t){return{threshold:Math.max(-60,Math.min(0,t.threshold??-20)),ratio:Math.max(1,Math.min(20,t.ratio??4)),attack:Math.max(.001,Math.min(1,t.attack??.01)),release:Math.max(.01,Math.min(3,t.release??.1)),knee:Math.max(0,Math.min(40,t.knee??6))}}function Cu(t){return{roomSize:Math.max(0,Math.min(1,t.roomSize??.5)),damping:Math.max(0,Math.min(1,t.damping??.5)),wetLevel:Math.max(0,Math.min(1,t.wetLevel??.3)),dryLevel:Math.max(0,Math.min(1,t.dryLevel??1)),preDelay:Math.max(0,Math.min(100,t.preDelay??0))}}function Su(t){return{time:Math.max(0,Math.min(2,t.time??.25)),feedback:Math.max(0,Math.min(.95,t.feedback??.3)),wetLevel:Math.max(0,Math.min(1,t.wetLevel??.25))}}function Au(t){const s=ty.includes(t.focus??ns.focus)?t.focus??ns.focus:ns.focus,a=sy(t.profile)?{frequencyBins:[...t.profile.frequencyBins],magnitudes:[...t.profile.magnitudes],standardDeviations:t.profile.standardDeviations?[...t.profile.standardDeviations]:void 0,sampleRate:t.profile.sampleRate,fftSize:t.profile.fftSize}:void 0;return{threshold:Math.max(-80,Math.min(0,t.threshold??-40)),reduction:Math.max(0,Math.min(1,t.reduction??.5)),attack:Math.max(0,Math.min(100,t.attack??10)),release:Math.max(0,Math.min(500,t.release??100)),focus:s,profile:a}}function ay(t){const s=t.map(ku);return{id:`eq-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,type:"eq",params:{bands:s},enabled:!0}}function ry(t){const s=Nu(t);return{id:`compressor-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,type:"compressor",params:s,enabled:!0}}function ny(t){const s=Cu(t);return{id:`reverb-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,type:"reverb",params:s,enabled:!0}}function iy(t){const s=Su(t);return{id:`delay-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,type:"delay",params:s,enabled:!0}}function oy(t){const s=Au(t);return{id:`noiseReduction-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,type:"noiseReduction",params:s,enabled:!0}}class ly{audioEffectsEngine=null;noiseProfiles=new Map;initialized=!1;async initialize(){this.initialized||(this.audioEffectsEngine=Wm(),this.audioEffectsEngine.isInitialized()||await this.audioEffectsEngine.initialize(),this.initialized=!0)}isInitialized(){return this.initialized}getAudioEffectsEngine(){return this.audioEffectsEngine}applyEQ(s,a){try{const r=ay(a);return F.getState().addAudioEffect(s,r),{success:!0,effectId:r.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to apply EQ"}}}updateEQ(s,a,r){try{const n=r.map(ku);return F.getState().updateAudioEffect(s,a,{bands:n}),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to update EQ"}}}applyCompressor(s,a){try{const r=ry(a);return F.getState().addAudioEffect(s,r),{success:!0,effectId:r.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to apply compressor"}}}updateCompressor(s,a,r){try{const n=Nu(r);return F.getState().updateAudioEffect(s,a,n),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to update compressor"}}}applyReverb(s,a){try{const r=ny(a);return F.getState().addAudioEffect(s,r),{success:!0,effectId:r.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to apply reverb"}}}updateReverb(s,a,r){try{const n=Cu(r);return F.getState().updateAudioEffect(s,a,n),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to update reverb"}}}applyDelay(s,a){try{const r=iy(a);return F.getState().addAudioEffect(s,r),{success:!0,effectId:r.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to apply delay"}}}updateDelay(s,a,r){try{const n=Su(r);return F.getState().updateAudioEffect(s,a,n),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to update delay"}}}applyNoiseReduction(s,a){try{const r=oy(a);return F.getState().addAudioEffect(s,r),{success:!0,effectId:r.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to apply noise reduction"}}}updateNoiseReduction(s,a,r){try{const n=Au(r);return F.getState().updateAudioEffect(s,a,n),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to update noise reduction"}}}async learnNoiseProfile(s,a){if(!this.audioEffectsEngine)throw new Error("AudioBridgeEffects not initialized");const r=a??`noise-profile-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,n=await this.audioEffectsEngine.learnNoiseProfile(s,r),i={id:r,frequencyBins:n.frequencyBins,magnitudes:n.magnitudes,standardDeviations:n.standardDeviations,sampleRate:n.sampleRate,fftSize:n.fftSize,createdAt:Date.now()};return this.noiseProfiles.set(r,i),i}getNoiseProfile(s){return this.noiseProfiles.get(s)}getAllNoiseProfiles(){return Array.from(this.noiseProfiles.values())}removeNoiseProfile(s){return this.noiseProfiles.delete(s)}removeEffect(s,a){try{return F.getState().removeAudioEffect(s,a),{success:!0,effectId:a}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to remove effect"}}}toggleEffect(s,a,r){try{return F.getState().toggleAudioEffect(s,a,r),{success:!0,effectId:a}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to toggle effect"}}}async processAudio(s,a){if(!this.audioEffectsEngine)throw new Error("AudioBridgeEffects not initialized");return(await this.audioEffectsEngine.applyEffectChain(s,a)).buffer}dispose(){this.noiseProfiles.clear(),this.audioEffectsEngine=null,this.initialized=!1}}let No=null;function Us(){return No||(No=new ly),No}async function jl(){const t=Us();return await t.initialize(),t}const rr=(t,s,a)=>Math.min(a,Math.max(s,t)),wl=t=>t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,Tu=(t,s)=>{if(t.length===0)return 0;const a=t.reduce((r,n)=>r+(n-s)**2,0)/t.length;return Math.sqrt(a)},Rs=(t,s,a)=>{const r=[];for(let n=0;n0&&i>=s&&i<=a&&r.push(o)}return wl(r)},tl=[{id:"balanced",label:"Balanced",description:"General cleanup for moderate room noise without pushing too hard.",config:{...ns,threshold:-34,reduction:.56,attack:10,release:120,focus:"balanced"}},{id:"speech",label:"Speech Focus",description:"Preserve dialog presence while reducing hiss and ambient bed.",config:{...ns,threshold:-36,reduction:.64,attack:9,release:130,focus:"speech"}},{id:"whiteNoise",label:"White Noise",description:"Aggressive broadband hiss removal for fans, air, camera preamp noise, and room tone.",config:{...ns,threshold:-56,reduction:.92,attack:6,release:240,focus:"whiteNoise"}},{id:"music",label:"Music Bed",description:"Pushes background music down while keeping speech presence forward.",config:{...ns,threshold:-48,reduction:.82,attack:8,release:220,focus:"music"}},{id:"heavy",label:"Heavy Noise",description:"More aggressive broadband cleanup for loud air, fan, and street wash.",config:{...ns,threshold:-42,reduction:.8,attack:14,release:190,focus:"heavy"}},{id:"wind",label:"Wind & Rumble",description:"Targets low-end rumble, handling noise, and outdoor wind pressure.",config:{...ns,threshold:-40,reduction:.74,attack:8,release:210,focus:"wind"}},{id:"hum",label:"Hum & HVAC",description:"Focused cleanup for tonal hum, AC drone, and power-line style noise.",config:{...ns,threshold:-38,reduction:.7,attack:12,release:170,focus:"hum"}}],Ra=t=>tl.find(s=>s.id===t)??tl[0],Mu=t=>{const s=Array.from(t.magnitudes).filter(k=>Number.isFinite(k)&&k>0);if(s.length===0)return ns.focus??"balanced";const a=wl(s),r=Math.max(...s),n=Tu(s,a),i=rr(a/Math.max(r,1e-6),0,1),o=Rs(t,40,140),c=Rs(t,180,500),d=Rs(t,180,1200),u=Rs(t,1200,5e3),p=Rs(t,20,180),m=Rs(t,250,4e3),x=Rs(t,6e3,18e3),h=p/Math.max(m,1e-6),f=x/Math.max(m,1e-6),v=(d+u)/Math.max(m*2,1e-6),A=r/Math.max(a,1e-6),g=rr(n/Math.max(a,1e-6)/3,0,1);return h>1.55?A>5&&i<.35||o>c*2.2&&A>2.4?"hum":"wind":f>1.35?i>.45?"whiteNoise":"speech":i>.62||g<.18?"whiteNoise":v>.72&&A>2.1&&g>.22&&h<1.45&&f<1.45?"music":i>.5||g<.28?"heavy":A>5.5&&h>.9?"hum":"speech"},qc=t=>{const s=Array.from(t.magnitudes).filter(m=>Number.isFinite(m)&&m>0);if(s.length===0)return ns;const a=Ra(Mu(t)),r=wl(s),n=Math.max(...s),i=Tu(s,r),o=rr(r/Math.max(n,1e-6),0,1),c=rr(i/Math.max(r,1e-6)/3,0,1),d=Rs(t,20,180)/Math.max(Rs(t,250,4e3),1e-6),u=Rs(t,6e3,18e3)/Math.max(Rs(t,250,4e3),1e-6),p=(Rs(t,180,1200)+Rs(t,1200,5e3))/Math.max(Rs(t,250,4e3)*2,1e-6);return{...a.config,threshold:rr(a.config.threshold+o*6+c*4+Math.max(0,u-1)*4-Math.max(0,d-1)*2-Math.max(0,p-.7)*3,-64,-18),reduction:rr(a.config.reduction+o*.1+c*.05+Math.max(0,u-1)*.05+Math.max(0,d-1)*.03+Math.max(0,p-.7)*.04,.35,.97),attack:rr((a.config.attack??ns.attack??10)+c*12-o*5,5,35),release:rr((a.config.release??ns.release??100)+o*40+Math.max(0,d-1)*30,60,260),focus:a.config.focus}},cy={transform:{id:"transform",label:"Transform",icon:rn},color:{id:"color",label:"Color",icon:za},effects:{id:"effects",label:"Effects",icon:cr},audio:{id:"audio",label:"Audio",icon:Ts},speed:{id:"speed",label:"Speed",icon:Hd},animate:{id:"animate",label:"Animate",icon:lr},ai:{id:"ai",label:"AI",icon:gs},style:{id:"style",label:"Style",icon:Hs}},dy={video:["transform","color","effects","audio","speed","animate","ai"],image:["transform","color","effects","speed","animate","ai"],audio:["audio","ai"],text:["transform","style","effects","animate"],shape:["transform","style","effects","animate"],svg:["transform","style","effects","animate"],sticker:["transform","effects","animate"]};function Eu(t){return t?dy[t]:[]}function uy(t){return Eu(t).map(s=>cy[s])}const my=({tabs:t,activeId:s,onSelect:a})=>{const r=(n,i)=>{if(n.key!=="ArrowRight"&&n.key!=="ArrowLeft")return;n.preventDefault();const o=n.key==="ArrowRight"?1:-1,c=t[(i+o+t.length)%t.length];c&&a(c.id)};return e.jsx("div",{role:"tablist","aria-label":"Inspector tabs",className:"flex items-center gap-0.5 px-2 border-b border-border overflow-x-auto scrollbar-none shrink-0",children:t.map((n,i)=>{const o=n.icon,c=n.id===s;return e.jsxs("button",{role:"tab","aria-selected":c,tabIndex:c?0:-1,onClick:()=>a(n.id),onKeyDown:d=>r(d,i),className:qm("flex items-center gap-1.5 px-2.5 py-2 text-[12px] font-medium whitespace-nowrap transition-colors border-b-2 -mb-px",c?"text-accent border-accent":"text-fg-3 border-transparent hover:text-fg"),children:[e.jsx(o,{size:13}),e.jsx("span",{children:n.label})]},n.id)})})},py=({name:t,durationSeconds:s,typeLabel:a})=>e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border shrink-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11.5px] text-fg font-medium truncate",children:t}),e.jsxs("p",{className:"text-[10px] text-fg-muted mt-0.5",children:[s.toFixed(2),"s"]})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-fg-3 bg-bg-2 border border-border rounded px-1.5 py-0.5 shrink-0",children:a})]}),er=({tab:t,active:s,children:a})=>s===t?e.jsx("div",{role:"tabpanel",children:a}):null;class xy extends l.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?e.jsx("div",{className:"p-4 text-center text-xs text-text-secondary",children:"This panel hit an error. Switch tabs and back to retry."}):this.props.children}}const pt=({title:t,defaultOpen:s=!1,sectionId:a,children:r})=>{const[n,i]=_e.useState(s);return e.jsxs("div",{className:"mb-6 transition-all","data-section-id":a,children:[e.jsxs("button",{onClick:()=>i(!n),className:"flex items-center gap-2 text-text-secondary hover:text-text-primary transition-colors mb-3 w-full group",children:[e.jsx(qt,{size:12,className:`transition-transform duration-200 ${n?"":"-rotate-90"} text-text-muted group-hover:text-text-primary`}),e.jsx("span",{className:"text-xs font-medium",children:t})]}),n&&e.jsx("div",{className:"animate-in slide-in-from-top-2 duration-200",children:r})]})},Xt=ht,hy=({effect:t,onUpdate:s,onToggle:a,onRemove:r})=>{const[n,i]=_e.useState(!0),o={brightness:"Brightness",contrast:"Contrast",saturation:"Saturation",hue:"Hue",blur:"Blur",sharpen:"Sharpen",vignette:"Vignette",grain:"Grain",temperature:"Temperature",tint:"Tint",tonal:"Tonal",chromaKey:"Chroma Key",shadow:"Drop Shadow",glow:"Glow","motion-blur":"Motion Blur","radial-blur":"Radial Blur","chromatic-aberration":"Chromatic Aberration"},c=()=>{switch(t.type){case"brightness":return e.jsx(Xt,{label:"Value",value:t.params.value||0,onChange:d=>s(t.id,{value:d}),min:-100,max:100});case"contrast":return e.jsx(Xt,{label:"Value",value:(t.params.value||1)*100,onChange:d=>s(t.id,{value:d/100}),min:0,max:200,unit:"%"});case"saturation":return e.jsx(Xt,{label:"Value",value:(t.params.value||1)*100,onChange:d=>s(t.id,{value:d/100}),min:0,max:200,unit:"%"});case"blur":return e.jsx(Xt,{label:"Radius",value:t.params.radius||0,onChange:d=>s(t.id,{radius:d}),min:0,max:100,unit:"px"});case"sharpen":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Amount",value:t.params.amount||0,onChange:d=>s(t.id,{amount:d}),min:0,max:200,unit:"%"}),e.jsx(Xt,{label:"Radius",value:t.params.radius||1,onChange:d=>s(t.id,{radius:d}),min:.1,max:10,step:.1})]});case"vignette":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Amount",value:t.params.amount||0,onChange:d=>s(t.id,{amount:d}),min:0,max:100}),e.jsx(Xt,{label:"Midpoint",value:(t.params.midpoint||.5)*100,onChange:d=>s(t.id,{midpoint:d/100}),min:0,max:100,unit:"%"}),e.jsx(Xt,{label:"Feather",value:(t.params.feather||.3)*100,onChange:d=>s(t.id,{feather:d/100}),min:0,max:100,unit:"%"})]});case"grain":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Amount",value:t.params.amount||0,onChange:d=>s(t.id,{amount:d}),min:0,max:100}),e.jsx(Xt,{label:"Size",value:t.params.size||1,onChange:d=>s(t.id,{size:d}),min:.5,max:5,step:.1})]});case"temperature":return e.jsx(Xt,{label:"Value",value:t.params.value||0,onChange:d=>s(t.id,{value:d}),min:-100,max:100});case"tint":return e.jsx(Xt,{label:"Value",value:t.params.value||0,onChange:d=>s(t.id,{value:d}),min:-100,max:100});case"shadow":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Offset X",value:t.params.offsetX||5,onChange:d=>s(t.id,{offsetX:d}),min:-100,max:100,unit:"px"}),e.jsx(Xt,{label:"Offset Y",value:t.params.offsetY||5,onChange:d=>s(t.id,{offsetY:d}),min:-100,max:100,unit:"px"}),e.jsx(Xt,{label:"Blur",value:t.params.blur||10,onChange:d=>s(t.id,{blur:d}),min:0,max:100,unit:"px"}),e.jsx(Xt,{label:"Opacity",value:(t.params.opacity||.8)*100,onChange:d=>s(t.id,{opacity:d/100}),min:0,max:100,unit:"%"})]});case"glow":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Radius",value:t.params.radius||10,onChange:d=>s(t.id,{radius:d}),min:0,max:100,unit:"px"}),e.jsx(Xt,{label:"Intensity",value:(t.params.intensity||1)*100,onChange:d=>s(t.id,{intensity:d/100}),min:0,max:300,unit:"%"})]});case"motion-blur":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Angle",value:t.params.angle||0,onChange:d=>s(t.id,{angle:d}),min:0,max:360,unit:"°"}),e.jsx(Xt,{label:"Distance",value:t.params.distance||20,onChange:d=>s(t.id,{distance:d}),min:0,max:100,unit:"px"})]});case"radial-blur":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Amount",value:t.params.amount||20,onChange:d=>s(t.id,{amount:d}),min:0,max:100}),e.jsx(Xt,{label:"Center X",value:t.params.centerX||50,onChange:d=>s(t.id,{centerX:d}),min:0,max:100,unit:"%"}),e.jsx(Xt,{label:"Center Y",value:t.params.centerY||50,onChange:d=>s(t.id,{centerY:d}),min:0,max:100,unit:"%"})]});case"chromatic-aberration":return e.jsxs(e.Fragment,{children:[e.jsx(Xt,{label:"Amount",value:t.params.amount||5,onChange:d=>s(t.id,{amount:d}),min:0,max:50,step:.5,unit:"px"}),e.jsx(Xt,{label:"Angle",value:t.params.angle||0,onChange:d=>s(t.id,{angle:d}),min:0,max:360,unit:"°"})]});default:return null}};return e.jsxs("div",{className:`border rounded-lg ${t.enabled?"border-border":"border-border/50 opacity-60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-t-lg",children:[e.jsx($x,{size:12,className:"text-text-muted cursor-grab"}),e.jsxs("button",{onClick:()=>i(!n),className:"flex-1 flex items-center gap-1 text-left",children:[e.jsx(qt,{size:12,className:`transition-transform ${n?"":"-rotate-90"} text-text-muted`}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:o[t.type]||t.type})]}),e.jsx("button",{onClick:()=>a(t.id,!t.enabled),className:"p-1 hover:bg-background-secondary rounded transition-colors",title:t.enabled?"Disable effect":"Enable effect",children:t.enabled?e.jsx($s,{size:12,className:"text-text-secondary"}):e.jsx(Xs,{size:12,className:"text-text-muted"})}),e.jsx("button",{onClick:()=>r(t.id),className:"p-1 hover:bg-red-500/20 rounded transition-colors text-text-muted hover:text-red-400",title:"Remove effect",children:e.jsx(Ns,{size:12})})]}),n&&e.jsx("div",{className:"p-3 space-y-3",children:c()})]})},Ru=[{type:"brightness",label:"Brightness",category:"Basic"},{type:"contrast",label:"Contrast",category:"Basic"},{type:"saturation",label:"Saturation",category:"Basic"},{type:"temperature",label:"Temperature",category:"Color"},{type:"tint",label:"Tint",category:"Color"},{type:"blur",label:"Blur",category:"Blur"},{type:"motion-blur",label:"Motion Blur",category:"Blur"},{type:"radial-blur",label:"Radial Blur",category:"Blur"},{type:"sharpen",label:"Sharpen",category:"Creative"},{type:"vignette",label:"Vignette",category:"Creative"},{type:"grain",label:"Film Grain",category:"Creative"},{type:"shadow",label:"Drop Shadow",category:"Stylize"},{type:"glow",label:"Glow",category:"Stylize"},{type:"chromatic-aberration",label:"Chromatic Aberration",category:"Stylize"}],fy=[...new Set(Ru.map(t=>t.category))],gy=({onSelect:t})=>e.jsxs(Di,{children:[e.jsx(Ii,{asChild:!0,children:e.jsx("button",{className:"w-full py-2 bg-primary/10 border border-primary/30 rounded-lg text-[10px] text-primary hover:bg-primary/20 transition-colors",children:"+ Add Effect"})}),e.jsx(Bi,{align:"start",className:"w-48 max-h-64 overflow-y-auto",children:fy.map(s=>e.jsxs(_e.Fragment,{children:[e.jsx(Qm,{className:"text-[9px] uppercase tracking-wider text-text-muted",children:s}),Ru.filter(a=>a.category===s).map(a=>e.jsx(ws,{onClick:()=>t(a.type),className:"text-[10px]",children:a.label},a.type))]},s))})]}),by=({clipId:t})=>{const{getVideoEffects:s,addVideoEffect:a,updateVideoEffect:r,removeVideoEffect:n,toggleVideoEffect:i}=F(),o=F(x=>x.project.modifiedAt),c=l.useMemo(()=>s(t),[t,s,o]),d=l.useCallback(x=>{a(t,x)},[t,a]),u=l.useCallback((x,h)=>{r(t,x,h)},[t,r]),p=l.useCallback((x,h)=>{i(t,x,h)},[t,i]),m=l.useCallback(x=>{n(t,x)},[t,n]);return e.jsxs("div",{className:"space-y-3",children:[c.length===0?e.jsx("p",{className:"text-[10px] text-text-muted text-center py-2",children:"No effects applied"}):e.jsx("div",{className:"space-y-2",children:c.map(x=>e.jsx(hy,{effect:x,onUpdate:u,onToggle:p,onRemove:m},x.id))}),e.jsx(gy,{onSelect:d})]})},yy=({color:t,onClick:s})=>e.jsx("button",{onClick:s,className:"w-8 h-8 rounded-lg border-2 border-border hover:border-primary transition-colors",style:{backgroundColor:`rgb(${Math.round(t.r*255)}, ${Math.round(t.g*255)}, ${Math.round(t.b*255)})`},title:"Click to pick color from video"}),Co=({label:t,value:s,onChange:a,min:r=0,max:n=1,step:i=.01})=>{const o=(s-r)/(n-r)*100;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[Math.round(s*100),"%"]})]}),e.jsxs("div",{className:"relative h-1.5",children:[e.jsx("input",{type:"range",min:r,max:n,step:i,value:s,onChange:c=>a(parseFloat(c.target.value)),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"}),e.jsx("div",{className:"absolute inset-0 bg-background-tertiary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${o}%`}})}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-2.5 h-2.5 bg-white rounded-full shadow-sm pointer-events-none",style:{left:`calc(${o}% - 5px)`}})]})]})},vy=({color:t,label:s,isActive:a,onClick:r})=>e.jsxs("button",{onClick:r,className:`flex items-center gap-1.5 px-2 py-1 rounded text-[9px] transition-colors ${a?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,children:[e.jsx("div",{className:"w-3 h-3 rounded-sm border border-border",style:{backgroundColor:`rgb(${Math.round(t.r*255)}, ${Math.round(t.g*255)}, ${Math.round(t.b*255)})`}}),s]}),jy=[{color:{r:0,g:1,b:0},label:"Green"},{color:{r:0,g:0,b:1},label:"Blue"},{color:{r:1,g:0,b:1},label:"Magenta"},{color:{r:0,g:1,b:1},label:"Cyan"}],wy=({clipId:t})=>{const s=F(v=>v.project),a=Ct(v=>v.getChromaKeyEngine),[r,n]=l.useState(!1),[i,o]=l.useState(null);l.useEffect(()=>{let v=!1;return(async()=>{const g=await a();v||o(g)})(),()=>{v=!0}},[a]);const c=l.useMemo(()=>i?i.getSettings(t)||{enabled:!1,keyColor:{r:0,g:1,b:0},tolerance:.3,edgeSoftness:.1,spillSuppression:.5}:{enabled:!1,keyColor:{r:0,g:1,b:0},tolerance:.3,edgeSoftness:.1,spillSuppression:.5},[i,t,s.modifiedAt]),d=l.useCallback(()=>{i&&(c.enabled?i.disableChromaKey(t):i.enableChromaKey(t),F.setState(v=>({project:{...v.project,modifiedAt:Date.now()}})))},[i,t,c.enabled]),u=l.useCallback(v=>{i&&(i.setKeyColor(t,v),F.setState(A=>({project:{...A.project,modifiedAt:Date.now()}})))},[i,t]),p=l.useCallback(v=>{i&&(i.setTolerance(t,v),F.setState(A=>({project:{...A.project,modifiedAt:Date.now()}})))},[i,t]),m=l.useCallback(v=>{i&&(i.setEdgeSoftness(t,v),F.setState(A=>({project:{...A.project,modifiedAt:Date.now()}})))},[i,t]),x=l.useCallback(v=>{i&&(i.setSpillSuppression(t,v),F.setState(A=>({project:{...A.project,modifiedAt:Date.now()}})))},[i,t]),h=l.useCallback(()=>{i&&(i.setSettings(t,{enabled:!0,keyColor:{r:0,g:1,b:0},tolerance:.3,edgeSoftness:.1,spillSuppression:.5}),F.setState(v=>({project:{...v.project,modifiedAt:Date.now()}})))},[i,t]),f=v=>Math.abs(c.keyColor.r-v.r)<.1&&Math.abs(c.keyColor.g-v.g)<.1&&Math.abs(c.keyColor.b-v.b)<.1;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gradient-to-r from-green-500/20 to-emerald-500/20 rounded-lg border border-green-500/30",children:[e.jsx(zs,{size:16,className:"text-green-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Green Screen"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Remove background color from video"})]}),e.jsx("button",{onClick:d,className:`p-1.5 rounded transition-colors ${c.enabled?"bg-green-500/30 text-green-400":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,title:c.enabled?"Disable chroma key":"Enable chroma key",children:c.enabled?e.jsx($s,{size:14}):e.jsx(Xs,{size:14})})]}),c.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:"Key Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>n(!r),className:`p-1.5 rounded transition-colors ${r?"bg-primary text-white":"bg-background-tertiary text-text-muted hover:text-text-primary"}`,title:"Pick color from video",children:e.jsx(Rh,{size:12})}),e.jsx(yy,{color:c.keyColor})]})]}),r&&e.jsx("div",{className:"p-2 bg-primary/10 border border-primary/30 rounded-lg",children:e.jsx("p",{className:"text-[9px] text-primary text-center",children:"Click on the video preview to pick a color"})}),e.jsx("div",{className:"flex flex-wrap gap-1",children:jy.map(v=>e.jsx(vy,{color:v.color,label:v.label,isActive:f(v.color),onClick:()=>u(v.color)},v.label))})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border",children:[e.jsx(Co,{label:"Tolerance",value:c.tolerance,onChange:p}),e.jsx(Co,{label:"Edge Softness",value:c.edgeSoftness,onChange:m}),e.jsx(Co,{label:"Spill Suppression",value:c.spillSuppression,onChange:x})]}),e.jsx("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:e.jsxs("button",{onClick:h,className:"flex-1 flex items-center justify-center gap-1.5 py-2 text-[10px] text-text-secondary hover:text-text-primary bg-background-tertiary rounded-lg transition-colors",children:[e.jsx(na,{size:12}),"Reset to Defaults"]})}),e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg",children:[e.jsx(Os,{size:12,className:"text-text-muted"}),e.jsx("p",{className:"text-[9px] text-text-muted flex-1",children:"Place video clips below this one to use as background"})]})]}),!c.enabled&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx(zs,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Enable to remove background color"}),e.jsx("button",{onClick:d,className:"mt-2 px-4 py-1.5 text-[10px] bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-colors",children:"Enable Green Screen"})]})]})},ky=[{id:"rectangle",name:"Rectangle",icon:Gs},{id:"ellipse",name:"Ellipse",icon:or},{id:"polygon",name:"Polygon",icon:Ah}],Ny=({mask:t,isSelected:s,isExpanded:a,matteSourceOptions:r,ownClipId:n,onSelect:i,onToggleExpand:o,onDelete:c,onDuplicate:d,onUpdateFeathering:u,onUpdateExpansion:p,onUpdateOpacity:m,onToggleInvert:x,onSetMatteSource:h})=>{const v=t.type==="shape"?Gs:t.type==="track-matte"?Os:eu,A=t.type==="shape"?"Shape Mask":t.type==="track-matte"?"Track Matte":"Drawn Mask",g=r.filter(k=>k.id!==n);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${s?"border-primary bg-primary/10":"border-border"}`,children:[e.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2 p-2 hover:bg-background-tertiary transition-colors",children:[e.jsx("button",{onClick:k=>{k.stopPropagation(),o()},className:"p-0.5",children:a?e.jsx(qt,{size:12,className:"text-text-muted"}):e.jsx(bs,{size:12,className:"text-text-muted"})}),e.jsx(v,{size:12,className:"text-primary"}),e.jsx("span",{className:"flex-1 text-left text-[10px] font-medium text-text-primary",children:A}),e.jsx("button",{onClick:k=>{k.stopPropagation(),x()},className:`p-1 rounded transition-colors ${t.inverted?"bg-amber-500/20 text-amber-400":"text-text-muted hover:text-text-primary"}`,title:t.inverted?"Mask Inverted":"Mask Normal",children:t.inverted?e.jsx(Xs,{size:10}):e.jsx($s,{size:10})}),e.jsx("button",{onClick:k=>{k.stopPropagation(),d()},className:"p-1 text-text-muted hover:text-text-primary transition-colors",title:"Duplicate Mask",children:e.jsx(dn,{size:10})}),e.jsx("button",{onClick:k=>{k.stopPropagation(),c()},className:"p-1 text-text-muted hover:text-red-400 transition-colors",title:"Delete Mask",children:e.jsx($t,{size:10})})]}),a&&e.jsxs("div",{className:"p-2 space-y-3 border-t border-border bg-background-tertiary/50",children:[t.type==="track-matte"&&e.jsxs("div",{className:"space-y-2 p-2 bg-primary/5 border border-primary/20 rounded",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Os,{size:11,className:"text-primary"}),e.jsx("span",{className:"text-[9.5px] font-medium text-text-primary",children:"Matte source"})]}),e.jsxs(ot,{value:t.sourceClipId??"",onValueChange:k=>h(k,t.matteSource??"bounds"),children:[e.jsx(lt,{className:"h-7 text-[10px]",children:e.jsx(ct,{placeholder:"Pick a clip…"})}),e.jsx(dt,{children:g.length===0?e.jsx("div",{className:"px-2 py-1 text-[10px] text-text-muted",children:"No other clips available"}):g.map(k=>e.jsx(ge,{value:k.id,children:k.label},k.id))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:"Channel"}),e.jsx("div",{className:"flex gap-1",children:["bounds","alpha","luminance"].map(k=>e.jsx("button",{onClick:()=>h(t.sourceClipId??"",k),disabled:!t.sourceClipId,className:`px-1.5 py-0.5 text-[9px] rounded border transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${(t.matteSource??"bounds")===k?"bg-primary/20 border-primary text-primary":"bg-background-secondary border-border text-text-secondary hover:border-primary/50"}`,children:k},k))})]}),e.jsxs("p",{className:"text-[8.5px] text-text-muted leading-tight",children:["The chosen clip's ",t.matteSource??"bounds"," ","drive the visible region of this clip. Animate the source clip's transform to animate the mask."]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Feathering"}),e.jsxs("span",{className:"text-[9px] text-text-secondary",children:[t.feathering,"px"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[t.feathering],onValueChange:k=>u(k[0])})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Expansion"}),e.jsxs("span",{className:"text-[9px] text-text-secondary",children:[t.expansion,"px"]})]}),e.jsx(st,{min:-100,max:100,step:1,value:[t.expansion],onValueChange:k=>p(k[0])})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Opacity"}),e.jsxs("span",{className:"text-[9px] text-text-secondary",children:[Math.round(t.opacity*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[t.opacity*100],onValueChange:k=>m(k[0]/100)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:[e.jsxs("button",{onClick:x,className:`flex-1 flex items-center justify-center gap-1 py-1.5 text-[9px] rounded transition-colors ${t.inverted?"bg-amber-500/20 text-amber-400":"bg-background-secondary text-text-secondary hover:text-text-primary"}`,children:[t.inverted?e.jsx(Xs,{size:10}):e.jsx($s,{size:10}),t.inverted?"Inverted":"Invert"]}),e.jsx("span",{className:"text-[8px] text-text-muted",children:t.keyframes.length>0?`${t.keyframes.length} keyframes`:"No keyframes"})]})]})]})},Cy=({clipId:t})=>{const s=Ct(C=>C.getMaskEngine),a=F(C=>C.project),r=F(C=>C.getAllTextClips),[n,i]=l.useState(null),[o,c]=l.useState(new Set),[d,u]=l.useState(0),[p,m]=l.useState(null),x=l.useMemo(()=>{const C=[];for(const M of a.timeline.tracks)for(const z of M.clips){const L=a.mediaLibrary.items.find(B=>B.id===z.mediaId)?.name??z.mediaId.slice(0,8);C.push({id:z.id,label:`${M.name} • ${L}`})}try{for(const M of r())C.push({id:M.id,label:`Text • "${M.text.slice(0,20)}${M.text.length>20?"…":""}"`})}catch{}return C},[a,r]);l.useEffect(()=>{let C=!1;return(async()=>{const z=await s();C||m(z)})(),()=>{C=!0}},[s]);const h=l.useMemo(()=>p?p.getMasksForClip(t):[],[p,t,d]);l.useEffect(()=>{if(!p)return;const C=h.filter(z=>z.type==="track-matte");if(C.length===0)return;let M=!1;for(const z of C){if(!z.sourceClipId)continue;let L=null;for(const G of a.timeline.tracks){const V=G.clips.find(P=>P.id===z.sourceClipId);if(V){L={position:V.transform.position,scale:V.transform.scale};break}}if(!L)try{const V=r().find(P=>P.id===z.sourceClipId);V&&(L={position:V.transform.position,scale:V.transform.scale})}catch{}if(!L)continue;const B=Jm(L),O=z.path;JSON.stringify(O)!==JSON.stringify(B)&&(p.updateMaskPath(z.id,B),M=!0)}M&&u(z=>z+1)},[p,h,a,r]);const f=l.useCallback(()=>{u(C=>C+1),F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}}))},[]),v=l.useCallback(C=>{if(!p)return;const M={rectangle:{type:"rectangle",x:.25,y:.25,width:.5,height:.5},ellipse:{type:"ellipse",cx:.5,cy:.5,rx:.25,ry:.25},polygon:{type:"polygon",points:[{x:.5,y:.2},{x:.8,y:.5},{x:.5,y:.8},{x:.2,y:.5}]}},z=p.createShapeMask(t,M[C]);i(z.id),c(L=>new Set([...L,z.id])),f()},[p,t,f]),A=l.useCallback(C=>{p&&(p.deleteMask(C),n===C&&i(null),c(M=>{const z=new Set(M);return z.delete(C),z}),f())},[p,n,f]),g=l.useCallback(C=>{if(!p)return;const M=p.createDrawnMask(t,{...C.path});p.setFeathering(M.id,C.feathering),p.setExpansion(M.id,C.expansion),p.setInverted(M.id,C.inverted),i(M.id),f()},[p,t,f]),k=l.useCallback((C,M)=>{p&&(p.setFeathering(C,M),f())},[p,f]),N=l.useCallback((C,M)=>{p&&(p.setExpansion(C,M),f())},[p,f]),b=l.useCallback((C,M)=>{if(!p)return;const z=p.getMask(C);z&&(p.updateMaskPath(C,z.path),f())},[p,f]),j=l.useCallback(C=>{if(!p)return;const M=p.getMask(C);M&&(p.setInverted(C,!M.inverted),f())},[p,f]),y=l.useCallback(()=>{if(!p)return;const C=x.find(z=>z.id!==t),M=p.createTrackMatteMask(t,C?.id??"","bounds");i(M.id),c(z=>new Set([...z,M.id])),f()},[p,t,x,f]),w=l.useCallback((C,M,z)=>{p&&(p.setMatteSource(C,M,z),f())},[p,f]),S=C=>{c(M=>{const z=new Set(M);return z.has(C)?z.delete(C):z.add(C),z})},T=l.useCallback(()=>{if(p){for(const C of h)p.deleteMask(C.id);i(null),c(new Set),f()}},[p,h,f]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gradient-to-r bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Gs,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Masking"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Control visible regions of clip"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Add Mask Shape"})}),e.jsxs("div",{className:"grid grid-cols-5 gap-1",children:[ky.map(C=>{const M=C.icon;return e.jsxs("button",{onClick:()=>v(C.id),className:"flex flex-col items-center gap-1 p-2 rounded-lg bg-background-tertiary hover:bg-primary/20 border border-transparent hover:border-primary/30 transition-colors",title:C.name,children:[e.jsx(M,{size:14,className:"text-text-secondary"}),e.jsx("span",{className:"text-[8px] text-text-muted",children:C.name})]},C.id)}),e.jsxs("button",{onClick:()=>{},className:"flex flex-col items-center gap-1 p-2 rounded-lg bg-background-tertiary hover:bg-primary/20 border border-transparent hover:border-primary/30 transition-colors",title:"Draw Freehand",children:[e.jsx(eu,{size:14,className:"text-text-secondary"}),e.jsx("span",{className:"text-[8px] text-text-muted",children:"Freehand"})]}),e.jsxs("button",{onClick:y,className:"flex flex-col items-center gap-1 p-2 rounded-lg bg-background-tertiary hover:bg-primary/20 border border-transparent hover:border-primary/30 transition-colors",title:"Use another clip as a track matte (Premiere-style object masking)",children:[e.jsx(Os,{size:14,className:"text-text-secondary"}),e.jsx("span",{className:"text-[8px] text-text-muted",children:"Track Matte"})]})]})]}),h.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[10px] font-medium text-text-secondary",children:["Masks (",h.length,")"]}),e.jsxs("button",{onClick:T,className:"flex items-center gap-1 px-2 py-1 text-[9px] text-red-400 hover:bg-red-400/10 rounded transition-colors",children:[e.jsx(na,{size:10}),"Clear All"]})]}),e.jsx("div",{className:"space-y-2",children:h.map(C=>e.jsx(Ny,{mask:C,isSelected:n===C.id,isExpanded:o.has(C.id),matteSourceOptions:x,ownClipId:t,onSelect:()=>i(C.id),onToggleExpand:()=>S(C.id),onDelete:()=>A(C.id),onDuplicate:()=>g(C),onUpdateFeathering:M=>k(C.id,M),onUpdateExpansion:M=>N(C.id,M),onUpdateOpacity:M=>b(C.id,M),onToggleInvert:()=>j(C.id),onSetMatteSource:(M,z)=>w(C.id,M,z)},C.id))})]}):e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Gs,{size:24,className:"mx-auto mb-2 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No masks on this clip"}),e.jsx("p",{className:"text-[9px] text-text-muted mt-1",children:"Click a shape above to add a mask"})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Masks control which parts of the clip are visible"})})]})},Sy=[{id:"slow-25",name:"0.25x",speed:.25,icon:uo},{id:"slow-50",name:"0.5x",speed:.5,icon:uo},{id:"slow-75",name:"0.75x",speed:.75,icon:uo},{id:"normal",name:"1x",speed:1,icon:As},{id:"fast-150",name:"1.5x",speed:1.5,icon:ni},{id:"fast-200",name:"2x",speed:2,icon:ni},{id:"fast-400",name:"4x",speed:4,icon:ni},{id:"fast-800",name:"8x",speed:8,icon:ni}],Ay=({keyframes:t,duration:s,baseSpeed:a,onAddKeyframe:r,onRemoveKeyframe:n,onMoveKeyframe:i})=>{const o=l.useRef(null),[c,d]=l.useState(null),[u,p]=l.useState(null),m=l.useRef({keyframeId:null,didDrag:!1,downX:0,downY:0}),x=l.useMemo(()=>[...t].sort((j,y)=>j.time-y.time),[t]);l.useEffect(()=>{const j=o.current;if(!j)return;const y=j.getContext("2d");if(!y)return;const w=j.width,S=j.height,T=20,C=w-T*2,M=S-T*2;y.clearRect(0,0,w,S),y.fillStyle="#1a1a1a",y.fillRect(0,0,w,S),y.strokeStyle="#333",y.lineWidth=1;for(let V=0;V<=4;V++){const P=T+M*V/4;y.beginPath(),y.moveTo(T,P),y.lineTo(w-T,P),y.stroke()}y.strokeStyle="#444",y.setLineDash([5,5]);const z=T+M*(1-(1-fa)/(ar-fa));y.beginPath(),y.moveTo(T,z),y.lineTo(w-T,z),y.stroke(),y.setLineDash([]),y.strokeStyle="#22c55e",y.lineWidth=2,y.beginPath();const L=V=>{if(x.length===0)return a;if(V<=x[0].time)return x[0].speed;if(V>=x[x.length-1].time)return x[x.length-1].speed;for(let P=0;P=x[P].time&&V<=x[P+1].time){const _=x[P],se=x[P+1],R=(V-_.time)/(se.time-_.time);return _.speed+(se.speed-_.speed)*R}return a},B=V=>{const P=(Math.log(V)-Math.log(fa))/(Math.log(ar)-Math.log(fa));return T+M*(1-P)},O=V=>T+V/s*C,G=100;for(let V=0;V<=G;V++){const P=V/G*s,_=L(P),se=O(P),R=B(_);V===0?y.moveTo(se,R):y.lineTo(se,R)}y.stroke(),x.forEach(V=>{const P=O(V.time),_=B(V.speed),se=c===V.id,R=u===V.id;y.beginPath(),y.arc(P,_,R?8:se?7:6,0,Math.PI*2),y.fillStyle=R?"#16a34a":se?"#4ade80":"#22c55e",y.fill(),y.strokeStyle="#fff",y.lineWidth=2,y.stroke()}),y.fillStyle="#666",y.font="10px sans-serif",y.textAlign="left",y.fillText(`${ar}x`,2,T+4),y.fillText("1x",2,z+4),y.fillText(`${fa}x`,2,S-T+4)},[x,s,a,c,u]);const h=20,f=10,v=l.useCallback((j,y)=>{const w=j.getBoundingClientRect(),S=j.width/w.width,T=j.height/w.height,C=(y.clientX-w.left)*S,M=(y.clientY-w.top)*T,z=j.width-h*2,L=j.height-h*2,B=(C-h)/z*s,O=(M-h)/L,G=Math.exp(Math.log(ar)-O*(Math.log(ar)-Math.log(fa)));return{canvasX:C,canvasY:M,time:B,speed:Math.max(fa,Math.min(ar,G))}},[s]),A=l.useCallback((j,y,w)=>{const S=j.width-h*2,T=j.height-h*2;return x.find(C=>{const M=h+C.time/s*S,z=h+T*(1-(Math.log(C.speed)-Math.log(fa))/(Math.log(ar)-Math.log(fa)));return Math.abs(y-M){const y=o.current;if(!y)return;const{canvasX:w,canvasY:S}=v(y,j),T=A(y,w,S);m.current={keyframeId:T?.id??null,didDrag:!1,downX:j.clientX,downY:j.clientY},T&&p(T.id)},[v,A]),k=l.useCallback(j=>{const y=o.current;if(!y)return;const{canvasX:w,canvasY:S,time:T,speed:C}=v(y,j);if(!m.current.keyframeId){const M=A(y,w,S);d(M?.id??null)}if(m.current.keyframeId){const M=Math.abs(j.clientX-m.current.downX),z=Math.abs(j.clientY-m.current.downY);(M>3||z>3)&&(m.current.didDrag=!0);const L=Math.max(0,Math.min(s,T));i(m.current.keyframeId,L,C)}},[v,A,s,i]),N=l.useCallback(j=>{const y=o.current;if(!y)return;const w=m.current,{canvasX:S,canvasY:T,time:C,speed:M}=v(y,j);if(w.keyframeId)w.didDrag||n(w.keyframeId);else{const z=Math.abs(j.clientX-w.downX),L=Math.abs(j.clientY-w.downY);z<4&&L<4&&C>=0&&C<=s&&S>=h&&S<=y.width-h&&T>=h&&T<=y.height-h&&r(C,M)}m.current={keyframeId:null,didDrag:!1,downX:0,downY:0},p(null)},[v,s,r,n]),b=l.useCallback(()=>{m.current.keyframeId&&(m.current={keyframeId:null,didDrag:!1,downX:0,downY:0},p(null)),d(null)},[]);return e.jsxs("div",{className:"relative",children:[e.jsx("canvas",{ref:o,width:280,height:120,onMouseDown:g,onMouseMove:k,onMouseUp:N,onMouseLeave:b,className:`w-full rounded-lg border border-border ${u?"cursor-grabbing":c?"cursor-grab":"cursor-crosshair"}`}),e.jsx("div",{className:"absolute bottom-1 right-1 text-[8px] text-text-muted pointer-events-none",children:"Click to add • Drag to move • Click a point to remove"})]})},Ty=({clip:t})=>{const s=Et(T=>T.playheadPosition),a=l.useMemo(()=>ba(),[]),[r,n]=l.useState(!1),[i,o]=l.useState(!1);l.useEffect(()=>{a.initializeClip(t.id,t.duration)},[t.id,t.duration,a]);const c=l.useMemo(()=>a.getClipSpeedData(t.id),[t.id,a]),d=c?.baseSpeed??1,u=c?.reverse??!1,p=c?.keyframes??[],m=c?.freezeFrames??[],x=c?.pitchCorrection??!0,h=l.useCallback(T=>{a.setClipSpeed(t.id,T,t.duration),F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}}))},[t.id,t.duration,a]),f=l.useCallback(()=>{a.setReverse(t.id,!u,t.duration),F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}}))},[t.id,t.duration,u,a]),v=l.useCallback(()=>{a.setPitchCorrection(t.id,!x),F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}}))},[t.id,x,a]),A=l.useCallback((T,C)=>{a.addSpeedKeyframe(t.id,T,C,"ease-in-out"),F.setState(M=>({project:{...M.project,modifiedAt:Date.now()}}))},[t.id,a]),g=l.useCallback(T=>{a.removeSpeedKeyframe(t.id,T),F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}}))},[t.id,a]),k=l.useCallback((T,C,M)=>{a.updateSpeedKeyframe(t.id,T,{time:C,speed:M}),F.setState(z=>({project:{...z.project,modifiedAt:Date.now()}}))},[t.id,a]),N=l.useCallback(()=>{const T=s,C=t.startTime,M=T-C;M>=0&&M<=t.duration&&(a.createFreezeFrame(t.id,M,M,2),F.setState(z=>({project:{...z.project,modifiedAt:Date.now()}})))},[t.id,t.startTime,t.duration,a,s]),b=l.useCallback(T=>{a.removeFreezeFrame(t.id,T),F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}}))},[t.id,a]),j=l.useCallback(T=>{const C=oc.find(M=>M.id===T);if(C){p.forEach(M=>a.removeSpeedKeyframe(t.id,M.id));for(const M of C.keyframes){const z=M.time*t.duration;a.addSpeedKeyframe(t.id,z,M.speed,M.easing)}o(!0),F.setState(M=>({project:{...M.project,modifiedAt:Date.now()}}))}},[t.id,t.duration,p,a]),y=l.useCallback(()=>{a.setClipSpeed(t.id,1,t.duration),a.setReverse(t.id,!1,t.duration),p.forEach(T=>a.removeSpeedKeyframe(t.id,T.id)),m.forEach(T=>a.removeFreezeFrame(t.id,T.id)),F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}}))},[t.id,t.duration,p,m,a]),w=l.useMemo(()=>a.getEffectiveDuration(t.id),[t.id,a,d,p]),S=T=>{const C=Math.floor(T/60),M=(T%60).toFixed(2);return`${C}:${M.padStart(5,"0")}`};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"p-2 bg-background-tertiary rounded-lg border border-border",children:e.jsxs("p",{className:"text-[10px] text-text-muted",children:["Effective duration: ",S(w)]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Playback Speed"}),e.jsxs("span",{className:"text-[10px] font-mono text-primary",children:[d.toFixed(2),"x"]})]}),e.jsx(st,{min:Math.log(fa),max:Math.log(ar),step:.01,value:[Math.log(d)],onValueChange:T=>h(Math.exp(T[0]))}),e.jsxs("div",{className:"flex justify-between text-[8px] text-text-muted",children:[e.jsx("span",{children:"0.1x"}),e.jsx("span",{children:"1x"}),e.jsx("span",{children:"20x"})]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:Sy.map(T=>e.jsx("button",{onClick:()=>h(T.speed),className:`py-1.5 px-2 text-[9px] rounded-lg border transition-colors ${Math.abs(d-T.speed)<.01?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:T.name},T.id))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:f,className:`flex-1 flex items-center justify-center gap-1.5 py-2 text-[10px] rounded-lg border transition-colors ${u?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:[e.jsx(Ns,{size:12}),"Reverse"]}),e.jsx("button",{onClick:v,className:`flex-1 flex items-center justify-center gap-1.5 py-2 text-[10px] rounded-lg border transition-colors ${x?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:"Pitch Correct"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Speed Curve Presets"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:oc.map(T=>e.jsx("button",{onClick:()=>j(T.id),className:"py-1.5 px-2 text-[9px] rounded-lg border bg-background-tertiary border-border text-text-secondary hover:border-primary/50 hover:text-primary transition-colors text-left",title:T.description,children:T.name},T.id))})]}),e.jsxs("button",{onClick:()=>o(!i),className:"w-full flex items-center gap-2 py-2 text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[i?e.jsx(qt,{size:12}):e.jsx(bs,{size:12}),e.jsx("span",{className:"font-medium",children:"Speed Ramping"}),p.length>0&&e.jsxs("span",{className:"ml-auto text-[9px] text-primary",children:[p.length," keyframes"]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ay,{keyframes:p,duration:t.duration,baseSpeed:d,onAddKeyframe:A,onRemoveKeyframe:g,onMoveKeyframe:k}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-24 overflow-y-auto",children:p.map((T,C)=>e.jsxs("div",{className:"flex items-center gap-2 p-1.5 bg-background-tertiary rounded text-[9px]",children:[e.jsxs("span",{className:"text-text-muted",children:["#",C+1]}),e.jsxs("span",{className:"text-text-secondary",children:[T.time.toFixed(2),"s"]}),e.jsxs("span",{className:"text-primary font-mono",children:[T.speed.toFixed(2),"x"]}),e.jsx("button",{onClick:()=>g(T.id),className:"ml-auto p-0.5 text-text-muted hover:text-red-400",children:e.jsx($t,{size:10})})]},T.id))})]}),e.jsxs("button",{onClick:()=>n(!r),className:"w-full flex items-center gap-2 py-2 text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[r?e.jsx(qt,{size:12}):e.jsx(bs,{size:12}),e.jsx("span",{className:"font-medium",children:"Freeze Frames"}),m.length>0&&e.jsxs("span",{className:"ml-auto text-[9px] text-primary",children:[m.length," freeze"]})]}),r&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:N,className:"w-full flex items-center justify-center gap-1.5 py-2 text-[10px] bg-primary/20 border border-primary/30 text-primary rounded-lg hover:bg-primary/20 transition-colors",children:[e.jsx(dr,{size:12}),"Add Freeze Frame at Playhead"]}),m.length>0&&e.jsx("div",{className:"space-y-1 max-h-24 overflow-y-auto",children:m.map(T=>e.jsxs("div",{className:"flex items-center gap-2 p-1.5 bg-background-tertiary rounded text-[9px]",children:[e.jsx(dr,{size:10,className:"text-primary"}),e.jsxs("span",{className:"text-text-secondary",children:[T.startTime.toFixed(2),"s"]}),e.jsx("span",{className:"text-text-muted",children:"for"}),e.jsxs("span",{className:"text-primary font-mono",children:[T.duration.toFixed(1),"s"]}),e.jsx("button",{onClick:()=>b(T.id),className:"ml-auto p-0.5 text-text-muted hover:text-red-400",children:e.jsx($t,{size:10})})]},T.id))})]}),e.jsxs("button",{onClick:y,className:"w-full flex items-center justify-center gap-1.5 py-2 text-[10px] bg-background-tertiary border border-border text-text-secondary rounded-lg hover:border-red-500/50 hover:text-red-400 transition-colors",children:[e.jsx(Ns,{size:12}),"Reset Speed & Effects"]})]})},yi=[{id:"top-left",name:"Top Left",icon:"corner",transform:{position:{x:-.35,y:-.35},scale:{x:.3,y:.3}}},{id:"top-right",name:"Top Right",icon:"corner",transform:{position:{x:.35,y:-.35},scale:{x:.3,y:.3}}},{id:"bottom-left",name:"Bottom Left",icon:"corner",transform:{position:{x:-.35,y:.35},scale:{x:.3,y:.3}}},{id:"bottom-right",name:"Bottom Right",icon:"corner",transform:{position:{x:.35,y:.35},scale:{x:.3,y:.3}}},{id:"split-left",name:"Split Left",icon:"split",transform:{position:{x:-.25,y:0},scale:{x:.5,y:1}}},{id:"split-right",name:"Split Right",icon:"split",transform:{position:{x:.25,y:0},scale:{x:.5,y:1}}},{id:"split-top",name:"Split Top",icon:"split",transform:{position:{x:0,y:-.25},scale:{x:1,y:.5}}},{id:"split-bottom",name:"Split Bottom",icon:"split",transform:{position:{x:0,y:.25},scale:{x:1,y:.5}}},{id:"center-small",name:"Center Small",icon:"center",transform:{position:{x:0,y:0},scale:{x:.5,y:.5}}},{id:"center-medium",name:"Center Medium",icon:"center",transform:{position:{x:0,y:0},scale:{x:.7,y:.7}}},{id:"fullscreen",name:"Full Screen",icon:"center",transform:{position:{x:0,y:0},scale:{x:1,y:1}}}],My=({type:t,className:s=""})=>{switch(t){case"corner":return e.jsx(Gs,{size:14,className:s});case"split":return e.jsx(Cd,{size:14,className:s});case"center":return e.jsx(zr,{size:14,className:s});default:return e.jsx(rn,{size:14,className:s})}},Cr=({label:t,value:s,onChange:a,min:r=-1,max:n=1,step:i=.01,unit:o=""})=>{const c=(s-r)/(n-r)*100;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[s.toFixed(2),o]})]}),e.jsxs("div",{className:"relative h-1.5",children:[e.jsx("input",{type:"range",min:r,max:n,step:i,value:s,onChange:d=>a(parseFloat(d.target.value)),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"}),e.jsx("div",{className:"absolute inset-0 bg-background-tertiary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${c}%`}})}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-2.5 h-2.5 bg-white rounded-full shadow-sm pointer-events-none",style:{left:`calc(${c}% - 5px)`}})]})]})},So=({preset:t,isActive:s,onClick:a})=>e.jsxs("button",{onClick:a,className:`flex flex-col items-center gap-1 p-2 rounded-lg border transition-colors ${s?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-muted hover:text-text-primary hover:border-primary/50"}`,title:t.name,children:[e.jsx(My,{type:t.icon}),e.jsx("span",{className:"text-[8px] truncate max-w-full",children:t.name})]}),Ey=({clipId:t})=>{const s=F(g=>g.project),a=F(g=>g.updateClipTransform),[r,n]=l.useState(!1),i=l.useMemo(()=>{for(const g of s.timeline.tracks){const k=g.clips.find(N=>N.id===t);if(k)return k}return null},[s,t]),o=l.useMemo(()=>i?i.transform:{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},[i]),c=l.useMemo(()=>{for(const g of yi){const k=g.transform;if(k.position&&k.scale&&Math.abs(o.position.x-k.position.x)<.05&&Math.abs(o.position.y-k.position.y)<.05&&Math.abs(o.scale.x-k.scale.x)<.05&&Math.abs(o.scale.y-k.scale.y)<.05)return g.id}return null},[o]),d=l.useCallback(g=>{if(!i)return;const k={...o,position:g.transform.position||o.position,scale:g.transform.scale||o.scale};a(t,k)},[i,t,o,a]),u=l.useCallback((g,k)=>{if(!i)return;const N={...o,position:{...o.position,[g]:k}};a(t,N)},[i,t,o,a]),p=l.useCallback((g,k)=>{if(!i)return;const N=g==="both"?{x:k,y:k}:{...o.scale,[g]:k},b={...o,scale:N};a(t,b)},[i,t,o,a]),m=l.useCallback(g=>{if(!i)return;const k={...o,borderRadius:g};a(t,k)},[i,t,o,a]),x=l.useCallback(g=>{if(!i)return;const k={...o,opacity:g};a(t,k)},[i,t,o,a]),h=l.useCallback(()=>{if(!i)return;a(t,{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1,borderRadius:0})},[i,t,a]),f=yi.filter(g=>g.icon==="corner"),v=yi.filter(g=>g.icon==="split"),A=yi.filter(g=>g.icon==="center");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gradient-to-r bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Mh,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Picture-in-Picture"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Position and scale video overlay"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Corner Positions"}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:f.map(g=>e.jsx(So,{preset:g,isActive:c===g.id,onClick:()=>d(g)},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Split Screen"}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:v.map(g=>e.jsx(So,{preset:g,isActive:c===g.id,onClick:()=>d(g)},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Center & Full"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:A.map(g=>e.jsx(So,{preset:g,isActive:c===g.id,onClick:()=>d(g)},g.id))})]}),e.jsxs("button",{onClick:()=>n(!r),className:"w-full py-1.5 text-[10px] text-text-secondary hover:text-text-primary bg-background-tertiary rounded-lg transition-colors",children:[r?"Hide":"Show"," Advanced Controls"]}),r&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Position"}),e.jsx(Cr,{label:"X Position",value:o.position.x,onChange:g=>u("x",g),min:-1,max:1}),e.jsx(Cr,{label:"Y Position",value:o.position.y,onChange:g=>u("y",g),min:-1,max:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Scale"}),e.jsx(Cr,{label:"Uniform Scale",value:o.scale.x,onChange:g=>p("both",g),min:.1,max:2}),e.jsx(Cr,{label:"X Scale",value:o.scale.x,onChange:g=>p("x",g),min:.1,max:2}),e.jsx(Cr,{label:"Y Scale",value:o.scale.y,onChange:g=>p("y",g),min:.1,max:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Appearance"}),e.jsx(Cr,{label:"Border Radius",value:o.borderRadius||0,onChange:m,min:0,max:50,unit:"px"}),e.jsx(Cr,{label:"Opacity",value:o.opacity,onChange:x,min:0,max:1})]})]}),e.jsxs("button",{onClick:h,className:"w-full flex items-center justify-center gap-1.5 py-2 text-[10px] text-text-secondary hover:text-text-primary bg-background-tertiary rounded-lg transition-colors",children:[e.jsx(Ns,{size:12}),"Reset to Default"]}),e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Drag clip in preview to fine-tune position"})]})},Ry=async(t,s,a={})=>{const r=a.audioTrackIndex??0;try{const{getFFmpegFallback:n}=await zi(async()=>{const{getFFmpegFallback:u}=await import("./index-Dws9LQij.js").then(p=>p.eB);return{getFFmpegFallback:u}},__vite__mapDeps([1,2,3,4,5])),i=n();a.onProgress?.({stage:"extracting",progress:.08,message:"Extracting audio track"});const o=await i.extractAudioAsWav(s,r,{onProgress:u=>{a.onProgress?.({stage:"extracting",progress:Math.min(.82,.08+u.progress*.72),message:"Extracting audio track"})}});a.onProgress?.({stage:"decoding",progress:.88,message:"Decoding extracted audio"});const c=await o.arrayBuffer(),d=await t.decodeAudioData(c);return a.onProgress?.({stage:"decoding",progress:1,message:"Audio ready for analysis"}),d}catch{a.onProgress?.({stage:"decoding",progress:.45,message:"Falling back to source audio decode"})}if(r===0)try{a.onProgress?.({stage:"decoding",progress:.55,message:"Decoding source audio"});const n=await s.arrayBuffer(),i=await t.decodeAudioData(n);return a.onProgress?.({stage:"decoding",progress:1,message:"Audio ready for analysis"}),i}catch{return null}return null},Ao={threshold:ns.threshold,reduction:ns.reduction,attack:ns.attack,release:ns.release,focus:ns.focus},To=24,Py=3,zy=4,Dy=(t,s)=>{for(const a of t.timeline.tracks){const r=a.clips.find(n=>n.id===s);if(r)return r}return null},Iy=t=>{if(!Number.isFinite(t)||t<=0)return[];if(t<=To)return[{start:0,end:t}];const s=Math.max(1,Math.min(Py,Math.floor(t/zy))),a=Math.max(1,Math.min(s,Math.ceil(t/To))),r=Math.min(t,To/a),n=a===1?.5:.18,i=a===1?.5:.82;return Array.from({length:a},(o,c)=>{const d=a===1?.5:n+(i-n)*c/(a-1),u=Math.max(0,t-r),p=Math.min(u,Math.max(0,t*d-r/2));return{start:p,end:Math.min(t,p+r)}})},By=(t,s,a)=>{const r=Iy(t.duration);if(r.length===0)throw new Error("Clip audio range is empty");if(r.length===1&&r[0].start<=0&&r[0].end>=t.duration)return a?.({progress:.4,message:"Analyzing clip audio"}),{sampleBuffer:t,sampleCount:1};const n=r.map((d,u)=>(a?.({progress:(u+1)/(r.length+1),message:`Sampling clip audio (${u+1}/${r.length})`}),Ed(t,d.start,d.end,s))),i=n.reduce((d,u)=>d+u.length,0),o=s.createBuffer(t.numberOfChannels,i,t.sampleRate);let c=0;for(const d of n){for(let u=0;u{const{sampleBuffer:n,sampleCount:i}=By(s,a,r),c=new ep().learnNoiseProfile(n);return r?.({progress:1,message:i>1?`Analyzed ${i} clip samples`:"Analyzed clip audio"}),{id:`analysis-${t}`,frequencyBins:c.frequencyBins,magnitudes:c.magnitudes,standardDeviations:c.standardDeviations,sampleRate:c.sampleRate,fftSize:c.fftSize,createdAt:Date.now()}},Ly=({clipId:t})=>{const s=ns.focus??"balanced",a=F(K=>K.project),n=_e.useMemo(()=>{const K=Dy(a,t);return K?Md(K,a.timeline):null},[t,a])?.id??t,i=F(K=>K.getAudioEffects(n)),o=F(K=>K.setAudioEffectPreviewBypass),c=F(K=>K.toggleAudioEffect),[d,u]=l.useState(!1),[p,m]=l.useState(null),[x,h]=l.useState(Ao),[f,v]=l.useState("idle"),[A,g]=l.useState(s),[k,N]=l.useState(null),[b,j]=l.useState(null),[y,w]=l.useState(null),[S,T]=l.useState(null),[C,M]=l.useState(!0),z=Ra(A),B=i.find(K=>K.type==="noiseReduction")?.metadata?.previewBypass===!0;l.useEffect(()=>{jl().catch(K=>{console.error("Failed to initialize AudioBridgeEffects:",K)})},[]),l.useEffect(()=>{j(null),v("idle"),N(null),w(null),T(null)},[n,t]),l.useEffect(()=>{const K=i.find(ue=>ue.type==="noiseReduction");if(K){u(K.enabled),m(K.id);const ue=K.params;h({...Ao,...ue}),g(ue.focus??s);return}u(!1),m(null),h(Ao),g(s)},[i,t,s]);const O=l.useCallback((K,ue=p)=>{const Te=Us();if(ue){const fe=Te.updateNoiseReduction(n,ue,K);if(!fe.success)throw new Error(fe.error??"Failed to update noise reduction");return c(n,ue,!0),o(n,ue,!1),u(!0),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate")),ue}const pe=Te.applyNoiseReduction(n,K);if(!pe.success||!pe.effectId)throw new Error(pe.error??"Failed to apply noise reduction");return m(pe.effectId),o(n,pe.effectId,!1),u(!0),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate")),pe.effectId},[n,p,o,c]),G=l.useCallback(K=>{if(K&&!p)try{O(x)}catch(ue){N(ue instanceof Error?ue.message:"Failed to apply noise reduction");return}else p&&(c(n,p,K),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate")));u(K)},[O,n,x,p,c]),V=l.useCallback((K,ue)=>{const Te=Us();h(pe=>{const fe={...pe,[K]:ue};return p&&d&&(Te.updateNoiseReduction(n,p,fe),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"))),fe})},[n,p,d]),P=l.useCallback(K=>{T({progress:Math.max(0,Math.min(1,K.progress)),message:K.message})},[]),_=l.useCallback(async()=>{const K=F.getState().project,ue=K.timeline.tracks.flatMap(fe=>fe.clips).find(fe=>fe.id===n);if(!ue)throw new Error("Clip not found");const Te=K.mediaLibrary.items.find(fe=>fe.id===ue.mediaId);if(!Te?.blob)throw new Error("No audio data available for this clip");let pe=null;try{P({progress:.03,message:"Preparing clip analysis"}),pe=new AudioContext;const fe=await Ry(pe,Te.blob,{audioTrackIndex:ue.audioTrackIndex??0,onProgress:P});if(!fe)throw new Error("Failed to decode audio for analysis");const We=Math.max(0,ue.inPoint||0),Ze=Math.min(fe.duration,ue.outPoint>We?ue.outPoint:We+ue.duration);if(Ze<=We)throw new Error("Clip audio range is empty");const at=new OfflineAudioContext(fe.numberOfChannels,Math.max(1,Math.ceil((Ze-We)*fe.sampleRate)),fe.sampleRate),de=Ed(fe,We,Ze,at);P({progress:.84,message:"Analyzing noise signature"});const Ce=Fy(n,de,at,qe=>{P({progress:.84+qe.progress*.08,message:qe.message})});P({progress:.93,message:"Learning custom cleanup profile"});const Ne=await Zm(de,at);if(P({progress:1,message:"Recommendation ready"}),!Ne)return{recommendationProfile:Ce,learnedProfile:null};const Me={id:`profile-${n}`,frequencyBins:Ne.frequencyBins,magnitudes:Ne.magnitudes,standardDeviations:Ne.standardDeviations,sampleRate:Ne.sampleRate,fftSize:Ne.fftSize,createdAt:Date.now()};return{recommendationProfile:Ce,learnedProfile:{profile:Me,serializedProfile:{frequencyBins:Array.from(Me.frequencyBins),magnitudes:Array.from(Me.magnitudes),standardDeviations:Me.standardDeviations?Array.from(Me.standardDeviations):void 0,sampleRate:Me.sampleRate,fftSize:Me.fftSize}}}}finally{await pe?.close()}},[n,P]),se=l.useCallback(async K=>{N(null),j(null),w(null),v("applying");try{const ue=Ra(K).config,Te=x.profile?{...ue,profile:x.profile}:{...ue};g(K),h(Te);const pe=O(Te);let fe=`${Ra(K).label} applied to this clip.`;try{const{learnedProfile:We}=await _();if(!We){T(null),w(fe),v("success"),setTimeout(()=>{v("idle")},2e3);return}const Ze={...ue,profile:We.serializedProfile};h(Ze),O(Ze,pe),fe=`${Ra(K).label} learned and applied to this clip.`}catch{fe=`${Ra(K).label} applied to this clip.`}T(null),w(fe),v("success"),setTimeout(()=>{v("idle")},2e3)}catch(ue){v("error"),N(ue instanceof Error?ue.message:"Failed to apply noise reduction preset")}},[O,_,x.profile]),R=l.useCallback(K=>{p&&(o(n,p,K==="original"),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate")))},[n,p,o]),U=l.useCallback(async()=>{v("learning"),N(null),j(null),w(null),T({progress:.02,message:"Preparing clip analysis"});try{const{recommendationProfile:K,learnedProfile:ue}=await _(),Te=Mu(K),pe=ue?{...qc(K),profile:ue.serializedProfile}:qc(K);j({presetId:Te,config:pe,profile:ue?.serializedProfile,hasLearnedProfile:ue!==null}),T(null),v("ready")}catch(K){v("error"),N(K instanceof Error?K.message:"Failed to analyze this clip"),T(null),setTimeout(()=>{v("idle"),N(null)},3e3)}},[_]),D=l.useCallback(()=>{if(b){v("applying"),N(null);try{h(b.config),g(b.presetId),O(b.config),j(null),w(`${Ra(b.presetId).label} applied to this clip.`),v("success"),setTimeout(()=>{v("idle")},2e3)}catch(K){v("error"),N(K instanceof Error?K.message:"Failed to apply recommended cleanup")}}},[O,b]),X=b?Ra(b.presetId):null;return e.jsxs("div",{className:`border rounded-lg overflow-hidden ${d?"border-border":"border-border/50 opacity-60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary",children:[e.jsxs("button",{onClick:()=>M(!C),className:"flex-1 flex items-center gap-1",children:[e.jsx(qt,{size:12,className:`transition-transform ${C?"":"-rotate-90"} text-text-muted`}),e.jsx(Ts,{size:12,className:"text-text-muted"}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:"Noise Reduction"})]}),e.jsx("button",{onClick:()=>G(!d),className:`w-8 h-4 rounded-full transition-colors ${d?"bg-primary":"bg-background-tertiary border border-border"}`,children:e.jsx("div",{className:`w-3 h-3 rounded-full bg-white shadow-sm transition-transform ${d?"translate-x-4":"translate-x-0.5"}`})})]}),C&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx("p",{className:"text-[9px] leading-relaxed text-text-muted",children:"Reduce white noise, wind, hum, room tone, and background music while keeping speech or the wanted audio in front."}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:tl.map(K=>{const ue=K.id===A;return e.jsxs("button",{onClick:()=>se(K.id),disabled:f==="learning"||f==="applying",className:`rounded-lg border px-2 py-2 text-left transition-colors ${ue?"border-primary bg-primary/10 text-text-primary":"border-border bg-background-secondary text-text-secondary hover:border-primary/50 hover:bg-primary/5"} disabled:cursor-wait disabled:opacity-70`,children:[e.jsx("div",{className:"text-[10px] font-medium",children:K.label}),e.jsx("div",{className:"mt-1 text-[9px] leading-relaxed opacity-80",children:K.description})]},K.id)})}),e.jsxs("div",{className:"rounded-lg border border-border/70 bg-background-secondary/60 px-2 py-2 text-[9px] text-text-muted",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{children:["Current mode: ",e.jsx("span",{className:"text-text-primary",children:z.label})]}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[8px] font-medium ${d?"bg-green-500/15 text-green-400":"bg-background-tertiary text-text-muted"}`,children:d?"Applied":"Off"})]}),e.jsx("div",{className:"mt-1",children:z.description}),y&&e.jsx("div",{className:"mt-2 rounded-md border border-green-500/20 bg-green-500/10 px-2 py-1 text-green-400",children:y})]}),b&&X&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-primary/40 bg-primary/10 px-3 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(cr,{size:12}),e.jsx("span",{className:"text-[10px] font-medium",children:"Recommendation ready"})]}),e.jsxs("p",{className:"text-[9px] leading-relaxed text-text-secondary",children:["Detected noise best matches ",X.label.toLowerCase(),".",b.hasLearnedProfile?` Apply ${Math.round(b.config.reduction*100)}% cleanup at ${b.config.threshold.toFixed(0)} dB to save this profile on the clip.`:` Apply ${Math.round(b.config.reduction*100)}% cleanup at ${b.config.threshold.toFixed(0)} dB. A custom profile could not be isolated, so this recommendation uses the best preset match for the clip.`]}),e.jsx("button",{onClick:D,disabled:f==="applying",className:"w-full rounded-lg bg-primary px-3 py-2 text-[10px] font-medium text-white transition-colors hover:bg-primary-hover disabled:cursor-wait disabled:opacity-70",children:f==="applying"?"Applying...":"Apply Recommended Cleanup"})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/70 bg-background-secondary/60 px-2 py-2",children:[e.jsx("div",{className:"text-[9px] font-medium text-text-primary",children:"A/B Preview"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{onClick:()=>R("original"),disabled:!p,className:`rounded-lg border px-2 py-1.5 text-[10px] transition-colors ${B?"border-primary bg-primary/10 text-text-primary":"border-border bg-background-secondary text-text-secondary hover:border-primary/50"} disabled:cursor-not-allowed disabled:opacity-50`,children:"Hear Original"}),e.jsx("button",{onClick:()=>R("cleaned"),disabled:!p,className:`rounded-lg border px-2 py-1.5 text-[10px] transition-colors ${B?"border-border bg-background-secondary text-text-secondary hover:border-primary/50":"border-primary bg-primary/10 text-text-primary"} disabled:cursor-not-allowed disabled:opacity-50`,children:"Hear Cleaned"})]}),e.jsx("p",{className:"text-[9px] leading-relaxed text-text-muted",children:"Preview only. Export still uses the cleaned audio effect chain."})]}),e.jsx(ht,{label:"Threshold",value:x.threshold,onChange:K=>V("threshold",K),min:-80,max:0,unit:"dB"}),e.jsx(ht,{label:"Reduction",value:x.reduction*100,onChange:K=>V("reduction",K/100),min:0,max:100,unit:"%"}),e.jsx(ht,{label:"Attack",value:x.attack??10,onChange:K=>V("attack",K),min:0,max:100,unit:"ms"}),e.jsx(ht,{label:"Release",value:x.release??100,onChange:K=>V("release",K),min:0,max:500,unit:"ms"}),e.jsx("button",{onClick:U,disabled:f==="learning"||f==="applying",className:`w-full py-2 rounded-lg text-[10px] font-medium transition-colors flex items-center justify-center gap-2 ${f==="learning"||f==="applying"?"bg-primary/20 text-primary cursor-wait":f==="ready"?"bg-primary/10 border border-primary/40 text-primary hover:bg-primary/20":f==="success"?"bg-green-500/20 text-green-500":f==="error"?"bg-red-500/20 text-red-500":"bg-primary/10 border border-primary/30 text-primary hover:bg-primary/20"}`,children:f==="learning"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin"}),"Analyzing..."]}):f==="applying"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 border-2 border-primary border-t-transparent rounded-full animate-spin"}),"Applying cleanup..."]}):f==="ready"?e.jsxs(e.Fragment,{children:[e.jsx(is,{size:12}),"Recommendation Ready"]}):f==="success"?e.jsxs(e.Fragment,{children:[e.jsx(is,{size:12}),"Cleanup Applied"]}):f==="error"?e.jsxs(e.Fragment,{children:[e.jsx(Ba,{size:12}),"Analysis Failed"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{size:12}),"Analyze & Recommend"]})}),S&&(f==="learning"||f==="applying")&&e.jsxs("div",{className:"space-y-1 rounded-lg border border-primary/20 bg-primary/5 px-2 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-[9px] text-text-secondary",children:[e.jsx("span",{children:S.message}),e.jsxs("span",{children:[Math.round(S.progress*100),"%"]})]}),e.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-background-tertiary",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Math.max(6,Math.round(S.progress*100))}%`}})})]}),k&&e.jsx("div",{className:"text-[9px] text-red-500 text-center",children:k}),x.profile&&!b&&f!=="error"&&e.jsxs("div",{className:"text-[9px] text-text-muted text-center",children:["Learned noise profile is active on this clip.",e.jsx("br",{}),"Auto-tuned with ",z.label.toLowerCase()," and reused for export cleanup."]})]})]})},$y=[{value:"blur",label:"Blur",icon:e.jsx(Gd,{size:14})},{value:"color",label:"Color",icon:e.jsx(za,{size:14})},{value:"image",label:"Image",icon:e.jsx(va,{size:14})},{value:"transparent",label:"Transparent",icon:e.jsx(hl,{size:14})}],Oy=["#00ff00","#0000ff","#ffffff","#000000","#ff0000","#ffff00","#00ffff","#ff00ff"],_y=({clipId:t,onSettingsChange:s})=>{const[a,r]=l.useState(tp),[n,i]=l.useState(!1),[o,c]=l.useState(!1),[d,u]=l.useState(!1),{addTask:p,updateTaskProgress:m,completeTask:x,failTask:h}=ju();l.useEffect(()=>{const k=an();k&&(r(k.getSettings(t)),c(k.isInitialized()))},[t]);const f=l.useCallback(async()=>{i(!0);try{await sp().initialize(),c(!0)}catch(k){console.error("Failed to initialize background removal:",k)}finally{i(!1)}},[]),v=l.useCallback(k=>{const N={...a,...k};r(N);const b=an();b&&b.setSettings(t,N),s?.(N),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"))},[a,t,s]),A=l.useCallback(async()=>{const k=p(t,"background-removal");u(!0);try{m(k,10,"Initializing AI model..."),o||await f(),m(k,30,"Preparing background detection..."),await new Promise(N=>setTimeout(N,500)),m(k,60,"Configuring effect pipeline..."),await new Promise(N=>setTimeout(N,400)),m(k,90,"Finalizing setup..."),await new Promise(N=>setTimeout(N,300)),v({enabled:!0}),x(k),Fe.success("Background Removal Ready","Effect will be applied during playback")}catch(N){h(k,N instanceof Error?N.message:"Unknown error"),Fe.error("Processing Failed","Could not enable background removal")}finally{u(!1)}},[t,o,f,v,p,m,x,h]),g=l.useCallback(()=>{a.enabled?(v({enabled:!1}),Fe.info("Background Removal Disabled")):A()},[a.enabled,v,A]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:g,disabled:n||d,className:`px-3 py-1 text-[10px] font-medium rounded transition-colors ${a.enabled?"bg-primary text-white":"bg-background-tertiary text-text-secondary hover:bg-background-secondary"}`,children:n||d?e.jsx(ds,{size:12,className:"animate-spin"}):a.enabled?"On":"Off"})}),a.enabled&&e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-2",children:"Background Mode"}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:$y.map(k=>e.jsxs("button",{onClick:()=>v({mode:k.value}),className:`flex flex-col items-center gap-1 p-2 rounded transition-colors ${a.mode===k.value?"bg-primary/20 border border-primary":"bg-background-secondary hover:bg-background-primary border border-transparent"}`,children:[k.icon,e.jsx("span",{className:"text-[9px] text-text-primary",children:k.label})]},k.value))})]}),a.mode==="blur"&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Blur Amount"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[a.blurAmount,"px"]})]}),e.jsx(st,{min:0,max:50,step:1,value:[a.blurAmount],onValueChange:k=>v({blurAmount:k[0]})})]}),a.mode==="color"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-2",children:"Background Color"}),e.jsx("div",{className:"grid grid-cols-8 gap-1 mb-2",children:Oy.map(k=>e.jsx("button",{onClick:()=>v({backgroundColor:k}),className:`w-6 h-6 rounded border-2 transition-all ${a.backgroundColor===k?"border-primary scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:k}},k))}),e.jsx("input",{type:"color",value:a.backgroundColor,onChange:k=>v({backgroundColor:k.target.value}),className:"w-full h-8 rounded cursor-pointer"})]}),a.mode==="image"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-2",children:"Background Image"}),e.jsxs("button",{onClick:()=>{const k=document.createElement("input");k.type="file",k.accept="image/*",k.onchange=async N=>{const b=N.target.files?.[0];if(b){const j=URL.createObjectURL(b);v({backgroundImageUrl:j});const y=an();y&&await y.setBackgroundImage(j)}},k.click()},className:"w-full py-2 bg-background-secondary hover:bg-background-primary text-text-primary rounded text-[10px] transition-colors flex items-center justify-center gap-2",children:[e.jsx(va,{size:14}),"Choose Image"]}),a.backgroundImageUrl&&e.jsx("div",{className:"mt-2 text-[9px] text-text-muted truncate",children:"Image loaded"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Edge Smoothing"}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono",children:a.edgeBlur})]}),e.jsx(st,{min:0,max:10,step:1,value:[a.edgeBlur],onValueChange:k=>v({edgeBlur:k[0]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Detection Threshold"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[Math.round(a.threshold*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[a.threshold*100],onValueChange:k=>v({threshold:k[0]/100})})]}),e.jsxs("div",{className:"flex items-start gap-2 p-2 bg-primary/10 rounded border border-primary/20",children:[e.jsx(jd,{size:14,className:"text-primary flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Background removal is processed in real-time. For best results, export your video after previewing."})]})]})]})},Vy=({clip:t})=>{const s=F(c=>c.updateClipTransform),a=vt(c=>c.setCropMode),r=t.transform.crop||{x:0,y:0,width:1,height:1},n=r.x!==0||r.y!==0||r.width!==1||r.height!==1,i=()=>{s(t.id,{crop:void 0})},o=()=>{a(!0,t.id)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:o,className:"w-full py-2.5 bg-primary hover:bg-primary/90 text-white rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-2",children:[e.jsx(px,{size:14}),n?"Adjust Crop":"Crop Video"]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[9px] text-text-muted space-y-0.5 p-2 bg-background-tertiary rounded border border-border",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Crop Region:"}),e.jsxs("span",{children:[Math.round(r.width*100),"% × ",Math.round(r.height*100),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Position:"}),e.jsxs("span",{children:["(",Math.round(r.x*100),"%, ",Math.round(r.y*100),"%)"]})]})]}),e.jsxs("button",{onClick:i,className:"w-full py-2 text-xs text-text-secondary hover:text-text-primary bg-background-tertiary hover:bg-background-elevated border border-border rounded-lg transition-colors flex items-center justify-center gap-2",children:[e.jsx(Ns,{size:12}),"Reset Crop"]})]})]})},Uy=[{label:"0.25×",value:.25},{label:"0.5×",value:.5},{label:"0.75×",value:.75},{label:"1×",value:1},{label:"1.25×",value:1.25},{label:"1.5×",value:1.5},{label:"2×",value:2},{label:"3×",value:3},{label:"5×",value:5}],Ky=({clip:t})=>{const s=ba(),{project:a}=F(),[r,n]=l.useState(s.getClipSpeed(t.id)||1),[i,o]=l.useState(()=>s.getClipSpeedData(t.id)?.reverse||!1),[c,d]=l.useState(r.toString()),[u,p]=l.useState(!0);l.useEffect(()=>{d(r.toString())},[r]);const m=()=>!!a.timeline.tracks.find(k=>k.type==="audio"&&k.clips.some(N=>N.mediaId===t.mediaId)),x=g=>{const N=(t.outPoint-t.inPoint)/g,b=a.timeline.tracks.map(j=>{const y=j.clips.findIndex(T=>T.id===t.id);if(y===-1){if(u&&j.type==="audio"){const T=j.clips.findIndex(C=>C.mediaId===t.mediaId);if(T!==-1){const C=j.clips[T],M={...C,duration:N,speed:g},z=[...j.clips];return z[T]=M,s.setClipSpeed(C.id,g,C.duration),{...j,clips:z}}}return j}const w={...j.clips[y],duration:N,speed:g},S=[...j.clips];return S[y]=w,{...j,clips:S}});F.setState({project:{...a,timeline:{...a.timeline,tracks:b},modifiedAt:Date.now()}})},h=g=>{const k=a.timeline.tracks.map(N=>{const b=N.clips.findIndex(w=>w.id===t.id);if(b===-1){if(u&&N.type==="audio"){const w=N.clips.findIndex(S=>S.mediaId===t.mediaId);if(w!==-1){const S=N.clips[w],T={...S,reversed:g},C=[...N.clips];return C[w]=T,s.setReverse(S.id,g,S.duration),{...N,clips:C}}}return N}const j={...N.clips[b],reversed:g},y=[...N.clips];return y[b]=j,{...N,clips:y}});F.setState({project:{...a,timeline:{...a.timeline,tracks:k},modifiedAt:Date.now()}})},f=g=>{s.setClipSpeed(t.id,g,t.duration),x(g),n(g)},v=()=>{const g=parseFloat(c);!isNaN(g)&&g>=.1&&g<=100&&(s.setClipSpeed(t.id,g,t.duration),x(g),n(g))},A=()=>{const g=!i;s.setReverse(t.id,g,t.duration),h(g),o(g)};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Uy.map(g=>e.jsx("button",{onClick:()=>f(g.value),className:`px-3 py-2 text-xs font-medium rounded-lg transition-all ${r===g.value?"bg-primary text-white shadow-lg shadow-primary/20":"bg-background-tertiary hover:bg-background-elevated text-text-secondary hover:text-text-primary border border-border"}`,children:g.label},g.value))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-xs text-text-tertiary",children:"Custom Speed"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{type:"number",min:.1,max:100,step:.1,value:c,onChange:g=>d(g.target.value),onBlur:v,onKeyDown:g=>{g.key==="Enter"&&v()},className:"flex-1 bg-background-tertiary border-border text-text-primary",placeholder:"1.0"}),e.jsx("span",{className:"flex items-center text-xs text-text-tertiary",children:"×"})]}),e.jsx("p",{className:"text-xs text-text-tertiary",children:"Range: 0.1× (slowest) to 100× (fastest)"})]}),m()&&e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-background-tertiary border border-border",children:[e.jsx(kt,{htmlFor:"affect-audio",className:"text-xs text-text-secondary",children:"Apply speed to audio"}),e.jsx(oa,{id:"affect-audio",checked:u,onCheckedChange:p})]}),e.jsxs("button",{onClick:A,className:`w-full px-3 py-2.5 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${i?"bg-primary text-white shadow-lg shadow-primary/20":"bg-background-tertiary hover:bg-background-elevated text-text-secondary hover:text-text-primary border border-border"}`,children:[e.jsx(Ns,{size:14}),i?"Reversed":"Reverse Clip"]}),r<1&&e.jsxs("div",{className:"space-y-2 p-3 rounded-lg bg-background-tertiary border border-border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{size:14,className:"text-primary"}),e.jsx(kt,{htmlFor:"smooth-slowmo",className:"text-xs text-text-secondary",children:"Smooth Slow Motion"})]}),e.jsx(oa,{id:"smooth-slowmo",checked:t.smoothSlowMo??!1,onCheckedChange:g=>{const k=a.timeline.tracks.map(N=>{const b=N.clips.findIndex(w=>w.id===t.id);if(b===-1)return N;const j={...N.clips[b],smoothSlowMo:g},y=[...N.clips];return y[b]=j,{...N,clips:y}});F.setState({project:{...a,timeline:{...a.timeline,tracks:k},modifiedAt:Date.now()}})}})]}),t.smoothSlowMo&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(kt,{className:"text-xs text-text-tertiary",children:"Quality"}),e.jsxs(ot,{value:t.interpolationQuality??"medium",onValueChange:g=>{const k=a.timeline.tracks.map(N=>{const b=N.clips.findIndex(w=>w.id===t.id);if(b===-1)return N;const j={...N.clips[b],interpolationQuality:g},y=[...N.clips];return y[b]=j,{...N,clips:y}});F.setState({project:{...a,timeline:{...a.timeline,tracks:k},modifiedAt:Date.now()}})},children:[e.jsx(lt,{className:"h-8 text-xs bg-background-elevated border-border",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"low",children:"Low (faster)"}),e.jsx(ge,{value:"medium",children:"Medium"}),e.jsx(ge,{value:"high",children:"High (slower)"})]})]}),e.jsx("p",{className:"text-[10px] text-text-tertiary",children:"Uses optical flow to generate smooth in-between frames"})]})]}),(r!==1||i)&&e.jsxs("div",{className:"p-3 rounded-lg bg-background-tertiary border border-border",children:[e.jsx("div",{className:"text-xs text-text-tertiary mb-1",children:"Current Settings"}),e.jsxs("div",{className:"text-sm text-text-primary",children:["Speed: ",r,"× ",i&&"• Reversed",t.smoothSlowMo&&" • Smooth"]})]})]})},Yy=({clip:t})=>{const{project:s,getMediaItem:a}=F(),[r,n]=l.useState(!1),[i,o]=l.useState(null),[c,d]=l.useState(0),[u,p]=l.useState(null),m=t.stabilization??{enabled:!1,strength:50,cropMode:"auto",analyzed:!1},x=Ma(),h=x.hasStabilized(t.id),f=l.useCallback(N=>{const b={...m,...N},j=s.timeline.tracks.map(y=>{const w=y.clips.findIndex(C=>C.id===t.id);if(w===-1)return y;const S={...y.clips[w],stabilization:b},T=[...y.clips];return T[w]=S,{...y,clips:T}});F.setState({project:{...s,timeline:{...s.timeline,tracks:j},modifiedAt:Date.now()}})},[t.id,s,m]),v=l.useCallback(async()=>{const N=a(t.mediaId);if(N?.blob){n(!0),d(0),p(null),o("downloading");try{await x.load(b=>{o(b.stage),d(Math.round(b.progress*100))}),o("detecting"),d(0),await x.stabilize(t.id,N.blob,{strength:m.strength,cropMode:m.cropMode,analysisInterval:1},b=>{o(b.stage),d(Math.round(b.progress*100))},{inPoint:t.inPoint,outPoint:t.outPoint}),f({enabled:!0,analyzed:!0})}catch(b){console.error("Stabilization failed:",b),o(null),p(b instanceof Error?b.message:"Stabilization failed")}finally{n(!1),o(null)}}},[t.id,t.mediaId,a,x,m.strength,m.cropMode,f]),A=l.useCallback(N=>{if(N&&!h){v();return}f({enabled:N})},[h,v,f]),g=l.useCallback(N=>{const b=N[0];if(h){x.removeStabilized(t.id),f({strength:b,analyzed:!1,enabled:!1});return}f({strength:b})},[t.id,h,x,f]),k=(()=>{switch(i){case"downloading":return"Downloading stabilization engine...";case"detecting":return"Analyzing motion...";case"stabilizing":return"Stabilizing video...";default:return""}})();return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(kt,{className:"flex items-center gap-2 text-sm",children:[e.jsx(zs,{className:"h-4 w-4"}),"Stabilize"]}),e.jsx(oa,{checked:m.enabled&&h,onCheckedChange:A,disabled:r})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(kt,{className:"text-xs text-muted-foreground",children:"Strength"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[m.strength,"%"]})]}),e.jsx(st,{value:[m.strength],min:10,max:100,step:5,onValueChange:g,disabled:r})]}),!x.isLoaded()&&!r&&!h&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground",children:[e.jsx(nl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"First use requires a one-time download (~65 MB)"})]}),r&&i&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:k}),e.jsxs("span",{children:[c,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${c}%`}})})]}),u&&!r&&e.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:u}),h&&!r&&e.jsx(zt,{variant:"outline",size:"sm",className:"w-full",onClick:v,children:"Re-stabilize"})]})},Mo=({label:t,value:s,onChange:a,min:r,max:n,defaultValue:i,step:o=.01})=>{const c=(s-r)/(n-r)*100,d=l.useCallback(()=>{a(i)},[a,i]);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsx("span",{className:"text-[10px] font-mono text-text-primary cursor-pointer hover:text-accent",onDoubleClick:d,title:"Double-click to reset",children:s.toFixed(2)})]}),e.jsxs("div",{className:"h-1.5 bg-background-tertiary rounded-full relative overflow-hidden",children:[e.jsx("input",{type:"range",min:r,max:n,step:o,value:s,onChange:u=>a(parseFloat(u.target.value)),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"}),e.jsx("div",{className:"absolute top-0 left-0 h-full bg-text-secondary rounded-full transition-all",style:{width:`${c}%`}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-2.5 h-2.5 bg-white rounded-full shadow-sm pointer-events-none transition-all",style:{left:`calc(${c}% - 5px)`}})]})]})},Eo=({label:t,color:s,onChange:a,onReset:r})=>{const n=l.useRef(null),i=l.useRef(!1),o=l.useMemo(()=>{const u=s.r,p=-s.b,m=Math.sqrt(u*u+p*p),x=Math.atan2(p,u);return{x:Math.cos(x)*m*44,y:Math.sin(x)*m*44,saturation:Math.min(m,1)}},[s.r,s.b]),c=l.useCallback(u=>{const p=n.current;if(!p)return;i.current=!0;const m=p.getBoundingClientRect(),x=m.width/2,h=m.height/2,f=(g,k)=>{const N=(g-m.left-x)/x,b=(k-m.top-h)/h,j=Math.sqrt(N*N+b*b),y=Math.min(j,1),w=j>0?N/j*y:0,S=j>0?b/j*y:0,T=w,C=-S,M=-(T+C)/2;a({r:T,g:M,b:C})};f(u.clientX,u.clientY);const v=g=>{i.current&&f(g.clientX,g.clientY)},A=()=>{i.current=!1,document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",A)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",A)},[a]),d=l.useCallback(()=>{r()},[r]);return e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:t}),e.jsxs("div",{ref:n,className:"w-24 h-24 rounded-full relative cursor-crosshair shadow-inner",style:{background:`conic-gradient( + from 90deg, + hsl(0, 70%, 50%), + hsl(60, 70%, 50%), + hsl(120, 70%, 50%), + hsl(180, 70%, 50%), + hsl(240, 70%, 50%), + hsl(300, 70%, 50%), + hsl(360, 70%, 50%) + )`},onMouseDown:c,onDoubleClick:d,title:"Drag to adjust color. Double-click to reset.",children:[e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"radial-gradient(circle, rgba(128,128,128,1) 0%, rgba(128,128,128,0) 70%)"}}),e.jsx("div",{className:"absolute w-4 h-4 border-2 border-white rounded-full shadow-md pointer-events-none z-10",style:{left:`calc(50% + ${o.x}px - 8px)`,top:`calc(50% + ${o.y}px - 8px)`,backgroundColor:o.saturation>.1?`rgb(${128+s.r*127}, ${128+s.g*127}, ${128+s.b*127})`:"white"}})]})]})},Xy=({values:t,onChange:s,onReset:a})=>{const r=l.useCallback(x=>{s({...t,shadows:x})},[t,s]),n=l.useCallback(x=>{s({...t,midtones:x})},[t,s]),i=l.useCallback(x=>{s({...t,highlights:x})},[t,s]),o=l.useCallback(x=>{s({...t,shadowsLift:x})},[t,s]),c=l.useCallback(x=>{s({...t,midtonesGamma:x})},[t,s]),d=l.useCallback(x=>{s({...t,highlightsGain:x})},[t,s]),u=l.useCallback(()=>{s({...t,shadows:{r:0,g:0,b:0}})},[t,s]),p=l.useCallback(()=>{s({...t,midtones:{r:0,g:0,b:0}})},[t,s]),m=l.useCallback(()=>{s({...t,highlights:{r:0,g:0,b:0}})},[t,s]);return e.jsxs("div",{className:"space-y-4",children:[a&&e.jsx("div",{className:"flex justify-end",children:e.jsxs("button",{onClick:a,className:"flex items-center gap-1 px-2 py-1 text-[10px] text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(Ns,{size:10}),"Reset"]})}),e.jsxs("div",{className:"flex justify-around items-start",children:[e.jsx(Eo,{label:"Shadows",color:t.shadows,onChange:r,onReset:u}),e.jsx(Eo,{label:"Midtones",color:t.midtones,onChange:n,onReset:p}),e.jsx(Eo,{label:"Highlights",color:t.highlights,onChange:i,onReset:m})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border",children:[e.jsx(Mo,{label:"Lift (Shadows)",value:t.shadowsLift,onChange:o,min:-1,max:1,defaultValue:0}),e.jsx(Mo,{label:"Gamma (Midtones)",value:t.midtonesGamma,onChange:c,min:.1,max:4,defaultValue:1}),e.jsx(Mo,{label:"Gain (Highlights)",value:t.highlightsGain,onChange:d,min:0,max:4,defaultValue:1})]})]})},Qc={rgb:[{x:0,y:0},{x:1,y:1}],red:[{x:0,y:0},{x:1,y:1}],green:[{x:0,y:0},{x:1,y:1}],blue:[{x:0,y:0},{x:1,y:1}]},sl={rgb:"#ffffff",red:"#ef4444",green:"#22c55e",blue:"#3b82f6"},vi=({channel:t,label:s,isActive:a,onClick:r})=>e.jsx("button",{onClick:r,className:`px-3 py-1 text-[10px] font-medium rounded transition-colors ${a?"bg-background-tertiary text-text-primary":"text-text-muted hover:text-text-secondary"}`,style:{borderBottom:a?`2px solid ${sl[t]}`:"none"},children:s});function Gy(t,s){if(t.length<2)return s;const a=[...t].sort((x,h)=>x.x-h.x);let r=0;for(let x=0;x=a[x].x&&s<=a[x+1].x){r=x;break}const n=r>0?a[r-1]:a[r],i=a[r],o=a[Math.min(r+1,a.length-1)],c=a[Math.min(r+2,a.length-1)],d=o.x!==i.x?(s-i.x)/(o.x-i.x):0,u=d*d,p=u*d,m=.5*(2*i.y+(-n.y+o.y)*d+(2*n.y-5*i.y+4*o.y-c.y)*u+(-n.y+3*i.y-3*o.y+c.y)*p);return Math.max(0,Math.min(1,m))}function Hy(t,s,a){if(t.length<2)return"";const r=[...t].sort((o,c)=>o.x-c.x),n=[],i=100;for(let o=0;o<=i;o++){const c=o/i,d=Gy(r,c),u=c*s,p=a-d*a;n.push(o===0?`M ${u} ${p}`:`L ${u} ${p}`)}return n.join(" ")}const Wy=({values:t,onChange:s,onReset:a})=>{const[r,n]=l.useState("rgb"),[i,o]=l.useState(null),[c,d]=l.useState(!1),u=l.useRef(null),p=200,m=200,x=8,h=l.useMemo(()=>t[r]||Qc[r],[t,r]),f=l.useCallback(j=>{if(!u.current||i===null)return;const y=u.current.getBoundingClientRect(),w=Math.max(0,Math.min(1,(j.clientX-y.left-x)/(p-2*x))),S=Math.max(0,Math.min(1,1-(j.clientY-y.top-x)/(m-2*x))),T=[...h];if(i===0)T[i]={x:0,y:S};else if(i===h.length-1)T[i]={x:1,y:S};else{const C=T[i-1]?.x||0,M=T[i+1]?.x||1,z=Math.max(C+.01,Math.min(M-.01,w));T[i]={x:z,y:S}}s({...t,[r]:T})},[i,h,r,t,s]),v=l.useCallback(j=>y=>{y.preventDefault(),y.stopPropagation(),o(j),d(!0)},[]);l.useEffect(()=>{const j=()=>{d(!1),o(null)},y=w=>{c&&f(w)};return c&&(document.addEventListener("mousemove",y),document.addEventListener("mouseup",j)),()=>{document.removeEventListener("mousemove",y),document.removeEventListener("mouseup",j)}},[c,f]);const A=l.useCallback(j=>{if(!u.current||c)return;const y=u.current.getBoundingClientRect(),w=(j.clientX-y.left-x)/(p-2*x),S=1-(j.clientY-y.top-x)/(m-2*x);if(w<.01||w>.99||S<0||S>1)return;const T=[...h,{x:w,y:S}].sort((C,M)=>C.x-M.x);s({...t,[r]:T})},[h,r,t,s,c]),g=l.useCallback(j=>y=>{if(y.preventDefault(),y.stopPropagation(),j===0||j===h.length-1)return;const w=h.filter((S,T)=>T!==j);s({...t,[r]:w})},[h,r,t,s]),k=l.useCallback(()=>{s({...t,[r]:[...Qc[r]]})},[r,t,s]),N=l.useMemo(()=>Hy(h,p-2*x,m-2*x),[h]),b=`M ${x} ${m-x} L ${p-x} ${x}`;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-1 justify-center",children:[e.jsx(vi,{channel:"rgb",label:"RGB",isActive:r==="rgb",onClick:()=>n("rgb")}),e.jsx(vi,{channel:"red",label:"R",isActive:r==="red",onClick:()=>n("red")}),e.jsx(vi,{channel:"green",label:"G",isActive:r==="green",onClick:()=>n("green")}),e.jsx(vi,{channel:"blue",label:"B",isActive:r==="blue",onClick:()=>n("blue")})]}),e.jsx("div",{className:"relative bg-background-tertiary rounded-lg overflow-hidden",children:e.jsxs("svg",{ref:u,width:p,height:m,className:"cursor-crosshair",onClick:A,children:[e.jsx("defs",{children:e.jsx("pattern",{id:"grid",width:p/4,height:m/4,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M ${p/4} 0 L 0 0 0 ${m/4}`,fill:"none",stroke:"rgba(255,255,255,0.1)",strokeWidth:"0.5"})})}),e.jsx("rect",{width:p,height:m,fill:"url(#grid)"}),e.jsx("path",{d:b,fill:"none",stroke:"rgba(255,255,255,0.2)",strokeWidth:"1",strokeDasharray:"4,4"}),e.jsxs("g",{transform:`translate(${x}, ${x})`,children:[e.jsx("path",{d:N,fill:"none",stroke:sl[r],strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),h.map((j,y)=>{const w=j.x*(p-2*x),S=(1-j.y)*(m-2*x),T=i===y,C=y===0||y===h.length-1;return e.jsxs("g",{children:[e.jsx("circle",{cx:w,cy:S,r:12,fill:"transparent",className:"cursor-pointer",onMouseDown:v(y),onDoubleClick:g(y)}),e.jsx("circle",{cx:w,cy:S,r:T?6:4,fill:C?"#666":sl[r],stroke:"white",strokeWidth:T?2:1,className:"pointer-events-none"})]},y)})]})]})}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:"Click to add point • Double-click to remove"}),e.jsxs("button",{onClick:k,className:"flex items-center gap-1 px-2 py-1 text-[10px] text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(Ns,{size:10}),"Reset"]})]}),e.jsxs("div",{className:"text-[9px] text-text-muted text-center",children:[h.length," points"]})]})},qy=({value:t,onChange:s})=>{const a=Math.round(t*100);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Intensity"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[a,"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[a],onValueChange:r=>s(r[0]/100)})]})};function Qy(t){const s=t.split(` +`).map(i=>i.trim());let a=0;const r=[];for(const i of s){if(i.startsWith("#")||i==="")continue;if(i.startsWith("LUT_3D_SIZE")){const c=i.split(/\s+/);if(a=parseInt(c[1],10),isNaN(a)||a<2||a>256)throw new Error(`Invalid LUT size: ${c[1]}`);continue}if(i.startsWith("TITLE")||i.startsWith("DOMAIN_"))continue;const o=i.split(/\s+/).map(parseFloat);o.length===3&&o.every(c=>!isNaN(c))&&r.push(Math.round(Math.max(0,Math.min(1,o[0]))*255),Math.round(Math.max(0,Math.min(1,o[1]))*255),Math.round(Math.max(0,Math.min(1,o[2]))*255))}if(a===0)throw new Error("LUT size not specified in file");const n=a*a*a*3;if(r.length!==n)throw new Error(`Invalid LUT data: expected ${n} values, got ${r.length}`);return{data:new Uint8Array(r),size:a,intensity:1}}function Jy(t){const s=t.split(` +`).map(n=>n.trim()),a=[];let r=0;for(const n of s){if(n===""||n.startsWith("#"))continue;if(r===0){const o=n.split(/\s+/).map(parseFloat);if(o.length>=1&&!isNaN(o[0])){r=Math.round(Math.cbrt(o.length/3))||17,o.length===3&&(r=17,a.push(Math.round(o[0]/4095*255),Math.round(o[1]/4095*255),Math.round(o[2]/4095*255)));continue}}const i=n.split(/\s+/).map(parseFloat);if(i.length===3&&i.every(o=>!isNaN(o))){const o=Math.max(...i),c=o>255?4095:o>1?255:1;a.push(Math.round(i[0]/c*255),Math.round(i[1]/c*255),Math.round(i[2]/c*255))}}if(r===0||r*r*r*3!==a.length){const n=Math.round(Math.cbrt(a.length/3));if(n*n*n*3===a.length)r=n;else throw new Error("Could not determine LUT size from data")}if(a.length===0)throw new Error("No valid LUT data found in file");return{data:new Uint8Array(a),size:r,intensity:1}}const Zy=({lutData:t,onChange:s,onError:a})=>{const r=l.useRef(null),[n,i]=l.useState(null),[o,c]=l.useState(null),[d,u]=l.useState(!1),p=l.useCallback(async f=>{const v=f.target.files?.[0];if(v){u(!0),i(null);try{const A=await v.text(),g=v.name.toLowerCase().split(".").pop();let k;if(g==="cube")k=Qy(A);else if(g==="3dl")k=Jy(A);else throw new Error("Unsupported file format. Please use .cube or .3dl files.");c(v.name),s(k)}catch(A){const g=A instanceof Error?A.message:"Failed to parse LUT file";i(g),a?.(g)}finally{u(!1),r.current&&(r.current.value="")}}},[s,a]),m=l.useCallback(f=>{t&&s({...t,intensity:f})},[t,s]),x=l.useCallback(()=>{s(null),c(null),i(null)},[s]),h=l.useCallback(()=>{r.current?.click()},[]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:r,type:"file",accept:".cube,.3dl",onChange:p,className:"hidden"}),t?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] text-text-primary truncate",children:o||"LUT Loaded"}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:[t.size,"x",t.size,"x",t.size," LUT"]})]}),e.jsx("button",{onClick:x,className:"p-1 text-text-muted hover:text-text-primary transition-colors",title:"Remove LUT",children:e.jsx(Ls,{size:14})})]}),e.jsx(qy,{value:t.intensity,onChange:m}),e.jsx("button",{onClick:h,disabled:d,className:"w-full py-1.5 text-[10px] text-text-muted hover:text-text-secondary transition-colors",children:"Load Different LUT"})]}):e.jsx("button",{onClick:h,disabled:d,className:"w-full py-2 bg-background-tertiary border border-border rounded-lg text-[10px] text-text-secondary hover:text-text-primary hover:border-text-secondary transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 border border-text-muted border-t-transparent rounded-full animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ya,{size:12}),"Load LUT (.cube, .3dl)"]})}),n&&e.jsxs("div",{className:"flex items-start gap-2 p-2 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx(Ba,{size:14,className:"text-red-500 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[10px] text-red-400",children:n})]})]})},Ro=[{key:"reds",label:"R",fullLabel:"Reds",color:"#ef4444",index:0},{key:"oranges",label:"O",fullLabel:"Oranges",color:"#f97316",index:1},{key:"yellows",label:"Y",fullLabel:"Yellows",color:"#eab308",index:2},{key:"greens",label:"G",fullLabel:"Greens",color:"#22c55e",index:3},{key:"cyans",label:"C",fullLabel:"Cyans",color:"#06b6d4",index:4},{key:"blues",label:"B",fullLabel:"Blues",color:"#3b82f6",index:5},{key:"purples",label:"P",fullLabel:"Purples",color:"#a855f7",index:6},{key:"magentas",label:"M",fullLabel:"Magentas",color:"#ec4899",index:7}],e1=({color:t,isActive:s,onClick:a})=>e.jsx("button",{onClick:a,className:`flex-1 py-1.5 text-[9px] font-medium rounded transition-all ${s?"bg-background-tertiary text-text-primary shadow-sm":"text-text-muted hover:text-text-secondary"}`,style:{borderBottom:s?`2px solid ${t.color}`:"2px solid transparent"},title:t.fullLabel,children:t.label}),Po=({label:t,value:s,onChange:a,min:r,max:n,unit:i="",color:o})=>{const c=n-r,d=(s-r)/c*100,u=(0-r)/c*100,p=r<0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[s>0?"+":"",Math.round(s),i]})]}),e.jsxs("div",{className:"h-1.5 bg-background-tertiary rounded-full relative overflow-hidden",children:[e.jsx("input",{type:"range",min:r,max:n,step:1,value:s,onChange:m=>a(parseFloat(m.target.value)),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"}),p?e.jsx("div",{className:"absolute top-0 h-full rounded-full transition-all",style:{backgroundColor:o||"rgb(var(--text-secondary))",left:s>=0?`${u}%`:`${d}%`,width:`${Math.abs(d-u)}%`}}):e.jsx("div",{className:"absolute top-0 left-0 h-full rounded-full transition-all",style:{backgroundColor:o||"rgb(var(--text-secondary))",width:`${d}%`}}),p&&e.jsx("div",{className:"absolute top-0 w-0.5 h-full bg-text-muted/50",style:{left:`${u}%`}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-2.5 h-2.5 bg-white rounded-full shadow-sm pointer-events-none transition-all",style:{left:`calc(${d}% - 5px)`}})]})]})},t1=({values:t,onChange:s,onReset:a})=>{const[r,n]=l.useState(0),i=Ro[r],o=t.hue[r]||0,c=(t.saturation[r]||0)*100,d=(t.luminance[r]||0)*100,u=l.useCallback(f=>{const v=[...t.hue];v[r]=f,s({...t,hue:v})},[t,r,s]),p=l.useCallback(f=>{const v=[...t.saturation];v[r]=f/100,s({...t,saturation:v})},[t,r,s]),m=l.useCallback(f=>{const v=[...t.luminance];v[r]=f/100,s({...t,luminance:v})},[t,r,s]),x=l.useCallback(()=>{const f=[...t.hue],v=[...t.saturation],A=[...t.luminance];f[r]=0,v[r]=0,A[r]=0,s({hue:f,saturation:v,luminance:A})},[t,r,s]),h=l.useMemo(()=>o!==0||c!==0||d!==0,[o,c,d]);return e.jsxs("div",{className:"space-y-3",children:[a&&e.jsx("div",{className:"flex justify-end",children:e.jsxs("button",{onClick:a,className:"flex items-center gap-1 px-2 py-1 text-[10px] text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(Ns,{size:10}),"Reset All"]})}),e.jsx("div",{className:"flex gap-0.5",children:Ro.map(f=>e.jsx(e1,{color:f,isActive:r===f.index,onClick:()=>n(f.index)},f.key))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:i.fullLabel})]}),h&&e.jsx("button",{onClick:x,className:"text-[9px] text-text-muted hover:text-text-secondary transition-colors",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Po,{label:"Hue",value:o,onChange:u,min:-180,max:180,unit:"°",color:i.color}),e.jsx(Po,{label:"Saturation",value:c,onChange:p,min:-100,max:100,unit:"%",color:i.color}),e.jsx(Po,{label:"Luminance",value:d,onChange:m,min:-100,max:100,unit:"%",color:i.color})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("div",{className:"flex gap-1",children:Ro.map(f=>{const v=t.hue[f.index]!==0||t.saturation[f.index]!==0||t.luminance[f.index]!==0;return e.jsx("div",{className:`flex-1 h-1 rounded-full transition-all ${v?"opacity-100":"opacity-20"}`,style:{backgroundColor:f.color},title:`${f.fullLabel}${v?" (adjusted)":""}`},f.key)})})})]})},s1=[{label:"Tungsten",temperature:-40,tint:8},{label:"Fluorescent",temperature:-15,tint:-10},{label:"Daylight",temperature:0,tint:0},{label:"Cloudy",temperature:15,tint:0},{label:"Shade",temperature:30,tint:5}],vn=({title:t,defaultOpen:s=!1,children:a})=>{const[r,n]=_e.useState(s);return e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(!r),className:"flex items-center gap-2 w-full p-2 bg-background-tertiary hover:bg-background-tertiary/80 transition-colors",children:[e.jsx(qt,{size:12,className:`transition-transform ${r?"":"-rotate-90"} text-text-muted`}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:t})]}),r&&e.jsx("div",{className:"p-3 space-y-3",children:a})]})},a1=({clipId:t})=>{const{getColorGrading:s,updateColorGrading:a,resetColorGrading:r}=F(),n=F(w=>w.project.modifiedAt),i=l.useMemo(()=>s(t),[t,s,n]),o=l.useMemo(()=>i.colorWheels||{...Yl},[i.colorWheels]),c=l.useMemo(()=>i.hsl||{...Xl},[i.hsl]),d=l.useMemo(()=>i.curves||{...Gl},[i.curves]),u=i.temperature??0,p=i.tint??0,m=l.useCallback(w=>{a(t,{temperature:w})},[t,a]),x=l.useCallback(w=>{a(t,{tint:w})},[t,a]),h=l.useCallback(()=>{a(t,{temperature:0,tint:0})},[t,a]),f=l.useCallback(w=>{a(t,{temperature:w.temperature,tint:w.tint})},[t,a]),v=l.useCallback(w=>{a(t,{colorWheels:w})},[t,a]),A=l.useCallback(()=>{a(t,{colorWheels:{...Yl}})},[t,a]),g=l.useCallback(w=>{a(t,{curves:w})},[t,a]),k=l.useCallback(()=>{a(t,{curves:{...Gl}})},[t,a]),N=l.useCallback(w=>{a(t,{lut:w||void 0})},[t,a]),b=l.useCallback(w=>{a(t,{hsl:w})},[t,a]),j=l.useCallback(()=>{a(t,{hsl:{...Xl}})},[t,a]),y=l.useCallback(()=>{r(t)},[t,r]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs("button",{onClick:y,className:"flex items-center gap-1 px-2 py-1 text-[10px] text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(Ns,{size:10}),"Reset All"]})}),e.jsx(vn,{title:"White Balance",defaultOpen:!0,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-[10px] text-text-muted leading-snug",children:"Warm up cool shots or cool down warm ones. Tint corrects green or magenta casts."}),e.jsxs("button",{onClick:h,className:"flex items-center gap-1 px-2 py-0.5 text-[10px] text-text-muted hover:text-text-primary transition-colors shrink-0",title:"Reset white balance",children:[e.jsx(Ns,{size:10}),"Reset"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(vf,{size:12,className:"text-text-muted"}),e.jsx(ht,{label:"Temperature",value:u,onChange:m,min:-100,max:100,step:1,className:"flex-1"})]}),e.jsx("div",{className:"h-1 rounded-full pointer-events-none mx-5",style:{background:"linear-gradient(to right, #4aa8ff 0%, #cccccc 50%, #ff9a3c 100%)",opacity:.7}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ru,{size:12,className:"text-text-muted"}),e.jsx(ht,{label:"Tint",value:p,onChange:x,min:-100,max:100,step:1,className:"flex-1"})]}),e.jsx("div",{className:"h-1 rounded-full pointer-events-none mx-5",style:{background:"linear-gradient(to right, #4ad17f 0%, #cccccc 50%, #d44ad1 100%)",opacity:.7}})]}),e.jsxs("div",{className:"pt-1",children:[e.jsx("span",{className:"text-[10px] text-text-muted block mb-1.5",children:"Presets"}),e.jsx("div",{className:"grid grid-cols-5 gap-1",children:s1.map(w=>{const S=Math.abs(w.temperature-u)<.5&&Math.abs(w.tint-p)<.5;return e.jsx("button",{onClick:()=>f(w),className:`py-1 rounded text-[9px] transition-colors ${S?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,title:`Temp: ${w.temperature}, Tint: ${w.tint}`,children:w.label},w.label)})})]})]})}),e.jsx(vn,{title:"Color Wheels",defaultOpen:!1,children:e.jsx(Xy,{values:o,onChange:v,onReset:A})}),e.jsx(vn,{title:"Curves",children:e.jsx(Wy,{values:d,onChange:g,onReset:k})}),e.jsx(vn,{title:"LUT",children:e.jsx(Zy,{lutData:i.lut,onChange:N})}),e.jsx(vn,{title:"HSL",children:e.jsx(t1,{values:c,onChange:b,onReset:j})})]})},ji=({label:t,value:s,onChange:a,showAlpha:r=!1,allowTransparent:n=!1})=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsx(ll,{value:s,onChange:a,showAlpha:r,allowTransparent:n,className:"max-w-[170px]"})]}),Fs=({label:t,value:s,onChange:a,min:r=0,max:n=1e3,step:i=1,unit:o=""})=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"number",value:s,onChange:c=>a(parseFloat(c.target.value)||0),min:r,max:n,step:i,className:"w-16 px-2 py-1 text-[10px] font-mono text-text-primary bg-background-tertiary border border-border rounded text-right outline-none focus:border-primary"}),o&&e.jsx("span",{className:"text-[10px] text-text-muted",children:o})]})]}),r1=({options:t,value:s,onChange:a})=>e.jsx("div",{className:"flex gap-1",children:t.map(r=>e.jsx("button",{onClick:()=>a(r.value),className:`p-1.5 rounded transition-colors ${s===r.value?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,title:r.label,children:r.icon},r.value))}),n1=({value:t,onChange:s})=>{const a=zd();return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Font"}),e.jsxs(ot,{value:t,onValueChange:s,children:[e.jsx(lt,{className:"max-w-[140px] bg-background-tertiary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border max-h-80",children:[Object.entries(Dd).map(([r,n])=>e.jsxs(Rn,{children:[e.jsx(Pn,{className:"text-text-muted text-[10px] font-medium",children:r}),n.map(i=>e.jsx(ge,{value:i,style:{fontFamily:i},children:i},i))]},r)),a.length>0&&e.jsxs(Rn,{children:[e.jsx(Pn,{className:"text-text-muted text-[10px] font-medium",children:"Custom Uploads"}),a.map(r=>e.jsx(ge,{value:r,style:{fontFamily:r},children:r},r))]})]})]})]})},i1=({clipId:t})=>{const{getTextClip:s,updateTextContent:a,updateTextStyle:r,updateTextTransform:n,project:i}=F(),o=l.useRef(null),c=l.useMemo(()=>s(t),[t,s,i.modifiedAt]),d={fontFamily:"Inter",fontSize:48,fontWeight:"normal",fontStyle:"normal",color:"#ffffff",backgroundColor:"transparent",textAlign:"center",verticalAlign:"middle",lineHeight:1.2,letterSpacing:0,textDecoration:"none",strokeColor:"#000000",strokeWidth:0,shadowColor:"#000000",shadowOffsetX:0,shadowOffsetY:0,shadowBlur:0},u=c?.style||d,p=c?.text||"",m=l.useCallback(g=>{a(t,g)},[t,a]),x=l.useCallback(async g=>{if(g.fontFamily)try{const k=u.fontSize||48;await document.fonts.load(`${k}px "${g.fontFamily}"`)}catch{}r(t,g)},[t,r,u.fontSize]),h=l.useCallback(()=>{const g=c?.transform?.position?.y??.5;n(t,{position:{x:.5,y:g}})},[t,c,n]),f=l.useCallback(()=>{const g=c?.transform?.position?.x??.5;n(t,{position:{x:g,y:.5}})},[t,c,n]),v=l.useCallback(()=>{n(t,{position:{x:.5,y:.5}})},[t,n]),A=l.useCallback(async g=>{const k=g.target.files?.[0];if(!k)return;const N=await Rd(k);N.success?(await x({fontFamily:N.fontFamily}),Fe.success("Custom font uploaded",`${N.fontFamily} is ready to use.`)):Fe.error("Font upload failed",N.error??"Unknown error."),g.target.value=""},[x]);return c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Text Content"}),e.jsx("textarea",{value:p,onChange:g=>m(g.target.value),placeholder:"Enter text...",className:"w-full h-20 px-3 py-2 text-sm text-text-primary bg-background-tertiary border border-border rounded-lg resize-none outline-none focus:border-primary",style:{fontFamily:u.fontFamily}})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("input",{ref:o,type:"file",accept:Pd,onChange:A,className:"hidden"}),e.jsx(n1,{value:u.fontFamily,onChange:g=>x({fontFamily:g})}),e.jsxs("button",{onClick:()=>o.current?.click(),className:"w-full py-1.5 px-2 bg-background-secondary border border-border rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center gap-1.5",children:[e.jsx(ya,{size:11}),"Upload Custom Font"]}),e.jsx(Fs,{label:"Size",value:u.fontSize,onChange:g=>x({fontSize:g}),min:8,max:500,unit:"px"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Style"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>x({fontWeight:u.fontWeight==="bold"?"normal":"bold"}),className:`p-1.5 rounded transition-colors ${u.fontWeight==="bold"?"bg-primary text-white":"bg-background-secondary border border-border text-text-secondary hover:text-text-primary"}`,title:"Bold",children:e.jsx(qp,{size:12})}),e.jsx("button",{onClick:()=>x({fontStyle:u.fontStyle==="italic"?"normal":"italic"}),className:`p-1.5 rounded transition-colors ${u.fontStyle==="italic"?"bg-primary text-white":"bg-background-secondary border border-border text-text-secondary hover:text-text-primary"}`,title:"Italic",children:e.jsx(Xx,{size:12})}),e.jsx("button",{onClick:()=>x({textDecoration:u.textDecoration==="underline"?"none":"underline"}),className:`p-1.5 rounded transition-colors ${u.textDecoration==="underline"?"bg-primary text-white":"bg-background-secondary border border-border text-text-secondary hover:text-text-primary"}`,title:"Underline",children:e.jsx(kf,{size:12})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Text Align"}),e.jsx(r1,{options:[{value:"left",icon:e.jsx(nu,{size:12}),label:"Left"},{value:"center",icon:e.jsx(hf,{size:12}),label:"Center"},{value:"right",icon:e.jsx(gf,{size:12}),label:"Right"}],value:u.textAlign,onChange:g=>x({textAlign:g})})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Position on Canvas"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:"Align to Canvas"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:h,className:"p-1.5 rounded bg-background-secondary border border-border text-text-secondary hover:text-text-primary transition-colors",title:"Center Horizontally",children:e.jsx(Vd,{size:12})}),e.jsx("button",{onClick:f,className:"p-1.5 rounded bg-background-secondary border border-border text-text-secondary hover:text-text-primary transition-colors",title:"Center Vertically",children:e.jsx(Ud,{size:12})}),e.jsx("button",{onClick:v,className:"p-1.5 rounded bg-primary text-white transition-colors",title:"Center Both",children:e.jsx(hx,{size:12})})]})]})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx(ji,{label:"Text Color",value:u.color,onChange:g=>x({color:g})}),e.jsx(ji,{label:"Background",value:u.backgroundColor||"transparent",onChange:g=>x({backgroundColor:g}),showAlpha:!0,allowTransparent:!0})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Stroke"}),e.jsx(ji,{label:"Color",value:u.strokeColor||"#000000",onChange:g=>x({strokeColor:g})}),e.jsx(Fs,{label:"Width",value:u.strokeWidth||0,onChange:g=>x({strokeWidth:g}),min:0,max:20,unit:"px"})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Shadow"}),e.jsx(ji,{label:"Color",value:u.shadowColor||"#000000",onChange:g=>x({shadowColor:g}),showAlpha:!0}),e.jsx(Fs,{label:"Offset X",value:u.shadowOffsetX||0,onChange:g=>x({shadowOffsetX:g}),min:-50,max:50,unit:"px"}),e.jsx(Fs,{label:"Offset Y",value:u.shadowOffsetY||0,onChange:g=>x({shadowOffsetY:g}),min:-50,max:50,unit:"px"}),e.jsx(Fs,{label:"Blur",value:u.shadowBlur||0,onChange:g=>x({shadowBlur:g}),min:0,max:50,unit:"px"})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx(Fs,{label:"Line Height",value:u.lineHeight||1.2,onChange:g=>x({lineHeight:g}),min:.5,max:3,step:.1}),e.jsx(Fs,{label:"Letter Spacing",value:u.letterSpacing||0,onChange:g=>x({letterSpacing:g}),min:-10,max:50,unit:"px"})]}),e.jsx(o1,{clipId:t})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(Hs,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No text clip selected"})]})},tr={enabled:!0,depth:12,bevelThickness:1.5,bevelSize:.8,bevelSegments:3,material:"physical",metalness:.4,roughness:.45},o1=({clipId:t})=>{const{getTextClip:s,updateText3D:a,project:r,updateClipRotate3D:n}=F(),i=l.useMemo(()=>s(t),[t,s,r.modifiedAt]),o=i?.text3d,c=o?.enabled??!1,d=l.useCallback(u=>{const p={...o??tr,...u};a(t,p)},[o,t,a]);return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-primary font-medium",children:"3D Text"}),e.jsx("button",{onClick:()=>{if(c)d({enabled:!1});else{d({...tr,enabled:!0});const u=i?.transform.rotate3d??{x:0,y:0};u.x===0&&u.y===0&&n(t,{x:-10,y:18,z:0})}},className:`px-2 py-1 rounded text-[10px] font-medium border transition-colors ${c?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:c?"On":"Off"})]}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Fs,{label:"Depth",value:o?.depth??tr.depth,onChange:u=>d({depth:u}),min:1,max:120,step:1,unit:"px"}),e.jsx(Fs,{label:"Bevel Thickness",value:o?.bevelThickness??tr.bevelThickness,onChange:u=>d({bevelThickness:u}),min:0,max:20,step:.1}),e.jsx(Fs,{label:"Bevel Size",value:o?.bevelSize??tr.bevelSize,onChange:u=>d({bevelSize:u}),min:0,max:10,step:.1}),e.jsx(Fs,{label:"Bevel Segments",value:o?.bevelSegments??tr.bevelSegments,onChange:u=>d({bevelSegments:Math.max(1,Math.round(u))}),min:1,max:8,step:1}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Material"}),e.jsx("div",{className:"flex gap-1",children:["basic","physical"].map(u=>e.jsx("button",{onClick:()=>d({material:u}),className:`px-2 py-0.5 text-[10px] rounded border transition-colors ${(o?.material??"physical")===u?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:u},u))})]}),(o?.material??"physical")==="physical"&&e.jsxs(e.Fragment,{children:[e.jsx(Fs,{label:"Metalness",value:o?.metalness??tr.metalness,onChange:u=>d({metalness:Math.max(0,Math.min(1,u))}),min:0,max:1,step:.05}),e.jsx(Fs,{label:"Roughness",value:o?.roughness??tr.roughness,onChange:u=>d({roughness:Math.max(0,Math.min(1,u))}),min:0,max:1,step:.05})]})]})]})},Jc=[{value:"none",label:"None",description:"No animation"},{value:"typewriter",label:"Typewriter",description:"Characters appear one by one"},{value:"fade",label:"Fade",description:"Fade in and out"},{value:"slide-left",label:"Slide Left",description:"Slide in from the right"},{value:"slide-right",label:"Slide Right",description:"Slide in from the left"},{value:"slide-up",label:"Slide Up",description:"Slide in from below"},{value:"slide-down",label:"Slide Down",description:"Slide in from above"},{value:"scale",label:"Scale",description:"Scale up from small"},{value:"bounce",label:"Bounce",description:"Bouncy entrance"},{value:"rotate",label:"Rotate",description:"Rotate into view"},{value:"wave",label:"Wave",description:"Characters wave up and down"},{value:"shake",label:"Shake",description:"Vibrating text effect"},{value:"pop",label:"Pop",description:"Poppy entrance with overshoot"},{value:"glitch",label:"Glitch",description:"Digital glitch effect"},{value:"split",label:"Split",description:"Text splits from center"},{value:"flip",label:"Flip",description:"3D flip animation"},{value:"word-by-word",label:"Word by Word",description:"Words appear sequentially"},{value:"rainbow",label:"Rainbow",description:"Color cycles through spectrum"}],ys=ht,l1=({value:t,onChange:s})=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Animation Preset"}),e.jsxs(ot,{value:t,onValueChange:a=>s(a),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border max-h-60",children:Jc.map(a=>e.jsx(ge,{value:a.value,children:a.label},a.value))})]}),e.jsx("p",{className:"text-[9px] text-text-muted",children:Jc.find(a=>a.value===t)?.description})]}),c1=({value:t,onChange:s})=>{const a=[{value:"linear",label:"Linear"},{value:"ease-in",label:"Ease In"},{value:"ease-out",label:"Ease Out"},{value:"ease-in-out",label:"Ease In Out"}];return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Easing"}),e.jsxs(ot,{value:t,onValueChange:s,children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:a.map(r=>e.jsx(ge,{value:r.value,children:r.label},r.value))})]})]})},d1=({clipId:t})=>{const s=F(x=>x.getTextClip),a=F(x=>x.applyTextAnimationPreset);F(x=>x.project);const r=s(t),n=r?.animation?.preset||"none",i=r?.animation?.inDuration??.5,o=r?.animation?.outDuration??.5,c=r?.animation?.params?.easing??"ease-out",d=l.useCallback(x=>{a(t,x,i,o)},[t,a,i,o]),u=l.useCallback(x=>{a(t,n,x,o)},[t,a,n,o]),p=l.useCallback(x=>{a(t,n,i,x)},[t,a,n,i]),m=l.useCallback(x=>{a(t,n,i,o,{easing:x})},[t,a,n,i,o]);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(l1,{value:n,onChange:d}),n!=="none"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ia,{size:12,className:"text-text-muted"}),e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Timing"})]}),e.jsx(ys,{label:"In Duration",value:i,onChange:u,min:0,max:5,step:.1,unit:"s"}),e.jsx(ys,{label:"Out Duration",value:o,onChange:p,min:0,max:5,step:.1,unit:"s"})]}),e.jsx("div",{className:"p-3 bg-background-tertiary rounded-lg",children:e.jsx(c1,{value:c,onChange:m})}),e.jsxs("div",{className:"p-3 bg-background-secondary rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(As,{size:12,className:"text-text-muted"}),e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Preview"})]}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:["Animation will play during preview and export. Total animation time: ",(i+o).toFixed(1),"s"]})]})]}),n==="fade"&&e.jsx(u1,{clipId:t,animation:r.animation}),(n==="slide-left"||n==="slide-right"||n==="slide-up"||n==="slide-down")&&e.jsx(m1,{clipId:t,animation:r.animation}),n==="scale"&&e.jsx(p1,{clipId:t,animation:r.animation}),n==="bounce"&&e.jsx(x1,{clipId:t,animation:r.animation}),n==="rotate"&&e.jsx(h1,{clipId:t,animation:r.animation}),n==="wave"&&e.jsx(f1,{clipId:t,animation:r.animation}),n==="shake"&&e.jsx(g1,{clipId:t,animation:r.animation}),n==="pop"&&e.jsx(b1,{clipId:t,animation:r.animation}),n==="glitch"&&e.jsx(y1,{clipId:t,animation:r.animation})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(Hs,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No text clip selected"})]})},u1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.fadeOpacity?.start??0,o=s?.params?.fadeOpacity?.end??1,c=(d,u)=>{n?.animation&&a(t,"fade",n.animation.inDuration,n.animation.outDuration,{fadeOpacity:{start:d,end:u}})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Fade Settings"}),e.jsx(ys,{label:"Start Opacity",value:i,onChange:d=>c(d,o),min:0,max:1,step:.1,unit:""}),e.jsx(ys,{label:"End Opacity",value:o,onChange:d=>c(i,d),min:0,max:1,step:.1,unit:""})]})},m1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.slideDistance??.2,o=c=>{n?.animation&&a(t,n.animation.preset,n.animation.inDuration,n.animation.outDuration,{slideDistance:c})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Slide Settings"}),e.jsx(ys,{label:"Distance",value:i,onChange:o,min:.05,max:1,step:.05,unit:""})]})},p1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.scaleFrom??0,o=s?.params?.scaleTo??1,c=(d,u)=>{n?.animation&&a(t,"scale",n.animation.inDuration,n.animation.outDuration,{scaleFrom:d,scaleTo:u})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Scale Settings"}),e.jsx(ys,{label:"Scale From",value:i,onChange:d=>c(d,o),min:0,max:2,step:.1,unit:"x"}),e.jsx(ys,{label:"Scale To",value:o,onChange:d=>c(i,d),min:0,max:2,step:.1,unit:"x"})]})},x1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.bounceHeight??.1,o=s?.params?.bounceCount??3,c=(d,u)=>{n?.animation&&a(t,"bounce",n.animation.inDuration,n.animation.outDuration,{bounceHeight:d,bounceCount:u})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Bounce Settings"}),e.jsx(ys,{label:"Height",value:i,onChange:d=>c(d,o),min:.01,max:.5,step:.01,unit:""}),e.jsx(ys,{label:"Bounces",value:o,onChange:d=>c(i,Math.round(d)),min:1,max:10,step:1,unit:""})]})},h1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.rotateAngle??360,o=c=>{n?.animation&&a(t,"rotate",n.animation.inDuration,n.animation.outDuration,{rotateAngle:c})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Rotate Settings"}),e.jsx(ys,{label:"Angle",value:i,onChange:o,min:-720,max:720,step:15,unit:"°"})]})},f1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.waveAmplitude??.02,o=s?.params?.waveFrequency??2,c=(d,u)=>{n?.animation&&a(t,"wave",n.animation.inDuration,n.animation.outDuration,{waveAmplitude:d,waveFrequency:u})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Wave Settings"}),e.jsx(ys,{label:"Amplitude",value:i,onChange:d=>c(d,o),min:.005,max:.1,step:.005,unit:""}),e.jsx(ys,{label:"Frequency",value:o,onChange:d=>c(i,d),min:.5,max:5,step:.5,unit:""})]})},g1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.shakeIntensity??.01,o=s?.params?.shakeSpeed??20,c=(d,u)=>{n?.animation&&a(t,"shake",n.animation.inDuration,n.animation.outDuration,{shakeIntensity:d,shakeSpeed:u})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Shake Settings"}),e.jsx(ys,{label:"Intensity",value:i,onChange:d=>c(d,o),min:.001,max:.05,step:.001,unit:""}),e.jsx(ys,{label:"Speed",value:o,onChange:d=>c(i,d),min:5,max:50,step:5,unit:""})]})},b1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.popOvershoot??1.2,o=c=>{n?.animation&&a(t,"pop",n.animation.inDuration,n.animation.outDuration,{popOvershoot:c})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Pop Settings"}),e.jsx(ys,{label:"Overshoot",value:i,onChange:o,min:1,max:2,step:.05,unit:"x"})]})},y1=({clipId:t,animation:s})=>{const{applyTextAnimationPreset:a,getTextClip:r}=F(),n=r(t),i=s?.params?.glitchIntensity??.02,o=s?.params?.glitchSpeed??10,c=(d,u)=>{n?.animation&&a(t,"glitch",n.animation.inDuration,n.animation.outDuration,{glitchIntensity:d,glitchSpeed:u})};return e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Glitch Settings"}),e.jsx(ys,{label:"Intensity",value:i,onChange:d=>c(d,o),min:.005,max:.1,step:.005,unit:""}),e.jsx(ys,{label:"Speed",value:o,onChange:d=>c(i,d),min:1,max:30,step:1,unit:""})]})},Zc={isProcessing:!1,progress:null,beatAnalysis:null,selectedAudioClipId:null,selectedTrackIds:[],clipsToSync:[],previewTimings:[],config:cg,error:null};let v1=class{state={...Zc};listeners=new Set;audioContext=null;subscribe(s){return this.listeners.add(s),s(this.state),()=>this.listeners.delete(s)}setState(s){this.state={...this.state,...s},this.listeners.forEach(a=>a(this.state))}getState(){return this.state}setSelectedAudioClip(s){this.setState({selectedAudioClipId:s,beatAnalysis:null,previewTimings:[],error:null})}setSelectedTracks(s){this.setState({selectedTrackIds:s}),this.updateClipsToSync(),this.updatePreview()}toggleTrackSelection(s){const{selectedTrackIds:a}=this.state,r=a.includes(s)?a.filter(n=>n!==s):[...a,s];this.setSelectedTracks(r)}updateConfig(s){this.setState({config:{...this.state.config,...s}}),this.updatePreview()}updateClipsToSync(){const{selectedTrackIds:s}=this.state,a=F.getState(),{project:r}=a,n=[];for(const i of r.timeline.tracks)if(s.includes(i.id))for(const o of i.clips)n.push({id:o.id,startTime:o.startTime,duration:o.duration,trackId:i.id});this.setState({clipsToSync:n})}updatePreview(){const{beatAnalysis:s,clipsToSync:a,config:r,selectedAudioClipId:n}=this.state;if(!s||a.length===0){this.setState({previewTimings:[]});return}const i=F.getState(),c=(n?i.getClip(n):null)?.startTime??0,u=uc().calculateSyncedTimings(a,s,c,r);this.setState({previewTimings:u})}async analyzeBeats(){const{selectedAudioClipId:s}=this.state;if(!s){this.setState({error:"No audio clip selected"});return}const a=F.getState(),r=a.getClip(s);if(!r){this.setState({error:"Clip not found"});return}const n=a.getMediaItem(r.mediaId);if(!n?.blob){this.setState({error:"Media blob not found"});return}this.setState({isProcessing:!0,error:null});try{const i=await this.extractAudioFromBlob(n.blob,r.inPoint??0,r.outPoint??r.duration),c=await uc().analyzeBeats(i,d=>this.setState({progress:d}));this.setState({beatAnalysis:c,isProcessing:!1,progress:null}),this.updatePreview()}catch(i){this.setState({isProcessing:!1,error:i instanceof Error?i.message:"Beat analysis failed",progress:null})}}async applySync(){const{previewTimings:s}=this.state;if(s.length===0)return this.setState({error:"No clips to sync"}),!1;const a=F.getState();this.setState({isProcessing:!0,error:null});try{for(const r of s){await a.moveClip(r.clipId,r.newStartTime);const n=a.getClip(r.clipId);if(n&&this.state.config.syncMode!=="preserve-duration"){const i=(n.inPoint??0)+r.newDuration;await a.trimClip(r.clipId,n.inPoint,i)}}return this.setState({isProcessing:!1,progress:{phase:"complete",percent:100,message:`Synced ${s.length} clips to beats`}}),!0}catch(r){return this.setState({isProcessing:!1,error:r instanceof Error?r.message:"Failed to apply sync"}),!1}}getAvailableTracks(){const s=F.getState(),{project:a}=s,{selectedAudioClipId:r}=this.state,i=(r?s.getClip(r):null)?a.timeline.tracks.find(o=>o.clips.some(c=>c.id===r))?.id:null;return a.timeline.tracks.filter(o=>o.id!==i&&o.clips.length>0).map(o=>({id:o.id,name:o.name,type:o.type,clipCount:o.clips.length}))}async extractAudioFromBlob(s,a,r){this.audioContext||(this.audioContext=new AudioContext);const n=await s.arrayBuffer(),i=await this.audioContext.decodeAudioData(n),o=Math.min(r-a,i.duration-a),c=i.sampleRate,d=Math.floor(a*c),u=Math.floor(o*c),p=new OfflineAudioContext(1,u,c),m=p.createBuffer(1,u,c),x=m.getChannelData(0),h=i.getChannelData(0);for(let A=0;A{for(let N=0;N{const[s,a]=l.useState(null),[r,n]=l.useState(!1),i=l.useMemo(()=>j1(),[]);l.useEffect(()=>{const N=i.subscribe(a);return i.setSelectedAudioClip(t),N},[i,t]);const o=l.useMemo(()=>i.getAvailableTracks(),[i,s?.beatAnalysis]),c=l.useCallback(()=>{i.analyzeBeats()},[i]),d=l.useCallback(N=>{i.toggleTrackSelection(N)},[i]),u=l.useCallback(async()=>{await i.applySync()},[i]),p=l.useCallback(N=>{i.updateConfig(N)},[i]);if(!s)return e.jsx("div",{className:"p-4 flex items-center justify-center",children:e.jsx(ds,{size:20,className:"animate-spin text-primary"})});const{isProcessing:m,progress:x,beatAnalysis:h,selectedTrackIds:f,clipsToSync:v,previewTimings:A,config:g,error:k}=s;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-text-secondary",children:[e.jsx(Ps,{size:14}),e.jsx("span",{className:"text-[10px]",children:"Sync clips to the beat of this audio"})]}),k&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:[e.jsx(Ba,{size:14,className:"text-red-400 shrink-0"}),e.jsx("span",{className:"text-[10px] text-red-400",children:k})]}),h?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-text-secondary block",children:"BPM Detected"}),e.jsx("span",{className:"text-lg font-bold text-primary",children:h.bpm})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-[10px] text-text-secondary block",children:"Beats"}),e.jsx("span",{className:"text-sm font-medium text-text-primary",children:h.beats.length})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary block",children:"Select tracks to sync to beats:"}),o.length===0?e.jsx("p",{className:"text-[10px] text-text-muted p-3 bg-background-tertiary rounded-lg",children:"No other tracks with clips found. Add clips to other tracks first."}):e.jsx("div",{className:"space-y-1",children:o.map(N=>e.jsxs("button",{onClick:()=>d(N.id),className:`w-full flex items-center justify-between p-2 rounded-lg text-left transition-colors ${f.includes(N.id)?"bg-primary/20 border border-primary/50":"bg-background-tertiary border border-transparent hover:border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[w1[N.type]||e.jsx(zs,{size:12}),e.jsx("span",{className:"text-[11px] text-text-primary",children:N.name})]}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[N.clipCount," ",N.clipCount===1?"clip":"clips"]})]},N.id))})]}),v.length>0&&e.jsx("div",{className:"p-2 bg-background-tertiary rounded-lg",children:e.jsxs("span",{className:"text-[9px] text-text-muted",children:[v.length," clips will be synced to ",h.beats.length," beats"]})}),e.jsxs("div",{className:"border-t border-border pt-3",children:[e.jsxs("button",{onClick:()=>n(!r),className:"flex items-center gap-2 text-[10px] text-text-secondary hover:text-text-primary mb-3",children:[e.jsx(Dn,{size:12}),"Sync Settings"]}),r&&e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-text-secondary block mb-2",children:"Sync Mode"}),e.jsx("div",{className:"space-y-1",children:[{value:"smart",label:"Smart",desc:"Adjust duration to fit nearest beat count"},{value:"one-per-beat",label:"One per Beat",desc:"Each clip gets exactly one beat"},{value:"preserve-duration",label:"Preserve Duration",desc:"Keep original duration, snap start to beat"}].map(N=>e.jsxs("button",{onClick:()=>p({syncMode:N.value}),className:`w-full text-left p-2 rounded transition-colors ${g.syncMode===N.value?"bg-primary/20 border border-primary/50":"bg-background-secondary border border-transparent hover:border-border"}`,children:[e.jsx("span",{className:"text-[10px] text-text-primary block",children:N.label}),e.jsx("span",{className:"text-[9px] text-text-muted",children:N.desc})]},N.value))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Beat Subdivision"}),e.jsx("div",{className:"flex gap-1",children:[1,2,4].map(N=>e.jsxs("button",{onClick:()=>p({beatSubdivision:N}),className:`px-2 py-1 text-[9px] rounded transition-colors ${g.beatSubdivision===N?"bg-primary text-black":"bg-background-secondary text-text-secondary hover:text-text-primary"}`,children:["1/",N]},N))})]}),e.jsx(ht,{label:"Offset",value:g.offsetMs,onChange:N=>p({offsetMs:N}),min:-500,max:500,step:10,unit:"ms"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Downbeats Only"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>p({snapToDownbeats:!1}),className:`px-2 py-1 text-[9px] rounded transition-colors ${g.snapToDownbeats?"bg-background-secondary text-text-secondary":"bg-primary text-black"}`,children:"All Beats"}),e.jsx("button",{onClick:()=>p({snapToDownbeats:!0}),className:`px-2 py-1 text-[9px] rounded transition-colors ${g.snapToDownbeats?"bg-primary text-black":"bg-background-secondary text-text-secondary"}`,children:"Downbeats"})]})]})]})]}),A.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:"Preview:"}),e.jsxs("div",{className:"max-h-24 overflow-y-auto bg-background-tertiary rounded-lg p-2 space-y-1",children:[A.slice(0,5).map((N,b)=>e.jsxs("div",{className:"flex items-center justify-between text-[9px]",children:[e.jsxs("span",{className:"text-text-muted",children:["Clip ",b+1]}),e.jsxs("span",{className:"text-text-primary",children:[N.originalStartTime.toFixed(2),"s → ",N.newStartTime.toFixed(2),"s"]})]},N.clipId)),A.length>5&&e.jsxs("span",{className:"text-[9px] text-text-muted",children:["...and ",A.length-5," more"]})]})]}),x?.phase==="complete"&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-green-500/10 rounded-lg border border-green-500/30",children:[e.jsx(is,{size:14,className:"text-green-400"}),e.jsx("span",{className:"text-[10px] text-green-400",children:x.message})]}),e.jsx(zt,{onClick:u,disabled:m||A.length===0,className:"w-full bg-primary hover:bg-primary/80 text-black disabled:opacity-50",children:m?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"mr-2 animate-spin"}),"Syncing..."]}):`Sync ${A.length} Clips to Beats`}),e.jsx(zt,{onClick:c,variant:"outline",className:"w-full",children:"Re-analyze Beats"})]}):e.jsx("div",{className:"space-y-3",children:m&&x?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{size:12,className:"animate-spin text-primary"}),e.jsx("span",{className:"text-[10px] text-text-primary",children:x.message})]}),e.jsx("div",{className:"h-1.5 bg-background-tertiary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${x.percent}%`}})})]}):e.jsxs(zt,{onClick:c,className:"w-full bg-primary/20 hover:bg-primary/30 text-primary border border-primary/30",children:[e.jsx(Ps,{size:14,className:"mr-2"}),"Detect Beats"]})})]})},Do=({label:t,value:s,onChange:a,showAlpha:r=!1})=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsx(ll,{value:s,onChange:a,showAlpha:r,className:"max-w-[170px]"})]}),Io=({label:t,value:s,onChange:a,min:r=0,max:n=1e3,step:i=1,unit:o=""})=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"number",value:s,onChange:c=>a(parseFloat(c.target.value)||0),min:r,max:n,step:i,className:"w-16 px-2 py-1 text-[10px] font-mono text-text-primary bg-background-tertiary border border-border rounded text-right outline-none focus:border-primary"}),o&&e.jsx("span",{className:"text-[10px] text-text-muted",children:o})]})]}),N1=({value:t,onChange:s})=>{const a=[{value:void 0,label:"Solid",preview:"────"},{value:[5,5],label:"Dashed",preview:"- - -"},{value:[2,2],label:"Dotted",preview:"• • •"}];return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Style"}),e.jsx("div",{className:"flex gap-1",children:a.map((r,n)=>e.jsx("button",{onClick:()=>s(r.value),className:`px-2 py-1 text-[9px] rounded transition-colors ${r.value===void 0&&t===void 0||r.value&&t&&r.value[0]===t[0]?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,title:r.label,children:r.preview},n))})]})},C1=({shapeType:t})=>{const s={rectangle:e.jsx(Gs,{size:16}),circle:e.jsx(or,{size:16}),ellipse:e.jsx(or,{size:16}),triangle:e.jsx(iu,{size:16}),star:e.jsx(Ys,{size:16}),polygon:e.jsx(Qd,{size:16}),arrow:e.jsx(Pr,{size:16})};return e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg",children:[e.jsx("div",{className:"p-1.5 bg-background-secondary rounded",children:s[t]||e.jsx(Gs,{size:16})}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-medium text-text-primary capitalize",children:t}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Shape clip"})]})]})},S1=({clipId:t})=>{const{getShapeClip:s,updateShapeStyle:a,project:r}=F(),n=l.useMemo(()=>s(t),[t,s,r.modifiedAt]),c={fill:{type:"solid",color:"#3b82f6",opacity:1},stroke:{color:"#1d4ed8",width:2,opacity:1}},d=n?.style||c,u=n?.shapeType||"rectangle",p=l.useCallback(m=>{a(t,m)},[t,a]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(C1,{shapeType:u}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Fill"}),e.jsx(Do,{label:"Color",value:d.fill?.color||"#3b82f6",onChange:m=>p({fill:{...d.fill,color:m,type:"solid",opacity:d.fill?.opacity||1}})}),e.jsx(ht,{label:"Opacity",value:(d.fill?.opacity||1)*100,onChange:m=>p({fill:{...d.fill,opacity:m/100,type:d.fill?.type||"solid"}}),min:0,max:100,unit:"%"})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Stroke"}),e.jsx(Do,{label:"Color",value:d.stroke?.color||"#1d4ed8",onChange:m=>p({stroke:{...d.stroke,color:m,width:d.stroke?.width||2,opacity:d.stroke?.opacity||1}})}),e.jsx(Io,{label:"Width",value:d.stroke?.width||0,onChange:m=>p({stroke:{...d.stroke,width:m,color:d.stroke?.color||"#1d4ed8",opacity:d.stroke?.opacity||1}}),min:0,max:50,unit:"px"}),e.jsx(N1,{value:d.stroke?.dashArray,onChange:m=>p({stroke:{...d.stroke,dashArray:m,color:d.stroke?.color||"#1d4ed8",width:d.stroke?.width||2,opacity:d.stroke?.opacity||1}})})]}),u==="rectangle"&&e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Corners"}),e.jsx(ht,{label:"Radius",value:d.cornerRadius||0,onChange:m=>p({cornerRadius:m}),min:0,max:100,unit:"px"})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-background-tertiary rounded-lg",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Shadow"}),e.jsx(Do,{label:"Color",value:d.shadow?.color||"#000000",onChange:m=>p({shadow:{color:m,offsetX:d.shadow?.offsetX||0,offsetY:d.shadow?.offsetY||0,blur:d.shadow?.blur||0}}),showAlpha:!0}),e.jsx(Io,{label:"Offset X",value:d.shadow?.offsetX||0,onChange:m=>p({shadow:{offsetX:m,color:d.shadow?.color||"#000000",offsetY:d.shadow?.offsetY||0,blur:d.shadow?.blur||0}}),min:-50,max:50,unit:"px"}),e.jsx(Io,{label:"Offset Y",value:d.shadow?.offsetY||0,onChange:m=>p({shadow:{offsetY:m,color:d.shadow?.color||"#000000",offsetX:d.shadow?.offsetX||0,blur:d.shadow?.blur||0}}),min:-50,max:50,unit:"px"}),e.jsx(ht,{label:"Blur",value:d.shadow?.blur||0,onChange:m=>p({shadow:{blur:m,color:d.shadow?.color||"#000000",offsetX:d.shadow?.offsetX||0,offsetY:d.shadow?.offsetY||0}}),min:0,max:50,unit:"px"})]})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(Gs,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"No shape clip selected"})]})},A1=({label:t,value:s,onChange:a})=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsx(ll,{value:s,onChange:a,className:"max-w-[170px]"})]}),ed=ug.map(t=>({value:t.id,label:t.name,description:t.description})),T1=({clipId:t})=>{const{getSVGClipById:s,updateSVGClip:a,project:r}=F(),n=l.useMemo(()=>s(t),[t,s,r.modifiedAt]),i=n?.colorStyle||{colorMode:"none",tintColor:"#ffffff",tintOpacity:1},o=n?.entryAnimation,c=n?.exitAnimation,d=l.useCallback(v=>{if(!n){console.warn(`[SVGSection] No SVG clip found for ${t}`);return}const A={...i,colorMode:v};a(t,{colorStyle:A})},[t,n,i,a]),u=l.useCallback(v=>{n&&a(t,{colorStyle:{...i,tintColor:v}})},[t,n,i,a]),p=l.useCallback(v=>{n&&a(t,{colorStyle:{...i,tintOpacity:v}})},[t,n,i,a]),m=l.useCallback(v=>{if(!n){console.warn(`[SVGSection] No SVG clip found for ${t}`);return}const A={type:v,duration:o?.duration||.5,easing:o?.easing||"ease-out"};a(t,{entryAnimation:A})},[t,n,o,a]),x=l.useCallback(v=>{if(!n)return;const A={type:v,duration:c?.duration||.5,easing:c?.easing||"ease-out"};a(t,{exitAnimation:A})},[t,n,c,a]),h=l.useCallback(v=>{!n||!o||a(t,{entryAnimation:{...o,duration:v}})},[t,n,o,a]),f=l.useCallback(v=>{!n||!c||a(t,{exitAnimation:{...c,duration:v}})},[t,n,c,a]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Mode"}),e.jsx("div",{className:"flex gap-1",children:["none","tint","replace"].map(v=>e.jsx("button",{onClick:()=>d(v),className:`px-2 py-1 text-[9px] rounded capitalize transition-colors ${i.colorMode===v?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,children:v},v))})]}),i.colorMode!=="none"&&e.jsxs(e.Fragment,{children:[e.jsx(A1,{label:"Color",value:i.tintColor||"#ffffff",onChange:u}),e.jsx(ht,{label:"Opacity",value:i.tintOpacity||1,onChange:p,min:0,max:1,step:.1})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Entry Animation"}),e.jsxs(ot,{value:o?.type||"none",onValueChange:v=>m(v),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:ed.map(v=>e.jsx(ge,{value:v.value,children:v.label},v.value))})]}),o&&o.type!=="none"&&e.jsx(ht,{label:"Duration",value:o.duration,onChange:h,min:.1,max:3,step:.1})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Exit Animation"}),e.jsxs(ot,{value:c?.type||"none",onValueChange:v=>x(v),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:ed.map(v=>e.jsx(ge,{value:v.value,children:v.label},v.value))})]}),c&&c.type!=="none"&&e.jsx(ht,{label:"Duration",value:c.duration,onChange:f,min:.1,max:3,step:.1})]})]}):e.jsx("div",{className:"text-center py-8 text-text-muted text-xs",children:"No SVG clip selected"})},M1=({clipId:t})=>{const{updateClipTransform:s}=F(),a=l.useCallback(()=>{const{project:o}=F.getState();for(const c of o.timeline.tracks){const d=c.clips.find(u=>u.id===t);if(d)return d.transform??{position:{x:.5,y:.5}}}return{position:{x:.5,y:.5}}},[t]),r=l.useCallback((o,c)=>{const u=a().position??{x:.5,y:.5};s(t,{position:{...u,[o]:c}})},[t,s,a]),n=l.useCallback(()=>{s(t,{position:{x:.5,y:.5}})},[t,s]),i="p-2 rounded-md bg-background-tertiary border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-text-secondary hover:text-primary";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"Horizontal"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:i,onClick:()=>r("x",0),title:"Align Left",children:e.jsx(Bp,{size:14})}),e.jsx("button",{className:i,onClick:()=>r("x",.5),title:"Center Horizontally",children:e.jsx(Vd,{size:14})}),e.jsx("button",{className:i,onClick:()=>r("x",1),title:"Align Right",children:e.jsx(Dp,{size:14})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"Vertical"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:i,onClick:()=>r("y",0),title:"Align Top",children:e.jsx(_p,{size:14})}),e.jsx("button",{className:i,onClick:()=>r("y",.5),title:"Center Vertically",children:e.jsx(Ud,{size:14})}),e.jsx("button",{className:i,onClick:()=>r("y",1),title:"Align Bottom",children:e.jsx($p,{size:14})})]})]}),e.jsx("button",{className:"w-full py-1.5 text-[10px] rounded-md bg-background-tertiary border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-text-secondary hover:text-primary",onClick:n,title:"Center on Canvas",children:"Center on Canvas"})]})};class E1{playbackController=null;unsubscribeTimelineStore=null;unsubscribePlaybackEvents=null;initialized=!1;isUpdatingProject=!1;async initialize(){if(this.initialized)return;const s=Ct.getState();if(!s.initialized)throw new Error("EngineStore must be initialized before PlaybackBridge");if(this.playbackController=s.playbackController,!this.playbackController)throw new Error("PlaybackController not available in EngineStore");const a=F.getState();this.playbackController.setProject(a.project),this.setupPlaybackEventSubscriptions(),this.setupProjectSubscription(),this.initialized=!0}setupPlaybackEventSubscriptions(){if(!this.playbackController)return;const s=a=>{const r=Et.getState();switch(a.type){case"timeupdate":!this.isUpdatingProject&&!this.playbackController?.getIsScrubbing()&&r.setPlayheadPosition(a.time);break;case"statechange":this.syncPlaybackState(a.state);break;case"ended":r.pause();break;case"framerendered":a.frame&&Ct.setState({currentFrame:a.frame});break}};this.playbackController.addEventListener("timeupdate",s),this.playbackController.addEventListener("statechange",s),this.playbackController.addEventListener("ended",s),this.playbackController.addEventListener("framerendered",s),this.unsubscribePlaybackEvents=()=>{this.playbackController?.removeEventListener("timeupdate",s),this.playbackController?.removeEventListener("statechange",s),this.playbackController?.removeEventListener("ended",s),this.playbackController?.removeEventListener("framerendered",s)}}setupProjectSubscription(){this.unsubscribeTimelineStore=F.subscribe(s=>s.project,s=>{if(this.playbackController){const a=Et.getState(),r=a.playheadPosition,n=a.playbackState==="playing";this.isUpdatingProject=!0,this.playbackController.setProject(s),this.isUpdatingProject=!1,this.playbackController.scrubTo(r),a.setPlayheadPosition(r),n&&this.playbackController.play()}})}syncPlaybackState(s){if(this.isUpdatingProject||this.playbackController?.getIsScrubbing())return;const a=Et.getState(),r=a.playbackState,n=s==="seeking"?"paused":s;if(r!==n)switch(n){case"playing":a.play();break;case"paused":a.pause();break;case"stopped":a.stop();break}}isReady(){return this.initialized&&this.playbackController!==null}async play(){this.playbackController&&await this.playbackController.play(),Et.getState().play()}pause(){this.playbackController&&this.playbackController.pause(),Et.getState().pause()}stop(){this.playbackController&&this.playbackController.stop();const s=Et.getState();s.stop(),s.seekToStart()}async togglePlayback(){this.playbackController?await this.playbackController.togglePlayback():Et.getState().togglePlayback()}async seek(s){this.playbackController&&await this.playbackController.seek(s),Et.getState().seekTo(s)}startScrubbing(){this.playbackController&&this.playbackController.startScrubbing(),Et.getState().startScrubbing(Et.getState().playheadPosition)}scrubTo(s){this.playbackController&&this.playbackController.seek(s),Et.getState().updateScrubPosition(s)}endScrubbing(){this.playbackController&&this.playbackController.endScrubbing(),Et.getState().endScrubbing()}setPlaybackRate(s){this.playbackController&&this.playbackController.setPlaybackRate(s),Et.getState().setPlaybackRate(s)}isTrackAudible(s,a){return!(s.muted||a&&!s.solo)}getTrackAudibility(s){const a=s.some(r=>r.solo);return s.map(r=>({trackId:r.id,isAudible:this.isTrackAudible(r,a),isMuted:r.muted,isSolo:r.solo}))}getAudibleTrackIds(){const a=F.getState().project.timeline.tracks,r=this.getTrackAudibility(a),n=new Set;for(const i of r)i.isAudible&&n.add(i.trackId);return n}hasSoloTracks(){return F.getState().project.timeline.tracks.some(r=>r.solo)}getState(){return Et.getState().playbackState}getCurrentTime(){return this.playbackController?this.playbackController.getCurrentTime():Et.getState().playheadPosition}isPlaying(){return this.playbackController?.isPlaying()??!1}isScrubbing(){return this.playbackController?.getIsScrubbing()??!1}getStats(){return this.playbackController?.getStats()??null}dispose(){this.unsubscribePlaybackEvents&&(this.unsubscribePlaybackEvents(),this.unsubscribePlaybackEvents=null),this.unsubscribeTimelineStore&&(this.unsubscribeTimelineStore(),this.unsubscribeTimelineStore=null),this.playbackController=null,this.initialized=!1}}let on=null;function An(){return on||(on=new E1),on}async function R1(){const t=An();return await t.initialize(),t}function P1(){on&&(on.dispose(),on=null)}class z1{engine=Of();currentState={isTracking:!1,progress:0,currentJob:null,trackingData:null,lostFrames:[],error:null};listeners=new Set;clipTrackingMap=new Map;unsubscribeProgress=null;unsubscribeLost=null;constructor(){this.unsubscribeProgress=this.engine.onTrackingProgress(this.handleProgress),this.unsubscribeLost=this.engine.onTrackingLost(this.handleTrackingLost)}handleProgress=s=>{this.updateState({progress:s})};handleTrackingLost=s=>{const a=[...this.currentState.lostFrames,s];this.updateState({lostFrames:a})};updateState(s){this.currentState={...this.currentState,...s},this.notifyListeners()}notifyListeners(){for(const s of this.listeners)s(this.currentState)}subscribe(s){return this.listeners.add(s),s(this.currentState),()=>this.listeners.delete(s)}getState(){return this.currentState}async startTracking(s,a,r={}){this.updateState({isTracking:!0,progress:0,lostFrames:[],error:null,trackingData:null});try{const n=await this.engine.startTracking(s,a,r);this.updateState({currentJob:n});const i=setInterval(()=>{const o=this.engine.getTrackingJob(n.id);if(!o){clearInterval(i);return}if(this.updateState({currentJob:o,progress:o.progress}),o.status==="completed"||o.status==="failed"||o.status==="cancelled")if(clearInterval(i),o.status==="completed"){const c=this.engine.getTrackingDataForClip(s),d=c.length>0?c[c.length-1]:null;d&&this.clipTrackingMap.set(s,d.trackId),this.updateState({isTracking:!1,trackingData:d,currentJob:o})}else o.status==="failed"?this.updateState({isTracking:!1,error:o.error||"Tracking failed",currentJob:o}):this.updateState({isTracking:!1,currentJob:o})},100);return n}catch(n){const i=n instanceof Error?n.message:"Unknown error";throw this.updateState({isTracking:!1,error:i}),n}}cancelTracking(s){this.engine.cancelTracking(s),this.updateState({isTracking:!1,progress:0})}applyTrackingToElement(s,a,r={x:0,y:0}){this.engine.applyTrackingToElement(s,a,r)}applyTrackingToClip(s,a={x:0,y:0}){const r=this.clipTrackingMap.get(s);if(!r)return console.warn(`No tracking data found for clip ${s}`),!1;try{return this.applyTrackingToElement(r,s,a),!0}catch{return!1}}setTrackingOffset(s,a){this.engine.setTrackingOffset(s,a)}getTrackingOffset(s){return this.engine.getTrackingOffset(s)}setApplyScale(s,a){this.engine.setApplyScale(s,a)}setApplyRotation(s,a){this.engine.setApplyRotation(s,a)}getElementPositionAtTime(s,a){return this.engine.getElementPositionAtTime(s,a)}correctTrackingPoint(s,a,r){this.engine.correctTrackingPoint(s,a,r)}getTrackingDataForClip(s){return this.engine.getTrackingDataForClip(s)}getTrackingData(s,a){return this.engine.getTrackingData(s,a)}removeAttachment(s){this.engine.removeTrackingFromElement(s)}hasTrackingData(s){return this.clipTrackingMap.has(s)}getClipTrackId(s){return this.clipTrackingMap.get(s)||null}reset(){this.updateState({isTracking:!1,progress:0,currentJob:null,trackingData:null,lostFrames:[],error:null})}dispose(){this.unsubscribeProgress&&this.unsubscribeProgress(),this.unsubscribeLost&&this.unsubscribeLost(),this.listeners.clear()}}let Bo=null;function D1(){return Bo||(Bo=new z1),Bo}const I1={snapToBeats:!0,snapThreshold:.1,autoZoomOnBeats:!1,zoomIntensity:1.1,autoCutOnBeats:!1,beatsPerCut:4};class B1{engine;state={isAnalyzing:!1,progress:0,error:null,beatMarkers:[],beatAnalysis:null};options={...I1};listeners=new Set;constructor(){this.engine=gl()}getState(){return{...this.state}}getOptions(){return{...this.options}}setOptions(s){this.options={...this.options,...s}}subscribe(s){return this.listeners.add(s),()=>this.listeners.delete(s)}notifyListeners(){const s=this.getState();this.listeners.forEach(a=>a(s))}updateState(s){this.state={...this.state,...s},this.notifyListeners()}async analyzeAudioFromBlob(s,a){this.updateState({isAnalyzing:!0,progress:0,error:null});try{this.updateState({progress:10});const r=await this.engine.analyzeFromBlob(s);this.updateState({progress:80});const n=this.convertToBeatMarkers(r.beats,r.downbeats),i={bpm:r.bpm,confidence:r.confidence,sourceClipId:a,analyzedAt:Date.now()};return this.updateState({isAnalyzing:!1,progress:100,beatMarkers:n,beatAnalysis:i}),r}catch(r){const n=r instanceof Error?r.message:"Beat analysis failed";throw this.updateState({isAnalyzing:!1,progress:0,error:n}),r}}async analyzeAudioFromUrl(s,a){this.updateState({isAnalyzing:!0,progress:0,error:null});try{this.updateState({progress:10});const r=await this.engine.analyzeFromUrl(s);this.updateState({progress:80});const n=this.convertToBeatMarkers(r.beats,r.downbeats),i={bpm:r.bpm,confidence:r.confidence,sourceClipId:a,analyzedAt:Date.now()};return this.updateState({isAnalyzing:!1,progress:100,beatMarkers:n,beatAnalysis:i}),r}catch(r){const n=r instanceof Error?r.message:"Beat analysis failed";throw this.updateState({isAnalyzing:!1,progress:0,error:n}),r}}async analyzeAudioBuffer(s,a){this.updateState({isAnalyzing:!0,progress:0,error:null});try{this.updateState({progress:10});const r=await this.engine.analyzeAudioBuffer(s);this.updateState({progress:80});const n=this.convertToBeatMarkers(r.beats,r.downbeats),i={bpm:r.bpm,confidence:r.confidence,sourceClipId:a,analyzedAt:Date.now()};return this.updateState({isAnalyzing:!1,progress:100,beatMarkers:n,beatAnalysis:i}),r}catch(r){const n=r instanceof Error?r.message:"Beat analysis failed";throw this.updateState({isAnalyzing:!1,progress:0,error:n}),r}}convertToBeatMarkers(s,a){const r=new Set(a);return s.map(n=>({time:n.time,strength:n.strength,index:n.index,isDownbeat:r.has(n.time)||n.index%4===0}))}generateManualBeatMarkers(s,a,r=0){const i=this.engine.generateBeatMarkersAtInterval(s,a,r).map(c=>({time:c.time,strength:c.strength,index:c.index,isDownbeat:c.index%4===0})),o={bpm:s,confidence:1,analyzedAt:Date.now()};return this.updateState({beatMarkers:i,beatAnalysis:o}),i}snapTimeToNearestBeat(s){if(!this.options.snapToBeats||this.state.beatMarkers.length===0)return s;const a=this.state.beatMarkers.map(r=>({time:r.time,strength:r.strength,index:r.index}));return this.engine.snapTimeToNearestBeat(s,a,this.options.snapThreshold)}getBeatsInRange(s,a){return this.state.beatMarkers.filter(r=>r.time>=s&&r.time<=a)}getNearestBeat(s){if(this.state.beatMarkers.length===0)return null;let a=this.state.beatMarkers[0],r=Math.abs(a.time-s);for(const n of this.state.beatMarkers){const i=Math.abs(n.time-s);is)return a;return null}getPreviousBeat(s){let a=null;for(const r of this.state.beatMarkers){if(r.time>=s)break;a=r}return a}generateCutPointsForClips(s,a=4){const r=[],n=this.state.beatMarkers.filter(i=>i.isDownbeat);for(let i=a;i{const k=g.start-x,N=g.end-x,b=Math.max(0,k+a.paddingBefore),j=Math.min(f,N-a.paddingAfter);return{start:b,end:j,duration:j-b}}).filter(g=>g.duration>=a.minSilenceDuration&&g.start>=0&&g.end<=f&&g.startg+k.duration,0);return r?.(100,"Complete"),{silentRegions:v,totalSilenceDuration:A,clipDuration:f}}async cutSilence(s,a,r){if(a.length===0)return{success:!0};const n=F.getState(),i=n.getClip(s);if(!i)return{success:!1,error:"Clip not found"};const o=i.startTime,c=[...a].sort((u,p)=>p.start-u.start);r?.(0,"Preparing cuts...");const d=n.actionHistory;d.beginGroup("Cut silence");try{for(let u=0;u0&&!(await n.splitClip(A.id,g)).success)continue;const k=this.findClipInTimeRange(x,h);k&&await n.rippleDeleteClip(k.id)}return r?.(100,"Complete"),{success:!0}}catch(u){return{success:!1,error:u instanceof Error?u.message:"Unknown error occurred"}}finally{d.endGroup()}}findClipContainingTime(s){const a=F.getState(),{project:r}=a;for(const n of r.timeline.tracks)for(const i of n.clips){const o=i.startTime+i.duration;if(s>=i.startTime&&s=s&&c{const[i,o]=l.useState(r);return e.jsxs("div",{className:`border rounded-lg overflow-hidden ${s?"border-border":"border-border/50 opacity-60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary",children:[e.jsxs("button",{onClick:()=>o(!i),className:"flex-1 flex items-center gap-1",children:[e.jsx(qt,{size:12,className:`transition-transform ${i?"":"-rotate-90"} text-text-muted`}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:t})]}),a&&e.jsx("button",{onClick:()=>a(!s),className:`w-8 h-4 rounded-full transition-colors ${s?"bg-primary":"bg-background-tertiary border border-border"}`,children:e.jsx("div",{className:`w-3 h-3 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-4":"translate-x-0.5"}`})})]}),i&&e.jsx("div",{className:"p-3 space-y-3",children:n})]})},$1=({frequency:t,gain:s,onChange:a})=>{const r=(s+12)/24*100;return e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"h-16 w-4 bg-background-tertiary rounded-full relative overflow-hidden",children:[e.jsx("input",{type:"range",min:-12,max:12,value:s,onChange:n=>a(parseFloat(n.target.value)),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10",style:{writingMode:"vertical-lr",direction:"rtl"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-primary/50 rounded-full transition-all",style:{height:`${r}%`}}),e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2 w-3 h-3 bg-white rounded-full shadow-sm pointer-events-none transition-all",style:{bottom:`calc(${r}% - 6px)`}})]}),e.jsx("span",{className:"text-[8px] text-text-muted",children:t}),e.jsxs("span",{className:"text-[8px] font-mono text-text-secondary",children:[s>0?"+":"",s]})]})},O1=({clipId:t})=>{const s=F(R=>R.toggleAudioEffect),a=F(R=>R.getAudioEffects),[r,n]=l.useState(!1),[i,o]=l.useState(null),[c,d]=l.useState([{frequency:"60Hz",gain:0},{frequency:"250Hz",gain:0},{frequency:"1kHz",gain:0},{frequency:"4kHz",gain:0},{frequency:"16kHz",gain:0}]),[u,p]=l.useState(!1),[m,x]=l.useState(null),[h,f]=l.useState({threshold:-20,ratio:4,attack:.01,release:.1}),[v,A]=l.useState(!1),[g,k]=l.useState(null),[N,b]=l.useState({roomSize:.5,damping:.5,wetLevel:.3}),[j,y]=l.useState(!1),[w,S]=l.useState(null),[T,C]=l.useState({time:.25,feedback:.3,wetLevel:.25});l.useEffect(()=>{(async()=>{try{await jl()}catch(D){console.error("Failed to initialize AudioBridgeEffects:",D)}})();const U=a(t);for(const D of U)if(D.type==="eq"){n(D.enabled),o(D.id);const X=D.params;X.bands&&d(X.bands.map(K=>({frequency:M(K.frequency),gain:K.gain})))}else if(D.type==="compressor"){p(D.enabled),x(D.id);const X=D.params;f(K=>({...K,...X}))}else if(D.type==="reverb"){A(D.enabled),k(D.id);const X=D.params;b(K=>({...K,...X}))}else if(D.type==="delay"){y(D.enabled),S(D.id);const X=D.params;C(K=>({...K,...X}))}},[t,a]);const M=R=>R>=1e3?`${R/1e3}kHz`:`${R}Hz`,z=R=>R.includes("kHz")?parseFloat(R)*1e3:parseFloat(R),L=l.useCallback(R=>{const U=Us();if(R&&!i){const D=c.map((K,ue)=>({type:bi[ue].type,frequency:z(K.frequency),gain:K.gain,q:bi[ue].q})),X=U.applyEQ(t,D);X.success&&X.effectId&&o(X.effectId)}else i&&s(t,i,R);n(R)},[t,i,c,s]),B=l.useCallback((R,U)=>{const D=Us();d(X=>{const K=X.map((ue,Te)=>Te===R?{...ue,gain:U}:ue);if(i&&r){const ue=K.map((Te,pe)=>({type:bi[pe].type,frequency:z(Te.frequency),gain:Te.gain,q:bi[pe].q}));D.updateEQ(t,i,ue)}return K})},[t,i,r]),O=l.useCallback(R=>{const U=Us();if(R&&!m){const D=U.applyCompressor(t,h);D.success&&D.effectId&&x(D.effectId)}else m&&s(t,m,R);p(R)},[t,m,h,s]),G=l.useCallback((R,U)=>{const D=Us();f(X=>{const K={...X,[R]:U};return m&&u&&D.updateCompressor(t,m,K),K})},[t,m,u]),V=l.useCallback(R=>{const U=Us();if(R&&!g){const D=U.applyReverb(t,N);D.success&&D.effectId&&k(D.effectId)}else g&&s(t,g,R);A(R)},[t,g,N,s]),P=l.useCallback((R,U)=>{const D=Us();b(X=>{const K={...X,[R]:U};return g&&v&&D.updateReverb(t,g,K),K})},[t,g,v]),_=l.useCallback(R=>{const U=Us();if(R&&!w){const D=U.applyDelay(t,T);D.success&&D.effectId&&S(D.effectId)}else w&&s(t,w,R);y(R)},[t,w,T,s]),se=l.useCallback((R,U)=>{const D=Us();C(X=>{const K={...X,[R]:U};return w&&j&&D.updateDelay(t,w,K),K})},[t,w,j]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg",children:[e.jsx(Ts,{size:14,className:"text-text-secondary"}),e.jsxs("span",{className:"text-[10px] text-text-secondary",children:["Audio clip: ",t.substring(0,8),"..."]})]}),e.jsx(wi,{title:"Equalizer",enabled:r,onToggle:L,defaultOpen:!0,children:e.jsx("div",{className:"flex justify-around py-2",children:c.map((R,U)=>e.jsx($1,{frequency:R.frequency,gain:R.gain,onChange:D=>B(U,D)},R.frequency))})}),e.jsx(wi,{title:"Compressor",enabled:u,onToggle:O,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ht,{label:"Threshold",value:h.threshold,onChange:R=>G("threshold",R),min:-60,max:0,unit:"dB"}),e.jsx(ht,{label:"Ratio",value:h.ratio,onChange:R=>G("ratio",R),min:1,max:20,step:.5,unit:":1"}),e.jsx(ht,{label:"Attack",value:h.attack*1e3,onChange:R=>G("attack",R/1e3),min:1,max:100,step:1,unit:"ms"}),e.jsx(ht,{label:"Release",value:h.release*1e3,onChange:R=>G("release",R/1e3),min:10,max:1e3,unit:"ms"})]})}),e.jsx(wi,{title:"Reverb",enabled:v,onToggle:V,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ht,{label:"Room Size",value:N.roomSize*100,onChange:R=>P("roomSize",R/100),min:0,max:100,unit:"%"}),e.jsx(ht,{label:"Damping",value:N.damping*100,onChange:R=>P("damping",R/100),min:0,max:100,unit:"%"}),e.jsx(ht,{label:"Wet/Dry",value:N.wetLevel*100,onChange:R=>P("wetLevel",R/100),min:0,max:100,unit:"%"})]})}),e.jsx(wi,{title:"Delay",enabled:j,onToggle:_,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ht,{label:"Time",value:T.time*1e3,onChange:R=>se("time",R/1e3),min:1,max:2e3,unit:"ms"}),e.jsx(ht,{label:"Feedback",value:T.feedback*100,onChange:R=>se("feedback",R/100),min:0,max:95,unit:"%"}),e.jsx(ht,{label:"Wet Level",value:T.wetLevel*100,onChange:R=>se("wetLevel",R/100),min:0,max:100,unit:"%"})]})})]})},ki={enabled:!1,sourceTrackId:null,threshold:-30,reduction:.7,attack:.1,release:.3,holdTime:.2},sd=[{id:"subtle",name:"Subtle",settings:{threshold:-35,reduction:.4,attack:.15,release:.5}},{id:"moderate",name:"Moderate",settings:{threshold:-30,reduction:.6,attack:.1,release:.3}},{id:"aggressive",name:"Aggressive",settings:{threshold:-25,reduction:.8,attack:.05,release:.2}},{id:"podcast",name:"Podcast",settings:{threshold:-28,reduction:.75,attack:.08,release:.4,holdTime:.3}}],_1=t=>{if(!t||typeof t!="object")return!1;const s=t;return typeof s.enabled=="boolean"&&(typeof s.sourceTrackId=="string"||s.sourceTrackId===null)&&typeof s.threshold=="number"&&typeof s.reduction=="number"&&typeof s.attack=="number"&&typeof s.release=="number"&&typeof s.holdTime=="number"},V1=(t,s)=>{for(const a of t.timeline.tracks){const r=a.clips.find(n=>n.id===s);if(r)return r}return null},U1=t=>{const s=t.type==="video"?"Video":"Audio";return t.name||`${s} ${t.id.slice(-4)}`},K1=async(t,s,a)=>{const r=a.clips.filter(i=>{const o=i.startTime+i.duration,c=s.startTime+s.duration;return i.id!==s.id&&i.startTimes.startTime});if(r.length===0)throw new Error("No overlapping trigger clips were found for this clip.");const n=new AudioContext;try{const i=new OfflineAudioContext(Math.max(1,t.settings.channels),Math.max(1,Math.ceil(s.duration*t.settings.sampleRate)),t.settings.sampleRate);let o=0;for(const c of r){if(c.reversed)continue;const d=t.mediaLibrary.items.find(m=>m.id===c.mediaId);if(!d?.blob)continue;const u=Math.max(s.startTime,c.startTime),p=Math.min(s.startTime+s.duration,c.startTime+c.duration);if(!(p<=u))try{const m=await d.blob.arrayBuffer(),x=await n.decodeAudioData(m.slice(0)),h=i.createBufferSource(),f=i.createGain(),v=Math.max(.1,c.speed??1),A=u-s.startTime,g=c.inPoint+Math.max(0,u-c.startTime)*v,k=p-u;h.buffer=x,h.playbackRate.value=v,f.gain.value=c.volume,h.connect(f),f.connect(i.destination),h.start(A,g,k*v),o+=1}catch{continue}}if(o===0)throw new Error("No decodable trigger audio was found on the selected source track.");return i.startRendering()}finally{await n.close()}},Y1=({clipId:t})=>{const s=F(w=>w.project),a=F(w=>w.setClipAudioDucking),r=F(w=>w.clearClipAudioDucking),[n,i]=l.useState(ki),[o,c]=l.useState(!1),[d,u]=l.useState(!1),[p,m]=l.useState(null),x=l.useMemo(()=>V1(s,t),[s,t]),h=l.useMemo(()=>x?Md(x,s.timeline):null,[s.timeline,x]),f=l.useMemo(()=>{const w=new Set([t,h?.id].filter(Boolean));return s.timeline.tracks.filter(S=>(S.type==="audio"||S.type==="video")&&!S.clips.every(T=>w.has(T.id)))},[h?.id,t,s.timeline.tracks]),v=l.useMemo(()=>{for(const w of s.timeline.tracks)for(const S of w.clips)if(S.id===(h?.id??t))return w;return null},[h?.id,s.timeline.tracks,t]),A=l.useMemo(()=>{const w=h?.metadata?.audioDucking;return _1(w)?w:null},[h]),g=!!(A?.enabled&&(h?.automation?.volume?.length??0)>0),k=n.enabled||g;l.useEffect(()=>{i(A?{...ki,...A}:ki),m(null)},[t,A]);const N=l.useCallback((w,S)=>{i(T=>({...T,[w]:S})),m(null)},[]),b=l.useCallback(w=>{const S=sd.find(T=>T.id===w);S&&(i(T=>({...T,...S.settings})),m(null))},[]),j=l.useCallback(async()=>{if(!h||!n.sourceTrackId)return;const w=s.timeline.tracks.find(S=>S.id===n.sourceTrackId);if(!w){m("Select a valid trigger source track.");return}u(!0),m(null);try{const S=await K1(s,h,w),C=new rp().generateDuckingKeyframes(S,n,h.volume>0?h.volume:1);if(C.length===0)throw new Error("No speech crossed the trigger threshold. Lower the threshold or choose a louder source track.");const M={...n,enabled:!0};if(!a(h.id,M,C))throw new Error("Failed to persist ducking on this clip.");window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"))}catch(S){m(S instanceof Error?S.message:"Failed to apply ducking.")}finally{u(!1)}},[h,s,a,n]),y=l.useCallback(()=>{if(!r(h?.id??t)){m("Failed to remove ducking from this clip.");return}i(ki),m(null),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"))},[h?.id,r,t]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx($i,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Audio Ducking"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Auto-lower music when speech plays"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${k?"bg-green-400":"bg-gray-500"}`}),e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:k?"Ducking Enabled":"Ducking Disabled"})]}),e.jsx("button",{onClick:()=>N("enabled",!n.enabled),className:`relative w-10 h-5 rounded-full transition-colors ${k?"bg-primary":"bg-background-secondary"}`,children:e.jsx("div",{className:`absolute top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${k?"translate-x-5":"translate-x-0.5"}`})})]}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[10px] font-medium text-text-secondary flex items-center gap-2",children:[e.jsx(Rr,{size:12}),"Trigger Source (Voice Track)"]}),f.length>0?e.jsx("div",{className:"space-y-1",children:f.filter(w=>w.id!==v?.id).map(w=>e.jsxs("button",{onClick:()=>N("sourceTrackId",w.id),className:`w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors ${n.sourceTrackId===w.id?"bg-primary/20 border border-primary":"bg-background-tertiary border border-transparent hover:border-border"}`,children:[e.jsx(Ts,{size:12,className:"text-text-muted"}),e.jsx("span",{className:"flex-1 text-[10px] text-text-primary",children:U1(w)}),n.sourceTrackId===w.id&&e.jsx(is,{size:12,className:"text-primary"})]},w.id))}):e.jsxs("div",{className:"p-3 bg-background-tertiary rounded-lg text-center",children:[e.jsx(Rr,{size:16,className:"mx-auto mb-1 text-text-muted opacity-50"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Add another audio or video track with speech to use as trigger"})]})]}),n.sourceTrackId&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[10px] font-medium text-text-secondary flex items-center gap-2",children:[e.jsx(Ps,{size:12}),"Ducking Presets"]}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:sd.map(w=>e.jsx("button",{onClick:()=>b(w.id),className:"p-2 text-[9px] text-text-secondary bg-background-tertiary rounded-lg hover:bg-primary/10 hover:text-primary transition-colors",children:w.name},w.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Detection Threshold"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[n.threshold," dB"]})]}),e.jsx(st,{min:-50,max:-10,step:1,value:[n.threshold],onValueChange:w=>N("threshold",w[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"Voice level that triggers ducking"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Volume Reduction"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[Math.round(n.reduction*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:5,value:[n.reduction*100],onValueChange:w=>N("reduction",w[0]/100)}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"How much to lower background music"})]})]}),e.jsxs("button",{onClick:()=>c(!o),className:"w-full flex items-center gap-2 py-1.5 text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[o?e.jsx(qt,{size:12}):e.jsx(bs,{size:12}),"Timing Controls"]}),o&&e.jsxs("div",{className:"space-y-3 p-2 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Attack"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[n.attack.toFixed(2),"s"]})]}),e.jsx(st,{min:.01,max:.5,step:.01,value:[n.attack],onValueChange:w=>N("attack",w[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"How fast volume drops when voice starts"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Release"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[n.release.toFixed(2),"s"]})]}),e.jsx(st,{min:.1,max:1,step:.05,value:[n.release],onValueChange:w=>N("release",w[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"How fast volume returns after voice stops"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Hold Time"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[n.holdTime.toFixed(2),"s"]})]}),e.jsx(st,{min:0,max:.5,step:.05,value:[n.holdTime],onValueChange:w=>N("holdTime",w[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"Minimum time to stay ducked between words"})]})]}),g?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-green-500/10 border border-green-500/20 rounded-lg",children:[e.jsx(is,{size:12,className:"text-green-400"}),e.jsx("span",{className:"text-[10px] text-green-400",children:"Ducking Applied"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{onClick:j,disabled:d,className:"flex items-center justify-center gap-1 py-2 bg-background-tertiary rounded-lg text-[10px] text-text-secondary hover:text-text-primary transition-colors disabled:cursor-wait disabled:opacity-60",children:[e.jsx(na,{size:10,className:d?"animate-spin":void 0}),d?"Updating...":"Update"]}),e.jsx("button",{onClick:y,disabled:d,className:"py-2 bg-red-500/10 border border-red-500/20 rounded-lg text-[10px] text-red-400 hover:bg-red-500/20 transition-colors",children:"Remove"})]})]}):e.jsx("button",{onClick:j,disabled:d,className:"w-full py-2.5 bg-primary hover:bg-primary-hover rounded-lg text-[11px] font-medium text-white flex items-center justify-center gap-2 transition-colors disabled:cursor-wait disabled:opacity-60",children:d?e.jsxs(e.Fragment,{children:[e.jsx(na,{size:14,className:"animate-spin"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx($i,{size:14}),"Apply Ducking"]})})]})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-2 py-2 text-[9px] text-red-400",children:[e.jsx(Ba,{size:12}),e.jsx("span",{children:p})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Automatically reduces music volume when voice is detected"})})]})},X1=({clipId:t})=>{const{getClip:s,getMediaItem:a}=F(),[r,n]=l.useState(F1),[i,o]=l.useState(!1),[c,d]=l.useState(!1),[u,p]=l.useState(null),[m,x]=l.useState(0),[h,f]=l.useState(""),v=s(t),A=v?a(v.mediaId):void 0,g=A?.type==="audio"||A?.type==="video",k=l.useCallback(j=>{n(y=>({...y,...j})),p(null)},[]),N=l.useCallback(async()=>{if(t){o(!0),x(0),f("Initializing...");try{const y=await td().analyzeClip(t,r,(w,S)=>{x(w),f(S)});p(y),y.silentRegions.length===0&&Fe.info("No Silence Detected","No silent sections found with current settings. Try lowering the threshold.")}catch(j){console.error("Silence analysis failed:",j),Fe.error("Analysis Failed",j instanceof Error?j.message:"Unknown error")}finally{o(!1)}}},[t,r]),b=l.useCallback(async()=>{if(!(!u||u.silentRegions.length===0)){d(!0),x(0),f("Preparing...");try{const y=await td().cutSilence(t,u.silentRegions,(w,S)=>{x(w),f(S)});y.success?(Fe.success("Silence Removed",`Removed ${u.silentRegions.length} silent section${u.silentRegions.length>1?"s":""}`),p(null)):Fe.error("Cut Failed",y.error??"Unknown error")}catch(j){console.error("Cut silence failed:",j),Fe.error("Cut Failed",j instanceof Error?j.message:"Unknown error")}finally{d(!1)}}},[t,u]);return g?e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("label",{className:"text-[10px] text-text-secondary flex items-center gap-1",children:[e.jsx(Ts,{size:10}),"Silence Threshold"]}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[r.threshold," dB"]})]}),e.jsx(st,{min:-80,max:-20,step:1,value:[r.threshold],onValueChange:j=>k({threshold:j[0]})}),e.jsx("p",{className:"text-[8px] text-text-muted mt-1",children:"Lower values detect more silence"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Min Duration"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[r.minSilenceDuration.toFixed(1),"s"]})]}),e.jsx(st,{min:.1,max:2,step:.1,value:[r.minSilenceDuration],onValueChange:j=>k({minSilenceDuration:j[0]})}),e.jsx("p",{className:"text-[8px] text-text-muted mt-1",children:"Minimum silence length to detect"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Pad Before"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[r.paddingBefore.toFixed(1),"s"]})]}),e.jsx(st,{min:0,max:2,step:.05,value:[r.paddingBefore],onValueChange:j=>k({paddingBefore:j[0]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Pad After"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[r.paddingAfter.toFixed(1),"s"]})]}),e.jsx(st,{min:0,max:2,step:.05,value:[r.paddingAfter],onValueChange:j=>k({paddingAfter:j[0]})})]})]}),u&&e.jsxs("div",{className:"p-2 bg-background-secondary rounded border border-primary/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Silent Sections Found"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:u.silentRegions.length})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Total Silence"}),e.jsxs("span",{className:"text-[10px] text-text-primary",children:[u.totalSilenceDuration.toFixed(1),"s of"," ",u.clipDuration.toFixed(1),"s (",Math.round(u.totalSilenceDuration/u.clipDuration*100),"%)"]})]})]}),(i||c)&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:h}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[m,"%"]})]}),e.jsx("div",{className:"h-1 bg-background-secondary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${m}%`}})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:N,disabled:i||c,className:`flex-1 py-2 rounded text-[11px] font-medium transition-colors flex items-center justify-center gap-2 ${u?"bg-background-secondary hover:bg-background-primary border border-border text-text-primary":"bg-primary hover:bg-primary-hover disabled:bg-primary/50 text-white"}`,children:i?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(la,{size:14}),u?"Re-analyze":"Analyze"]})}),u&&u.silentRegions.length>0&&e.jsx("button",{onClick:b,disabled:c,className:"flex-1 py-2 bg-primary hover:bg-primary-hover disabled:bg-primary/50 text-white rounded text-[11px] font-medium transition-colors flex items-center justify-center gap-2",children:c?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"}),"Cutting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(xl,{size:14}),"Cut ",u.silentRegions.length]})})]}),e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Tip: Use Ctrl+Z to undo all cuts at once"})]})}):null},Ni=ht,$o=({value:t,onChange:s,options:a=["left","right","up","down"]})=>{const r={left:e.jsx(Yi,{size:14}),right:e.jsx(Pr,{size:14}),up:e.jsx(Yd,{size:14}),down:e.jsx(Kd,{size:14})};return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Direction"}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:a.map(n=>e.jsx("button",{onClick:()=>s(n),className:`p-2 rounded-lg border transition-colors flex items-center justify-center ${t===n?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:text-text-primary"}`,title:n.charAt(0).toUpperCase()+n.slice(1),children:r[n]||n},n))})]})},G1=({label:t,value:s,onChange:a})=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:t}),e.jsx(oa,{checked:s,onCheckedChange:a})]}),H1=({type:t,isPlaying:s})=>{const[a,r]=_e.useState(0);_e.useEffect(()=>{if(!s){r(0);return}const c=1e3,d=Date.now();let u;const p=()=>{const m=Date.now()-d,x=Math.min(m/c,1);r(x),x<1?u=requestAnimationFrame(p):setTimeout(()=>r(0),200)};return u=requestAnimationFrame(p),()=>cancelAnimationFrame(u)},[s]);const i=(()=>{const c=a;switch(t){case"crossfade":return{clipA:{opacity:1-c},clipB:{opacity:c}};case"wipe":return{clipA:{clipPath:`inset(0 ${c*100}% 0 0)`},clipB:{clipPath:`inset(0 0 0 ${(1-c)*100}%)`}};case"slide":return{clipA:{transform:`translateX(${-c*100}%)`},clipB:{transform:`translateX(${(1-c)*100}%)`}};case"push":return{clipA:{transform:`translateX(${-c*100}%)`},clipB:{transform:`translateX(${(1-c)*100}%)`}};case"zoom":return{clipA:{transform:`scale(${1+c*2})`,opacity:1-c},clipB:{transform:`scale(${2-c})`,opacity:c}};case"dipToBlack":return{clipA:{opacity:c<.5?1-c*2:0},clipB:{opacity:c>.5?(c-.5)*2:0}};case"dipToWhite":return{clipA:{opacity:c<.5?1-c*2:0},clipB:{opacity:c>.5?(c-.5)*2:0}};default:return{clipA:{},clipB:{}}}})(),o=t==="dipToWhite"?"bg-white":"bg-black";return e.jsxs("div",{className:"relative w-full h-8 rounded overflow-hidden bg-background-secondary mb-2",children:[e.jsx("div",{className:"absolute inset-0 bg-primary/20",style:{...i.clipA,transition:"none"}}),e.jsx("div",{className:"absolute inset-0 bg-green-500/30",style:{...i.clipB,transition:"none"}}),(t==="dipToBlack"||t==="dipToWhite")&&e.jsx("div",{className:`absolute inset-0 ${o}`,style:{opacity:a<.5?a*2:(1-a)*2,transition:"none"}})]})},W1=({typeInfo:t,isSelected:s,onSelect:a})=>{const[r,n]=_e.useState(!1);return e.jsxs("button",{onClick:a,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),className:`p-3 rounded-lg border transition-all text-left ${s?"bg-primary/20 border-primary":"bg-background-tertiary border-border hover:border-text-secondary"}`,children:[e.jsx(H1,{type:t.type,isPlaying:r||s}),e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:`text-[10px] font-medium ${s?"text-primary":"text-text-primary"}`,children:t.name}),s&&e.jsx(is,{size:12,className:"text-primary"})]}),e.jsx("p",{className:"text-[9px] text-text-muted",children:t.description})]})},q1=({clipA:t,clipB:s,transition:a,onTransitionCreate:r,onTransitionUpdate:n,onTransitionRemove:i})=>{const o=Bn(),c=l.useMemo(()=>o.getAvailableTransitionTypes(),[]),[d,u]=l.useState(a?.type||"crossfade"),[p,m]=l.useState(a?.duration||1),[x,h]=l.useState(a?.params||o.getDefaultParams(d));l.useEffect(()=>{const y=a?.type||"crossfade";u(y),m(a?.duration||1),h(a?.params||o.getDefaultParams(y))},[o,t.id,s.id,a]);const f=l.useMemo(()=>(o.isInitialized()||o.initialize(),o.validateTransition(t,s,p)),[t,s,p]),v=l.useCallback(y=>{u(y);const w=o.getDefaultParams(y);h(w),a&&n?.(a.id,{type:y,params:w})},[a,n]),A=l.useCallback(y=>{const w=f.maxDuration?Math.min(y,f.maxDuration):y;m(w),a&&n?.(a.id,{duration:w})},[a,f.maxDuration,n]),g=l.useCallback((y,w)=>{const S={...x,[y]:w};h(S),a&&n?.(a.id,{params:S})},[x,a,n]),k=l.useCallback(()=>{const y=o.createTransition(t,s,d,p,x);if(y.success&&y.transitionId){const w=o.getTransition(y.transitionId);w&&(r?.(w),Fe.success("Transition Applied",`${d} transition added (${p}s)`))}else Fe.error("Transition Failed",y.error||"Could not apply transition")},[t,s,d,p,x,r]),N=l.useCallback(()=>{a&&(o.removeTransition(a.id),i?.(a.id),Fe.success("Transition Removed"))},[a,i]),b=()=>{switch(d){case"wipe":return e.jsxs(e.Fragment,{children:[e.jsx($o,{value:x.direction||"left",onChange:y=>g("direction",y),options:["left","right","up","down"]}),e.jsx(Ni,{label:"Softness",value:(x.softness||0)*100,onChange:y=>g("softness",y/100),min:0,max:100,unit:"%"})]});case"slide":return e.jsxs(e.Fragment,{children:[e.jsx($o,{value:x.direction||"left",onChange:y=>g("direction",y)}),e.jsx(G1,{label:"Push Out",value:x.pushOut||!1,onChange:y=>g("pushOut",y)})]});case"push":return e.jsx($o,{value:x.direction||"left",onChange:y=>g("direction",y)});case"zoom":return e.jsx(Ni,{label:"Scale",value:x.scale||2,onChange:y=>g("scale",y),min:1.1,max:4,step:.1,unit:"x"});case"dipToBlack":case"dipToWhite":return e.jsx(Ni,{label:"Hold Duration",value:x.holdDuration||.1,onChange:y=>g("holdDuration",y),min:0,max:1,step:.05,unit:"s"});case"crossfade":default:return null}},j=c.find(y=>y.type===d);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg border border-border",children:[e.jsxs("div",{className:"flex-1 text-center",children:[e.jsx("p",{className:"text-[9px] text-text-muted",children:"From"}),e.jsxs("p",{className:"text-[10px] text-text-primary truncate",children:[t.id.substring(0,12),"..."]})]}),e.jsx(Pr,{size:14,className:"text-text-muted"}),e.jsxs("div",{className:"flex-1 text-center",children:[e.jsx("p",{className:"text-[9px] text-text-muted",children:"To"}),e.jsxs("p",{className:"text-[10px] text-text-primary truncate",children:[s.id.substring(0,12),"..."]})]})]}),f.warning&&e.jsx("div",{className:"p-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:e.jsx("p",{className:"text-[10px] text-yellow-500",children:f.warning})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Transition Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:c.map(y=>e.jsx(W1,{typeInfo:y,isSelected:d===y.type,onSelect:()=>v(y.type)},y.type))})]}),e.jsx(Ni,{label:"Duration",value:p,onChange:A,min:.1,max:f.maxDuration||5,step:.1,unit:"s"}),j?.hasCustomParams&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Parameters"}),b()]}),e.jsx("div",{className:"flex gap-2 pt-2",children:a?e.jsxs("button",{onClick:N,className:"flex-1 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-[10px] text-red-400 hover:bg-red-500/20 transition-colors flex items-center justify-center gap-1",children:[e.jsx(Ls,{size:12}),"Remove Transition"]}):e.jsxs("button",{onClick:k,disabled:!f.valid,className:`flex-1 py-2 rounded-lg text-[10px] transition-colors flex items-center justify-center gap-1 ${f.valid?"bg-primary/10 border border-primary/30 text-primary hover:bg-primary/20":"bg-background-tertiary border border-border text-text-muted cursor-not-allowed"}`,children:[e.jsx(is,{size:12}),"Apply Transition"]})}),!f.valid&&f.error&&e.jsx("p",{className:"text-[10px] text-red-400 text-center",children:f.error})]})},ad=[{id:"none",label:"None",icon:null},{id:"fade",label:"Fade",icon:e.jsx($s,{size:12})},{id:"slide-left",label:"Slide Left",icon:e.jsx(Yi,{size:12})},{id:"slide-right",label:"Slide Right",icon:e.jsx(Pr,{size:12})},{id:"slide-up",label:"Slide Up",icon:e.jsx(Yd,{size:12})},{id:"slide-down",label:"Slide Down",icon:e.jsx(Kd,{size:12})},{id:"zoom-in",label:"Zoom In",icon:e.jsx(ou,{size:12})},{id:"zoom-out",label:"Zoom Out",icon:e.jsx(Ef,{size:12})},{id:"rotate",label:"Rotate",icon:e.jsx(Fh,{size:12})},{id:"blur",label:"Blur",icon:e.jsx(Gd,{size:12})},{id:"iris-circle",label:"Iris Circle",icon:e.jsx(or,{size:12})},{id:"iris-rectangle",label:"Iris Rect",icon:e.jsx(Gs,{size:12})},{id:"iris-diamond",label:"Iris Diamond",icon:e.jsx(Gi,{size:12})},{id:"iris-star",label:"Iris Star",icon:e.jsx(Ys,{size:12})}],rd=[{id:"linear",label:"Linear"},{id:"ease-in",label:"Ease In"},{id:"ease-out",label:"Ease Out"},{id:"ease-in-out",label:"Ease In Out"}];function Q1(t,s){const a=t.position.x,r=t.position.y,n=.1;return{left:a+.5+n,right:1-a+.5+n,up:r+.5+n,down:1-r+.5+n}}function J1(t,s,a,r,n){const i=[],o=t.transform,c=t.duration,d=s.duration,u=c-a.duration,p=Q1(o);if(s.preset!=="none")switch(s.preset){case"fade":i.push({id:"kf-entry-opacity-0",time:0,property:"opacity",value:0,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break;case"slide-left":i.push({id:"kf-entry-pos-0",time:0,property:"position.x",value:o.position.x-p.left,easing:s.easing},{id:"kf-entry-pos-1",time:d,property:"position.x",value:o.position.x,easing:s.easing});break;case"slide-right":i.push({id:"kf-entry-pos-0",time:0,property:"position.x",value:o.position.x+p.right,easing:s.easing},{id:"kf-entry-pos-1",time:d,property:"position.x",value:o.position.x,easing:s.easing});break;case"slide-up":i.push({id:"kf-entry-pos-0",time:0,property:"position.y",value:o.position.y-p.up,easing:s.easing},{id:"kf-entry-pos-1",time:d,property:"position.y",value:o.position.y,easing:s.easing});break;case"slide-down":i.push({id:"kf-entry-pos-0",time:0,property:"position.y",value:o.position.y+p.down,easing:s.easing},{id:"kf-entry-pos-1",time:d,property:"position.y",value:o.position.y,easing:s.easing});break;case"zoom-in":i.push({id:"kf-entry-scale-0",time:0,property:"scale.x",value:.3,easing:s.easing},{id:"kf-entry-scale-1",time:0,property:"scale.y",value:.3,easing:s.easing},{id:"kf-entry-scale-2",time:d,property:"scale.x",value:o.scale.x,easing:s.easing},{id:"kf-entry-scale-3",time:d,property:"scale.y",value:o.scale.y,easing:s.easing},{id:"kf-entry-opacity-0",time:0,property:"opacity",value:0,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break;case"zoom-out":i.push({id:"kf-entry-scale-0",time:0,property:"scale.x",value:1.8,easing:s.easing},{id:"kf-entry-scale-1",time:0,property:"scale.y",value:1.8,easing:s.easing},{id:"kf-entry-scale-2",time:d,property:"scale.x",value:o.scale.x,easing:s.easing},{id:"kf-entry-scale-3",time:d,property:"scale.y",value:o.scale.y,easing:s.easing},{id:"kf-entry-opacity-0",time:0,property:"opacity",value:0,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break;case"rotate":i.push({id:"kf-entry-rot-0",time:0,property:"rotation",value:o.rotation-90,easing:s.easing},{id:"kf-entry-rot-1",time:d,property:"rotation",value:o.rotation,easing:s.easing},{id:"kf-entry-scale-0",time:0,property:"scale.x",value:.5,easing:s.easing},{id:"kf-entry-scale-1",time:0,property:"scale.y",value:.5,easing:s.easing},{id:"kf-entry-scale-2",time:d,property:"scale.x",value:o.scale.x,easing:s.easing},{id:"kf-entry-scale-3",time:d,property:"scale.y",value:o.scale.y,easing:s.easing},{id:"kf-entry-opacity-0",time:0,property:"opacity",value:0,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break;case"blur":i.push({id:"kf-entry-blur-0",time:0,property:"blur",value:30,easing:s.easing},{id:"kf-entry-blur-1",time:d,property:"blur",value:0,easing:s.easing},{id:"kf-entry-opacity-0",time:0,property:"opacity",value:0,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break;case"iris-circle":case"iris-rectangle":case"iris-diamond":case"iris-star":i.push({id:"kf-entry-scale-0",time:0,property:"scale.x",value:0,easing:s.easing},{id:"kf-entry-scale-1",time:0,property:"scale.y",value:0,easing:s.easing},{id:"kf-entry-scale-2",time:d,property:"scale.x",value:o.scale.x,easing:s.easing},{id:"kf-entry-scale-3",time:d,property:"scale.y",value:o.scale.y,easing:s.easing},{id:"kf-entry-opacity-0",time:0,property:"opacity",value:.5,easing:s.easing},{id:"kf-entry-opacity-1",time:d,property:"opacity",value:o.opacity,easing:s.easing});break}if(a.preset!=="none")switch(a.preset){case"fade":i.push({id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:0,easing:a.easing});break;case"slide-left":i.push({id:"kf-exit-pos-0",time:u,property:"position.x",value:o.position.x,easing:a.easing},{id:"kf-exit-pos-1",time:c,property:"position.x",value:o.position.x-p.left,easing:a.easing});break;case"slide-right":i.push({id:"kf-exit-pos-0",time:u,property:"position.x",value:o.position.x,easing:a.easing},{id:"kf-exit-pos-1",time:c,property:"position.x",value:o.position.x+p.right,easing:a.easing});break;case"slide-up":i.push({id:"kf-exit-pos-0",time:u,property:"position.y",value:o.position.y,easing:a.easing},{id:"kf-exit-pos-1",time:c,property:"position.y",value:o.position.y-p.up,easing:a.easing});break;case"slide-down":i.push({id:"kf-exit-pos-0",time:u,property:"position.y",value:o.position.y,easing:a.easing},{id:"kf-exit-pos-1",time:c,property:"position.y",value:o.position.y+p.down,easing:a.easing});break;case"zoom-in":i.push({id:"kf-exit-scale-0",time:u,property:"scale.x",value:o.scale.x,easing:a.easing},{id:"kf-exit-scale-1",time:u,property:"scale.y",value:o.scale.y,easing:a.easing},{id:"kf-exit-scale-2",time:c,property:"scale.x",value:1.8,easing:a.easing},{id:"kf-exit-scale-3",time:c,property:"scale.y",value:1.8,easing:a.easing},{id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:0,easing:a.easing});break;case"zoom-out":i.push({id:"kf-exit-scale-0",time:u,property:"scale.x",value:o.scale.x,easing:a.easing},{id:"kf-exit-scale-1",time:u,property:"scale.y",value:o.scale.y,easing:a.easing},{id:"kf-exit-scale-2",time:c,property:"scale.x",value:.3,easing:a.easing},{id:"kf-exit-scale-3",time:c,property:"scale.y",value:.3,easing:a.easing},{id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:0,easing:a.easing});break;case"rotate":i.push({id:"kf-exit-rot-0",time:u,property:"rotation",value:o.rotation,easing:a.easing},{id:"kf-exit-rot-1",time:c,property:"rotation",value:o.rotation+90,easing:a.easing},{id:"kf-exit-scale-0",time:u,property:"scale.x",value:o.scale.x,easing:a.easing},{id:"kf-exit-scale-1",time:u,property:"scale.y",value:o.scale.y,easing:a.easing},{id:"kf-exit-scale-2",time:c,property:"scale.x",value:.5,easing:a.easing},{id:"kf-exit-scale-3",time:c,property:"scale.y",value:.5,easing:a.easing},{id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:0,easing:a.easing});break;case"blur":i.push({id:"kf-exit-blur-0",time:u,property:"blur",value:0,easing:a.easing},{id:"kf-exit-blur-1",time:c,property:"blur",value:30,easing:a.easing},{id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:0,easing:a.easing});break;case"iris-circle":case"iris-rectangle":case"iris-diamond":case"iris-star":i.push({id:"kf-exit-scale-0",time:u,property:"scale.x",value:o.scale.x,easing:a.easing},{id:"kf-exit-scale-1",time:u,property:"scale.y",value:o.scale.y,easing:a.easing},{id:"kf-exit-scale-2",time:c,property:"scale.x",value:0,easing:a.easing},{id:"kf-exit-scale-3",time:c,property:"scale.y",value:0,easing:a.easing},{id:"kf-exit-opacity-0",time:u,property:"opacity",value:o.opacity,easing:a.easing},{id:"kf-exit-opacity-1",time:c,property:"opacity",value:.5,easing:a.easing});break}return i}function Z1(t){const s={preset:"none",duration:.5,easing:"ease-out"},a={preset:"none",duration:.5,easing:"ease-in"},r=t.keyframes||[],n=r.filter(o=>o.id.startsWith("kf-entry-")),i=r.filter(o=>o.id.startsWith("kf-exit-"));if(n.length>0){const o=n.find(f=>f.property==="opacity"),c=n.find(f=>f.property==="position.x"),d=n.find(f=>f.property==="position.y"),u=n.find(f=>f.property==="scale.x"),p=n.find(f=>f.property==="rotation");n.find(f=>f.property==="blur")?s.preset="blur":p?s.preset="rotate":u&&Number(u.value)===0?s.preset="iris-circle":u&&Number(u.value)<1?s.preset="zoom-in":u&&Number(u.value)>1?s.preset="zoom-out":c&&Number(c.value)t.transform.position.x?s.preset="slide-right":d&&Number(d.value)t.transform.position.y?s.preset="slide-down":o&&(s.preset="fade");const x=Math.max(...n.map(f=>f.time));x>0&&(s.duration=x);const h=n[0];h&&(s.easing=h.easing)}if(i.length>0){const o=i.find(f=>f.property==="opacity"&&f.time===t.duration),c=i.find(f=>f.property==="position.x"&&f.time===t.duration),d=i.find(f=>f.property==="position.y"&&f.time===t.duration),u=i.find(f=>f.property==="scale.x"&&f.time===t.duration),p=i.find(f=>f.property==="rotation"&&f.time===t.duration);i.find(f=>f.property==="blur"&&f.time===t.duration)?a.preset="blur":p?a.preset="rotate":u&&Number(u.value)===0?a.preset="iris-circle":u&&Number(u.value)>1?a.preset="zoom-in":u&&Number(u.value)<1?a.preset="zoom-out":c&&Number(c.value)t.transform.position.x?a.preset="slide-right":d&&Number(d.value)t.transform.position.y?a.preset="slide-down":o&&(a.preset="fade");const x=Math.min(...i.filter(f=>f.id.includes("-0")).map(f=>f.time));x{const{project:s,updateClipKeyframes:a,updateTextClipKeyframes:r,getTextClip:n,getShapeClip:i,getSVGClip:o,getStickerClip:c,addClipTransition:d,updateClipTransition:u,removeClipTransition:p}=F(),m=Ct(P=>P.getTitleEngine),x=Ct(P=>P.getGraphicsEngine),{settings:h}=s,f=l.useMemo(()=>{for(const P of s.timeline.tracks){const _=[...P.clips].sort((X,K)=>X.startTime!==K.startTime?X.startTime-K.startTime:X.id.localeCompare(K.id)),se=_.findIndex(X=>X.id===t);if(se===-1)continue;const R=_[se],U=se>0?_[se-1]:void 0,D=se<_.length-1?_[se+1]:void 0;return{currentClip:R,previousClip:U,nextClip:D,incomingTransition:U?P.transitions.find(X=>X.clipAId===U.id&&X.clipBId===R.id):void 0,outgoingTransition:D?P.transitions.find(X=>X.clipAId===R.id&&X.clipBId===D.id):void 0}}return null},[s.timeline.tracks,t]),v=l.useMemo(()=>{const P=f?.currentClip;if(P)return{type:"regular",data:P};const _=n(t);if(_)return{type:"text",data:_};const se=i(t);if(se)return{type:"shape",data:se};const R=o(t);if(R)return{type:"svg",data:R};const U=c(t);return U?{type:"sticker",data:U}:null},[f,t,n,i,o,c,m,s.modifiedAt]),A=l.useMemo(()=>{if(!f)return[];const P=[];return f.previousClip&&P.push({key:"incoming",title:"Incoming Transition",description:"From the previous clip into this clip",clipA:f.previousClip,clipB:f.currentClip,transition:f.incomingTransition}),f.nextClip&&P.push({key:"outgoing",title:"Outgoing Transition",description:"From this clip into the next clip",clipA:f.currentClip,clipB:f.nextClip,transition:f.outgoingTransition}),P},[f]),g=l.useCallback(P=>{d(P)},[d]),k=l.useCallback((P,_)=>{u(P,_)},[u]),N=l.useCallback(P=>{p(P)},[p]),b=v?Z1(v.data):{entry:{preset:"none",duration:.5,easing:"ease-out"},exit:{preset:"none",duration:.5,easing:"ease-in"}},[j,y]=l.useState(b.entry.preset),[w,S]=l.useState(b.entry.duration),[T,C]=l.useState(b.entry.easing),[M,z]=l.useState(b.exit.preset),[L,B]=l.useState(b.exit.duration),[O,G]=l.useState(b.exit.easing),V=l.useCallback(()=>{if(!v)return;const P=(v.data.keyframes||[]).filter(U=>!U.id.startsWith("kf-entry-")&&!U.id.startsWith("kf-exit-"));h.width,h.height,(v.type==="regular"||v.type==="text")&&v.type;const _=J1(v.data,{preset:j,duration:w,easing:T},{preset:M,duration:L,easing:O}),se=[...P,..._];if(v.type==="text")r(t,se);else if(v.type==="shape"||v.type==="svg"||v.type==="sticker"){const U=x();if(U){const D=v.type==="shape"?U.getShapeClip(t):v.type==="svg"?U.getSVGClip(t):U.getStickerClip(t);D&&(D.keyframes=se,F.setState(X=>({project:{...X.project,modifiedAt:Date.now()}})))}}else a(t,se);const R=[];j!=="none"&&R.push(`Entry: ${j}`),M!=="none"&&R.push(`Exit: ${M}`),R.length>0?Fe.success("Clip Animation Applied",R.join(", ")):Fe.info("Animations Cleared")},[v,t,j,w,T,M,L,O,a,r,h]);return v?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary uppercase tracking-wider",children:"Entry Animation"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:ad.map(P=>e.jsxs("button",{onClick:()=>y(P.id),className:`flex items-center justify-center gap-1 py-1.5 px-2 rounded text-[9px] transition-all ${j===P.id?"bg-primary text-white font-medium":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary hover:border-text-muted"}`,children:[P.icon,e.jsx("span",{children:P.label})]},`entry-${P.id}`))}),j!=="none"&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Duration"}),e.jsx("input",{type:"number",step:"0.1",min:"0.1",max:v.data.duration/2,value:w,onChange:P=>S(parseFloat(P.target.value)||.5),className:"w-full px-2 py-1 text-[10px] bg-background-tertiary border border-border rounded"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Easing"}),e.jsxs(ot,{value:T,onValueChange:P=>C(P),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary text-[10px] h-7",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:rd.map(P=>e.jsx(ge,{value:P.id,children:P.label},P.id))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary uppercase tracking-wider",children:"Exit Animation"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:ad.map(P=>e.jsxs("button",{onClick:()=>z(P.id),className:`flex items-center justify-center gap-1 py-1.5 px-2 rounded text-[9px] transition-all ${M===P.id?"bg-primary text-white font-medium":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary hover:border-text-muted"}`,children:[P.icon,e.jsx("span",{children:P.label})]},`exit-${P.id}`))}),M!=="none"&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Duration"}),e.jsx("input",{type:"number",step:"0.1",min:"0.1",max:v.data.duration/2,value:L,onChange:P=>B(parseFloat(P.target.value)||.5),className:"w-full px-2 py-1 text-[10px] bg-background-tertiary border border-border rounded"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Easing"}),e.jsxs(ot,{value:O,onValueChange:P=>G(P),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary text-[10px] h-7",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:rd.map(P=>e.jsx(ge,{value:P.id,children:P.label},P.id))})]})]})]})]}),e.jsx("button",{onClick:V,className:"w-full py-2 bg-primary hover:bg-primary-hover text-white font-medium rounded-lg text-[11px] transition-all",children:"Apply Entry/Exit Animations"}),e.jsxs("div",{className:"space-y-3 border-t border-border pt-3",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary uppercase tracking-wider",children:"Clip-to-Clip Transitions"}),f?A.length>0?A.map(P=>e.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background-secondary p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-medium text-text-primary",children:P.title}),e.jsx("p",{className:"text-[9px] text-text-muted",children:P.description})]}),e.jsx(q1,{clipA:P.clipA,clipB:P.clipB,transition:P.transition,onTransitionCreate:g,onTransitionUpdate:k,onTransitionRemove:N})]},P.key)):e.jsx("p",{className:"text-[10px] text-text-muted",children:"No adjacent clips are available on this track."}):e.jsx("p",{className:"text-[10px] text-text-muted",children:"Clip-to-clip transitions are available for timeline media clips."})]})]}):null},Wr=new np,Pi=[{id:"position.x",label:"Position X",category:"Transform",defaultValue:0,min:-2e3,max:2e3},{id:"position.y",label:"Position Y",category:"Transform",defaultValue:0,min:-2e3,max:2e3},{id:"scale.x",label:"Scale X",category:"Transform",defaultValue:1,min:0,max:10,step:.01},{id:"scale.y",label:"Scale Y",category:"Transform",defaultValue:1,min:0,max:10,step:.01},{id:"rotation",label:"Rotation",category:"Transform",defaultValue:0,min:-360,max:360},{id:"opacity",label:"Opacity",category:"Transform",defaultValue:1,min:0,max:1,step:.01},{id:"effect.brightness",label:"Brightness",category:"Effects",defaultValue:0,min:-100,max:100},{id:"effect.contrast",label:"Contrast",category:"Effects",defaultValue:1,min:0,max:2,step:.01},{id:"effect.saturation",label:"Saturation",category:"Effects",defaultValue:1,min:0,max:2,step:.01},{id:"effect.blur",label:"Blur",category:"Effects",defaultValue:0,min:0,max:100},{id:"volume",label:"Volume",category:"Audio",defaultValue:1,min:0,max:2,step:.01},{id:"pan",label:"Pan",category:"Audio",defaultValue:0,min:-1,max:1,step:.01}],nd=t=>t.replace(/([A-Z])/g," $1").replace(/^ease/,"").trim()||t,tv=({selectedProperty:t,onSelect:s,existingProperties:a})=>{const[r,n]=l.useState(!1),i=[...new Set(Pi.map(c=>c.category))],o=t?Pi.find(c=>c.id===t)?.label||t:"Select Property";return e.jsxs(Fn,{open:r,onOpenChange:n,children:[e.jsx(Ln,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between px-3 py-2 bg-background-tertiary border border-border rounded-lg text-[10px] text-text-primary hover:border-text-secondary transition-colors",children:[e.jsx("span",{children:o}),e.jsx(qt,{size:12,className:`transition-transform ${r?"rotate-180":""}`})]})}),e.jsx($n,{align:"start",sideOffset:4,className:"w-[var(--radix-popover-trigger-width)] min-w-[200px] p-0 bg-background-secondary border-border max-h-64 overflow-y-auto",children:i.map(c=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-medium text-text-muted uppercase tracking-wider bg-background-tertiary",children:c}),Pi.filter(d=>d.category===c).map(d=>{const u=a.includes(d.id);return e.jsxs("button",{type:"button",onClick:()=>{s(d.id),n(!1)},className:`w-full px-3 py-2 text-left text-[10px] flex items-center justify-between hover:bg-background-tertiary transition-colors ${t===d.id?"bg-primary/10 text-primary":"text-text-primary"}`,children:[e.jsx("span",{children:d.label}),u&&e.jsx(Gi,{size:10,className:"text-primary fill-primary"})]},d.id)})]},c))})]})},id=({easing:t,size:s=16})=>{const a=r=>{const n={linear:"M0,16 L16,0",easeIn:"M0,16 Q8,16 16,0",easeOut:"M0,16 Q8,0 16,0",easeInOut:"M0,16 Q4,16 8,8 Q12,0 16,0",easeInQuad:"M0,16 C0,16 12,16 16,0",easeOutQuad:"M0,16 C4,0 16,0 16,0",easeInOutQuad:"M0,16 C0,16 6,16 8,8 C10,0 16,0 16,0",easeInCubic:"M0,16 C0,16 14,16 16,0",easeOutCubic:"M0,16 C2,0 16,0 16,0",easeInOutCubic:"M0,16 C0,16 5,16 8,8 C11,0 16,0 16,0",easeInElastic:"M0,16 Q2,18 4,16 Q6,14 8,16 Q12,8 16,0",easeOutElastic:"M0,16 Q4,8 8,0 Q10,2 12,0 Q14,-2 16,0",easeInBounce:"M0,16 L4,16 L6,14 L8,16 L12,8 L16,0",easeOutBounce:"M0,16 L4,8 L8,0 L10,2 L12,0 L14,2 L16,0"};return n[r]||n.linear};return e.jsx("svg",{width:s,height:s,viewBox:"0 0 16 16",className:"text-primary",children:e.jsx("path",{d:a(t),fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})},sv=({value:t,onChange:s})=>{const[a,r]=l.useState(!1),n=nd(t);return e.jsxs(Fn,{open:a,onOpenChange:r,children:[e.jsx(Ln,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 px-2 py-1 bg-background-tertiary border border-border rounded text-[9px] text-text-secondary hover:text-text-primary hover:border-primary/50 transition-colors",title:`Easing: ${n}`,children:[e.jsx(id,{easing:t,size:14}),e.jsx("span",{children:n}),e.jsx(qt,{size:10})]})}),e.jsx($n,{align:"end",sideOffset:4,className:"min-w-[180px] w-auto p-0 bg-background-secondary border-border max-h-64 overflow-y-auto",children:ip.map(i=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 py-1 text-[8px] font-medium text-text-muted uppercase tracking-wider bg-background-tertiary sticky top-0",children:i.name}),i.easings.map(o=>e.jsxs("button",{type:"button",onClick:()=>{s(o),r(!1)},className:`w-full px-3 py-1.5 text-left text-[10px] hover:bg-background-tertiary transition-colors flex items-center gap-2 ${t===o?"text-primary":"text-text-primary"}`,children:[e.jsx(id,{easing:o,size:14}),nd(o)]},o))]},i.name))})]})},av=({keyframe:t,onUpdate:s,onDelete:a,onEasingChange:r,property:n})=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg border border-border",children:[e.jsx(Gi,{size:12,className:"text-primary fill-primary flex-shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-text-secondary",children:[t.time.toFixed(2),"s"]}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"•"}),e.jsx("input",{type:"number",value:typeof t.value=="number"?t.value:0,onChange:i=>s({value:parseFloat(i.target.value)||0}),min:n?.min,max:n?.max,step:n?.step||1,className:"w-16 text-[10px] font-mono text-text-primary bg-background-secondary px-1.5 py-0.5 rounded border border-border outline-none focus:border-primary"})]})}),e.jsx(sv,{value:t.easing,onChange:r}),e.jsx("button",{onClick:a,className:"p-1 hover:bg-red-500/20 rounded transition-colors text-text-muted hover:text-red-400",title:"Delete keyframe",children:e.jsx($t,{size:12})})]}),rv=({clipId:t})=>{const{getClip:s,updateClipKeyframes:a,project:r}=F(),n=Et(b=>b.playheadPosition),i=Ct(b=>b.getGraphicsEngine),o=Ct(b=>b.getTitleEngine),[c,d]=l.useState(null),u=l.useMemo(()=>{const b=s(t);if(b)return b;const j=i(),y=j?.getSVGClip(t);if(y)return y;const w=j?.getShapeClip(t);if(w)return w;const S=j?.getStickerClip(t);if(S)return S;const C=o()?.getTextClip(t);if(C)return C},[t,s,i,o,r.modifiedAt]),p=u?.keyframes||[],m=l.useMemo(()=>[...new Set(p.map(b=>b.property))],[p]),x=l.useMemo(()=>c?Wr.getKeyframesForProperty(p,c):[],[p,c]),h=l.useMemo(()=>Pi.find(b=>b.id===c),[c]),f=l.useMemo(()=>!c||x.length===0?h?.defaultValue??0:Wr.getValueAtTime(x,n).value,[c,x,n,h]),v=l.useMemo(()=>c?x.some(b=>Math.abs(b.time-n)<.01):!1,[c,x,n]),A=l.useCallback(()=>{if(!c||!u)return;const b=Wr.addKeyframe(t,c,n,f,"linear"),j=[...p,b].sort((y,w)=>y.time-w.time);a(t,j)},[t,u,c,n,f,p,a]),g=l.useCallback((b,j)=>{const y=Wr.updateKeyframe(p,b,j);a(t,y)},[t,p,a]),k=l.useCallback(b=>{const j=Wr.removeKeyframe(p,b);a(t,j)},[t,p,a]),N=l.useCallback((b,j)=>{const y=Wr.updateKeyframe(p,b,{easing:j});a(t,y)},[t,p,a]);return u?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] text-text-secondary font-medium",children:"Animate Property"}),e.jsx(tv,{selectedProperty:c,onSelect:d,existingProperties:m})]}),c&&e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background-tertiary rounded-lg border border-border",children:[e.jsxs("span",{className:"text-[10px] text-text-secondary",children:["Value at ",n.toFixed(2),"s"]}),e.jsx("span",{className:"text-[10px] font-mono text-text-primary",children:typeof f=="number"?f.toFixed(2):String(f)})]}),c&&e.jsx("button",{onClick:A,disabled:v,className:`w-full py-2 rounded-lg text-[10px] flex items-center justify-center gap-2 transition-colors ${v?"bg-background-tertiary border border-border text-text-muted cursor-not-allowed":"bg-primary/10 border border-primary/30 text-primary hover:bg-primary/20"}`,children:v?e.jsxs(e.Fragment,{children:[e.jsx(zn,{size:12}),"Keyframe exists at ",n.toFixed(2),"s"]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{size:12}),"Add Keyframe at ",n.toFixed(2),"s"]})}),c&&x.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("span",{className:"text-[10px] text-text-secondary font-medium",children:["Keyframes (",x.length,")"]})}),e.jsx("div",{className:"space-y-1.5 max-h-48 overflow-y-auto",children:x.map(b=>e.jsx(av,{keyframe:b,property:h,onUpdate:j=>g(b.id,j),onDelete:()=>k(b.id),onEasingChange:j=>N(b.id,j)},b.id))})]}),!c&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx(zn,{size:24,className:"mx-auto text-text-muted mb-2"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Select a property to animate"})]}),c&&x.length===0&&e.jsx("p",{className:"text-[10px] text-text-muted text-center py-2",children:"No keyframes for this property. Add one to start animating."})]}):e.jsx("div",{className:"text-[10px] text-text-muted text-center py-4",children:"No clip selected"})},nv=({clipId:t})=>{const{getClip:s,getTextClip:a,getShapeClip:r,getSVGClip:n,getStickerClip:i,updateClipBlendMode:o,updateClipBlendOpacity:c,project:d}=F(),u=l.useMemo(()=>{const v=s(t);if(v)return v;const A=a(t);if(A)return A;const g=r(t);if(g)return g;const k=n(t);if(k)return k;const N=i(t);return N||null},[t,s,a,r,n,i,d.modifiedAt]),p=u?.blendMode||"normal",m=u?.blendOpacity??100,x=l.useMemo(()=>Ff(),[]),h=l.useCallback(v=>{o(t,v)},[t,o]),f=l.useCallback(v=>{c(t,v)},[t,c]);return u?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Blend Mode"}),e.jsxs(ot,{value:p,onValueChange:v=>h(v),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:x.map(v=>e.jsx(ge,{value:v,children:Lf(v)},v))})]}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:[p==="normal"&&"Default blending, no special effect",p==="multiply"&&"Darkens by multiplying colors",p==="screen"&&"Lightens by screening colors",p==="overlay"&&"Combines multiply and screen",p==="darken"&&"Keeps darker pixels",p==="lighten"&&"Keeps lighter pixels",p==="color-dodge"&&"Brightens base color",p==="color-burn"&&"Darkens base color",p==="hard-light"&&"Strong contrast effect",p==="soft-light"&&"Subtle contrast effect",p==="difference"&&"Subtracts colors",p==="exclusion"&&"Similar to difference but softer"]})]}),e.jsx(ht,{label:"Opacity",value:m,onChange:f,min:0,max:100,step:1,unit:"%"}),p!=="normal"&&e.jsx("div",{className:"p-2 bg-primary/5 border border-primary/20 rounded-lg",children:e.jsxs("p",{className:"text-[9px] text-text-muted",children:[e.jsx("span",{className:"text-primary font-medium",children:"Tip:"})," Blend modes affect how this layer combines with layers below it. Experiment with different modes for creative effects."]})})]}):e.jsx("div",{className:"text-center py-8 text-text-muted text-xs",children:"No clip selected"})},iv=({clipId:t})=>{const{getClip:s,getTextClip:a,getShapeClip:r,getSVGClip:n,getStickerClip:i,updateClipRotate3D:o,updateClipPerspective:c,updateClipTransformStyle:d,project:u}=F(),p=l.useMemo(()=>{const N=s(t);if(N)return N;const b=a(t);if(b)return b;const j=r(t);if(j)return j;const y=n(t);if(y)return y;const w=i(t);return w||null},[t,s,a,r,n,i,u.modifiedAt]),m=p?.transform.rotate3d??{x:0,y:0,z:0},x=p?.transform.perspective??1e3,h=p?.transform.transformStyle??"flat",f=l.useCallback(N=>{o(t,{...m,x:N})},[t,m,o]),v=l.useCallback(N=>{o(t,{...m,y:N})},[t,m,o]),A=l.useCallback(N=>{o(t,{...m,z:N})},[t,m,o]),g=l.useCallback(N=>{c(t,N)},[t,c]),k=l.useCallback(N=>{d(t,N)},[t,d]);return p?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ht,{label:"Rotation X",value:m.x,onChange:f,min:-360,max:360,step:1,unit:"°"}),e.jsx(ht,{label:"Rotation Y",value:m.y,onChange:v,min:-360,max:360,step:1,unit:"°"}),e.jsx(ht,{label:"Rotation Z",value:m.z,onChange:A,min:-360,max:360,step:1,unit:"°"}),e.jsx(ht,{label:"Perspective",value:x,onChange:g,min:100,max:2e3,step:10,unit:"px"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Transform Style"}),e.jsxs(ot,{value:h,onValueChange:N=>k(N),children:[e.jsx(lt,{className:"w-full bg-background-tertiary border-border text-text-primary",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"flat",children:"Flat"}),e.jsx(ge,{value:"preserve-3d",children:"Preserve 3D"})]})]}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:[h==="flat"&&"Flattens children into the plane of this element",h==="preserve-3d"&&"Children positioned in 3D space"]})]}),(m.x!==0||m.y!==0||m.z!==0)&&e.jsx("div",{className:"p-2 bg-primary/5 border border-primary/20 rounded-lg",children:e.jsxs("p",{className:"text-[9px] text-text-muted",children:[e.jsx("span",{className:"text-primary font-medium",children:"Tip:"})," 3D rotations allow you to rotate layers along X, Y, and Z axes for depth effects. Adjust perspective to control the 3D depth perception."]})})]}):e.jsx("div",{className:"text-center py-8 text-text-muted text-xs",children:"No clip selected"})},ov="openreel-motion-presets",lv=1,Ui="userPresets";function cv(){return new Promise((t,s)=>{const a=indexedDB.open(ov,lv);a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.result),a.onupgradeneeded=r=>{const n=r.target.result;n.objectStoreNames.contains(Ui)||n.createObjectStore(Ui,{keyPath:"id"})}})}async function dv(){try{const t=await cv();return new Promise((s,a)=>{const i=t.transaction(Ui,"readonly").objectStore(Ui).getAll();i.onsuccess=()=>s(i.result),i.onerror=()=>a(i.error)})}catch{return[]}}const uv=[{id:"fade-in",name:"Fade In",category:"entrance",description:"Smooth fade in from transparent",duration:.5,tags:["simple","opacity"],tracks:[{property:"opacity",keyframes:[{time:0,value:0,easing:"ease-out"},{time:.5,value:1}]}]},{id:"slide-in-left",name:"Slide In Left",category:"entrance",description:"Slide in from the left edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.x",keyframes:[{time:0,value:-200,easing:"ease-out-cubic"},{time:.6,value:0}],relative:!0},{property:"opacity",keyframes:[{time:0,value:0},{time:.2,value:1}]}]},{id:"slide-in-right",name:"Slide In Right",category:"entrance",description:"Slide in from the right edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.x",keyframes:[{time:0,value:200,easing:"ease-out-cubic"},{time:.6,value:0}],relative:!0},{property:"opacity",keyframes:[{time:0,value:0},{time:.2,value:1}]}]},{id:"slide-in-top",name:"Slide In Top",category:"entrance",description:"Slide in from the top edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.y",keyframes:[{time:0,value:-200,easing:"ease-out-cubic"},{time:.6,value:0}],relative:!0},{property:"opacity",keyframes:[{time:0,value:0},{time:.2,value:1}]}]},{id:"slide-in-bottom",name:"Slide In Bottom",category:"entrance",description:"Slide in from the bottom edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.y",keyframes:[{time:0,value:200,easing:"ease-out-cubic"},{time:.6,value:0}],relative:!0},{property:"opacity",keyframes:[{time:0,value:0},{time:.2,value:1}]}]},{id:"scale-in",name:"Scale In",category:"entrance",description:"Pop in with scale animation",duration:.4,tags:["scale","pop"],tracks:[{property:"scale.x",keyframes:[{time:0,value:0,easing:"ease-out-back"},{time:.4,value:1}]},{property:"scale.y",keyframes:[{time:0,value:0,easing:"ease-out-back"},{time:.4,value:1}]},{property:"opacity",keyframes:[{time:0,value:0},{time:.1,value:1}]}]},{id:"pop",name:"Pop",category:"entrance",description:"Quick pop entrance with overshoot",duration:.3,tags:["scale","quick"],tracks:[{property:"scale.x",keyframes:[{time:0,value:.5,easing:"ease-out-back"},{time:.3,value:1}]},{property:"scale.y",keyframes:[{time:0,value:.5,easing:"ease-out-back"},{time:.3,value:1}]},{property:"opacity",keyframes:[{time:0,value:0},{time:.05,value:1}]}]},{id:"bounce-in",name:"Bounce In",category:"entrance",description:"Bouncy scale entrance",duration:.6,tags:["bounce","playful"],tracks:[{property:"scale.x",keyframes:[{time:0,value:0},{time:.4,value:1.15,easing:"ease-out"},{time:.5,value:.9},{time:.6,value:1}]},{property:"scale.y",keyframes:[{time:0,value:0},{time:.4,value:1.15,easing:"ease-out"},{time:.5,value:.9},{time:.6,value:1}]},{property:"opacity",keyframes:[{time:0,value:0},{time:.1,value:1}]}]},{id:"flip-in",name:"Flip In",category:"entrance",description:"3D flip entrance effect",duration:.5,tags:["3d","rotation"],tracks:[{property:"rotation",keyframes:[{time:0,value:-90,easing:"ease-out"},{time:.5,value:0}]},{property:"opacity",keyframes:[{time:0,value:0},{time:.25,value:1}]}]},{id:"blur-in",name:"Blur In",category:"entrance",description:"Fade in with blur effect",duration:.5,tags:["blur","soft"],tracks:[{property:"opacity",keyframes:[{time:0,value:0,easing:"ease-out"},{time:.5,value:1}]},{property:"scale.x",keyframes:[{time:0,value:1.1,easing:"ease-out"},{time:.5,value:1}]},{property:"scale.y",keyframes:[{time:0,value:1.1,easing:"ease-out"},{time:.5,value:1}]}]},{id:"fade-out",name:"Fade Out",category:"exit",description:"Smooth fade out to transparent",duration:.5,tags:["simple","opacity"],tracks:[{property:"opacity",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:0}]}]},{id:"slide-out-left",name:"Slide Out Left",category:"exit",description:"Slide out to the left edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.x",keyframes:[{time:0,value:0,easing:"ease-in-cubic"},{time:.6,value:-200}],relative:!0},{property:"opacity",keyframes:[{time:.4,value:1},{time:.6,value:0}]}]},{id:"slide-out-right",name:"Slide Out Right",category:"exit",description:"Slide out to the right edge",duration:.6,tags:["slide","direction"],tracks:[{property:"position.x",keyframes:[{time:0,value:0,easing:"ease-in-cubic"},{time:.6,value:200}],relative:!0},{property:"opacity",keyframes:[{time:.4,value:1},{time:.6,value:0}]}]},{id:"scale-out",name:"Scale Out",category:"exit",description:"Shrink and fade out",duration:.4,tags:["scale"],tracks:[{property:"scale.x",keyframes:[{time:0,value:1,easing:"ease-in-back"},{time:.4,value:0}]},{property:"scale.y",keyframes:[{time:0,value:1,easing:"ease-in-back"},{time:.4,value:0}]},{property:"opacity",keyframes:[{time:.3,value:1},{time:.4,value:0}]}]},{id:"shrink",name:"Shrink",category:"exit",description:"Quick shrink exit",duration:.3,tags:["scale","quick"],tracks:[{property:"scale.x",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.3,value:.5}]},{property:"scale.y",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.3,value:.5}]},{property:"opacity",keyframes:[{time:0,value:1},{time:.3,value:0}]}]},{id:"blur-out",name:"Blur Out",category:"exit",description:"Fade out with blur effect",duration:.5,tags:["blur","soft"],tracks:[{property:"opacity",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:0}]},{property:"scale.x",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:1.1}]},{property:"scale.y",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:1.1}]}]},{id:"pulse",name:"Pulse",category:"emphasis",description:"Subtle pulsing scale effect",duration:.8,tags:["attention","loop"],tracks:[{property:"scale.x",keyframes:[{time:0,value:1,easing:"ease-in-out"},{time:.4,value:1.1},{time:.8,value:1}]},{property:"scale.y",keyframes:[{time:0,value:1,easing:"ease-in-out"},{time:.4,value:1.1},{time:.8,value:1}]}]},{id:"shake",name:"Shake",category:"emphasis",description:"Quick horizontal shake",duration:.5,tags:["attention","error"],tracks:[{property:"position.x",keyframes:[{time:0,value:0},{time:.1,value:-10},{time:.2,value:10},{time:.3,value:-10},{time:.4,value:10},{time:.5,value:0}],relative:!0}]},{id:"bounce",name:"Bounce",category:"emphasis",description:"Bouncing attention effect",duration:.6,tags:["attention","playful"],tracks:[{property:"position.y",keyframes:[{time:0,value:0},{time:.2,value:-20,easing:"ease-out"},{time:.4,value:0,easing:"ease-in"},{time:.5,value:-10,easing:"ease-out"},{time:.6,value:0,easing:"ease-in"}],relative:!0}]},{id:"wiggle",name:"Wiggle",category:"emphasis",description:"Playful wiggle rotation",duration:.6,tags:["attention","playful"],tracks:[{property:"rotation",keyframes:[{time:0,value:0},{time:.1,value:-5},{time:.2,value:5},{time:.3,value:-5},{time:.4,value:5},{time:.5,value:-2},{time:.6,value:0}],relative:!0}]},{id:"rubber-band",name:"Rubber Band",category:"emphasis",description:"Elastic stretch effect",duration:.6,tags:["attention","playful"],tracks:[{property:"scale.x",keyframes:[{time:0,value:1},{time:.2,value:1.25},{time:.35,value:.85},{time:.5,value:1.1},{time:.6,value:1}]},{property:"scale.y",keyframes:[{time:0,value:1},{time:.2,value:.85},{time:.35,value:1.15},{time:.5,value:.95},{time:.6,value:1}]}]},{id:"glow-pulse",name:"Glow Pulse",category:"emphasis",description:"Subtle opacity pulse",duration:1,tags:["attention","subtle"],tracks:[{property:"opacity",keyframes:[{time:0,value:1,easing:"ease-in-out"},{time:.5,value:.7},{time:1,value:1}]}]},{id:"cross-dissolve",name:"Cross Dissolve",category:"transition",description:"Simple opacity crossfade",duration:.5,tags:["simple"],tracks:[{property:"opacity",keyframes:[{time:0,value:1,easing:"linear"},{time:.5,value:0}]}]},{id:"wipe-left",name:"Wipe Left",category:"transition",description:"Wipe transition to the left",duration:.5,tags:["wipe","direction"],tracks:[{property:"position.x",keyframes:[{time:0,value:0,easing:"ease-in-out"},{time:.5,value:-100}],relative:!0},{property:"opacity",keyframes:[{time:.3,value:1},{time:.5,value:0}]}]},{id:"zoom-transition",name:"Zoom Transition",category:"transition",description:"Zoom out transition",duration:.5,tags:["zoom","scale"],tracks:[{property:"scale.x",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:1.5}]},{property:"scale.y",keyframes:[{time:0,value:1,easing:"ease-in"},{time:.5,value:1.5}]},{property:"opacity",keyframes:[{time:.2,value:1},{time:.5,value:0}]}]}];let al=[],Oo=!1;async function mv(){if(!Oo)try{al=await dv(),Oo=!0}catch{al=[],Oo=!0}}mv();function pv(){return[...uv,...al]}function xv(){const t=pv();return{entrance:t.filter(s=>s.category==="entrance"),exit:t.filter(s=>s.category==="exit"),emphasis:t.filter(s=>s.category==="emphasis"),transition:t.filter(s=>s.category==="transition")}}const hv=[{id:"entrance",name:"In",icon:Pr},{id:"exit",name:"Out",icon:Yi},{id:"emphasis",name:"Emphasis",icon:ks},{id:"transition",name:"Transition",icon:na}];function fv(t){return{linear:"linear",ease:"ease-in-out","ease-in":"ease-in","ease-out":"ease-out","ease-in-out":"ease-in-out","ease-in-cubic":"ease-in","ease-out-cubic":"ease-out","ease-in-out-cubic":"ease-in-out","ease-out-back":"ease-out","ease-in-back":"ease-in"}[t]||"ease-in-out"}function gv(t,s,a,r,n,i){const o=[],c=n||t.duration,d=r==="entrance"?"motion-in":r==="exit"?"motion-out":"motion-emphasis";let u=0;r==="exit"?u=s-c:r==="emphasis"&&(u=(s-c)/2);const p=n?n/t.duration:1,m=i?.width||1920,x=i?.height||1080;for(const h of t.tracks)for(let f=0;f0?1:-1,b=m+100;k=a.position.x+N*b}else k=a.position.x;break}case"position.y":{if(v.value!==0){const N=v.value>0?1:-1,b=x+100;k=a.position.y+N*b}else k=a.position.y;break}case"rotation":k=a.rotation+v.value;break}else h.property==="opacity"&&v.value===1?k=a.opacity:(h.property==="scale.x"||h.property==="scale")&&v.value===1?k=a.scale.x:h.property==="scale.y"&&v.value===1&&(k=a.scale.y);o.push({id:`${d}-${h.property}-${f}-${Nd().slice(0,4)}`,time:A,property:h.property,value:k,easing:g})}return o}function bv(t){const s=[];for(let r=0;r<=10;r++){const n=r/10,i=n*t.duration;let o=1,c=0,d=0,u=1,p=1,m=0;for(const x of t.tracks){let h=0;const f=x.keyframes.filter(A=>A.time<=i),v=x.keyframes.filter(A=>A.time>i);if(f.length>0&&v.length>0){const A=f[f.length-1],g=v[0],k=(i-A.time)/(g.time-A.time);h=A.value+(g.value-A.value)*k}else f.length>0?h=f[f.length-1].value:v.length>0&&(h=v[0].value);switch(x.property){case"opacity":o=h;break;case"position.x":c=h*.3;break;case"position.y":d=h*.3;break;case"scale":case"scale.x":u=h;break;case"scale.y":p=h;break;case"rotation":m=h;break}}s.push({opacity:o,transform:`translate(${c}px, ${d}px) scale(${u}, ${p}) rotate(${m}deg)`,offset:n})}return s}const yv=({preset:t,isApplied:s,onApply:a})=>{const[r,n]=l.useState(!1),i=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{if(!r||!i.current){o.current&&(o.current.cancel(),o.current=null);return}const c=i.current,d=bv(t);return o.current=c.animate(d,{duration:t.duration*1e3,iterations:1/0,easing:"ease-in-out"}),()=>{o.current?.cancel()}},[r,t]),e.jsxs("button",{onClick:a,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),className:`relative w-full rounded-lg border transition-all overflow-hidden ${s?"border-primary bg-primary/10":"border-border bg-background-tertiary hover:border-primary/50"}`,children:[e.jsxs("div",{className:"relative h-20 bg-gradient-to-br from-background-secondary to-background-tertiary flex items-center justify-center overflow-hidden",children:[e.jsx("div",{ref:i,className:"w-10 h-10 rounded bg-primary/80 flex items-center justify-center",children:e.jsx(As,{size:16,className:"text-white"})}),s&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(is,{size:14,className:"text-primary"})}),r&&!s&&e.jsx("div",{className:"absolute inset-0 bg-black/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] text-white font-medium px-2 py-1 bg-primary rounded",children:"Apply"})})]}),e.jsxs("div",{className:"p-2 text-left",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-primary block truncate",children:t.name}),e.jsxs("span",{className:"text-[8px] text-text-muted",children:[t.duration,"s"]})]})]})},vv=({clipId:t})=>{const s=vt(j=>j.getSelectedClipIds()),a=F(j=>j.project),r=F(j=>j.updateClipKeyframes),n=F(j=>j.updateTextClipKeyframes),i=F(j=>j.getTextClip),o=F(j=>j.getShapeClip),c=F(j=>j.getSVGClip),d=F(j=>j.getStickerClip),u=Ct(j=>j.getGraphicsEngine),[p,m]=l.useState("entrance"),x={},h=t||s[0],v=l.useMemo(()=>xv(),[])[p]||[],A=l.useMemo(()=>{if(!h)return null;const j=a.timeline.tracks.flatMap(C=>C.clips).find(C=>C.id===h);if(j)return{type:"regular",data:j};const y=i(h);if(y)return{type:"text",data:y};const w=o(h);if(w)return{type:"shape",data:w};const S=c(h);if(S)return{type:"svg",data:S};const T=d(h);return T?{type:"sticker",data:T}:null},[h,a.timeline.tracks,i,o,c,d,a.modifiedAt]),k=l.useCallback(()=>{if(!A)return{entrance:null,exit:null,emphasis:null};const j=A.data.keyframes||[],y=j.some(T=>T.id.startsWith("motion-in-")),w=j.some(T=>T.id.startsWith("motion-out-")),S=j.some(T=>T.id.startsWith("motion-emphasis-"));return{entrance:y?"applied":null,exit:w?"applied":null,emphasis:S?"applied":null}},[A])(),N=l.useCallback(j=>{if(!A||!h)return;const y=j.category==="entrance"?"motion-in-":j.category==="exit"?"motion-out-":"motion-emphasis-",w=(A.data.keyframes||[]).filter(L=>!L.id.startsWith(y)),S=A.data.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,opacity:1},T=x[j.id],C={width:a.settings.width,height:a.settings.height},M=gv(j,A.data.duration,S,j.category,T,C),z=[...w,...M];if(A.type==="text")n(h,z);else if(A.type==="shape"||A.type==="svg"||A.type==="sticker"){const L=u();if(L){const B=A.type==="shape"?L.getShapeClip(h):A.type==="svg"?L.getSVGClip(h):L.getStickerClip(h);B&&(B.keyframes=z,F.setState(O=>({project:{...O.project,modifiedAt:Date.now()}})))}}else r(h,z);Fe.success("Motion Preset Applied",`${j.name} added to clip`)},[A,h,x,r,n,u,a.settings]),b=l.useCallback(j=>{if(!A||!h)return;const y=j==="entrance"?"motion-in-":j==="exit"?"motion-out-":"motion-emphasis-",w=(A.data.keyframes||[]).filter(S=>!S.id.startsWith(y));if(A.type==="text")n(h,w);else if(A.type==="shape"||A.type==="svg"||A.type==="sticker"){const S=u();if(S){const T=A.type==="shape"?S.getShapeClip(h):A.type==="svg"?S.getSVGClip(h):S.getStickerClip(h);T&&(T.keyframes=w,F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}})))}}else r(h,w);Fe.info("Preset Removed")},[A,h,r,n,u]);return h?A?e.jsxs("div",{className:"space-y-4",children:[(k.entrance||k.exit||k.emphasis)&&e.jsxs("div",{className:"space-y-1 p-2 bg-background-tertiary rounded-lg border border-border",children:[e.jsx("span",{className:"text-[10px] text-text-secondary font-medium",children:"Applied Animations"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[k.entrance&&e.jsxs("button",{onClick:()=>b("entrance"),className:"flex items-center gap-1 px-2 py-1 bg-green-500/20 text-green-400 rounded text-[9px] hover:bg-green-500/30",children:[e.jsx(Pr,{size:10}),"Entry ×"]}),k.exit&&e.jsxs("button",{onClick:()=>b("exit"),className:"flex items-center gap-1 px-2 py-1 bg-red-500/20 text-red-400 rounded text-[9px] hover:bg-red-500/30",children:[e.jsx(Yi,{size:10}),"Exit ×"]}),k.emphasis&&e.jsxs("button",{onClick:()=>b("emphasis"),className:"flex items-center gap-1 px-2 py-1 bg-yellow-500/20 text-yellow-400 rounded text-[9px] hover:bg-yellow-500/30",children:[e.jsx(ks,{size:10}),"Emphasis ×"]})]})]}),e.jsx("div",{className:"flex gap-1",children:hv.map(j=>{const y=j.icon,w=j.id==="entrance"&&k.entrance||j.id==="exit"&&k.exit||j.id==="emphasis"&&k.emphasis||j.id==="transition"&&k.emphasis;return e.jsxs("button",{onClick:()=>m(j.id),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] whitespace-nowrap transition-colors relative ${p===j.id?"bg-primary text-white font-medium":"bg-background-tertiary text-text-secondary hover:text-text-primary"}`,children:[e.jsx(y,{size:12}),j.name,w&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-green-500 rounded-full"})]},j.id)})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 max-h-72 overflow-y-auto",children:v.map(j=>{const y=j.category==="entrance"?"entrance":j.category==="exit"?"exit":"emphasis";return e.jsx(yv,{preset:j,isApplied:!!k[y],onApply:()=>N(j)},j.id)})}),e.jsxs("p",{className:"text-[9px] text-text-muted text-center",children:[v.length," presets in ",p]})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(ks,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Clip not found"})]}):e.jsxs("div",{className:"p-4 text-center",children:[e.jsx(ks,{size:24,className:"mx-auto mb-2 text-text-muted"}),e.jsx("p",{className:"text-[10px] text-text-muted",children:"Select a clip to apply motion presets"})]})},jv=({clipId:t})=>{const{getClip:s,project:a}=F(),{motionPathMode:r,motionPathClipId:n,setMotionPathMode:i}=vt(),o=Ct(C=>C.getGraphicsEngine),c=Ct(C=>C.getTitleEngine),[d,u]=l.useState(0),p=l.useMemo(()=>{const C=s(t);if(C)return C;const M=o(),z=M?.getSVGClip(t);if(z)return z;const L=M?.getShapeClip(t);if(L)return L;const B=M?.getStickerClip(t);if(B)return B;const G=c()?.getTextClip(t);if(G)return G},[t,s,o,c,a.modifiedAt]),m=l.useMemo(()=>op(),[]),x=l.useMemo(()=>m.getMotionPath(t),[t,m,d]),h=r&&n===t,f=l.useCallback(C=>{if(C){const M=m.getMotionPath(t);if(M)m.setMotionPath(t,{...M,enabled:!0});else{const z=[{x:0,y:0,time:0},{x:100,y:0,time:1}];m.setMotionPath(t,{enabled:!0,pathType:"bezier",points:lp(z),showPath:!0,autoOrient:!1,alignOrigin:[.5,.5]})}}else{const M=m.getMotionPath(t);M&&m.setMotionPath(t,{...M,enabled:!1})}u(M=>M+1)},[t,m]),v=l.useCallback(C=>{const M=m.getMotionPath(t);M&&(m.setMotionPath(t,{...M,showPath:C}),u(z=>z+1))},[t,m]),A=l.useCallback(C=>{const M=m.getMotionPath(t);M&&(m.setMotionPath(t,{...M,autoOrient:C}),u(z=>z+1))},[t,m]),g=l.useCallback(C=>{const M=m.getMotionPath(t);M&&(m.setMotionPath(t,{...M,pathType:C}),u(z=>z+1))},[t,m]),k=l.useCallback(()=>{h?i(!1):i(!0,t)},[h,t,i]),N=l.useCallback(()=>{const C=m.getMotionPath(t);if(!C)return;const M=C.points[C.points.length-1],z={x:M.x+50,y:M.y,time:Math.min(1,M.time+.2)};m.addGSAPMotionPathPoint(t,z),u(L=>L+1)},[t,m]),b=l.useCallback(()=>{m.removeMotionPath(t),i(!1),u(C=>C+1)},[t,m,i]);if(!p)return e.jsx("div",{className:"text-center py-8 text-text-muted text-xs",children:"No clip selected"});const j=x?.enabled??!1,y=x?.showPath??!0,w=x?.autoOrient??!1,S=x?.pathType??"bezier",T=x?.points.length??0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nc,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Motion Path"})]}),e.jsx(oa,{checked:j,onCheckedChange:f})]}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 bg-background-tertiary rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Show Path"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:()=>v(!y),className:`p-1.5 rounded transition-colors ${y?"bg-primary/20 text-primary":"bg-background-elevated text-text-muted"}`,children:y?e.jsx($s,{size:12}):e.jsx(Xs,{size:12})})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Auto Orient"}),e.jsx(oa,{checked:w,onCheckedChange:A})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Path Type"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:["linear","bezier","catmull-rom"].map(C=>e.jsx("button",{onClick:()=>g(C),className:`py-1.5 rounded text-[9px] capitalize transition-colors ${S===C?"bg-primary text-white":"bg-background-elevated border border-border text-text-secondary hover:text-text-primary"}`,children:C==="catmull-rom"?"Smooth":C},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Path Points"}),e.jsxs("p",{className:"text-sm font-medium text-text-primary",children:[T," points"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:N,className:"p-1.5 rounded bg-primary/20 text-primary hover:bg-primary/30 transition-colors",title:"Add point",children:e.jsx(cs,{size:12})}),e.jsx("button",{onClick:b,className:"p-1.5 rounded bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors",title:"Clear path",children:e.jsx($t,{size:12})})]})]}),e.jsxs(zt,{onClick:k,className:`w-full ${h?"bg-primary text-white":"bg-background-tertiary text-text-primary border border-border hover:bg-background-elevated"}`,size:"sm",children:[e.jsx(nc,{size:14,className:"mr-2"}),h?"Exit Edit Mode":"Edit Path on Canvas"]}),h&&e.jsx("div",{className:"p-2 bg-primary/10 border border-primary/30 rounded-lg",children:e.jsxs("p",{className:"text-[9px] text-primary",children:[e.jsx("span",{className:"font-medium",children:"Editing:"})," Click on the path to add points. Drag points to move them. Right-click to remove. Drag handles to adjust curves."]})}),e.jsx("div",{className:"p-2 bg-background-tertiary/50 border border-border rounded-lg",children:e.jsxs("p",{className:"text-[9px] text-text-muted",children:[e.jsx("span",{className:"text-text-secondary font-medium",children:"Tip:"})," ","Motion paths animate the clip's position along a curved path over time. Use bezier handles for smooth curves."]})})]})]})},Ci=t=>{const s=Math.floor(t/60),a=(t%60).toFixed(1);return s>0?`${s}:${a.padStart(4,"0")}`:`${a}s`},od=[{category:"Attention",animations:[{type:"pulse",label:"Pulse",description:"Gentle scale breathing effect"},{type:"heartbeat",label:"Heartbeat",description:"Double-beat pulse like a heart"},{type:"flash",label:"Flash",description:"Opacity pulsing effect"},{type:"glow",label:"Glow",description:"Scale and opacity pulse"},{type:"breathe",label:"Breathe",description:"Slow, calming scale effect"}]},{category:"Movement",animations:[{type:"shake",label:"Shake",description:"Quick side-to-side shake"},{type:"bounce",label:"Bounce",description:"Bouncing up and down"},{type:"float",label:"Float",description:"Gentle floating motion"},{type:"vibrate",label:"Vibrate",description:"Random small movements"},{type:"wave",label:"Wave",description:"Wave-like motion"}]},{category:"Rotation",animations:[{type:"spin",label:"Spin",description:"Continuous rotation"},{type:"swing",label:"Swing",description:"Pendulum-like rotation"},{type:"wobble",label:"Wobble",description:"Wobbling with rotation"},{type:"tilt",label:"Tilt",description:"Slow tilting motion"},{type:"tada",label:"Tada",description:"Attention-grabbing wiggle"}]},{category:"Distortion",animations:[{type:"jello",label:"Jello",description:"Jelly-like squish effect"},{type:"rubber-band",label:"Rubber Band",description:"Stretchy rubber effect"},{type:"flicker",label:"Flicker",description:"Random visibility flicker"}]},{category:"Zoom & Pan",animations:[{type:"zoom-pulse",label:"Zoom Pulse",description:"Scale in and out"},{type:"focus-zoom",label:"Focus Zoom",description:"Zoom to point and back"},{type:"ken-burns",label:"Ken Burns",description:"Slow zoom with pan"},{type:"pan-left",label:"Pan Left",description:"Slow pan to the left"},{type:"pan-right",label:"Pan Right",description:"Slow pan to the right"},{type:"pan-up",label:"Pan Up",description:"Slow pan upward"},{type:"pan-down",label:"Pan Down",description:"Slow pan downward"}]}],ld={type:"none",speed:1,intensity:1,loop:!0},wv=({clipId:t})=>{const{project:s,updateClipEmphasisAnimation:a}=F(),r=Ct(m=>m.getTitleEngine),n=Ct(m=>m.getGraphicsEngine),i=l.useMemo(()=>{const m=s.timeline.tracks.flatMap(k=>k.clips).find(k=>k.id===t);if(m)return m.duration;const h=r()?.getTextClip(t);if(h)return h.duration;const f=n(),v=f?.getShapeClip(t);if(v)return v.duration;const A=f?.getSVGClip(t);if(A)return A.duration;const g=f?.getStickerClip(t);return g?g.duration:5},[t,s.timeline.tracks,r,n,s.modifiedAt]),o=l.useMemo(()=>{const m=s.timeline.tracks.flatMap(k=>k.clips).find(k=>k.id===t);if(m?.emphasisAnimation)return m.emphasisAnimation;const h=r()?.getTextClip(t);if(h?.emphasisAnimation)return h.emphasisAnimation;const f=n(),v=f?.getShapeClip(t);if(v?.emphasisAnimation)return v.emphasisAnimation;const A=f?.getSVGClip(t);if(A?.emphasisAnimation)return A.emphasisAnimation;const g=f?.getStickerClip(t);return g?.emphasisAnimation?g.emphasisAnimation:ld},[t,s.timeline.tracks,r,n,s.modifiedAt]),c=l.useCallback(m=>{const x={...o,...m};a(t,x)},[t,o,a]),d=l.useCallback(m=>{c(m==="focus-zoom"?{type:m,focusPoint:{x:.5,y:.5},zoomScale:1.5,holdDuration:.3,loop:!1}:m==="ken-burns"?{type:m,loop:!1}:{type:m})},[c]),u=l.useCallback(()=>{c(ld)},[c]),p=od.flatMap(m=>m.animations).find(m=>m.type===o.type);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{onClick:()=>d("none"),className:`py-2 rounded-lg text-[10px] font-medium transition-all ${o.type==="none"?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,children:"None"}),e.jsxs("button",{onClick:u,className:"py-2 rounded-lg text-[10px] font-medium bg-background-tertiary border border-border text-text-secondary hover:text-text-primary transition-all flex items-center justify-center gap-1",children:[e.jsx(Ns,{size:10}),"Reset"]})]}),od.map(m=>e.jsxs("div",{children:[e.jsx("h4",{className:"text-[10px] font-medium text-text-muted mb-2",children:m.category}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:m.animations.map(x=>e.jsx("button",{onClick:()=>d(x.type),className:`py-2 px-2 rounded-lg text-[10px] transition-all text-left ${o.type===x.type?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary hover:border-primary/50"}`,children:x.label},x.type))})]},m.category)),o.type!=="none"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"pt-3 border-t border-border space-y-3",children:[p&&e.jsx("p",{className:"text-[10px] text-text-muted italic",children:p.description}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Speed"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[o.speed.toFixed(1),"x"]})]}),e.jsx(st,{min:.1,max:3,step:.1,value:[o.speed],onValueChange:m=>c({speed:m[0]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Intensity"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[Math.round(o.intensity*100),"%"]})]}),e.jsx(st,{min:.1,max:2,step:.1,value:[o.intensity],onValueChange:m=>c({intensity:m[0]})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Loop Animation"}),e.jsx("button",{onClick:()=>c({loop:!o.loop}),className:`w-10 h-5 rounded-full transition-colors ${o.loop?"bg-primary":"bg-background-tertiary border border-border"}`,children:e.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${o.loop?"translate-x-5":"translate-x-0.5"}`})})]})]}),e.jsxs("div",{className:"pt-3 border-t border-border space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Ia,{size:12}),e.jsx("span",{className:"text-[10px] font-medium",children:"Timing"}),e.jsxs("span",{className:"text-[9px] text-text-muted ml-auto",children:["Clip: ",Ci(i)]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Start Time"}),e.jsx("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:Ci(o.startTime??0)})]}),e.jsx(st,{min:0,max:i,step:.1,value:[o.startTime??0],onValueChange:m=>c({startTime:m[0]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Duration"}),e.jsx("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:o.animationDuration?Ci(o.animationDuration):"Full clip"})]}),e.jsx(st,{min:0,max:i-(o.startTime??0),step:.1,value:[o.animationDuration??i-(o.startTime??0)],onValueChange:m=>{const x=m[0];c({animationDuration:x>0?x:void 0})}}),e.jsxs("div",{className:"flex justify-between text-[9px] text-text-muted",children:[e.jsx("span",{children:"0s"}),e.jsx("button",{onClick:()=>c({startTime:0,animationDuration:void 0}),className:"text-primary hover:underline",children:"Reset to full clip"}),e.jsx("span",{children:Ci(i-(o.startTime??0))})]})]})]}),o.type==="focus-zoom"&&e.jsxs("div",{className:"pt-3 border-t border-border space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Uo,{size:12}),e.jsx("span",{className:"text-[10px] font-medium",children:"Focus Zoom Settings"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Zoom Scale"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[(o.zoomScale||1.5).toFixed(1),"x"]})]}),e.jsx(st,{min:1.1,max:3,step:.1,value:[o.zoomScale||1.5],onValueChange:m=>c({zoomScale:m[0]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Hold Duration"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border",children:[((o.holdDuration||.3)*100).toFixed(0),"%"]})]}),e.jsx(st,{min:0,max:1,step:.05,value:[o.holdDuration||.3],onValueChange:m=>c({holdDuration:m[0]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Focus Point"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:"X Position"}),e.jsx(st,{min:0,max:1,step:.05,value:[o.focusPoint?.x||.5],onValueChange:m=>c({focusPoint:{x:m[0],y:o.focusPoint?.y||.5}})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:"Y Position"}),e.jsx(st,{min:0,max:1,step:.05,value:[o.focusPoint?.y||.5],onValueChange:m=>c({focusPoint:{x:o.focusPoint?.x||.5,y:m[0]}})})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1 mt-2",children:[{x:0,y:0,label:"TL"},{x:.5,y:0,label:"TC"},{x:1,y:0,label:"TR"},{x:0,y:.5,label:"ML"},{x:.5,y:.5,label:"C"},{x:1,y:.5,label:"MR"},{x:0,y:1,label:"BL"},{x:.5,y:1,label:"BC"},{x:1,y:1,label:"BR"}].map(m=>e.jsx("button",{onClick:()=>c({focusPoint:{x:m.x,y:m.y}}),className:`py-1.5 rounded text-[9px] transition-all ${o.focusPoint?.x===m.x&&o.focusPoint?.y===m.y?"bg-primary text-white":"bg-background-tertiary border border-border text-text-muted hover:text-text-primary"}`,children:m.label},m.label))})]})]})]}),e.jsx("div",{className:"pt-3 border-t border-border",children:e.jsxs("div",{className:"flex items-center gap-2 text-text-muted",children:[e.jsx(ks,{size:10}),e.jsx("span",{className:"text-[9px]",children:"Emphasis animations play while the clip is visible (not during entry/exit)"})]})})]})},kv=[{id:"correlation",name:"Correlation",description:"Best for high-contrast objects"},{id:"optical-flow",name:"Optical Flow",description:"Good for smooth motion"},{id:"feature",name:"Feature Match",description:"Works with complex textures"}],Nv=({clipId:t})=>{const[s,a]=l.useState({isTracking:!1,progress:0,currentJob:null,trackingData:null,lostFrames:[],error:null}),[r,n]=l.useState({x:100,y:100,width:200,height:200}),[i,o]=l.useState("correlation"),[c,d]=l.useState(70),[u,p]=l.useState(!1),[m,x]=l.useState(0),[h,f]=l.useState(0),[v,A]=l.useState(!0),[g,k]=l.useState(!0),[N,b]=l.useState(0),[j,y]=l.useState(!1),w=D1();l.useEffect(()=>{const B=w.subscribe(a),O=w.getTrackingDataForClip(t);return O.length>0&&a(G=>({...G,trackingData:O[O.length-1]})),B},[w,t]);const S=l.useCallback(async()=>{try{await w.startTracking(t,r,{frameRate:30,startFrame:0,endFrame:150,algorithm:i,confidenceThreshold:c/100})}catch(B){console.error("Failed to start tracking:",B)}},[w,t,r,i,c]),T=l.useCallback(()=>{s.currentJob&&w.cancelTracking(s.currentJob.id)},[w,s.currentJob]),C=l.useCallback(()=>{w.applyTrackingToClip(t,{x:m,y:h})&&(w.setApplyScale(t,v),w.setApplyRotation(t,g),y(!0))},[w,t,m,h,v,g]),M=l.useCallback(()=>{w.removeAttachment(t),y(!1)},[w,t]),z=l.useCallback((B,O)=>{B==="x"?x(O):f(O),j&&w.setTrackingOffset(t,{x:B==="x"?O:m,y:B==="y"?O:h})},[w,t,j,m,h]),L=s.trackingData!==null||w.hasTrackingData(t);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Uo,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Motion Tracking"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Track objects to attach elements"})]})]}),!s.isTracking&&!L&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Tracking Region"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"X Position"}),e.jsx("input",{type:"number",value:r.x,onChange:B=>n({...r,x:Number(B.target.value)}),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Y Position"}),e.jsx("input",{type:"number",value:r.y,onChange:B=>n({...r,y:Number(B.target.value)}),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Width"}),e.jsx("input",{type:"number",value:r.width,onChange:B=>n({...r,width:Number(B.target.value)}),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Height"}),e.jsx("input",{type:"number",value:r.height,onChange:B=>n({...r,height:Number(B.target.value)}),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]})]}),e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Draw region in preview or enter coordinates"})]}),e.jsxs("button",{onClick:()=>p(!u),className:"w-full flex items-center gap-2 py-1.5 text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[u?e.jsx(qt,{size:12}):e.jsx(bs,{size:12}),e.jsx(Dn,{size:12}),"Advanced Options"]}),u&&e.jsxs("div",{className:"space-y-3 p-2 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Algorithm"}),e.jsx("div",{className:"space-y-1",children:kv.map(B=>e.jsxs("button",{onClick:()=>o(B.id),className:`w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors ${i===B.id?"bg-primary/20 border border-primary":"bg-background-secondary border border-transparent hover:border-border"}`,children:[e.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${i===B.id?"border-primary":"border-border"}`,children:i===B.id&&e.jsx("div",{className:"w-1.5 h-1.5 bg-primary rounded-full"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-primary",children:B.name}),e.jsx("p",{className:"text-[8px] text-text-muted",children:B.description})]})]},B.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Confidence Threshold"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[c,"%"]})]}),e.jsx(st,{min:30,max:95,step:5,value:[c],onValueChange:B=>d(B[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"Higher = more accurate but may lose track easier"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Path Smoothing"}),e.jsx("span",{className:"text-[10px] font-mono text-text-primary",children:N})]}),e.jsx(st,{min:0,max:10,step:1,value:[N],onValueChange:B=>b(B[0])}),e.jsx("p",{className:"text-[8px] text-text-muted",children:"Reduces jitter in tracking path"})]})]}),e.jsxs("button",{onClick:S,className:"w-full py-2.5 bg-primary hover:bg-primary-hover rounded-lg text-[11px] font-medium text-white flex items-center justify-center gap-2 transition-colors",children:[e.jsx(Uo,{size:14}),"Start Tracking"]})]}),s.isTracking&&e.jsxs("div",{className:"space-y-3 p-3 bg-background-tertiary rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full animate-pulse"}),e.jsx("span",{className:"text-[11px] font-medium text-primary",children:"Tracking in Progress"})]}),e.jsx("button",{onClick:T,className:"p-1.5 text-text-muted hover:text-red-400 hover:bg-red-400/10 rounded transition-colors",title:"Cancel Tracking",children:e.jsx(Ls,{size:14})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[e.jsx("span",{className:"text-text-muted",children:"Analyzing frames..."}),e.jsxs("span",{className:"font-mono text-text-primary",children:[Math.round(s.progress),"%"]})]}),e.jsx("div",{className:"w-full h-2 bg-background-secondary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-200",style:{width:`${s.progress}%`}})})]}),s.lostFrames.length>0&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-amber-500/10 border border-amber-500/20 rounded text-[10px] text-amber-400",children:[e.jsx(ra,{size:12}),"Lost tracking on ",s.lostFrames.length," frame(s)"]})]}),s.error&&e.jsxs("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-[10px] text-red-400",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium mb-1",children:[e.jsx(ra,{size:12}),"Tracking Failed"]}),e.jsx("p",{className:"text-[9px] text-red-300/80",children:s.error})]}),L&&!s.isTracking&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-green-500/10 border border-green-500/30 rounded-lg",children:[e.jsx(is,{size:14,className:"text-green-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[10px] font-medium text-green-400",children:"Tracking Complete"}),s.trackingData&&e.jsxs("p",{className:"text-[9px] text-green-300/70",children:[s.trackingData.keyframes.length," keyframes captured",s.trackingData.lostFrames.length>0&&` • ${s.trackingData.lostFrames.length} frames lost`]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[10px] font-medium text-text-secondary flex items-center gap-2",children:[e.jsx(rn,{size:12}),"Position Offset"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"X Offset"}),e.jsx("input",{type:"number",value:m,onChange:B=>z("x",Number(B.target.value)),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-[9px] text-text-muted",children:"Y Offset"}),e.jsx("input",{type:"number",value:h,onChange:B=>z("y",Number(B.target.value)),className:"w-full px-2 py-1.5 text-[10px] bg-background-secondary border border-border rounded focus:border-primary focus:outline-none"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(kt,{className:"text-[10px] font-medium text-text-secondary",children:"Transform Options"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg",children:[e.jsx(Hl,{id:"apply-scale",checked:v,onCheckedChange:B=>{const O=B===!0;A(O),j&&w.setApplyScale(t,O)}}),e.jsxs(kt,{htmlFor:"apply-scale",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(zr,{size:10,className:"text-text-muted"}),e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Scale"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background-tertiary rounded-lg",children:[e.jsx(Hl,{id:"apply-rotation",checked:g,onCheckedChange:B=>{const O=B===!0;k(O),j&&w.setApplyRotation(t,O)}}),e.jsxs(kt,{htmlFor:"apply-rotation",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(Ns,{size:10,className:"text-text-muted"}),e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Rotation"})]})]})]})]}),j?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-primary/10 border border-primary/20 rounded-lg",children:[e.jsx(is,{size:12,className:"text-primary"}),e.jsx("span",{className:"text-[10px] text-primary",children:"Tracking Applied"})]}),e.jsx("button",{onClick:M,className:"w-full py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-[10px] text-red-400 hover:bg-red-500/20 transition-colors",children:"Remove Tracking"})]}):e.jsx("button",{onClick:C,className:"w-full py-2.5 bg-primary/20 border border-primary/30 rounded-lg text-[11px] font-medium text-primary hover:bg-primary/30 transition-colors",children:"Apply Tracking to Clip"}),e.jsxs("button",{onClick:S,className:"w-full flex items-center justify-center gap-2 py-1.5 text-[9px] text-text-muted hover:text-text-secondary transition-colors",children:[e.jsx(na,{size:10}),"Re-track with Different Settings"]})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Track objects to pin graphics, text, or effects"})})]})},Cv=({clipId:t})=>{const s=Ct(S=>S.getNestedSequenceEngine),a=F(S=>S.project),r=vt(S=>S.getSelectedClipIds()),[n,i]=l.useState(null),[o,c]=l.useState(null),[d,u]=l.useState(""),[p,m]=l.useState(null);l.useEffect(()=>{let S=!1;return(async()=>{const C=await s();S||m(C)})(),()=>{S=!0}},[s]);const x=l.useMemo(()=>p?.getAllCompoundClips()||[],[p]),h=l.useMemo(()=>p?p.getInstance(t):null,[p,t]),f=l.useMemo(()=>!p||!h?null:p.getCompoundClip(h.compoundClipId),[p,h]),v=l.useMemo(()=>{const S=[];for(const T of a.timeline.tracks)for(const C of T.clips)r.includes(C.id)&&S.push({id:C.id,trackId:T.id,startTime:C.startTime,duration:C.duration});return S},[a.timeline.tracks,r]),A=l.useCallback(()=>{if(!p||v.length<2)return;const S=[];for(const C of a.timeline.tracks)for(const M of C.clips)r.includes(M.id)&&S.push(M);if(S.length<2)return;const T=p.createCompoundClip(S,a.timeline.tracks);F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}})),i(T.id)},[p,v,r,a.timeline.tracks]),g=l.useCallback(()=>{if(!p||!t)return;p.flattenInstance(t)&&F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}}))},[p,t]),k=l.useCallback(S=>{p&&(p.duplicateCompoundClip(S),F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}})))},[p]),N=l.useCallback(S=>{if(!p)return;p.deleteCompoundClip(S)&&(F.setState(C=>({project:{...C.project,modifiedAt:Date.now()}})),n===S&&i(null))},[p,n]),b=l.useCallback(S=>{c(S.id),u(S.name)},[]),j=l.useCallback(()=>{!p||!o||(p.renameCompoundClip(o,d.trim()),F.setState(S=>({project:{...S.project,modifiedAt:Date.now()}})),c(null),u(""))},[p,o,d]),y=l.useCallback(()=>{c(null),u("")},[]),w=S=>{const T=Math.floor(S/60),C=Math.floor(S%60);return`${T}:${C.toString().padStart(2,"0")}`};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gradient-to-r bg-primary/10 rounded-lg border border-primary/30",children:[e.jsx(Os,{size:16,className:"text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Nested Sequences"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Create compound clips from selections"})]})]}),f&&e.jsxs("div",{className:"p-3 bg-primary/10 border border-primary/20 rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:f.name})]}),e.jsxs("div",{className:"flex gap-2 text-[9px] text-text-muted",children:[e.jsxs("span",{children:[f.content.clips.length," clips"]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:w(f.content.duration)})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs("button",{onClick:g,className:"flex-1 flex items-center justify-center gap-1 py-1.5 bg-background-tertiary rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[e.jsx(zr,{size:10}),"Flatten"]}),e.jsxs("button",{onClick:()=>k(f.id),className:"flex-1 flex items-center justify-center gap-1 py-1.5 bg-background-tertiary rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[e.jsx(dn,{size:10}),"Duplicate"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Create Compound Clip"}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[v.length," clips selected"]})]}),e.jsxs("button",{onClick:A,disabled:v.length<2,className:`w-full py-2.5 rounded-lg text-[11px] font-medium flex items-center justify-center gap-2 transition-colors ${v.length>=2?"bg-primary/20 border border-primary/30 text-primary hover:bg-primary/20":"bg-background-tertiary text-text-muted cursor-not-allowed"}`,children:[e.jsx(cs,{size:14}),"Create Compound Clip"]}),v.length<2&&e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Select 2+ clips to create a compound clip"})]}),x.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Compound Clips Library"}),e.jsx("div",{className:"space-y-1.5",children:x.map(S=>{const T=p?.getInstanceCount(S.id)||0,C=n===S.id,M=o===S.id;return e.jsxs("div",{className:"bg-background-tertiary rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 cursor-pointer hover:bg-background-secondary transition-colors",onClick:()=>i(C?null:S.id),children:[e.jsx(bs,{size:12,className:`text-text-muted transition-transform ${C?"rotate-90":""}`}),e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:S.color}}),M?e.jsx("input",{type:"text",value:d,onChange:z=>u(z.target.value),onClick:z=>z.stopPropagation(),onKeyDown:z=>{z.key==="Enter"&&j(),z.key==="Escape"&&y()},className:"flex-1 bg-background-secondary px-1.5 py-0.5 rounded text-[10px] text-text-primary outline-none border border-primary",autoFocus:!0}):e.jsx("span",{className:"flex-1 text-[10px] text-text-primary truncate",children:S.name}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[T," instance",T!==1?"s":""]})]}),C&&e.jsxs("div",{className:"px-2 pb-2 space-y-2",children:[e.jsxs("div",{className:"flex gap-2 text-[9px] text-text-muted pl-5",children:[e.jsxs("span",{children:[S.content.clips.length," clips"]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:w(S.content.duration)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[S.content.tracks.length," tracks"]})]}),e.jsx("div",{className:"flex gap-1 pl-5",children:M?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:z=>{z.stopPropagation(),j()},className:"p-1.5 bg-green-500/20 rounded text-green-400 hover:bg-green-500/30 transition-colors",children:e.jsx(is,{size:10})}),e.jsx("button",{onClick:z=>{z.stopPropagation(),y()},className:"p-1.5 bg-red-500/20 rounded text-red-400 hover:bg-red-500/30 transition-colors",children:e.jsx(Ls,{size:10})})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:z=>{z.stopPropagation(),b(S)},className:"p-1.5 bg-background-secondary rounded text-text-muted hover:text-text-primary transition-colors",title:"Rename",children:e.jsx(kh,{size:10})}),e.jsx("button",{onClick:z=>{z.stopPropagation(),k(S.id)},className:"p-1.5 bg-background-secondary rounded text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:e.jsx(dn,{size:10})}),e.jsx("button",{onClick:z=>{z.stopPropagation(),N(S.id)},disabled:T>0,className:`p-1.5 rounded transition-colors ${T>0?"bg-background-secondary text-text-muted cursor-not-allowed opacity-50":"bg-red-500/20 text-red-400 hover:bg-red-500/30"}`,title:T>0?"Cannot delete - has instances":"Delete",children:e.jsx($t,{size:10})})]})})]})]},S.id)})})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Group clips into reusable compound clips"})})]})},cd=[{id:"brightness",name:"Brightness",effect:{type:"brightness",params:{value:0},enabled:!0}},{id:"contrast",name:"Contrast",effect:{type:"contrast",params:{value:1},enabled:!0}},{id:"saturation",name:"Saturation",effect:{type:"saturation",params:{value:1},enabled:!0}},{id:"exposure",name:"Exposure",effect:{type:"exposure",params:{value:0},enabled:!0}},{id:"blur",name:"Blur",effect:{type:"blur",params:{radius:0},enabled:!0}},{id:"sharpen",name:"Sharpen",effect:{type:"sharpen",params:{amount:0},enabled:!0}},{id:"vignette",name:"Vignette",effect:{type:"vignette",params:{intensity:0},enabled:!0}},{id:"tint",name:"Tint",effect:{type:"tint",params:{color:"#ffffff",strength:0},enabled:!0}}],dd=[{id:"normal",name:"Normal",group:"Basic"},{id:"multiply",name:"Multiply",group:"Darken"},{id:"screen",name:"Screen",group:"Lighten"},{id:"overlay",name:"Overlay",group:"Contrast"},{id:"darken",name:"Darken",group:"Darken"},{id:"lighten",name:"Lighten",group:"Lighten"},{id:"color-dodge",name:"Color Dodge",group:"Lighten"},{id:"color-burn",name:"Color Burn",group:"Darken"},{id:"hard-light",name:"Hard Light",group:"Contrast"},{id:"soft-light",name:"Soft Light",group:"Contrast"},{id:"difference",name:"Difference",group:"Inversion"},{id:"exclusion",name:"Exclusion",group:"Inversion"},{id:"hue",name:"Hue",group:"Component"},{id:"saturation",name:"Saturation",group:"Component"},{id:"color",name:"Color",group:"Component"},{id:"luminosity",name:"Luminosity",group:"Component"}],Sv=({clipId:t})=>{const s=Ct(j=>j.getAdjustmentLayerEngine),a=F(j=>j.project),[r,n]=l.useState(null),[i,o]=l.useState(!1),[c,d]=l.useState(null);l.useEffect(()=>{let j=!1;return(async()=>{const w=await s();j||d(w)})(),()=>{j=!0}},[s]);const u=l.useMemo(()=>{for(const j of a.timeline.tracks)for(const y of j.clips)if(y.id===t)return j;return null},[a.timeline.tracks,t]),p=l.useMemo(()=>c?.getAllLayers()||[],[c,a.modifiedAt]),m=l.useMemo(()=>u?c?.getLayersForTrack(u.id)||[]:[],[c,u,a.modifiedAt]),x=l.useCallback(()=>{if(!c||!u)return;const j=u.clips.find(T=>T.id===t),y=j?.startTime||0,w=j?.duration||5,S=c.createAdjustmentLayer(u.id,y,{duration:w,name:`Adjustment ${p.length+1}`});n(S.id),F.setState(T=>({project:{...T.project,modifiedAt:Date.now()}}))},[c,u,t,p.length]),h=l.useCallback(j=>{c&&(c.deleteLayer(j),r===j&&n(null),F.setState(y=>({project:{...y.project,modifiedAt:Date.now()}})))},[c,r]),f=l.useCallback((j,y)=>{c&&(c.setEnabled(j,y),F.setState(w=>({project:{...w.project,modifiedAt:Date.now()}})))},[c]),v=l.useCallback((j,y)=>{c&&(c.setOpacity(j,y),F.setState(w=>({project:{...w.project,modifiedAt:Date.now()}})))},[c]),A=l.useCallback((j,y)=>{c&&(c.setBlendMode(j,y),o(!1),F.setState(w=>({project:{...w.project,modifiedAt:Date.now()}})))},[c]),g=l.useCallback((j,y)=>{if(!c)return;const w=cd.find(S=>S.id===y);w&&(c.addEffect(j,{id:`effect_${Date.now()}`,...w.effect}),F.setState(S=>({project:{...S.project,modifiedAt:Date.now()}})))},[c]),k=l.useCallback((j,y)=>{c&&(c.removeEffect(j,y),F.setState(w=>({project:{...w.project,modifiedAt:Date.now()}})))},[c]),N=l.useCallback(j=>{if(!c)return;const y=c.duplicateLayer(j);y&&n(y.id),F.setState(w=>({project:{...w.project,modifiedAt:Date.now()}}))},[c]),b=j=>{const y=r===j.id;return e.jsxs("div",{className:"bg-background-tertiary rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 cursor-pointer hover:bg-background-secondary transition-colors",onClick:()=>n(y?null:j.id),children:[e.jsx(bs,{size:12,className:`text-text-muted transition-transform ${y?"rotate-90":""}`}),e.jsx(Os,{size:12,className:"text-indigo-400"}),e.jsx("span",{className:"flex-1 text-[10px] text-text-primary truncate",children:j.name}),e.jsx("button",{onClick:w=>{w.stopPropagation(),f(j.id,!j.enabled)},className:`p-1 rounded transition-colors ${j.enabled?"text-text-primary":"text-text-muted opacity-50"}`,children:j.enabled?e.jsx($s,{size:12}):e.jsx(Xs,{size:12})})]}),y&&e.jsxs("div",{className:"px-2 pb-2 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Opacity"}),e.jsxs("span",{className:"text-[10px] font-mono text-text-primary",children:[Math.round(j.opacity*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[j.opacity*100],onValueChange:w=>v(j.id,w[0]/100)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-[10px] text-text-secondary flex items-center gap-1",children:[e.jsx(za,{size:10}),"Blend Mode"]}),e.jsxs(Fn,{open:i,onOpenChange:o,children:[e.jsx(Ln,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between p-2 bg-background-secondary rounded text-[10px] text-text-primary hover:bg-background-tertiary transition-colors",children:[e.jsx("span",{children:dd.find(w=>w.id===j.blendMode)?.name||"Normal"}),e.jsx(qt,{size:10})]})}),e.jsx($n,{align:"start",sideOffset:4,className:"w-[var(--radix-popover-trigger-width)] min-w-[180px] p-0 bg-background-secondary border-border max-h-48 overflow-y-auto",children:dd.map(w=>e.jsx("button",{type:"button",onClick:()=>A(j.id,w.id),className:`w-full text-left px-3 py-1.5 text-[10px] hover:bg-background-tertiary transition-colors ${j.blendMode===w.id?"text-indigo-400 bg-indigo-500/10":"text-text-secondary"}`,children:w.name},w.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-[10px] text-text-secondary flex items-center gap-1",children:[e.jsx(bx,{size:10}),"Effects (",j.effects.length,")"]}),j.effects.length>0&&e.jsx("div",{className:"space-y-1",children:j.effects.map(w=>e.jsxs("div",{className:"flex items-center justify-between p-1.5 bg-background-secondary rounded",children:[e.jsx("span",{className:"text-[9px] text-text-primary capitalize",children:w.type}),e.jsx("button",{onClick:()=>k(j.id,w.id),className:"p-0.5 text-red-400 hover:bg-red-500/20 rounded transition-colors",children:e.jsx($t,{size:10})})]},w.id))}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:cd.slice(0,4).map(w=>e.jsxs("button",{onClick:()=>g(j.id,w.id),className:"p-1.5 text-[9px] text-text-secondary bg-background-secondary rounded hover:bg-indigo-500/10 hover:text-indigo-400 transition-colors",children:["+ ",w.name]},w.id))})]}),e.jsxs("div",{className:"flex gap-1 pt-2 border-t border-border",children:[e.jsxs("button",{onClick:()=>N(j.id),className:"flex-1 flex items-center justify-center gap-1 py-1.5 bg-background-secondary rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors",children:[e.jsx(dn,{size:10}),"Duplicate"]}),e.jsxs("button",{onClick:()=>h(j.id),className:"flex-1 flex items-center justify-center gap-1 py-1.5 bg-red-500/10 rounded text-[10px] text-red-400 hover:bg-red-500/20 transition-colors",children:[e.jsx($t,{size:10}),"Delete"]})]})]})]},j.id)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gradient-to-r from-indigo-500/20 to-violet-500/20 rounded-lg border border-indigo-500/30",children:[e.jsx(Os,{size:16,className:"text-indigo-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Adjustment Layers"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Non-destructive effects on clips below"})]})]}),e.jsxs("button",{onClick:x,disabled:!u,className:`w-full py-2.5 rounded-lg text-[11px] font-medium flex items-center justify-center gap-2 transition-colors ${u?"bg-indigo-500/20 border border-indigo-500/30 text-indigo-400 hover:bg-indigo-500/30":"bg-background-tertiary text-text-muted cursor-not-allowed"}`,children:[e.jsx(cs,{size:14}),"Add Adjustment Layer"]}),m.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("span",{className:"text-[10px] font-medium text-text-secondary",children:["Track Layers (",m.length,")"]}),e.jsx("div",{className:"space-y-1.5",children:m.map(b)})]}),p.length>m.length&&e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border",children:[e.jsx("span",{className:"text-[10px] font-medium text-text-secondary",children:"Other Layers"}),e.jsx("div",{className:"space-y-1.5",children:p.filter(j=>!m.some(y=>y.id===j.id)).map(b)})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsx("p",{className:"text-[9px] text-text-muted text-center",children:"Apply color, effects to all clips below"})})]})},Av={youtube:e.jsx(Er,{size:14}),tiktok:e.jsx(Zr,{size:14}),"instagram-reels":e.jsx(Zr,{size:14}),"instagram-feed":e.jsx(Gs,{size:14}),"instagram-stories":e.jsx(Zr,{size:14}),"youtube-shorts":e.jsx(Zr,{size:14}),facebook:e.jsx(Er,{size:14}),twitter:e.jsx(Er,{size:14}),linkedin:e.jsx(Er,{size:14})},Tv=({clipId:t,onReframeComplete:s})=>{const a=F(S=>S.updateSettings),[r,n]=l.useState(pg),[i,o]=l.useState(!1),[c,d]=l.useState(!1),[u,p]=l.useState(!1),[m,x]=l.useState(!1),[h,f]=l.useState(0),[v,A]=l.useState(""),[g,k]=l.useState("tiktok");l.useEffect(()=>{const S=mc();S&&p(S.isInitialized())},[t]);const N=l.useCallback(async()=>{o(!0);try{await hg().initialize((T,C)=>{f(T),A(C)}),p(!0)}catch(S){console.error("Failed to initialize auto-reframe:",S)}finally{o(!1)}},[]),b=l.useCallback(S=>{n(T=>({...T,...S}))},[]),j=l.useCallback(S=>{k(S);const T=oi[S],C=Object.entries(Jr).find(([,M])=>Math.abs(M.ratio-T.ratio)<.01);C&&b({targetAspectRatio:C[0]})},[b]),y=l.useCallback(S=>{k(null),b({targetAspectRatio:S})},[b]),w=l.useCallback(async()=>{d(!0),f(0),A("Initializing...");try{if(u||(A("Loading AI engine..."),f(10),await N()),!mc())throw new Error("Engine not available");A("Configuring reframe settings..."),f(30),await new Promise(z=>setTimeout(z,300)),A("Applying smart crop configuration..."),f(60);const T=Jr[r.targetAspectRatio];await new Promise(z=>setTimeout(z,300)),A("Updating project settings..."),f(80),await a({width:T.width,height:T.height}),A("Finalizing..."),f(90),await new Promise(z=>setTimeout(z,200)),f(100),A("Complete!"),x(!0);const C={keyframes:[],outputWidth:T.width,outputHeight:T.height,success:!0,message:`Configured for ${T.name} (${T.width}x${T.height})`};s?.(C);const M=g?oi[g].name:r.targetAspectRatio;Fe.success("Auto Reframe Applied",`Project resized to ${M} (${T.width}x${T.height})`)}catch(S){console.error("Auto-reframe failed:",S),Fe.error("Auto Reframe Failed",S instanceof Error?S.message:"Unknown error"),x(!1)}finally{d(!1)}},[u,N,r,g,s,a]);return e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-2",children:"Platform Presets"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:Object.keys(oi).map(S=>e.jsxs("button",{onClick:()=>j(S),className:`flex items-center gap-1 p-2 rounded text-[9px] transition-colors ${g===S?"bg-primary/20 border border-primary text-text-primary":"bg-background-secondary hover:bg-background-primary border border-transparent text-text-secondary"}`,children:[Av[S],e.jsx("span",{className:"truncate",children:oi[S].name})]},S))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-2",children:"Aspect Ratio"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:Object.keys(Jr).filter(S=>S!=="custom").map(S=>e.jsx("button",{onClick:()=>y(S),className:`p-2 rounded text-[9px] transition-colors ${r.targetAspectRatio===S&&!g?"bg-primary/20 border border-primary text-text-primary":"bg-background-secondary hover:bg-background-primary border border-transparent text-text-secondary"}`,children:S},S))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Tracking Speed"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[Math.round(r.trackingSpeed*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[r.trackingSpeed*100],onValueChange:S=>b({trackingSpeed:S[0]/100})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Smoothing"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[Math.round(r.smoothing*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[r.smoothing*100],onValueChange:S=>b({smoothing:S[0]/100})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Center Bias"}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:[Math.round(r.centerBias*100),"%"]})]}),e.jsx(st,{min:0,max:100,step:1,value:[r.centerBias*100],onValueChange:S=>b({centerBias:S[0]/100})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Follow Subject"}),e.jsx("button",{onClick:()=>b({followSubject:!r.followSubject}),className:`w-8 h-4 rounded-full transition-colors ${r.followSubject?"bg-primary":"bg-background-secondary"}`,children:e.jsx("div",{className:`w-3 h-3 rounded-full bg-white transition-transform ${r.followSubject?"translate-x-4":"translate-x-0.5"}`})})]}),c&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[9px] text-text-muted",children:v}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[h,"%"]})]}),e.jsx("div",{className:"h-1 bg-background-secondary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${h}%`}})})]}),e.jsx("button",{onClick:w,disabled:i||c,className:"w-full py-2 rounded text-[11px] font-medium transition-colors flex items-center justify-center gap-2 bg-primary hover:bg-primary-hover disabled:bg-primary/50 text-white",children:i||c?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"}),i?"Initializing...":"Analyzing..."]}):m?e.jsxs(e.Fragment,{children:[e.jsx(ul,{size:14}),"Applied - Click to Reanalyze"]}):e.jsxs(e.Fragment,{children:[e.jsx(As,{size:14}),"Analyze & Reframe"]})}),e.jsxs("div",{className:"text-[9px] text-text-muted text-center",children:["Output:"," ",Jr[r.targetAspectRatio].width," x"," ",Jr[r.targetAspectRatio].height]})]})})},Mv=({clipId:t,clipDuration:s,clipStartTime:a,effects:r,onAddEffect:n,onUpdateEffect:i,onRemoveEffect:o,onToggleEffect:c,onUpdateTiming:d,onPreviewEffect:u})=>{const[p,m]=l.useState(new Set),[x,h]=l.useState(""),f=l.useCallback(b=>{m(j=>{const y=new Set(j);return y.has(b)?y.delete(b):y.add(b),y})},[]),v=l.useCallback(()=>{if(!x)return;const b=`particle-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,j=yg(x,b,t,a,s);j&&(n(j),m(y=>new Set(y).add(b)))},[x,t,a,s,n]),A=l.useCallback((b,j,y)=>{i(b,{[j]:y})},[i]),g=l.useCallback((b,j,y)=>{const w=a+y;d(b,w,j.duration)},[a,d]),k=l.useCallback((b,j,y)=>{d(b,j.startTime,y)},[d]),N=pu.reduce((b,j)=>(b[j.type]||(b[j.type]=[]),b[j.type].push(j),b),{});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ot,{value:x,onValueChange:h,children:[e.jsx(lt,{className:"flex-1 h-8 text-xs min-w-0 [&>span]:truncate",children:e.jsx(ct,{placeholder:"Select effect preset..."})}),e.jsx(dt,{children:Object.entries(N).map(([b,j])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-text-muted uppercase tracking-wider",children:b}),j.map(y=>e.jsx(ge,{value:y.id,textValue:y.name,children:y.name},y.id))]},b))})]}),e.jsxs(zt,{variant:"default",size:"sm",onClick:v,disabled:!x,className:"h-8 px-3",children:[e.jsx(cs,{size:14,className:"mr-1"}),"Add"]})]}),r.length===0?e.jsxs("div",{className:"text-center py-6 text-text-muted text-xs",children:[e.jsx(gs,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No particle effects added"}),e.jsx("p",{className:"mt-1 text-[10px]",children:"Select a preset above to add effects"})]}):e.jsx(ia,{className:"max-h-[400px]",children:e.jsx("div",{className:"space-y-2 pr-2",children:r.map(b=>{const j=b.startTime-a;return e.jsxs("div",{className:"bg-background-tertiary rounded-lg border border-border overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx("button",{onClick:()=>f(b.id),className:"p-0.5 rounded hover:bg-background-elevated text-text-muted",children:p.has(b.id)?e.jsx(qt,{size:14}):e.jsx(bs,{size:14})}),e.jsx("span",{className:"flex-1 text-xs font-medium text-text-primary capitalize",children:b.type}),u&&e.jsx("button",{onClick:()=>u(b.id),className:"p-1 rounded hover:bg-background-elevated text-text-muted hover:text-primary transition-colors",title:"Preview effect",children:e.jsx(As,{size:12})}),e.jsx("button",{onClick:()=>c(b.id,!b.enabled),className:`p-1 rounded transition-colors ${b.enabled?"text-primary hover:bg-primary/20":"text-text-muted hover:bg-background-elevated"}`,title:b.enabled?"Disable":"Enable",children:b.enabled?e.jsx($s,{size:12}):e.jsx(Xs,{size:12})}),e.jsx("button",{onClick:()=>o(b.id),className:"p-1 rounded hover:bg-red-500/20 text-text-muted hover:text-red-400 transition-colors",title:"Remove effect",children:e.jsx($t,{size:12})})]}),p.has(b.id)&&e.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border/50 pt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(kt,{className:"text-[10px] text-text-muted mb-1",children:"Start Time (s)"}),e.jsx(ts,{type:"number",value:j.toFixed(1),onChange:y=>{const w=parseFloat(y.target.value);!isNaN(w)&&w>=0&&w{const w=parseFloat(y.target.value);!isNaN(w)&&w>=.1&&k(b.id,b,w)},className:"h-7 text-xs",step:.1,min:.1})]})]}),e.jsxs(Wl,{children:[e.jsxs(ql,{className:"flex items-center gap-1 text-[10px] text-text-muted hover:text-text-primary",children:[e.jsx(bs,{size:10,className:"transition-transform data-[state=open]:rotate-90"}),"Particle Settings"]}),e.jsxs(Ql,{className:"pt-2 space-y-3",children:[e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Particle Count: ",b.config.particleCount]}),e.jsx(st,{value:[b.config.particleCount],onValueChange:([y])=>A(b.id,"particleCount",y),min:10,max:500,step:10,className:"w-full"})]}),e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Speed: ",b.config.speed]}),e.jsx(st,{value:[b.config.speed],onValueChange:([y])=>A(b.id,"speed",y),min:10,max:500,step:10,className:"w-full"})]}),e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Gravity: ",b.config.gravity]}),e.jsx(st,{value:[b.config.gravity],onValueChange:([y])=>A(b.id,"gravity",y),min:-500,max:500,step:10,className:"w-full"})]}),e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Emission Rate: ",b.config.emissionRate]}),e.jsx(st,{value:[b.config.emissionRate],onValueChange:([y])=>A(b.id,"emissionRate",y),min:1,max:200,step:1,className:"w-full"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Min Size: ",b.config.size.min]}),e.jsx(st,{value:[b.config.size.min],onValueChange:([y])=>A(b.id,"size",{...b.config.size,min:y}),min:1,max:20,step:1,className:"w-full"})]}),e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Max Size: ",b.config.size.max]}),e.jsx(st,{value:[b.config.size.max],onValueChange:([y])=>A(b.id,"size",{...b.config.size,max:y}),min:1,max:30,step:1,className:"w-full"})]})]}),e.jsxs("div",{children:[e.jsxs(kt,{className:"text-[10px] text-text-muted mb-1",children:["Turbulence: ",b.config.turbulence]}),e.jsx(st,{value:[b.config.turbulence],onValueChange:([y])=>A(b.id,"turbulence",y),min:0,max:100,step:5,className:"w-full"})]}),e.jsxs("div",{children:[e.jsx(kt,{className:"text-[10px] text-text-muted mb-1",children:"Blend Mode"}),e.jsxs(ot,{value:b.config.blendMode,onValueChange:y=>A(b.id,"blendMode",y),children:[e.jsx(lt,{className:"h-7 text-xs",children:e.jsx(ct,{})}),e.jsxs(dt,{children:[e.jsx(ge,{value:"normal",children:"Normal"}),e.jsx(ge,{value:"add",children:"Additive"}),e.jsx(ge,{value:"multiply",children:"Multiply"}),e.jsx(ge,{value:"screen",children:"Screen"})]})]})]})]})]}),e.jsxs(Wl,{children:[e.jsxs(ql,{className:"flex items-center gap-1 text-[10px] text-text-muted hover:text-text-primary",children:[e.jsx(bs,{size:10,className:"transition-transform data-[state=open]:rotate-90"}),"Colors (",b.config.colors.length,")"]}),e.jsx(Ql,{className:"pt-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[b.config.colors.map((y,w)=>e.jsx(Ev,{color:y,onChange:S=>{const T=[...b.config.colors];T[w]=S,A(b.id,"colors",T)},onRemove:b.config.colors.length>1?()=>{const S=b.config.colors.filter((T,C)=>C!==w);A(b.id,"colors",S)}:void 0},w)),e.jsx("button",{onClick:()=>{const y=[...b.config.colors,"#ffffff"];A(b.id,"colors",y)},className:"w-6 h-6 rounded border border-dashed border-border flex items-center justify-center text-text-muted hover:text-text-primary hover:border-primary transition-colors",children:e.jsx(cs,{size:12})})]})})]})]})]},b.id)})})})]})},Ev=({color:t,onChange:s,onRemove:a})=>{const[r,n]=l.useState(!1),i=l.useRef(null);return e.jsxs(Fn,{open:r,onOpenChange:n,children:[e.jsx(Ln,{asChild:!0,children:e.jsx("button",{className:"w-6 h-6 rounded border border-border cursor-pointer hover:ring-2 hover:ring-primary/50 transition-all",style:{backgroundColor:t}})}),e.jsx($n,{side:"top",align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:i,type:"color",value:t,onChange:o=>s(o.target.value),className:"w-32 h-24 cursor-pointer border-0 p-0"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{type:"text",value:t,onChange:o=>{const c=o.target.value;/^#[0-9A-Fa-f]{6}$/.test(c)&&s(c)},className:"h-7 text-xs font-mono flex-1",placeholder:"#ffffff"}),a&&e.jsx("button",{onClick:()=>{a(),n(!1)},className:"p-1.5 rounded hover:bg-red-500/20 text-text-muted hover:text-red-400 transition-colors",title:"Remove color",children:e.jsx($t,{size:12})})]})]})})]})},Rv=({clipId:t})=>{const s=Ct(m=>m.getTitleEngine),a=F(m=>m.updateTextBehindSubject),r=F(m=>m.project.modifiedAt),[n,i]=l.useState(!1),[o,c]=l.useState(!1),[d,u]=l.useState(null);l.useEffect(()=>{const x=s()?.getTextClip(t);c(x?.behindSubject??!1)},[t,s,r]);const p=l.useCallback(async m=>{if(!s())return;if(u(null),c(m),!m){a(t,!1);return}const h=Td();if(!h.isInitialized()){i(!0);try{await h.initialize()}catch{u("Failed to load AI model. Check your connection."),a(t,!1),c(!1),i(!1);return}i(!1)}a(t,!0)},[t,s,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[11px] text-text-primary",children:"Place Behind Subject"}),e.jsx("p",{className:"text-[9px] text-text-muted",children:"Text appears behind people in the video"})]}),n?e.jsx(ds,{size:14,className:"animate-spin text-primary"}):e.jsx(oa,{checked:o,onCheckedChange:p})]}),n&&e.jsx("p",{className:"text-[9px] text-text-muted",children:"Loading AI model..."}),d&&e.jsx("p",{className:"text-[9px] text-red-400",children:d})]})},Pv=({clipId:t,showColorGrading:s})=>e.jsx(e.Fragment,{children:s&&e.jsx(e.Fragment,{children:e.jsx(pt,{title:"Color Grading",sectionId:"color-grading",defaultOpen:!1,children:e.jsx(a1,{clipId:t})})})}),zv=({clipId:t,clipType:s,showAudioEffects:a,noiseReductionSectionTitle:r,selectedNoiseReductionEffect:n})=>e.jsxs(e.Fragment,{children:[a&&e.jsx(pt,{title:"Auto Cut Silence",sectionId:"auto-cut-silence",defaultOpen:!1,children:e.jsx(X1,{clipId:t})}),s==="audio"&&e.jsx(pt,{title:"Beat Sync",sectionId:"beat-sync",defaultOpen:!1,children:e.jsx(k1,{clipId:t})}),a&&e.jsx(pt,{title:r,sectionId:"background-noise-removal",defaultOpen:!!n,children:e.jsx(Ly,{clipId:t})}),a&&e.jsx(e.Fragment,{children:e.jsx(pt,{title:"Audio Effects",sectionId:"audio-effects",defaultOpen:!1,children:e.jsx(O1,{clipId:t})})}),a&&e.jsx(pt,{title:"Audio Ducking",sectionId:"audio-ducking",defaultOpen:!1,children:e.jsx(Y1,{clipId:t})})]}),Dv=({clipId:t,clipType:s,selectedClip:a,showTransformControls:r,showVideoControls:n,transform:i,handleTransformChange:o})=>e.jsxs(e.Fragment,{children:[r&&e.jsx(e.Fragment,{children:e.jsx(pt,{title:"Transform",sectionId:"transform",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(ht,{label:"Position X",value:i.position.x,onChange:c=>o({position:{...i.position,x:c}}),min:-1920,max:1920,step:1,unit:"px",defaultValue:0}),e.jsx(ht,{label:"Position Y",value:i.position.y,onChange:c=>o({position:{...i.position,y:c}}),min:-1080,max:1080,step:1,unit:"px",defaultValue:0}),e.jsx(ht,{label:"Scale X",value:i.scale.x*100,onChange:c=>o({scale:{...i.scale,x:c/100}}),min:0,max:300,step:1,unit:"%",defaultValue:100}),e.jsx(ht,{label:"Scale Y",value:i.scale.y*100,onChange:c=>o({scale:{...i.scale,y:c/100}}),min:0,max:300,step:1,unit:"%",defaultValue:100}),e.jsx(ht,{label:"Rotation",value:i.rotation,onChange:c=>o({rotation:c}),min:-180,max:180,step:1,unit:"°",defaultValue:0}),e.jsx(ht,{label:"Opacity",value:i.opacity*100,onChange:c=>o({opacity:c/100}),min:0,max:100,step:1,unit:"%",defaultValue:100}),e.jsx(ht,{label:"Border Radius",value:i.borderRadius||0,onChange:c=>o({borderRadius:c}),min:0,max:200,step:1,unit:"px",defaultValue:0}),(s==="image"||s==="video")&&e.jsxs("div",{className:"space-y-1 pt-2 border-t border-border",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Fit Mode"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:["contain","cover","stretch"].map(c=>{const d=!i.fitMode||i.fitMode==="none"?"contain":i.fitMode;return e.jsx("button",{onClick:()=>o({fitMode:c}),className:`py-1.5 rounded text-[9px] capitalize transition-colors ${d===c?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,children:c==="contain"?"Fit":c==="cover"?"Fill":c},c)})})]})]})})}),n&&a&&!a.mediaId.startsWith("text-")&&!a.mediaId.startsWith("shape-")&&!a.mediaId.startsWith("svg-")&&!a.mediaId.startsWith("sticker-")&&e.jsx(pt,{title:"Crop",sectionId:"crop",defaultOpen:!1,children:e.jsx(Vy,{clip:a})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Alignment",sectionId:"alignment",defaultOpen:!1,children:e.jsx(M1,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Blending",sectionId:"blending",defaultOpen:!1,children:e.jsx(nv,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"3D Transforms",sectionId:"transform-3d",defaultOpen:!1,children:e.jsx(iv,{clipId:t})})]}),Iv=({showVideoControls:t,selectedClip:s})=>e.jsxs(e.Fragment,{children:[t&&s&&!s.mediaId.startsWith("text-")&&!s.mediaId.startsWith("shape-")&&!s.mediaId.startsWith("svg-")&&!s.mediaId.startsWith("sticker-")&&e.jsx(e.Fragment,{children:e.jsx(pt,{title:"Speed & Direction",sectionId:"speed",defaultOpen:!0,children:e.jsx(Ky,{clip:s})})}),t&&s&&!s.mediaId.startsWith("text-")&&!s.mediaId.startsWith("shape-")&&!s.mediaId.startsWith("svg-")&&!s.mediaId.startsWith("sticker-")&&e.jsx(pt,{title:"Stabilization",sectionId:"stabilization",defaultOpen:!1,children:e.jsx(Yy,{clip:s})}),t&&s&&!s.mediaId.startsWith("text-")&&!s.mediaId.startsWith("shape-")&&!s.mediaId.startsWith("svg-")&&!s.mediaId.startsWith("sticker-")&&e.jsx(pt,{title:"Speed Curves",sectionId:"speed-curves",defaultOpen:!1,children:e.jsx(Ty,{clip:s})})]}),Bv=({clipId:t,clipType:s,showTextSection:a})=>e.jsxs(e.Fragment,{children:[e.jsx(pt,{title:"Keyframes",sectionId:"keyframes",children:e.jsx(rv,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Transitions",sectionId:"transitions",defaultOpen:!1,children:e.jsx(ev,{clipId:t})}),(s==="video"||s==="image"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Motion Presets",sectionId:"motion-presets",defaultOpen:!1,children:e.jsx(vv,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Motion Path",sectionId:"motion-path",defaultOpen:!1,children:e.jsx(jv,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&e.jsx(pt,{title:"Emphasis Animation",sectionId:"emphasis-animation",defaultOpen:!1,children:e.jsx(wv,{clipId:t})}),a&&e.jsx(pt,{title:"Text Animation",sectionId:"text-animation",defaultOpen:!1,children:e.jsx(d1,{clipId:t})})]}),Fv=({clipId:t,showTextSection:s,showShapeSection:a,showSVGSection:r})=>e.jsxs(e.Fragment,{children:[s&&e.jsx(pt,{title:"Text Properties",sectionId:"text-properties",children:e.jsx(i1,{clipId:t})}),a&&e.jsx(pt,{title:"Shape Properties",sectionId:"shape-properties",children:e.jsx(S1,{clipId:t})}),r&&e.jsx(pt,{title:"SVG Properties",children:e.jsx(T1,{clipId:t})})]}),Lv=({clipId:t,clipDuration:s,clipStartTime:a})=>{const[r,n]=_e.useState(0),i=_e.useMemo(()=>ol(),[]),o=_e.useMemo(()=>i.getEffectsForClip(t),[t,i,r]),c=_e.useCallback(x=>{i.addEffect(x),n(h=>h+1)},[i]),d=_e.useCallback((x,h)=>{i.updateEffect(x,h),n(f=>f+1)},[i]),u=_e.useCallback(x=>{i.removeEffect(x),n(h=>h+1)},[i]),p=_e.useCallback((x,h)=>{i.toggleEffect(x,h),n(f=>f+1)},[i]),m=_e.useCallback((x,h,f)=>{i.updateEffectTiming(x,h,f),n(v=>v+1)},[i]);return e.jsx(Mv,{clipId:t,clipDuration:s,clipStartTime:a,effects:o,onAddEffect:c,onUpdateEffect:d,onRemoveEffect:u,onToggleEffect:p,onUpdateTiming:m})},$v=({clipId:t,clipType:s,selectedClip:a,selectedTimelineClip:r,showVideoControls:n,showVideoEffects:i,showTextSection:o,appliedEditingTemplates:c,getEditingTemplate:d,removeEditingTemplateApplication:u,expandedRecipeApplicationId:p,setExpandedRecipeApplicationId:m,recipeControlValues:x,setRecipeControlValues:h,handleRecipeControlChange:f,handleToggleRecipeControls:v,handleResetRecipeControls:A,handleUpdateRecipeControls:g,chromaKeyEnabled:k,keyColor:N,tolerance:b,handleChromaKeyToggle:j,handleKeyColorChange:y,handleToleranceChange:w})=>e.jsxs(e.Fragment,{children:[n&&r&&(c.length>0||r.effects&&r.effects.length>0)&&e.jsx(pt,{title:`Applied (${c.length+(r.effects?.filter(S=>!S.metadata?.templateSource).length||0)})`,sectionId:"applied-effects",defaultOpen:!0,children:e.jsxs("div",{className:"space-y-2",children:[c.map(S=>{const T=d(S.templateId),C=!!T?.controls?.length,M=p===S.applicationId,z=T?x[S.applicationId]||Ei(T,S.controlValues):void 0;return e.jsxs("div",{className:"rounded-lg border border-border bg-background-tertiary/70 px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[e.jsx(gs,{size:11,className:"text-primary shrink-0"}),e.jsx("p",{className:"truncate text-[11px] font-medium text-text-primary",children:S.name}),e.jsx("span",{className:"text-[9px] text-text-muted capitalize shrink-0",children:S.category?.replace(/-/g," ")||"recipe"})]}),e.jsxs("div",{className:"flex shrink-0 gap-1",children:[C&&e.jsx("button",{onClick:()=>v(S.applicationId,S.templateId,S.controlValues),className:`h-6 px-1.5 rounded text-[9px] font-medium transition-colors ${M?"bg-primary/15 text-primary":"text-text-muted hover:text-text-primary"}`,children:"Edit"}),e.jsx("button",{onClick:()=>{if(!u(r.id,S.applicationId)){Fe.error("Could not remove recipe","The recipe could not be removed from this clip.");return}h(B=>{const O={...B};return delete O[S.applicationId],O}),p===S.applicationId&&m(null)},className:"h-6 px-1.5 rounded text-text-muted hover:text-red-400 transition-colors",children:e.jsx($t,{size:11})})]})]}),M&&T&&z&&e.jsxs("div",{className:"mt-2 space-y-3 rounded-lg border border-border/80 bg-background-secondary/80 p-2.5",children:[e.jsx(bu,{template:T,values:z,onChange:(L,B)=>f(S.applicationId,L,B)}),e.jsxs("div",{className:"flex justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>A(S.applicationId,S.templateId,S.controlValues),className:"h-6 px-2.5 rounded border border-border text-[9px] font-medium text-text-secondary hover:text-text-primary transition-colors",children:"Reset"}),e.jsx("button",{onClick:()=>g(S.applicationId,S.templateId,S.controlValues),className:"h-6 px-2.5 rounded bg-primary text-[9px] font-semibold text-black hover:bg-primary/85 transition-colors",children:"Update"})]})]})]},S.applicationId)}),r.effects?.filter(S=>!S.metadata?.templateSource).map(S=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-border bg-background-tertiary/70 px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ks,{size:11,className:"text-amber-400 shrink-0"}),e.jsx("p",{className:"truncate text-[11px] font-medium text-text-primary capitalize",children:S.type.replace(/-/g," ")})]}),e.jsx("span",{className:`text-[9px] font-medium ${S.enabled!==!1?"text-green-400":"text-text-muted"}`,children:S.enabled!==!1?"On":"Off"})]},S.id))]})}),s==="video"&&e.jsx(pt,{title:"Background Removal",sectionId:"background-removal",defaultOpen:!1,children:e.jsx(_y,{clipId:t})}),(s==="video"||s==="image"||s==="text"||s==="shape"||s==="svg"||s==="sticker")&&a&&e.jsx(pt,{title:"Particle Effects",sectionId:"particle-effects",defaultOpen:!1,children:e.jsx(Lv,{clipId:t,clipDuration:a.duration,clipStartTime:a.startTime})}),n&&e.jsx(pt,{title:"Chroma Key (Green Screen)",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Enable"}),e.jsx(oa,{checked:k,onCheckedChange:j})]}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Key Color"}),e.jsx("input",{type:"color",value:N,onChange:S=>y(S.target.value),className:"w-8 h-6 rounded border border-border cursor-pointer"})]}),e.jsx(ht,{label:"Tolerance",value:b,onChange:w,unit:"%"})]})]})}),n&&e.jsx(pt,{title:"Motion Tracking",sectionId:"motion-tracking",children:e.jsx(Nv,{clipId:t})}),i&&e.jsx(pt,{title:"Video Effects",sectionId:"video-effects",children:e.jsx(by,{clipId:t})}),i&&e.jsx(pt,{title:"Green Screen",sectionId:"green-screen",defaultOpen:!1,children:e.jsx(wy,{clipId:t})}),n&&e.jsx(pt,{title:"Picture-in-Picture",sectionId:"pip",defaultOpen:!1,children:e.jsx(Ey,{clipId:t})}),n&&e.jsx(pt,{title:"Masking",sectionId:"masking",defaultOpen:!1,children:e.jsx(Cy,{clipId:t})}),n&&e.jsx(pt,{title:"Nested Sequences",defaultOpen:!1,children:e.jsx(Cv,{clipId:t})}),n&&e.jsx(pt,{title:"Adjustment Layers",defaultOpen:!1,children:e.jsx(Sv,{clipId:t})}),o&&e.jsx(pt,{title:"Text Behind Subject",sectionId:"text-behind-subject",defaultOpen:!1,children:e.jsx(Rv,{clipId:t})})]}),Ov=({onClose:t})=>{const s=F(b=>b.project),[a,r]=l.useState("beats"),[n,i]=l.useState(.5),[o,c]=l.useState(.5),[d,u]=l.useState(!1),[p,m]=l.useState(null),[x,h]=l.useState(null),f=l.useMemo(()=>{const b=[];for(const j of s.timeline.tracks)j.type==="audio"&&b.push(...j.clips);return b},[s.timeline.tracks]),v=l.useMemo(()=>{const b=[];for(const j of s.timeline.tracks)j.type==="video"&&b.push(...j.clips);return b},[s.timeline.tracks]),[A,g]=l.useState(f[0]?.id??""),k=l.useCallback(async()=>{const b=f.find(j=>j.id===A);if(!(!b||v.length===0)){u(!0),h(null),m(null);try{const j=gl();let y;const w=s.timeline.beatAnalysis;if(w&&w.sourceClipId===A)y={bpm:w.bpm,confidence:w.confidence,beats:s.timeline.beatMarkers?.map((M,z)=>({time:M.time,strength:M.strength,index:z}))??[],duration:s.timeline.duration,downbeats:s.timeline.beatMarkers?.filter(M=>M.isDownbeat).map(M=>M.time)??[]};else{const M=F.getState().project.mediaLibrary.items.find(z=>z.id===b.mediaId);if(!M?.blob){h("Audio file not loaded"),u(!1);return}y=await j.analyzeFromBlob(M.blob)}const S={cutMode:a,minClipDuration:o,maxClipDuration:10,sensitivity:n},C=Bf().generateCuts(y,v,S);m(C)}catch(j){h(j instanceof Error?j.message:"Failed to analyze audio")}finally{u(!1)}}},[f,A,v,a,n,o,s.timeline]),N=l.useCallback(()=>{if(!p||p.cuts.length===0)return;const b=[...s.timeline.tracks],j=b.findIndex(S=>S.type==="video");if(j===-1)return;const y=p.cuts.map((S,T)=>{const C=v.find(M=>M.id===S.sourceClipId);return C?{...C,id:`auto-edit-${Date.now()}-${T}`,startTime:S.startTime,duration:S.duration,inPoint:S.inPoint,outPoint:S.outPoint}:null}).filter(S=>S!==null),w={...b[j],clips:y};b[j]=w,F.setState(S=>({project:{...S.project,timeline:{...S.project.timeline,tracks:b,duration:p.totalDuration},modifiedAt:Date.now()}})),t()},[p,s.timeline.tracks,v,t]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-[11px] font-medium text-text-primary",children:"Beat-Synced Auto-Edit"})]})}),f.length===0?e.jsxs("div",{className:"text-center py-6 text-text-muted text-[10px]",children:[e.jsx(Ps,{size:24,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"Add an audio track to use auto-edit"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Audio Source"}),e.jsx("select",{value:A,onChange:b=>g(b.target.value),className:"w-full px-2 py-1.5 text-[10px] bg-background-tertiary border border-border rounded-lg text-text-primary",children:f.map(b=>e.jsxs("option",{value:b.id,children:[b.mediaId," (",b.duration.toFixed(1),"s)"]},b.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Cut Mode"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:["beats","downbeats","segments"].map(b=>e.jsx("button",{onClick:()=>r(b),className:`py-1.5 text-[9px] rounded-lg border transition-colors capitalize ${a===b?"bg-primary/20 border-primary text-primary":"bg-background-tertiary border-border text-text-secondary hover:border-primary/50"}`,children:b},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Sensitivity"}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[Math.round(n*100),"%"]})]}),e.jsx(st,{min:0,max:1,step:.05,value:[n],onValueChange:b=>i(b[0])})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("label",{className:"text-[10px] font-medium text-text-secondary",children:"Min Clip Duration"}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:[o.toFixed(1),"s"]})]}),e.jsx(st,{min:.1,max:3,step:.1,value:[o],onValueChange:b=>c(b[0])})]}),e.jsx("button",{onClick:k,disabled:d||v.length===0,className:"w-full flex items-center justify-center gap-2 py-2.5 text-[10px] font-medium bg-primary/20 border border-primary/30 text-primary rounded-lg hover:bg-primary/30 transition-colors disabled:opacity-50",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:12,className:"animate-spin"}),"Analyzing beats..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ks,{size:12}),"Generate Auto-Edit"]})}),x&&e.jsx("p",{className:"text-[9px] text-red-400",children:x}),p&&e.jsxs("div",{className:"space-y-2 p-2.5 bg-background-tertiary rounded-lg border border-border",children:[e.jsx("p",{className:"text-[10px] font-medium text-text-primary",children:"Preview"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[9px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Cuts: "}),e.jsx("span",{className:"text-text-primary",children:p.cuts.length})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Duration: "}),e.jsxs("span",{className:"text-text-primary",children:[p.totalDuration.toFixed(1),"s"]})]})]}),e.jsx("button",{onClick:N,className:"w-full py-2 text-[10px] font-medium bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors",children:"Apply Auto-Edit"})]})]})]})},_v={targetClipCount:5,minClipDuration:5,maxClipDuration:60,contentType:"video"},Vv="https://openreel-cloud.niiyeboah1996.workers.dev";async function Uv(t,s,a={},r){const n={..._v,...a};r?.("analyze",10,"Analyzing audio energy...");const i=Zf(t,s);r?.("analyze",30,"Preparing data for AI...");const o=i.segments.filter(u=>!u.isSilence).map(u=>({start:u.start,end:u.end,rmsDb:u.rmsDb,peakDb:u.peakDb}));r?.("ai",40,"Sending to AI for highlight detection...");const c=await fetch(`${Vv}/highlights`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({transcript:s.map(u=>({text:u.text,start:u.start,end:u.end})),energy:o,duration:i.duration,preferences:n})});if(!c.ok){const u=await c.json().catch(()=>({}));throw new Error(u.error||`API error: ${c.status}`)}r?.("ai",80,"Processing AI response...");const d=await c.json();return r?.("done",100,"Highlights ready"),d.highlights}const Kv=({clipId:t})=>{const[s,a]=l.useState([]),[r,n]=l.useState(new Set),[i,o]=l.useState(""),[c,d]=l.useState(0),[u,p]=l.useState(!1),[m,x]=l.useState(null),h=F(y=>y.project),f=F(y=>y.getMediaItem),v=Et(y=>y.setPlayheadPosition),[A,g]=l.useState({targetClipCount:5,minClipDuration:5,maxClipDuration:60,contentType:"video"}),k=l.useCallback(async()=>{if(!h)return;const y=h.timeline.tracks.flatMap(S=>S.clips).find(S=>S.id===t);if(!y)return;const w=f(y.mediaId);if(!w?.blob){x("Media not found or not loaded");return}p(!0),x(null),a([]);try{o("Transcribing audio..."),d(5);const C=(await(tg()||du({apiEndpoint:`${Id}/transcribe`})).transcribeClip(y,w,O=>d(Math.round(O.progress*20)))).flatMap(O=>O.words?O.words.map(G=>({text:G.text,start:G.startTime,end:G.endTime})):[{text:O.text,start:O.startTime,end:O.endTime}]);if(C.length===0)throw new Error("No transcript words found");o("Decoding audio..."),d(25);const M=await w.blob.arrayBuffer(),L=await new OfflineAudioContext(1,44100,44100).decodeAudioData(M),B=await Uv(L,C,A,(O,G)=>{o(O),d(25+Math.round(G*.75))});a(B),n(new Set(B.map((O,G)=>G)))}catch(S){x(S instanceof Error?S.message:"Analysis failed")}finally{p(!1),o(""),d(0)}},[t,h,f,A]),N=l.useCallback(y=>{v(y.start)},[v]),b=l.useCallback(y=>{n(w=>{const S=new Set(w);return S.has(y)?S.delete(y):S.add(y),S})},[]),j=y=>{const w=Math.floor(y/60),S=Math.floor(y%60);return`${w}:${S.toString().padStart(2,"0")}`};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Clips"}),e.jsx("input",{type:"number",min:1,max:20,value:A.targetClipCount,onChange:y=>g(w=>({...w,targetClipCount:parseInt(y.target.value)||5})),className:"w-12 px-1 py-0.5 text-[10px] bg-background-secondary border border-border rounded text-text-primary"}),e.jsx("label",{className:"text-[10px] text-text-secondary",children:"Max"}),e.jsx("input",{type:"number",min:1,max:300,value:A.maxClipDuration,onChange:y=>g(w=>({...w,maxClipDuration:parseInt(y.target.value)||60})),className:"w-12 px-1 py-0.5 text-[10px] bg-background-secondary border border-border rounded text-text-primary"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"s"})]}),e.jsx("button",{onClick:k,disabled:u,className:"w-full flex items-center justify-center gap-2 px-3 py-2 bg-primary hover:bg-primary/90 text-white rounded text-[11px] font-medium transition-colors disabled:opacity-50",children:u?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:14,className:"animate-spin"}),i," (",c,"%)"]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{size:14}),"Find Highlights"]})}),m&&e.jsx("p",{className:"text-[10px] text-red-400",children:m})]}),s.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[s.map((y,w)=>e.jsxs("div",{className:`p-2 rounded border transition-colors cursor-pointer ${r.has(w)?"bg-primary/10 border-primary/30":"bg-background-tertiary border-transparent hover:border-border"}`,onClick:()=>b(w),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold text-white ${y.score>=8?"bg-green-500":y.score>=5?"bg-yellow-500":"bg-gray-500"}`,children:y.score}),e.jsx("span",{className:"text-[10px] text-text-primary font-medium truncate max-w-[140px]",children:y.title})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),N(y)},className:"p-1 hover:bg-background-secondary rounded",children:e.jsx(As,{size:10,className:"text-text-muted"})}),r.has(w)&&e.jsx(is,{size:12,className:"text-primary"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[9px] text-text-muted",children:[j(y.start)," - ",j(y.end)]}),e.jsx("span",{className:"text-[9px] text-text-muted italic truncate max-w-[120px]",children:y.reason})]})]},w)),e.jsxs("button",{onClick:async()=>{const y=s.filter((P,_)=>r.has(_)).sort((P,_)=>P.start-_.start);if(y.length===0)return;const w=F.getState(),T=w.project.timeline.tracks.find(P=>P.clips.some(_=>_.id===t));if(!T)return;const C=T.clips.find(P=>P.id===t);if(!C)return;const M=C.startTime,z=C.inPoint,L=[];for(const P of y){const _=M+(P.start-z),se=M+(P.end-z);L.push(_),L.push(se)}const B=[...new Set(L)].sort((P,_)=>P-_).filter(P=>P>M&&PU.id===T.id);if(!se)break;const R=se.clips.find(U=>U.startTimeP);R&&await w.splitClip(R.id,P)}const G=F.getState().project.timeline.tracks.find(P=>P.id===T.id);if(!G)return;const V=G.clips.filter(P=>{const _=P.inPoint,se=P.inPoint+P.duration;return!y.some(R=>R.start_)});for(const P of V.sort((_,se)=>se.startTime-_.startTime))await F.getState().rippleDeleteClip(P.id)},disabled:r.size===0,className:"w-full flex items-center justify-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 text-white rounded text-[11px] font-medium transition-colors disabled:opacity-50",children:[e.jsx(is,{size:14}),"Apply ",r.size," Highlight",r.size!==1?"s":""]})]})]})},Yv=({clipId:t,clipType:s,showVideoControls:a,showAudioEffects:r,showVideoEffects:n,transcriptionProgress:i,isTranscribing:o,targetLanguage:c,setTargetLanguage:d,defaultAnimationStyle:u,setDefaultAnimationStyle:p,handleGenerateSubtitles:m,handleSRTImport:x,srtInputRef:h,handleRemoveBackground:f,handleEnhanceAudio:v,handleAutoColor:A,isEnhancingAudio:g,audioEnhanced:k,isApplyingSelectedClipEffect:N})=>e.jsxs(e.Fragment,{children:[s==="video"&&e.jsx(e.Fragment,{children:e.jsx(pt,{title:"AI Auto-Captions",sectionId:"auto-captions",defaultOpen:!1,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:h,type:"file",accept:".srt,text/srt,text/plain",onChange:x,className:"hidden"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-1",children:"Animation Style"}),e.jsxs(ot,{value:u,onValueChange:b=>p(b),disabled:o,children:[e.jsx(lt,{className:"w-full bg-background-secondary border-border text-text-primary text-[11px]",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:mu.map(b=>e.jsx(ge,{value:b,children:uu(b)},b))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-text-secondary block mb-1",children:"Target Language"}),e.jsxs(ot,{value:c,onValueChange:d,disabled:o,children:[e.jsx(lt,{className:"w-full bg-background-secondary border-border text-text-primary text-[11px]",children:e.jsx(ct,{placeholder:"Original (no translation)"})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"none",children:"Original (no translation)"}),e.jsxs(Rn,{children:[e.jsx(Pn,{className:"text-[10px]",children:"Translate to"}),e.jsx(ge,{value:"en",children:"English"}),e.jsx(ge,{value:"es",children:"Spanish"}),e.jsx(ge,{value:"fr",children:"French"}),e.jsx(ge,{value:"de",children:"German"}),e.jsx(ge,{value:"pt",children:"Portuguese"}),e.jsx(ge,{value:"it",children:"Italian"}),e.jsx(ge,{value:"nl",children:"Dutch"}),e.jsx(ge,{value:"ru",children:"Russian"}),e.jsx(ge,{value:"zh",children:"Chinese"}),e.jsx(ge,{value:"ja",children:"Japanese"}),e.jsx(ge,{value:"ko",children:"Korean"}),e.jsx(ge,{value:"ar",children:"Arabic"}),e.jsx(ge,{value:"hi",children:"Hindi"}),e.jsx(ge,{value:"tr",children:"Turkish"}),e.jsx(ge,{value:"pl",children:"Polish"}),e.jsx(ge,{value:"sv",children:"Swedish"})]})]})]})]}),i?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{size:12,className:"animate-spin text-primary"}),e.jsx("span",{className:"text-[10px] text-text-primary",children:i.message})]}),e.jsx("div",{className:"h-1.5 bg-background-tertiary rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full transition-all duration-300 ${i.phase==="error"?"bg-red-500":i.phase==="complete"?"bg-green-500":"bg-primary"}`,style:{width:`${i.progress}%`}})})]}):e.jsxs("button",{onClick:m,disabled:o,className:"w-full py-2 bg-primary hover:bg-primary/80 text-black rounded-lg text-[11px] font-medium transition-all flex items-center justify-center gap-2",children:[e.jsx(Xi,{size:14}),"Generate Captions"]}),e.jsxs("button",{onClick:()=>h.current?.click(),disabled:o,className:"w-full py-2 bg-background-tertiary hover:bg-background-tertiary/80 border border-border text-text-primary rounded-lg text-[11px] font-medium transition-all flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(ya,{size:13}),"Import SRT File"]})]})})}),s==="video"&&e.jsx(pt,{title:"Auto Reframe",sectionId:"auto-reframe",defaultOpen:!1,children:e.jsx(Tv,{clipId:t})}),r&&e.jsx(pt,{title:"Beat-Synced Auto-Edit",sectionId:"auto-edit",defaultOpen:!1,children:e.jsx(Ov,{onClose:()=>{}})}),r&&e.jsx(pt,{title:"AI Highlights",sectionId:"ai-highlights",defaultOpen:!1,children:e.jsx(Kv,{clipId:t})}),(a||r||n)&&e.jsxs("div",{className:"border border-primary/30 bg-primary/5 rounded-xl p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary mb-3",children:[e.jsx(ks,{size:14}),e.jsx("span",{className:"text-xs font-bold",children:"Quick Actions"})]}),e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx("button",{onClick:f,disabled:N,className:`w-full py-2 border rounded-lg text-[10px] transition-all ${N?"bg-background-tertiary border-border text-text-muted cursor-not-allowed":"bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"}`,children:"Remove Background"}),r&&e.jsx("button",{onClick:v,disabled:g||N,className:`w-full py-2 border rounded-lg text-[10px] transition-all flex items-center justify-center gap-1.5 ${k?"bg-green-500/20 border-green-500 text-green-400":g||N?"bg-background-tertiary border-border text-text-muted cursor-not-allowed":"bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"}`,children:g?e.jsxs(e.Fragment,{children:[e.jsx(ds,{size:12,className:"animate-spin"}),"Cleaning up..."]}):k?"✓ Noise Reduced":"Quick Dialogue Cleanup"}),n&&e.jsx("button",{onClick:A,disabled:N,className:`w-full py-2 border rounded-lg text-[10px] transition-all ${N?"bg-background-tertiary border-border text-text-muted cursor-not-allowed":"bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"}`,children:N?"Applying...":"Auto-Color"})]})]})]}),sr=new cp({width:1920,height:1080}),qr=pt,Xv=()=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 text-center opacity-50",children:[e.jsx("p",{className:"text-sm text-text-secondary mb-2",children:"No selection"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Select a clip to view its properties"})]}),Gv=()=>{const{getClip:t,getMediaItem:s,addSubtitle:a,importSRT:r,updateSubtitle:n,getSubtitle:i,getEditingTemplate:o,updateEditingTemplateApplication:c,removeEditingTemplateApplication:d}=F(),u=F(Y=>Y.project),{getSelectedClipIds:p}=vt(),m=vt(Y=>Y.selectedItems),x=vt(Y=>Y.effectApplicationClipId),h=vt(Y=>Y.startEffectApplication),f=vt(Y=>Y.finishEffectApplication),v=p(),A=Et(Y=>Y.pause),g=Et(Y=>Y.lockPlayback),k=Et(Y=>Y.unlockPlayback),N=Ct(Y=>Y.getTitleEngine),b=Ct(Y=>Y.getGraphicsEngine),[j,y]=l.useState(null),[w,S]=l.useState(!1),[T,C]=l.useState("none"),[M,z]=l.useState("word-highlight"),[L,B]=l.useState(null),[O,G]=l.useState({}),V=l.useRef(null),P=l.useRef(null),_=zd();l.useEffect(()=>{B(null)},[v.join("|")]);const se=l.useMemo(()=>m.find(je=>je.type==="subtitle")?.id||null,[m]),R=l.useMemo(()=>se&&i(se)||null,[se,i,u.timeline.subtitles]),U=l.useMemo(()=>v.length!==1?null:t(v[0])||null,[t,u.modifiedAt,v]),D=l.useMemo(()=>{if(v.length!==1)return null;const Y=v[0],je=t(Y);if(je)return je;const Ae=N()?.getTextClip(Y);if(Ae)return{id:Ae.id,mediaId:`text-${Ae.id}`,startTime:Ae.startTime,duration:Ae.duration,inPoint:0,outPoint:Ae.duration,transform:Ae.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},effects:[],text:Ae.text,trackId:Ae.trackId};const Be=b(),jt=Be?.getShapeClip(Y);if(jt)return{id:jt.id,mediaId:`shape-${jt.id}`,startTime:jt.startTime,duration:jt.duration,inPoint:0,outPoint:jt.duration,transform:jt.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},effects:[],shapeType:jt.shapeType,trackId:jt.trackId};const Gt=Be?.getSVGClip(Y);if(Gt)return{id:Gt.id,mediaId:`svg-${Gt.id}`,startTime:Gt.startTime,duration:Gt.duration,inPoint:0,outPoint:Gt.duration,transform:Gt.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},effects:[],svgContent:Gt.svgContent,trackId:Gt.trackId};const Kt=Be?.getStickerClip(Y);return Kt?{id:Kt.id,mediaId:`sticker-${Kt.id}`,startTime:Kt.startTime,duration:Kt.duration,inPoint:0,outPoint:Kt.duration,transform:Kt.transform||{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},effects:[],imageUrl:Kt.imageUrl,trackId:Kt.trackId}:null},[v,t,N,b,u.modifiedAt]),[X,K]=_e.useReducer(Y=>Y+1,0),ue=D?.id||"",Te=l.useMemo(()=>ue?sr.getSettings(ue):null,[ue,X]),pe=F(Y=>Y.updateClipTransform),fe=l.useCallback(Y=>{D&&pe(D.id,Y)},[D,pe]),We=l.useCallback(Y=>{D&&(Y?sr.enableChromaKey(D.id):sr.disableChromaKey(D.id),K())},[D]),Ze=l.useCallback(Y=>{if(!D)return;const je=Y.replace("#",""),Se=parseInt(je.substring(0,2),16)/255,Ae=parseInt(je.substring(2,4),16)/255,Be=parseInt(je.substring(4,6),16)/255;sr.setKeyColor(D.id,{r:Se,g:Ae,b:Be}),K()},[D]),at=l.useCallback(Y=>{D&&(sr.setTolerance(D.id,Y/100),K())},[D]),{addVideoEffect:de,updateVideoEffect:Ce,getAudioEffects:Ne,updateAudioEffect:Me,toggleAudioEffect:qe}=F(),[nt,rt]=l.useState(!1),[Pe,Ie]=l.useState(!1),Ee=x!==null&&x===D?.id,ae=l.useCallback(()=>new Promise(Y=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>Y())})}),[]),W=l.useCallback(async(Y,je,Se)=>{A(),g(je),h(Y,je);try{await ae(),await Se(),window.dispatchEvent(new CustomEvent("openreel:preview-invalidate")),await ae()}finally{f(),k()}},[f,g,A,h,k,ae]),Q=l.useCallback(()=>{D&&W(D.id,"Applying background removal",()=>{sr.enableChromaKey(D.id),sr.setKeyColor(D.id,{r:0,g:1,b:0}),sr.setTolerance(D.id,.35),K()})},[W,K,D]),be=l.useCallback(async()=>{if(D){rt(!0);try{await W(D.id,"Applying audio cleanup",async()=>{await jl();const Y=Us(),je={...ns,...Ra("speech").config},Se=Ne(D.id).find(Ae=>Ae.type==="noiseReduction");if(Se)Me(D.id,Se.id,je),qe(D.id,Se.id,!0);else{const Ae=Y.applyNoiseReduction(D.id,je);if(!Ae.success)throw new Error(Ae.error??"Failed to apply noise cleanup")}Ie(!0),setTimeout(()=>Ie(!1),2e3),Fe.success("Noise cleanup applied","Fine-tune or switch presets in Background Noise Removal."),K()})}catch(Y){console.error("Failed to enhance audio:",Y),Fe.error("Could not clean up audio",Y instanceof Error?Y.message:"Noise cleanup could not be applied to this clip.")}finally{rt(!1)}}},[W,D,K,Ne,qe,Me]),Oe=l.useCallback(async()=>{D&&await W(D.id,"Applying auto color",()=>{de(D.id,"saturation"),de(D.id,"contrast"),de(D.id,"brightness");const Y=F.getState().getVideoEffects(D.id),je=Y.find(Be=>Be.type==="saturation"),Se=Y.find(Be=>Be.type==="contrast"),Ae=Y.find(Be=>Be.type==="brightness");je&&Ce(D.id,je.id,{value:1.15}),Se&&Ce(D.id,Se.id,{value:1.1}),Ae&&Ce(D.id,Ae.id,{value:5})})},[de,W,D,Ce]),Ue=l.useCallback(async()=>{if(!D||w)return;const Y=s(D.mediaId);if(!Y){console.error("[Subtitles] No media item found for clip");return}S(!0),y({phase:"extracting",progress:0,message:"Preparing audio..."});try{const je=du({apiEndpoint:`${Id}/transcribe`,targetLanguage:T!=="none"?T:void 0}),Se=t(D.id);if(!Se)throw new Error("Could not find clip data");const Ae=await je.transcribeClip(Se,Y,y);for(const Be of Ae)a({...Be,animationStyle:M});y({phase:"complete",progress:100,message:`Added ${Ae.length} subtitles`}),setTimeout(()=>{y(null),S(!1)},2e3)}catch(je){console.error("[Subtitles] Transcription failed:",je),y({phase:"error",progress:0,message:je instanceof Error?je.message:"Transcription failed"}),setTimeout(()=>{y(null),S(!1)},3e3)}},[D,w,s,t,a,M,T]),Le=l.useCallback(async Y=>{const je=Y.target.files?.[0];if(je)try{const Se=await je.text(),Ae=await r(Se);Ae.success?Ae.errors.length>0?Fe.warning("SRT imported with warnings",`${Ae.errors.length} subtitle segment(s) were skipped.`):Fe.success("SRT imported","Subtitles were added to the Captions track."):Fe.error("SRT import failed",Ae.errors[0]||"No valid subtitles found.")}catch{Fe.error("SRT import failed","Could not read the selected subtitle file.")}finally{Y.target.value=""}},[r]),Ye=l.useCallback(async Y=>{const je=Y.target.files?.[0];if(!je||!R)return;const Se=await Rd(je);Se.success?(n(R.id,{style:{...R.style||{},fontFamily:Se.fontFamily}}),Fe.success("Custom font uploaded",`${Se.fontFamily} is ready to use.`)):Fe.error("Font upload failed",Se.error??"Unknown error."),Y.target.value=""},[R,n]),Ke={position:{x:0,y:0},scale:{x:1,y:1},rotation:0,opacity:1,anchor:{x:.5,y:.5},borderRadius:0},mt=D?.transform||Ke,Ge=Te?.enabled||!1,gt=Te?`#${Math.round(Te.keyColor.r*255).toString(16).padStart(2,"0")}${Math.round(Te.keyColor.g*255).toString(16).padStart(2,"0")}${Math.round(Te.keyColor.b*255).toString(16).padStart(2,"0")}`:"#00ff00",Ft=(Te?.tolerance||.3)*100,Qe=l.useMemo(()=>{if(!D)return null;if(D.mediaId.startsWith("text-"))return"text";if(D.mediaId.startsWith("shape-"))return"shape";if(D.mediaId.startsWith("svg-"))return"svg";if(D.mediaId.startsWith("sticker-")||D.mediaId.startsWith("emoji-"))return"sticker";const Y=u.timeline.tracks.find(Se=>Se.clips.some(Ae=>Ae.id===D.id));if(!Y)return"video";const je=u.mediaLibrary.items.find(Se=>Se.id===D.mediaId);return Y.type==="audio"?"audio":Y.type==="image"||je?.type==="image"?"image":"video"},[D,u.timeline.tracks,u.mediaLibrary.items]),Ds=Qe==="video"||Qe==="image",Cs=Qe==="video"||Qe==="image",Dt=Qe==="video"||Qe==="audio",us=Qe==="text",Ws=Qe==="shape",Qt=Qe==="svg",Lt=U?.audioEffects?.find(Y=>Y.type==="noiseReduction"),ca=Lt?Lt.enabled?"Background Noise Removal (Active)":"Background Noise Removal (Configured)":"Background Noise Removal",ms=U?.metadata?.appliedTemplates||[],da=l.useCallback((Y,je,Se)=>{G(Ae=>({...Ae,[Y]:{...Ae[Y]||{},[je]:Se}}))},[]),ss=l.useCallback((Y,je,Se)=>{const Ae=o(je);!Ae||!Ae.controls||Ae.controls.length===0||(B(Be=>Be===Y?null:Y),G(Be=>Be[Y]?Be:{...Be,[Y]:Ei(Ae,Se)}))},[o]),ps=l.useCallback((Y,je,Se)=>{const Ae=o(je);Ae&&G(Be=>({...Be,[Y]:Ei(Ae,Se)}))},[o]),Ss=l.useCallback((Y,je,Se)=>{if(!U)return;const Ae=o(je);if(!Ae){Fe.error("Recipe unavailable","This recipe definition is no longer available.");return}const Be=O[Y]||Ei(Ae,Se);if(!c(U.id,Y,Be)){Fe.error("Could not update recipe","The recipe controls could not be saved for this clip.");return}Fe.success("Recipe updated",`${Ae.name} was updated on this clip.`)},[o,O,U,c]),qs=Qe==="video"||Qe==="image",ua=Qe==="video"||Qe==="image"||Qe==="text"||Qe==="shape"||Qe==="svg"||Qe==="sticker",He=l.useMemo(()=>uy(Qe),[Qe]),$=l.useMemo(()=>Eu(Qe),[Qe]),ve=vt(Y=>Y.inspectorActiveTab),ye=vt(Y=>Y.setInspectorActiveTab),we=($.includes(ve)?ve:$[0])??"transform";return l.useEffect(()=>{$.length>0&&!$.includes(ve)&&ye($[0])},[$,ve,ye]),e.jsxs("div",{"data-tour":"inspector",className:"w-full min-w-0 bg-bg-1 flex flex-col h-full",children:[D&&He.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(py,{name:`${D.id.substring(0,20)}…`,durationSeconds:D.duration,typeLabel:Qe??"clip"}),e.jsx(my,{tabs:He,activeId:we,onSelect:Y=>ye(Y)})]}),e.jsx("div",{className:"overflow-y-auto flex-1 min-h-0 pb-3.5 custom-scrollbar",children:e.jsx("div",{className:"px-4 pt-3",children:D?e.jsxs(xy,{children:[e.jsx(er,{tab:"effects",active:we,children:e.jsx($v,{clipId:ue,clipType:Qe,selectedClip:D,selectedTimelineClip:U,showVideoControls:qs,showVideoEffects:Ds,showTextSection:us,appliedEditingTemplates:ms,getEditingTemplate:o,removeEditingTemplateApplication:d,expandedRecipeApplicationId:L,setExpandedRecipeApplicationId:B,recipeControlValues:O,setRecipeControlValues:G,handleRecipeControlChange:da,handleToggleRecipeControls:ss,handleResetRecipeControls:ps,handleUpdateRecipeControls:Ss,chromaKeyEnabled:Ge,keyColor:gt,tolerance:Ft,handleChromaKeyToggle:We,handleKeyColorChange:Ze,handleToleranceChange:at})}),e.jsx(er,{tab:"ai",active:we,children:e.jsx(Yv,{clipId:ue,clipType:Qe,showVideoControls:qs,showAudioEffects:Dt,showVideoEffects:Ds,transcriptionProgress:j,isTranscribing:w,targetLanguage:T,setTargetLanguage:C,defaultAnimationStyle:M,setDefaultAnimationStyle:z,handleGenerateSubtitles:Ue,handleSRTImport:Le,srtInputRef:V,handleRemoveBackground:Q,handleEnhanceAudio:be,handleAutoColor:Oe,isEnhancingAudio:nt,audioEnhanced:Pe,isApplyingSelectedClipEffect:Ee})}),e.jsx(er,{tab:"audio",active:we,children:e.jsx(zv,{clipId:ue,clipType:Qe,showAudioEffects:Dt,noiseReductionSectionTitle:ca,selectedNoiseReductionEffect:Lt})}),e.jsx(er,{tab:"transform",active:we,children:e.jsx(Dv,{clipId:ue,clipType:Qe,selectedClip:D,showTransformControls:ua,showVideoControls:qs,transform:mt,handleTransformChange:fe})}),e.jsx(er,{tab:"speed",active:we,children:e.jsx(Iv,{showVideoControls:qs,selectedClip:D})}),e.jsx(er,{tab:"animate",active:we,children:e.jsx(Bv,{clipId:ue,clipType:Qe,showTextSection:us})}),e.jsx(er,{tab:"color",active:we,children:e.jsx(Pv,{clipId:ue,showColorGrading:Cs})}),e.jsx(er,{tab:"style",active:we,children:e.jsx(Fv,{clipId:ue,showTextSection:us,showShapeSection:Ws,showSVGSection:Qt})})]},we):R?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 p-3 bg-primary/10 rounded-lg border border-primary/30",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Xi,{size:14,className:"text-primary"}),e.jsx("span",{className:"text-xs font-bold text-primary",children:"Subtitle"})]}),e.jsxs("p",{className:"text-[10px] text-text-muted",children:[R.startTime.toFixed(2),"s -"," ",R.endTime.toFixed(2),"s"]})]}),e.jsx(qr,{title:"Text Content",children:e.jsx("div",{className:"space-y-3",children:e.jsx("textarea",{value:R.text,onChange:Y=>n(R.id,{text:Y.target.value}),className:"w-full h-24 px-3 py-2 bg-background-tertiary border border-border rounded-lg text-xs text-text-primary resize-none focus:outline-none focus:border-primary",placeholder:"Enter subtitle text..."})})}),e.jsx(qr,{title:"Timing",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Start Time"}),e.jsx(ts,{type:"number",step:"0.1",value:R.startTime.toFixed(2),onChange:Y=>n(R.id,{startTime:parseFloat(Y.target.value)||0}),className:"w-20 h-7 text-[10px] bg-background-tertiary border-border text-text-primary text-right"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"End Time"}),e.jsx(ts,{type:"number",step:"0.1",value:R.endTime.toFixed(2),onChange:Y=>n(R.id,{endTime:parseFloat(Y.target.value)||0}),className:"w-20 h-7 text-[10px] bg-background-tertiary border-border text-text-primary text-right"})]})]})}),e.jsx(qr,{title:"Position",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["top","center","bottom"].map(Y=>e.jsx("button",{onClick:()=>n(R.id,{style:{...R.style||{},position:Y}}),className:`py-1.5 rounded text-[10px] capitalize transition-colors ${(R.style?.position||"bottom")===Y?"bg-primary text-white":"bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"}`,children:Y},Y))})}),e.jsx(qr,{title:"Animation",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Style"}),e.jsxs(ot,{value:R.animationStyle||"none",onValueChange:Y=>n(R.id,{animationStyle:Y}),children:[e.jsx(lt,{className:"w-auto min-w-[100px] bg-background-tertiary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsx(dt,{className:"bg-background-secondary border-border",children:mu.map(Y=>e.jsx(ge,{value:Y,children:uu(Y)},Y))})]})]}),e.jsxs("p",{className:"text-[9px] text-text-muted",children:[R.animationStyle==="karaoke"&&"Words fill with color as they're spoken",R.animationStyle==="word-highlight"&&"Current word is highlighted and scaled",R.animationStyle==="word-by-word"&&"Shows one word at a time",R.animationStyle==="bounce"&&"Words bounce in as they appear",R.animationStyle==="typewriter"&&"Words appear progressively like typing",(!R.animationStyle||R.animationStyle==="none")&&"Static text, no animation"]}),R.animationStyle&&R.animationStyle!=="none"&&!R.words?.length&&e.jsx("p",{className:"text-[9px] text-amber-400 bg-amber-400/10 p-2 rounded",children:"⚠️ No word-level timing data. Re-generate captions to enable animation."}),R.animationStyle&&R.animationStyle!=="none"&&R.animationStyle!=="typewriter"&&R.animationStyle!=="word-by-word"&&e.jsxs("div",{className:"pt-2 border-t border-border space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Highlight Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:R.style?.highlightColor||"#ffff00",onChange:Y=>n(R.id,{style:{...R.style||{},highlightColor:Y.target.value}}),className:"w-6 h-6 rounded border border-border cursor-pointer"}),e.jsx("span",{className:"text-[9px] font-mono text-text-muted uppercase",children:R.style?.highlightColor||"#ffff00"})]})]}),e.jsx("div",{className:"grid grid-cols-6 gap-1",children:["#ffff00","#00ff00","#ff6b6b","#4ecdc4","#ff9f43","#a55eea"].map(Y=>e.jsx("button",{onClick:()=>n(R.id,{style:{...R.style||{},highlightColor:Y}}),className:`w-6 h-6 rounded border-2 transition-transform hover:scale-110 ${(R.style?.highlightColor||"#ffff00")===Y?"border-white":"border-transparent"}`,style:{backgroundColor:Y}},Y))})]})]})}),e.jsx(qr,{title:"Font",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:P,type:"file",accept:Pd,onChange:Ye,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Font Family"}),e.jsxs(ot,{value:R.style?.fontFamily||"Inter",onValueChange:Y=>n(R.id,{style:{...R.style||{},fontFamily:Y}}),children:[e.jsx(lt,{className:"max-w-[120px] bg-background-tertiary border-border text-text-primary text-[10px]",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border max-h-60",children:[Object.entries(Dd).map(([Y,je])=>e.jsxs(Rn,{children:[e.jsx(Pn,{className:"text-text-muted text-[10px] font-medium",children:Y}),je.map(Se=>e.jsx(ge,{value:Se,style:{fontFamily:Se},children:Se},Se))]},Y)),_.length>0&&e.jsxs(Rn,{children:[e.jsx(Pn,{className:"text-text-muted text-[10px] font-medium",children:"Custom Uploads"}),_.map(Y=>e.jsx(ge,{value:Y,style:{fontFamily:Y},children:Y},Y))]})]})]})]}),e.jsxs("button",{onClick:()=>P.current?.click(),className:"w-full py-1.5 px-2 bg-background-secondary border border-border rounded text-[10px] text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center gap-1.5",children:[e.jsx(ya,{size:11}),"Upload Custom Font"]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Font Size"}),e.jsx(ts,{type:"number",min:12,max:72,value:R.style?.fontSize||24,onChange:Y=>n(R.id,{style:{...R.style||{},fontSize:parseInt(Y.target.value)||24}}),className:"w-16 h-7 text-[10px] bg-background-tertiary border-border text-text-primary text-right"})]})]})}),e.jsx(qr,{title:"Colors",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Text Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:R.style?.color||"#ffffff",onChange:Y=>n(R.id,{style:{...R.style||{},color:Y.target.value}}),className:"w-6 h-6 rounded border border-border cursor-pointer"}),e.jsx("span",{className:"text-[10px] font-mono text-text-muted uppercase",children:R.style?.color||"#ffffff"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-text-secondary",children:"Background"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:R.style?.backgroundColor?.replace(/rgba?\([^)]+\)/,"#000000")||"#000000",onChange:Y=>{const je=Y.target.value,Se=parseInt(je.slice(1,3),16),Ae=parseInt(je.slice(3,5),16),Be=parseInt(je.slice(5,7),16);n(R.id,{style:{...R.style||{},backgroundColor:`rgba(${Se}, ${Ae}, ${Be}, 0.7)`}})},className:"w-6 h-6 rounded border border-border cursor-pointer"}),e.jsxs(ot,{value:R.style?.backgroundColor?.includes("0.7")?"0.7":R.style?.backgroundColor?.includes("0.5")?"0.5":"1",onValueChange:Y=>{const Se=(R.style?.backgroundColor||"rgba(0, 0, 0, 0.7)").replace(/[\d.]+\)$/,`${Y})`);n(R.id,{style:{...R.style||{},backgroundColor:Se}})},children:[e.jsx(lt,{className:"w-auto min-w-[50px] bg-background-tertiary border-border text-text-primary text-[9px] h-6",children:e.jsx(ct,{})}),e.jsxs(dt,{className:"bg-background-secondary border-border",children:[e.jsx(ge,{value:"0",children:"None"}),e.jsx(ge,{value:"0.5",children:"50%"}),e.jsx(ge,{value:"0.7",children:"70%"}),e.jsx(ge,{value:"1",children:"100%"})]})]})]})]})]})}),e.jsx("div",{className:"pt-4 border-t border-border",children:e.jsx("button",{onClick:()=>{const{removeSubtitle:Y}=F.getState();Y(R.id)},className:"w-full py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 rounded-lg text-[10px] transition-all",children:"Delete Subtitle"})})]}):e.jsx(Xv,{})})})]})},In=(t,s,a,r,n,i,o)=>{if(!n.enabled)return{time:t,snapped:!1};const c=n.snapThreshold/i,d=[];if(n.snapToClips)for(const f of a)for(const v of f.clips)v.id!==s&&(d.push({time:v.startTime,type:"clip-start"}),d.push({time:v.startTime+v.duration,type:"clip-end"}));if(n.snapToPlayhead&&d.push({time:r,type:"playhead"}),n.snapToGrid){const f=Math.round(t/n.gridSize)*n.gridSize;if(d.push({time:f,type:"grid"}),o){const v=t+o,A=Math.round(v/n.gridSize)*n.gridSize;d.push({time:A,type:"grid"})}}const u={"clip-start":0,"clip-end":0,playhead:1,grid:2};let p,m=1/0,x=1/0,h=!1;for(const f of d){const v=u[f.type]??2,A=Math.abs(f.time-t);if(A{if(!t||t.length===0)return"M0,20 L100,20";const a=Array.from(t),r=Math.max(1,Math.floor(a.length/s)),n=[];for(let i=0;i{if(!isFinite(t)||isNaN(t)||t<0)return"00:00:00:00";const a=Math.floor(t/3600),r=Math.floor(t%3600/60),n=Math.floor(t%60),i=Math.floor(t%1*s);return`${a.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`},zu=(t,s)=>{switch(t.type){case"video":return{label:`V${s+1}`,icon:lr,color:"bg-primary",textColor:"text-primary",bgLight:"bg-primary/20"};case"audio":return{label:`A${s+1}`,icon:Ts,color:"bg-blue-500",textColor:"text-blue-400",bgLight:"bg-blue-500/20"};case"image":return{label:`I${s+1}`,icon:va,color:"bg-purple-500",textColor:"text-purple-400",bgLight:"bg-purple-500/20"};case"text":return{label:`T${s+1}`,icon:Hs,color:"bg-amber-500",textColor:"text-amber-400",bgLight:"bg-amber-500/20"};case"graphics":return{label:`G${s+1}`,icon:mn,color:"bg-green-500",textColor:"text-green-400",bgLight:"bg-green-500/20"};default:return{label:`?${s+1}`,icon:Os,color:"bg-gray-500",textColor:"text-gray-400",bgLight:"bg-gray-500/20"}}},Wv=t=>{switch(t){case"video":return{bg:"bg-cyan-600/25",border:"border-cyan-500/60",text:"text-white/90",selectedText:"text-white"};case"audio":return{bg:"bg-emerald-600/25",border:"border-emerald-500/60",text:"text-white/85",selectedText:"text-white"};case"image":return{bg:"bg-violet-600/25",border:"border-violet-500/60",text:"text-white/85",selectedText:"text-white"};default:return{bg:"bg-bg-2",border:"border-border-strong",text:"text-fg-2",selectedText:"text-fg"}}},qv=({position:t,pixelsPerSecond:s,scrollX:a,headerOffset:r})=>{const n=t*s-a;return n<0?null:e.jsxs("div",{className:"absolute top-0 bottom-0 z-50 pointer-events-none",style:{left:r,transform:`translateX(${n}px)`,willChange:"transform"},children:[e.jsx("div",{className:"absolute -translate-x-1/2",style:{top:-1,width:0,height:0,borderLeft:"6px solid transparent",borderRight:"6px solid transparent",borderTop:"9px solid var(--accent)"}}),e.jsx("div",{className:"absolute",style:{top:8,bottom:0,left:0,width:"1.5px",background:"var(--accent)"}})]})},Qv=({pixelsPerSecond:t,scrollX:s,viewportWidth:a,onSeek:r,onScrubStart:n,onScrubEnd:i,snapPoints:o})=>{const c=l.useRef(null),[d,u]=l.useState(!1),[p,m]=l.useState(()=>Vi().getState());l.useEffect(()=>Vi().subscribe(m),[]);const x=t>0?t:100,h=s/x,f=(s+a)/x,v=l.useMemo(()=>{if(p.beatMarkers.length===0)return[];const T=1;return p.beatMarkers.filter(C=>C.time>=h-T&&C.time<=f+T)},[p.beatMarkers,h,f]),g=x>500?{minor:.01,major:.1,labelEvery:.5}:x>200?{minor:.05,major:.5,labelEvery:1}:x>100?{minor:.1,major:1,labelEvery:1}:x>50?{minor:.5,major:1,labelEvery:5}:x>20?{minor:1,major:5,labelEvery:5}:{minor:5,major:10,labelEvery:10},k=Math.floor(h/g.minor)*g.minor,N=Math.max(0,k),b=[];for(let T=N;T<=f+g.minor;T+=g.minor){if(T<0)continue;const C=Math.round(T*1e4)/1e4;if(!isFinite(C)||isNaN(C))continue;const M=C===0||Math.abs(C%g.major)<1e-4,z=C===0||Math.abs(C%g.labelEvery)<1e-4;b.push({time:C,isMajor:M,showLabel:z})}const j=l.useRef(s);j.current=s;const y=l.useCallback(T=>{const C=c.current?.parentElement?.parentElement;if(!C)return 0;const M=C.getBoundingClientRect(),z=T.clientX-M.left+j.current;return Math.max(0,z/x)},[x]),w=l.useCallback(T=>{T.preventDefault(),T.stopPropagation(),u(!0),n?.();const C=y(T);r(C)},[y,r,n]),S=l.useRef(o);return S.current=o,l.useEffect(()=>{if(!d)return;let T=null,C=null,M=null,z=0,L=0;const B=8,O=150,G=_=>{const se=S.current;if(!se||se.length===0||L>O)return _;const R=B/x;let U=1/0,D=_;for(const X of se){const K=Math.abs(_-X);K{_.preventDefault();const se=y(_),R=performance.now();if(M!==null&&R-z>0){const U=(R-z)/1e3;L=Math.abs(se-M)*x/U}M=se,z=R,C=G(se),T===null&&(T=requestAnimationFrame(()=>{T=null,C!==null&&r(C)}))},P=_=>{_.preventDefault(),T!==null&&cancelAnimationFrame(T),C!==null&&r(C),u(!1),i?.()};return window.addEventListener("mousemove",V),window.addEventListener("mouseup",P),()=>{T!==null&&cancelAnimationFrame(T),window.removeEventListener("mousemove",V),window.removeEventListener("mouseup",P)}},[d,y,r,i,x]),e.jsxs("div",{ref:c,className:`h-[26px] border-b border-border flex items-end relative bg-bg-1 select-none ${d?"cursor-grabbing":"cursor-pointer"}`,onMouseDown:w,style:{cursor:d?"grabbing":"pointer"},children:[b.map(T=>e.jsx("div",{className:`absolute top-0 bottom-0 border-l pointer-events-none ${T.isMajor?"border-border-strong":"border-border"}`,style:{left:`${T.time*x}px`},children:T.showLabel&&T.time>=0&&e.jsx("span",{className:"text-[10px] font-mono text-fg-3 pl-1 whitespace-nowrap absolute top-[7px]",children:Pu(Math.max(0,T.time)).slice(3)})},`tick-${T.time}`)),v.map(T=>e.jsx("div",{className:`absolute bottom-0 pointer-events-none ${T.isDownbeat?"w-[2px] h-5 bg-orange-500":"w-px h-3 bg-orange-400/50"}`,style:{left:`${T.time*x}px`}},`beat-ruler-${T.index}`)),p.beatAnalysis&&e.jsxs("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1.5 bg-orange-500/20 px-2 py-0.5 rounded text-[9px] text-orange-400 font-medium pointer-events-none",children:[e.jsx("span",{className:"opacity-70",children:"♪"}),e.jsxs("span",{children:[p.beatAnalysis.bpm," BPM"]})]})]})},Jv=({track:t,index:s,onDragStart:a,onDragOver:r,onDrop:n,keyframeCount:i=0})=>{const{lockTrack:o,hideTrack:c,muteTrack:d,removeTrack:u,renameTrack:p,consolidateTrack:m}=F(),{isTrackExpanded:x,toggleTrackExpanded:h,getTrackHeight:f}=Et(),v=x(t.id),[A,g]=l.useState(!1),[k,N]=l.useState(t.name),b=l.useRef(null),j=zu(t,s),y=j.icon,w=t.type==="video"||t.type==="image"||t.type==="text"||t.type==="graphics",S=async()=>{await u(t.id)},T=async()=>{await m(t.id)},C=_e.useMemo(()=>{if(t.clips.length===0)return!1;const B=[...t.clips].sort((O,G)=>O.startTime-G.startTime);if(B[0].startTime>1e-4)return!0;for(let O=1;O1e-4)return!0}return!1},[t.clips]),M=()=>{N(t.name),g(!0)},z=()=>{p(t.id,k||t.name),g(!1)},L=()=>{N(t.name),g(!1)};return l.useEffect(()=>{A&&(b.current?.focus(),b.current?.select())},[A]),e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{draggable:!A,onDragStart:B=>a(B,t.id),onDragOver:r,onDrop:B=>n(B,t.id),style:{height:f(t.id)},className:`border-b border-border flex flex-col justify-between py-1.5 px-2.5 relative group transition-colors cursor-grab active:cursor-grabbing ${t.hidden?"opacity-60":""} ${t.locked?"bg-bg-2/50":"bg-bg-1"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i>0&&e.jsx("button",{onClick:B=>{B.stopPropagation(),h(t.id)},className:"p-0.5 rounded transition-colors hover:bg-background-elevated text-text-muted",title:v?"Collapse keyframes":"Expand keyframes",children:v?e.jsx(qt,{size:12}):e.jsx(bs,{size:12})}),e.jsx("div",{className:`w-5 h-5 rounded flex items-center justify-center shrink-0 ${j.bgLight}`,children:e.jsx(y,{size:12,className:j.textColor})}),A?e.jsx("input",{ref:b,value:k,onChange:B=>N(B.target.value),onBlur:z,onKeyDown:B=>{B.key==="Enter"&&z(),B.key==="Escape"&&L(),B.stopPropagation()},onClick:B=>B.stopPropagation(),className:"text-[11px] font-semibold bg-background-elevated border border-primary/50 rounded px-1 w-[70px] outline-none text-text-primary"}):e.jsx("span",{className:`text-[11px] font-semibold truncate max-w-[70px] ${j.textColor}`,onDoubleClick:M,children:t.name||j.label}),i>0&&e.jsx("span",{className:"text-[8px] text-text-muted bg-background-elevated px-1 py-0.5 rounded",children:i})]}),e.jsxs("div",{className:"flex items-center gap-px text-fg-3",children:[w&&e.jsx("button",{onClick:B=>{B.stopPropagation(),c(t.id,!t.hidden)},className:`w-[22px] h-[22px] grid place-items-center rounded transition-colors ${t.hidden?"text-status-error":"text-fg-3 hover:bg-hover hover:text-fg"}`,title:t.hidden?"Show track":"Hide track",children:t.hidden?e.jsx(Xs,{size:12}):e.jsx($s,{size:12})}),t.type!=="image"&&t.type!=="text"&&t.type!=="graphics"&&e.jsx("button",{onClick:B=>{B.stopPropagation(),d(t.id,!t.muted)},className:`w-[22px] h-[22px] grid place-items-center rounded transition-colors ${t.muted?"text-status-error":"text-fg-3 hover:bg-hover hover:text-fg"}`,title:t.muted?"Unmute":"Mute",children:e.jsx(Ts,{size:12})}),e.jsx("button",{onClick:B=>{B.stopPropagation(),o(t.id,!t.locked)},className:`w-[22px] h-[22px] grid place-items-center rounded transition-colors ${t.locked?"text-accent":"text-fg-3 hover:bg-hover hover:text-fg"}`,title:t.locked?"Unlock":"Lock",children:e.jsx(Li,{size:12})}),e.jsx("button",{onClick:B=>{B.stopPropagation(),S()},className:"w-[22px] h-[22px] grid place-items-center rounded transition-colors text-fg-muted hover:bg-hover hover:text-status-error",title:"Delete track",children:e.jsx($t,{size:12})})]}),e.jsx("div",{className:`absolute left-0 top-0 w-1 h-full ${j.color} opacity-60 group-hover:opacity-100 transition-opacity`})]})}),e.jsxs(En,{className:"min-w-[160px]",children:[e.jsxs(rs,{onClick:M,children:[e.jsx(tu,{className:"mr-2 h-4 w-4"}),"Rename Track"]}),e.jsxs(rs,{onClick:T,disabled:!C,children:[e.jsx(nu,{className:"mr-2 h-4 w-4"}),"Remove Gaps"]}),e.jsx(Pa,{}),e.jsxs(rs,{onClick:S,className:"text-red-400 focus:text-red-400 hover:text-red-400",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Delete Track"]})]})]})},Zv=({clip:t,track:s,onClose:a})=>{const{copyClips:r,duplicateClip:n,removeClip:i,rippleDeleteClip:o,splitClip:c,separateAudio:d,getMediaItem:u,copyEffects:p,pasteEffects:m,copiedEffects:x,closeGapBeforeClip:h}=F(),{playheadPosition:f}=Et(),v=f>=t.startTime&&f<=t.startTime+t.duration,A=_e.useMemo(()=>{const _=[...s.clips].sort((D,X)=>D.startTime-X.startTime),se=_.findIndex(D=>D.id===t.id);if(se<0)return!1;const R=se>0?_[se-1]:null,U=R?R.startTime+R.duration:0;return t.startTime-U>1e-4},[s.clips,t.id,t.startTime]),g=u(t.mediaId),k=s.type==="video",N=s.type==="audio",b=s.type==="image",j=k&&g?.type==="video"&&g?.metadata?.channels&&g.metadata.channels>0,y=t.effects&&t.effects.length>0,w=x&&x.length>0,S=()=>{r([t.id]),a?.()},T=async()=>{await n(t.id),a?.()},C=async()=>{await i(t.id),a?.()},M=async()=>{await o(t.id),a?.()},z=async()=>{v&&await c(t.id,f),a?.()},L=async()=>{await h(t.id),a?.()},B=async()=>{await d(t.id),a?.()},O=()=>{p(t.id),a?.()},G=async()=>{await m(t.id),a?.()},V=()=>k?"Video Clip":N?"Audio Clip":b?"Image Clip":"Clip",P=()=>k?e.jsx(lr,{className:"mr-2 h-3 w-3 text-primary"}):N?e.jsx(Ts,{className:"mr-2 h-3 w-3 text-blue-400"}):b?e.jsx(va,{className:"mr-2 h-3 w-3 text-purple-400"}):null;return e.jsxs(En,{className:"min-w-[220px]",children:[e.jsxs(Bd,{className:"flex items-center text-[10px] text-text-muted",children:[P(),V()]}),e.jsx(Pa,{}),e.jsxs(rs,{onClick:S,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Copy Clip",e.jsx(en,{children:"⌘C"})]}),e.jsxs(rs,{onClick:T,children:[e.jsx(Os,{className:"mr-2 h-4 w-4"}),"Duplicate",e.jsx(en,{children:"⌘D"})]}),e.jsx(Pa,{}),e.jsxs(rs,{onClick:z,disabled:!v,children:[e.jsx(xl,{className:"mr-2 h-4 w-4"}),"Split at Playhead",e.jsx(en,{children:"S"})]}),e.jsxs(rs,{onClick:L,disabled:!A,children:[e.jsx(Xp,{className:"mr-2 h-4 w-4"}),"Close Gap to Previous"]}),(k||b)&&e.jsxs(e.Fragment,{children:[e.jsx(Pa,{}),e.jsxs(Jl,{children:[e.jsxs(Zl,{children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Effects"]}),e.jsxs(ec,{children:[e.jsx(rs,{onClick:O,disabled:!y,children:"Copy Effects"}),e.jsx(rs,{onClick:G,disabled:!w,children:"Paste Effects"})]})]})]}),j&&e.jsxs(e.Fragment,{children:[e.jsx(Pa,{}),e.jsxs(rs,{onClick:B,children:[e.jsx(Ps,{className:"mr-2 h-4 w-4"}),"Separate Audio"]})]}),N&&e.jsxs(e.Fragment,{children:[e.jsx(Pa,{}),e.jsxs(Jl,{children:[e.jsxs(Zl,{children:[e.jsx(Ts,{className:"mr-2 h-4 w-4"}),"Audio"]}),e.jsxs(ec,{children:[e.jsx(rs,{onClick:O,disabled:!y,children:"Copy Audio Effects"}),e.jsx(rs,{onClick:G,disabled:!w,children:"Paste Audio Effects"})]})]})]}),e.jsx(Pa,{}),e.jsxs(rs,{onClick:M,className:"text-red-400",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Ripple Delete",e.jsx(en,{children:"⌫"})]}),e.jsxs(rs,{onClick:C,className:"text-red-400",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Delete"]})]})},ud=80,md=10,ej=5,tj=({clip:t,track:s,allTracks:a,pixelsPerSecond:r,isSelected:n,trackHeights:i,timelineRef:o,onSelect:c,onMoveClip:d,onSnapIndicator:u,onTrimClip:p})=>{const{getMediaItem:m}=F(),{snapSettings:x}=vt(),h=vt(Q=>Q.effectApplicationClipId),f=vt(Q=>Q.effectApplicationLabel),{playheadPosition:v}=Et(),A=m(t.mediaId),[g,k]=l.useState(!1),[N,b]=l.useState(!1),[j,y]=l.useState(0),[w,S]=l.useState(0),[T,C]=l.useState(!1),[M,z]=l.useState(!1),[L,B]=l.useState(null),O=l.useRef([]),G=l.useRef({mouseX:0,startTime:t.startTime,duration:t.duration}),V=l.useRef({mouseY:0,clipY:0,scrollTop:0}),P=l.useRef({x:0,y:0}),_=l.useRef({time:0}),se=l.useRef({active:!1,startX:0,startY:0}),R=l.useRef(null),U=l.useRef(null),D=l.useRef(null),[X,K]=l.useState(null),ue=t.startTime*r,Te=t.duration*r,pe=s.type==="video",fe=s.type==="audio",We=s.type==="image",Ze=Wv(s.type),at=Q=>{Q.button===0&&(g||N||(Q.stopPropagation(),c(t.id,Q.shiftKey||Q.metaKey)))},de=Q=>{if(Q.button!==0||s.locked||M)return;Q.stopPropagation();const be=R.current?.parentElement?.getBoundingClientRect(),Oe=R.current?.getBoundingClientRect();if(!be||!Oe)return;const Ue=Q.clientX-be.left,Le=t.startTime*r;y(Ue-Le),V.current={mouseY:Q.clientY,clipY:Oe.top-be.top,scrollTop:o.current?.scrollTop||0},P.current={x:Q.clientX,y:Q.clientY},se.current={active:!0,startX:Q.clientX,startY:Q.clientY},S(0),C(!1),b(!0);const Ye=vt.getState().getSelectedClipIds();if(Ye.length>1&&Ye.includes(t.id)){const Ke=[];for(const mt of a)for(const Ge of mt.clips)Ge.id!==t.id&&Ye.includes(Ge.id)&&(mt.locked||Ke.push({clipId:Ge.id,startTime:Ge.startTime,trackId:mt.id}));O.current=Ke}else O.current=[]},Ce=Q=>{const be=Q.dataTransfer.types;return be.includes(Jo)?"effect":be.includes(Zo)?"transition":(be.includes("text/plain"),null)},Ne=l.useCallback(Q=>{const be=R.current?.getBoundingClientRect();return be&&(Q.clientX-be.left)/be.width<.5?"transition-left":"transition-right"},[]),Me=l.useCallback(Q=>{const be=Ce(Q);be!==null&&(Q.preventDefault(),Q.stopPropagation(),Q.dataTransfer.dropEffect="copy",K(be==="effect"?"effect":Ne(Q)))},[Ne]),qe=l.useCallback(Q=>{const be=Q.relatedTarget;(!be||!R.current?.contains(be))&&K(null)},[]),nt=l.useCallback((Q,be)=>{const Oe=F.getState(),Le=Oe.project.timeline.tracks.find(Dt=>Dt.clips.some(us=>us.id===t.id));if(!Le)return;const Ye=[...Le.clips].sort((Dt,us)=>Dt.startTime!==us.startTime?Dt.startTime-us.startTime:Dt.id.localeCompare(us.id)),Ke=Ye.findIndex(Dt=>Dt.id===t.id),mt=Ke>0?Ye[Ke-1]:void 0,Ge=Ke{K(null);const be=gt=>{if(!gt)return null;try{return JSON.parse(gt)}catch{return null}},Oe=be(Q.dataTransfer.getData(Jo)||null),Ue=be(Q.dataTransfer.getData(Zo)||null),Le=Q.dataTransfer.getData("text/plain"),Ye=Le.startsWith("effect:"),Ke=Le.startsWith("transition:"),mt=Oe?.effectType??(Ye?Le.slice(7):null),Ge=Ue?.transitionType??(Ke?Le.slice(11):null);if(!(!mt&&!Ge)){if(Q.preventDefault(),Q.stopPropagation(),mt){F.getState().addVideoEffect(t.id,mt)?(Fe.success("Effect applied",`${mt} added`),vt.getState().select({id:t.id,type:"clip"})):Fe.error("Effect failed","Could not apply effect");return}if(Ge){const gt=Ne(Q).endsWith("left")?"left":"right";nt(Ge,gt)}}},[t.id,nt,Ne]),Pe=Q=>be=>{be.button===0&&(s.locked||!p||(be.stopPropagation(),z(!0),B(Q),G.current={mouseX:be.clientX,startTime:t.startTime,duration:t.duration},document.body.style.cursor="ew-resize"))};l.useEffect(()=>{if(!N)return;const Q=Oe=>{const Ue=Oe.clientX-se.current.startX,Le=Oe.clientY-se.current.startY;Math.sqrt(Ue*Ue+Le*Le)>=ej&&(se.current.active=!1,b(!1),k(!0))},be=Oe=>{se.current.active=!1,b(!1),c(t.id,Oe.shiftKey||Oe.metaKey)};return window.addEventListener("mousemove",Q),window.addEventListener("mouseup",be),()=>{window.removeEventListener("mousemove",Q),window.removeEventListener("mouseup",be)}},[N,t.id,c]),l.useEffect(()=>{if(!g)return;const Q=F.getState();Q.beginHistoryGroup(O.current.length>0?"Move clips":"Move clip");let be=null;const Oe=()=>{if(!o.current){be=requestAnimationFrame(Oe);return}const Ge=o.current,gt=Ge.getBoundingClientRect(),Ft=P.current.y,Qe=gt.top,Ds=gt.bottom,Cs=Ge.scrollTop>0,Dt=Ge.scrollTop{U.current=null;const Ge=D.current;D.current=null,Ge?.()},Le=Ge=>{P.current.x=Ge.clientX,P.current.y=Ge.clientY;const gt=R.current?.parentElement?.getBoundingClientRect(),Ft=o.current?.getBoundingClientRect();if(!gt||!Ft)return;const Qe=Ge.clientX-gt.left-j,Ds=Math.max(0,Qe/r),Cs={...x,snapToPlayhead:!1},Dt=In(Ds,t.id,a,v,Cs,r,t.duration),Ws=(o.current?.scrollTop||0)-V.current.scrollTop,Qt=Ge.clientY-V.current.mouseY+Ws;S(Qt);const Lt=o.current?.scrollTop||0,ca=Ge.clientY-Ft.top+Lt;let ms,da,ss=0;for(const He of a){const $=i.get(He.id)||60;if(ca>=ss&&ca{if(d(t.id,Ss,void 0),ua.length>0){const He=Ss-qs;for(const $ of ua){const ve=Math.max(0,$.startTime+He);d($.clipId,ve,void 0)}}},U.current===null&&(U.current=requestAnimationFrame(Ue)),u(Dt.snapped&&Dt.snapPoint?Dt.snapPoint.time:null)};let Ye=!1;const Ke=()=>{Ye||(Ye=!0,Q.endHistoryGroup())},mt=()=>{be!==null&&cancelAnimationFrame(be),U.current!==null&&(cancelAnimationFrame(U.current),U.current=null);const Ge=D.current;D.current=null,Ge?.();const{time:gt,targetTrackId:Ft}=_.current;Ft&&d(t.id,gt,Ft),k(!1),S(0),C(!1),u(null),O.current=[],Ke()};return window.addEventListener("mousemove",Le),window.addEventListener("mouseup",mt),()=>{be!==null&&cancelAnimationFrame(be),U.current!==null&&(cancelAnimationFrame(U.current),U.current=null),window.removeEventListener("mousemove",Le),window.removeEventListener("mouseup",mt),Ke()}},[g,j,r,t.id,s.id,s.type,a,i,o,v,x,d,u]),l.useEffect(()=>{if(!M||!L||!p)return;const Q=Oe=>{const Le=(Oe.clientX-G.current.mouseX)/r;if(L==="left"){const Ye=Math.max(0,G.current.startTime+Le),Ke=G.current.startTime+G.current.duration-.1,mt=Math.min(Ye,Ke);p(t.id,"left",mt)}else{const Ye=G.current.startTime+G.current.duration+Le,Ke=G.current.startTime+.1,mt=Math.max(Ye,Ke);p(t.id,"right",mt)}},be=()=>{z(!1),B(null),document.body.style.cursor=""};return window.addEventListener("mousemove",Q),window.addEventListener("mouseup",be),()=>{window.removeEventListener("mousemove",Q),window.removeEventListener("mouseup",be)}},[M,L,t.id,r,p]);const Ie=Math.max(1,Math.floor(Te/60)),Ee=A?.name||t.mediaId.slice(0,8),ae=g||M,W=h===t.id;return e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{ref:R,onClick:at,onMouseDown:de,onDragOver:Me,onDragLeave:qe,onDrop:rt,className:`group absolute top-1 bottom-1 rounded-lg overflow-hidden shadow-sm ${g?`cursor-grabbing z-50 ${T?"opacity-50 ring-2 ring-red-500 border-red-500":"opacity-90 shadow-xl"}`:"cursor-grab"} ${n&&!g?W?"ring-2 ring-amber-400 border-amber-300 z-10":"ring-2 ring-primary border-primary z-10":g?"":"border-opacity-30 hover:border-opacity-60 hover:brightness-110"} ${Ze.bg} border ${Ze.border} ${s.locked?"cursor-not-allowed opacity-60":""}`,style:{transform:g?`translate(${ue}px, ${w}px)`:`translateX(${ue}px)`,width:`${Te}px`,willChange:ae?"transform, width":"auto",transition:ae?"none":"opacity 150ms, box-shadow 150ms",pointerEvents:g?"none":"auto"},children:[W&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -inset-px rounded-lg border border-amber-300/80 shadow-[0_0_18px_rgba(251,191,36,0.55)] pointer-events-none animate-pulse"}),e.jsx("div",{className:"absolute inset-0 bg-[linear-gradient(110deg,transparent_0%,rgba(255,255,255,0.08)_28%,rgba(251,191,36,0.28)_50%,rgba(255,255,255,0.08)_72%,transparent_100%)] pointer-events-none animate-pulse"}),e.jsx("div",{className:"absolute top-1 right-1 rounded-full bg-black/70 px-2 py-0.5 text-[9px] font-medium uppercase tracking-[0.12em] text-amber-200 pointer-events-none",children:f??"Applying effect"})]}),X==="effect"&&e.jsx("div",{className:"absolute inset-0 ring-2 ring-accent ring-inset rounded-lg bg-accent/15 pointer-events-none z-20"}),X==="transition-left"&&e.jsx("div",{className:"absolute inset-y-0 left-0 w-1/3 pointer-events-none z-20 bg-gradient-to-r from-accent/60 to-transparent",children:e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-accent"})}),X==="transition-right"&&e.jsx("div",{className:"absolute inset-y-0 right-0 w-1/3 pointer-events-none z-20 bg-gradient-to-l from-accent/60 to-transparent",children:e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-1 bg-accent"})}),pe&&(A?.filmstripThumbnails?.length||A?.thumbnailUrl)&&e.jsx("div",{className:"absolute inset-0 flex pointer-events-none",children:A?.filmstripThumbnails&&A.filmstripThumbnails.length>0?Array.from({length:Ie}).map((Q,be)=>{const Oe=be/Math.max(1,Ie-1),Ue=Math.min(Math.floor(Oe*A.filmstripThumbnails.length),A.filmstripThumbnails.length-1),Le=A.filmstripThumbnails[Ue];return e.jsx("div",{className:"flex-1 h-full bg-cover bg-center opacity-70",style:{backgroundImage:`url(${Le.url})`,borderRight:bee.jsx("div",{className:"flex-1 h-full bg-cover bg-center opacity-60",style:{backgroundImage:`url(${A.thumbnailUrl})`,borderRight:be0&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-3 flex items-center pointer-events-none",children:t.keyframes.map(Q=>{const be=Q.time-t.startTime;if(be<0||be>t.duration)return null;const Oe=be/t.duration*100;return e.jsx("div",{className:"absolute w-2 h-2 bg-yellow-400 rotate-45 border border-yellow-600",style:{left:`${Oe}%`,marginLeft:"-4px"},title:`${Q.property} @ ${Q.time.toFixed(2)}s`},Q.id)})}),n&&e.jsx("div",{className:"absolute inset-0 border-2 border-primary rounded-lg pointer-events-none"}),(pe||We||fe)&&p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{onMouseDown:Pe("left"),className:`absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"} ${n?"bg-primary":fe?"hover:bg-blue-400/50":pe?"hover:bg-green-400/50":"hover:bg-purple-400/50"}`,style:{borderRadius:"6px 0 0 6px"},onClick:Q=>Q.stopPropagation(),children:n&&e.jsx("div",{className:"w-0.5 h-3 bg-primary-foreground/80 rounded-full"})}),e.jsx("div",{onMouseDown:Pe("right"),className:`absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"} ${n?"bg-primary":fe?"hover:bg-blue-400/50":pe?"hover:bg-green-400/50":"hover:bg-purple-400/50"}`,style:{borderRadius:"0 6px 6px 0"},onClick:Q=>Q.stopPropagation(),children:n&&e.jsx("div",{className:"w-0.5 h-3 bg-primary-foreground/80 rounded-full"})})]})]})}),e.jsx(Zv,{clip:t,track:s})]})},Du=({clip:t,clipType:s,onClose:a,onDelete:r,onDuplicate:n})=>{const{deleteShapeClip:i,deleteSVGClip:o,deleteStickerClip:c,deleteTextClip:d}=F(),u=()=>{if(r)r();else switch(s){case"shape":i(t.id);break;case"svg":o(t.id);break;case"sticker":case"emoji":c(t.id);break;case"text":d(t.id);break}a?.()},p=()=>{n?.(),a?.()},m=()=>{switch(s){case"shape":return"Shape";case"svg":return"SVG";case"sticker":return"Sticker";case"emoji":return"Emoji";case"text":return"Text";default:return"Graphics"}},x=()=>{switch(s){case"text":return e.jsx(Hs,{className:"mr-2 h-3 w-3 text-amber-400"});default:return e.jsx(mn,{className:"mr-2 h-3 w-3 text-green-400"})}};return e.jsxs(En,{className:"min-w-[200px]",children:[e.jsxs(Bd,{className:"flex items-center text-[10px] text-text-muted",children:[x(),m()," Clip"]}),e.jsx(Pa,{}),n&&e.jsxs(e.Fragment,{children:[e.jsxs(rs,{onClick:p,children:[e.jsx(Os,{className:"mr-2 h-4 w-4"}),"Duplicate",e.jsx(en,{children:"⌘D"})]}),e.jsx(Pa,{})]}),e.jsxs(rs,{onClick:u,className:"text-red-400",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Delete",e.jsx(en,{children:"⌫"})]})]})},sj=({textClip:t,pixelsPerSecond:s,isSelected:a,onSelect:r,onTrim:n,onMoveClip:i})=>{const o=l.useRef(null),[c,d]=l.useState(null),[u,p]=l.useState(!1),[m,x]=l.useState(0),{snapSettings:h}=vt(),{playheadPosition:f}=Et(),v=l.useRef({mouseX:0,startTime:t.startTime,duration:t.duration}),A=t.startTime*s,g=t.duration*s,k=y=>{y.button===0&&(c||u||(y.stopPropagation(),r(t.id,y.shiftKey||y.metaKey)))},N=y=>{if(y.button!==0||c)return;y.stopPropagation();const w=o.current?.parentElement?.getBoundingClientRect();if(!w)return;const S=y.clientX-w.left,T=t.startTime*s;x(S-T),p(!0),r(t.id,y.shiftKey||y.metaKey)};l.useEffect(()=>{if(!u||!i)return;const y=S=>{const T=o.current?.parentElement?.getBoundingClientRect();if(!T)return;const C=S.clientX-T.left-m,M=Math.max(0,C/s),z=F.getState().project.timeline.tracks,L={...h,snapToPlayhead:!1},B=In(M,t.id,z,f,L,s,t.duration);i(t.id,B.time)},w=()=>{p(!1)};return window.addEventListener("mousemove",y),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",w)}},[u,t.id,t.duration,s,m,i,h,f]);const b=(y,w)=>{y.button===0&&(y.stopPropagation(),y.preventDefault(),d(w),v.current={mouseX:y.clientX,startTime:t.startTime,duration:t.duration},document.body.style.cursor="ew-resize",document.body.style.userSelect="none")};l.useEffect(()=>{if(!c)return;const y=S=>{const C=(S.clientX-v.current.mouseX)/s;if(c==="left"){const M=Math.max(0,v.current.startTime+C),z=v.current.startTime+v.current.duration-.1,L=Math.min(M,z);n(t.id,"left",L)}else{const M=v.current.startTime+v.current.duration+C,z=v.current.startTime+.1,L=Math.max(M,z);n(t.id,"right",L)}},w=()=>{d(null),document.body.style.cursor="",document.body.style.userSelect=""};return window.addEventListener("mousemove",y),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",w)}},[c,t.id,s,n]);const j=u||c;return e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{ref:o,onClick:k,onMouseDown:N,className:`absolute top-1 bottom-1 rounded-lg overflow-hidden cursor-grab group ${u?"cursor-grabbing opacity-75":""} ${a?"ring-2 ring-amber-400 border-amber-400 z-10":"border-amber-500/30 hover:border-amber-500/60 hover:brightness-110"} bg-amber-500/20 border`,style:{transform:`translateX(${A}px)`,width:`${Math.max(g,40)}px`,willChange:j?"transform, width":"auto",transition:j?"none":"opacity 150ms, box-shadow 150ms"},children:[e.jsx("div",{className:`absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${a?"opacity-100 bg-amber-400":"opacity-0 group-hover:opacity-100 hover:bg-amber-400/50"}`,style:{borderRadius:"6px 0 0 6px"},onMouseDown:y=>b(y,"left"),children:a&&e.jsx("div",{className:"w-0.5 h-3 bg-amber-900/60 rounded-full"})}),e.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${a?"opacity-100 bg-amber-400":"opacity-0 group-hover:opacity-100 hover:bg-amber-400/50"}`,style:{borderRadius:"0 6px 6px 0"},onMouseDown:y=>b(y,"right"),children:a&&e.jsx("div",{className:"w-0.5 h-3 bg-amber-900/60 rounded-full"})}),e.jsxs("div",{className:"w-full h-full flex items-center gap-1 px-3",children:[e.jsx(Hs,{size:12,className:"text-amber-400 flex-shrink-0"}),e.jsx("span",{className:"text-[10px] font-medium text-amber-200 truncate",children:t.text||"Text"})]}),a&&e.jsx("div",{className:"absolute inset-0 border-2 border-amber-400 rounded-lg pointer-events-none"})]})}),e.jsx(Du,{clip:t,clipType:"text"})]})},aj=({shapeClip:t,pixelsPerSecond:s,isSelected:a,onSelect:r,onTrim:n,onMoveClip:i})=>{const o=l.useRef(null),[c,d]=l.useState(!1),[u,p]=l.useState(0),[m,x]=l.useState(null),{snapSettings:h}=vt(),{playheadPosition:f}=Et(),v=l.useRef({mouseX:0,startTime:t.startTime,duration:t.duration}),A=t.startTime*s,g=t.duration*s,k=z=>{if(z.button!==0||m)return;z.stopPropagation();const L=o.current?.getBoundingClientRect();if(!L)return;const B=z.clientX-L.left;p(B),d(!0)},N=z=>{z.button===0&&(m||c||(z.stopPropagation(),r(t.id,z.shiftKey||z.metaKey)))},b=(z,L)=>{z.button===0&&(z.stopPropagation(),z.preventDefault(),x(L),v.current={mouseX:z.clientX,startTime:t.startTime,duration:t.duration},document.body.style.cursor="ew-resize",document.body.style.userSelect="none")};l.useEffect(()=>{if(!c)return;const z=B=>{const O=o.current?.parentElement;if(!O)return;const G=O.getBoundingClientRect(),V=B.clientX-G.left-u,P=Math.max(0,V/s),_=F.getState().project.timeline.tracks,se={...h,snapToPlayhead:!1},R=In(P,t.id,_,f,se,s,t.duration);i(t.id,R.time)},L=()=>{d(!1)};return window.addEventListener("mousemove",z),window.addEventListener("mouseup",L),()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",L)}},[c,u,s,t.id,t.duration,i,h,f]),l.useEffect(()=>{if(!m)return;const z=B=>{const G=(B.clientX-v.current.mouseX)/s;if(m==="left"){const V=Math.max(0,v.current.startTime+G),P=v.current.startTime+v.current.duration-.1,_=Math.min(V,P);n(t.id,"left",_)}else{const V=v.current.startTime+v.current.duration+G,P=v.current.startTime+.1,_=Math.max(V,P);n(t.id,"right",_)}},L=()=>{x(null),document.body.style.cursor="",document.body.style.userSelect=""};return window.addEventListener("mousemove",z),window.addEventListener("mouseup",L),()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",L)}},[m,t.id,s,n]);const j=t.type==="shape",y=t.type==="sticker"||t.type==="emoji",w=j&&"shapeType"in t?t.shapeType.charAt(0).toUpperCase()+t.shapeType.slice(1):y?t.type==="emoji"?"Emoji":"Sticker":"SVG",S=j?mn:y?su:Ki,T=j?"green":y?"pink":"purple",C=c||m,M=j?"shape":y?t.type==="emoji"?"emoji":"sticker":"svg";return e.jsxs(ln,{children:[e.jsx(cn,{asChild:!0,children:e.jsxs("div",{ref:o,onClick:N,onMouseDown:k,className:`absolute top-1 bottom-1 rounded-lg overflow-hidden cursor-grab group ${c?"cursor-grabbing opacity-75":""} ${a?`ring-2 ring-${T}-400 border-${T}-400 z-10`:`border-${T}-500/30 hover:border-${T}-500/60 hover:brightness-110`} bg-${T}-500/20 border`,style:{transform:`translateX(${A}px)`,width:`${Math.max(g,40)}px`,willChange:C?"transform, width":"auto",transition:C?"none":"opacity 150ms, box-shadow 150ms"},children:[e.jsx("div",{className:`absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${a?"opacity-100 bg-green-400":`opacity-0 group-hover:opacity-100 hover:bg-${T}-400/50`}`,style:{borderRadius:"6px 0 0 6px"},onMouseDown:z=>b(z,"left"),children:a&&e.jsx("div",{className:"w-0.5 h-3 bg-green-900/60 rounded-full"})}),e.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize z-20 flex items-center justify-center transition-opacity ${a?"opacity-100 bg-green-400":`opacity-0 group-hover:opacity-100 hover:bg-${T}-400/50`}`,style:{borderRadius:"0 6px 6px 0"},onMouseDown:z=>b(z,"right"),children:a&&e.jsx("div",{className:"w-0.5 h-3 bg-green-900/60 rounded-full"})}),e.jsxs("div",{className:"w-full h-full flex items-center gap-1 px-3",children:[e.jsx(S,{size:12,className:`text-${T}-400 flex-shrink-0`}),e.jsx("span",{className:`text-[10px] font-medium text-${T}-200 truncate`,children:w})]}),a&&e.jsx("div",{className:"absolute inset-0 border-2 border-green-400 rounded-lg pointer-events-none"})]})}),e.jsx(Du,{clip:t,clipType:M})]})},rj=({keyframe:t,xPosition:s,color:a,isSelected:r,onSelect:n,onMove:i,onDelete:o})=>{const[c,d]=l.useState(!1),[u,p]=l.useState(0),m=l.useRef(null),x=l.useCallback(g=>{g.preventDefault(),g.stopPropagation();const k=g.shiftKey||g.metaKey||g.ctrlKey;n(k),d(!0),p(g.clientX)},[n]),h=l.useCallback(g=>{if(!c)return;const k=g.clientX-u;Math.abs(k)>2&&(i(k),p(g.clientX))},[c,u,i]),f=l.useCallback(()=>{d(!1)},[]);l.useEffect(()=>{if(c)return window.addEventListener("mousemove",h),window.addEventListener("mouseup",f),()=>{window.removeEventListener("mousemove",h),window.removeEventListener("mouseup",f)}},[c,h,f]);const v=l.useCallback(g=>{g.preventDefault(),o()},[o]),A=l.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]);return e.jsxs("div",{ref:m,className:`absolute top-1/2 -translate-y-1/2 cursor-pointer transition-transform hover:scale-110 ${c?"scale-125 z-50":""}`,style:{left:s,transform:`translate(-50%, -50%) rotate(45deg) ${c?"scale(1.25)":""}`},onMouseDown:x,onContextMenu:v,onDoubleClick:A,children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-sm transition-all ${r?"ring-2 ring-white ring-offset-1 ring-offset-background-secondary":""}`,style:{backgroundColor:a,boxShadow:r?`0 0 8px ${a}`:"none"}}),r&&e.jsx("div",{className:"absolute -bottom-4 left-1/2 -translate-x-1/2 rotate-[-45deg] whitespace-nowrap",children:e.jsxs("span",{className:"text-[8px] text-text-muted bg-background-secondary/80 px-1 rounded",children:[t.time.toFixed(2),"s"]})})]})},nj=({startX:t,endX:s,easing:a,color:r,height:n})=>{const i=l.useMemo(()=>{const c=s-t;if(c<=0)return"";const u={linear:"linear","ease-in":"easeInQuad","ease-out":"easeOutQuad","ease-in-out":"easeInOutQuad",bezier:"easeInOutCubic"}[a]||a,p=Fi[u]||Fi.linear,m=4,x=n-m*2,h=[],f=Math.min(32,Math.max(8,Math.floor(c/4)));for(let v=0;v<=f;v++){const A=v/f,g=A*c,k=p(A),N=m+x*(1-k);v===0?h.push(`M ${g} ${N}`):h.push(`L ${g} ${N}`)}return h.join(" ")},[t,s,a,n]),o=s-t;return o<=0?null:e.jsxs("svg",{className:"absolute top-0 pointer-events-none",style:{left:t,width:o,height:n},viewBox:`0 0 ${o} ${n}`,preserveAspectRatio:"none",children:[e.jsx("line",{x1:"0",y1:n/2,x2:o,y2:n/2,stroke:r,strokeWidth:"1",opacity:"0.2"}),e.jsx("path",{d:i,fill:"none",stroke:r,strokeWidth:"1.5",opacity:"0.6",strokeLinecap:"round",strokeLinejoin:"round"})]})},pd={"position.x":"#22d3ee","position.y":"#a78bfa","scale.x":"#4ade80","scale.y":"#86efac",rotation:"#f472b6",opacity:"#fbbf24",borderRadius:"#94a3b8",default:"#64748b"},ij={"position.x":"Position X","position.y":"Position Y","scale.x":"Scale X","scale.y":"Scale Y",rotation:"Rotation",opacity:"Opacity",borderRadius:"Border Radius"},oj=({clip:t,pixelsPerSecond:s,onKeyframeSelect:a,onKeyframeMove:r,onKeyframeDelete:n,selectedKeyframeIds:i})=>{const o=l.useMemo(()=>{const u=new Map;for(const p of t.keyframes){const m=u.get(p.property)||[];m.push(p),u.set(p.property,m)}return Array.from(u.entries()).map(([p,m])=>({property:p,keyframes:m.sort((x,h)=>x.time-h.time),color:pd[p]||pd.default,label:ij[p]||p})).sort((p,m)=>p.label.localeCompare(m.label))},[t.keyframes]),c=l.useCallback((u,p)=>{const m=p/s,x=t.keyframes.find(f=>f.id===u);if(!x)return;const h=Math.max(0,Math.min(t.duration,x.time+m));r(u,h)},[t.keyframes,t.duration,s,r]);if(o.length===0)return e.jsx("div",{className:"h-8 flex items-center justify-center text-[9px] text-text-muted",children:"No keyframes"});const d=24;return e.jsx("div",{className:"bg-background-tertiary/30 border-t border-border/30",children:o.map(u=>e.jsxs("div",{className:"relative border-b border-border/20 last:border-b-0",style:{height:d},children:[e.jsxs("div",{className:"absolute left-0 top-0 bottom-0 w-20 flex items-center px-2 bg-background-tertiary/50 border-r border-border/30 z-10",children:[e.jsx("div",{className:"w-2 h-2 rounded-full mr-1.5 flex-shrink-0",style:{backgroundColor:u.color}}),e.jsx("span",{className:"text-[9px] text-text-muted truncate",children:u.label})]}),e.jsx("div",{className:"absolute left-20 right-0 top-0 bottom-0",children:u.keyframes.map((p,m)=>{const x=u.keyframes[m+1],h=p.time*s;return e.jsxs(_e.Fragment,{children:[x&&e.jsx(nj,{startX:h,endX:x.time*s,easing:p.easing,color:u.color,height:d}),e.jsx(rj,{keyframe:p,xPosition:h,color:u.color,isSelected:i.includes(p.id),onSelect:f=>a(p.id,f),onMove:f=>c(p.id,f),onDelete:()=>n(p.id)})]},p.id)})})]},u.property))})},lj=({track:t,allTracks:s,pixelsPerSecond:a,selectedClipIds:r,textClips:n,shapeClips:i,trackHeights:o,timelineRef:c,onSelectClip:d,onDropMedia:u,onMoveClip:p,onMoveTextClip:m,onSnapIndicator:x,onTrimClip:h,onTrimTextClip:f,onTrimShapeClip:v,scrollX:A,trackHeight:g,onResizeTrack:k,onKeyframeSelect:N,onKeyframeMove:b,onKeyframeDelete:j,selectedKeyframeIds:y=[]})=>{const{isTrackExpanded:w,playheadPosition:S}=Et(),T=w(t.id),{snapSettings:C}=vt(),[M,z]=l.useState(!1),[L,B]=l.useState(!1),O=l.useRef(null),G=l.useRef(0),V=l.useRef(0),P=l.useMemo(()=>t.clips.filter(D=>D.keyframes&&D.keyframes.length>0),[t.clips]),_=l.useCallback(D=>{D.preventDefault(),D.dataTransfer.dropEffect="copy",z(!0)},[]),se=l.useCallback(()=>{z(!1)},[]),R=l.useCallback(async D=>{if(D.preventDefault(),D.stopPropagation(),z(!1),D.dataTransfer.files&&D.dataTransfer.files.length>0){const X=O.current?.getBoundingClientRect();if(!X)return;const K=D.clientX-X.left+A,ue=Math.max(0,K/a),Te=In(ue,"",s,S,C,a),{importMedia:pe,addClip:fe}=F.getState();for(const We of Array.from(D.dataTransfer.files))try{const Ze=new Set(F.getState().project.mediaLibrary.items.map(de=>de.id));if((await pe(We)).success){const de=F.getState().project.mediaLibrary.items.find(Ce=>!Ze.has(Ce.id));de&&(await fe(t.id,de.id,Te.time),Fe.success(`Added to ${t.name}`,We.name))}}catch(Ze){console.error("[TrackLane] External file drop failed:",Ze)}return}try{const X=D.dataTransfer.getData("application/json");if(!X)return;const K=JSON.parse(X);if(!K||typeof K!="object"||typeof K.mediaId!="string"||!K.mediaId.trim())return;const ue=O.current?.getBoundingClientRect();if(ue){const Te=D.clientX-ue.left+A,pe=Math.max(0,Te/a),fe=In(pe,"",s,S,C,a);u(t.id,K.mediaId,fe.time)}}catch{}},[t.id,t.name,a,A,u]),U=l.useCallback(D=>{D.preventDefault(),D.stopPropagation(),B(!0),G.current=D.clientY,V.current=g,document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[g]);return l.useEffect(()=>{if(!L)return;const D=K=>{const ue=K.clientY-G.current,Te=V.current+ue;k(t.id,Te)},X=()=>{B(!1),document.body.style.cursor="",document.body.style.userSelect=""};return document.addEventListener("mousemove",D),document.addEventListener("mouseup",X),()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",X)}},[L,t.id,k]),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{ref:O,style:{height:g},className:`border-b border-border/50 relative transition-colors ${M?"bg-primary/10 border-primary/30":"bg-background-secondary/20"}`,onDragOver:_,onDragLeave:se,onDrop:R,children:[t.clips.filter(D=>!n.some(X=>X.id===D.id)).filter(D=>!i.some(X=>X.id===D.id)).map(D=>e.jsx(tj,{clip:D,track:t,allTracks:s,pixelsPerSecond:a,isSelected:r.includes(D.id),trackHeights:o,timelineRef:c,onSelect:d,onMoveClip:p,onSnapIndicator:x,onTrimClip:h},D.id)),n.map(D=>e.jsx(sj,{textClip:D,pixelsPerSecond:a,isSelected:r.includes(D.id),onSelect:d,onTrim:f,onMoveClip:m},D.id)),i.map(D=>e.jsx(aj,{shapeClip:D,pixelsPerSecond:a,isSelected:r.includes(D.id),onSelect:d,onTrim:v,onMoveClip:p},D.id)),M&&e.jsx("div",{className:"absolute inset-0 border-2 border-dashed border-primary/50 rounded pointer-events-none flex items-center justify-center",children:e.jsx("span",{className:"text-xs text-primary bg-background/80 px-2 py-1 rounded",children:"Drop to add clip"})})]}),e.jsx("div",{className:`absolute bottom-0 left-0 right-0 h-1 cursor-row-resize hover:bg-primary/50 transition-colors z-10 ${L?"bg-primary":""}`,onMouseDown:U}),T&&P.length>0&&e.jsx("div",{className:"absolute left-0 right-0",style:{top:g},children:P.map(D=>e.jsx("div",{className:"relative",style:{left:D.startTime*a},children:e.jsx(oj,{clip:D,pixelsPerSecond:a,onKeyframeSelect:N??(()=>{}),onKeyframeMove:b??(()=>{}),onKeyframeDelete:j??(()=>{}),selectedKeyframeIds:y})},`keyframes-${D.id}`))})]})},cj=({pixelsPerSecond:t,scrollX:s,viewportWidth:a,totalHeight:r})=>{const[n,i]=l.useState(()=>Vi().getState());l.useEffect(()=>Vi().subscribe(i),[]);const o=l.useMemo(()=>{if(n.beatMarkers.length===0)return[];const c=s/t,d=(s+a)/t,u=1;return n.beatMarkers.filter(p=>p.time>=c-u&&p.time<=d+u)},[n.beatMarkers,s,a,t]);return o.length===0?null:e.jsx("div",{className:"absolute inset-0 pointer-events-none z-5",children:o.map(c=>{const d=c.time*t,u=c.isDownbeat;return e.jsxs("div",{className:"absolute top-0",style:{left:`${d}px`,height:`${r}px`},children:[e.jsx("div",{className:`h-full transition-opacity ${u?"w-[2px] bg-orange-500/60":"w-px bg-orange-400/30"}`}),u&&e.jsx("div",{className:"absolute -top-0.5 left-1/2 -translate-x-1/2 w-2 h-2 rounded-full bg-orange-500",title:`Beat ${c.index+1}`})]},`beat-${c.index}`)})})},dj=({marker:t,pixelsPerSecond:s,scrollX:a,onSeek:r,onRemove:n,onUpdate:i})=>{const[o,c]=_e.useState(!1),[d,u]=_e.useState(!1),[p,m]=_e.useState(t.label),x=t.time*s-a,h=g=>{g.stopPropagation(),r&&r(t.time)},f=g=>{g.stopPropagation(),u(!0)},v=g=>{g.stopPropagation(),n&&n(t.id)},A=g=>{g.key==="Enter"?(i&&p.trim()&&i(t.id,{label:p.trim()}),u(!1)):g.key==="Escape"&&(m(t.label),u(!1))};return e.jsxs("div",{className:"absolute top-0 bottom-0 flex flex-col items-center cursor-pointer z-20",style:{left:`${x}px`},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onClick:h,onDoubleClick:f,children:[e.jsx("div",{className:"w-0.5 h-full transition-opacity",style:{backgroundColor:t.color,opacity:o?1:.6}}),e.jsxs("div",{className:"absolute top-1 flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-medium whitespace-nowrap transition-all shadow-lg",style:{backgroundColor:t.color,color:"#fff",transform:o?"scale(1.05)":"scale(1)"},children:[e.jsx(Mx,{size:10}),d?e.jsx("input",{type:"text",value:p,onChange:g=>m(g.target.value),onKeyDown:A,onBlur:()=>{m(t.label),u(!1)},className:"bg-transparent border-none outline-none text-white w-20 px-1",autoFocus:!0,onClick:g=>g.stopPropagation()}):e.jsx("span",{children:t.label}),o&&n&&e.jsx("button",{onClick:v,className:"ml-1 hover:bg-white/20 rounded p-0.5 transition-colors",children:e.jsx(Ls,{size:10})})]})]})},uj=()=>{const t=l.useRef(null),s=l.useRef(null),{project:a,undo:r,redo:n,canUndo:i,canRedo:o,splitClip:c,removeClip:d,addTrack:u,reorderTrack:p,deleteShapeClip:m,deleteSVGClip:x,deleteTextClip:h,removeMarker:f,updateMarker:v,updateClipKeyframes:A}=F(),g=a.timeline.tracks,[k,N]=_e.useState(null),{playheadPosition:b,playbackState:j,pixelsPerSecond:y,scrollX:w,scrollY:S,viewportWidth:T,setScrollX:C,setScrollY:M,setViewportDimensions:z,zoomIn:L,zoomOut:B,trackHeight:O,setTrackHeight:G,setTrackHeightById:V,getTrackHeight:P}=Et(),[_,se]=l.useState(!1),{select:R,selectMultiple:U,clearSelection:D,getSelectedClipIds:X,snapSettings:K,toggleSnap:ue,timelineMaximized:Te,toggleTimelineMaximized:pe}=vt(),fe=X(),{getTitleEngine:We,getGraphicsEngine:Ze}=Ct(),at=We(),de=l.useMemo(()=>at?.getAllTextClips()??[],[at,a.modifiedAt]),Ce=l.useCallback($=>de.filter(ve=>ve.trackId===$),[de]),Ne=Ze(),Me=l.useMemo(()=>{const $=Ne?.getAllShapeClips()??[],ve=Ne?.getAllSVGClips()??[],ye=Ne?.getAllStickerClips()??[];return[...$,...ve,...ye]},[Ne,a.modifiedAt]),qe=l.useCallback($=>Me.filter(ve=>ve.trackId===$),[Me]),[nt,rt]=_e.useState(!1),[Pe,Ie]=_e.useState(null),Ee=l.useMemo(()=>{let $=0;for(const ve of g)for(const ye of ve.clips){const we=ye.startTime+ye.duration;we>$&&($=we)}return Math.max($,60)},[g]),ae=l.useMemo(()=>{const $=new Set;for(const ve of g)for(const ye of ve.clips)$.add(ye.startTime),$.add(ye.startTime+ye.duration);return Array.from($).sort((ve,ye)=>ve-ye)},[g]),W=l.useMemo(()=>{let $=0;for(const ve of g)$+=P(ve.id);return $},[g,P]),Q=l.useMemo(()=>{const $=new Map;for(const ve of g)$.set(ve.id,P(ve.id));return $},[g,P]),be=l.useCallback(($,ve)=>{$.dataTransfer.setData("trackId",ve),$.dataTransfer.effectAllowed="move",N(ve)},[]),Oe=l.useCallback($=>{$.preventDefault(),$.dataTransfer.dropEffect="move"},[]),Ue=l.useCallback(async($,ve)=>{$.preventDefault();const ye=$.dataTransfer.getData("trackId");if(N(null),ye&&ye!==ve){const we=g.findIndex(Y=>Y.id===ve);we!==-1&&await p(ye,we)}},[g,p]);l.useEffect(()=>{if(!t.current)return;const $=new ResizeObserver(ve=>{for(const ye of ve)z(ye.contentRect.width,ye.contentRect.height)});return $.observe(t.current),()=>$.disconnect()},[z]),l.useEffect(()=>{if(j!=="playing")return;const $=s.current;if(!$)return;const ve=b*y,ye=Math.min(Math.max(T*.12,60),220),we=w+T-ye;(ve>we||ve{if(de.some(je=>je.id===$)){const je=de.find(Se=>Se.id===$);R({type:"text-clip",id:$,trackId:je?.trackId},ve);return}if(Me.some(je=>je.id===$)){const je=Me.find(Se=>Se.id===$);R({type:"shape-clip",id:$,trackId:je?.trackId},ve);return}let Y;for(const je of g)if(je.clips.some(Se=>Se.id===$)){Y=je.id;break}R({type:"clip",id:$,trackId:Y},ve)},[g,R,de,Me]),[Ye,Ke]=l.useState([]),mt=l.useCallback(($,ve)=>{Ke(ve?ye=>ye.includes($)?ye.filter(we=>we!==$):[...ye,$]:[$])},[]),Ge=l.useCallback(($,ve)=>{for(const ye of g)for(const we of ye.clips)if(we.keyframes?.find(je=>je.id===$)){const je=we.keyframes?.map(Se=>Se.id===$?{...Se,time:Math.max(0,ve)}:Se);je&&A(we.id,je);return}},[g,A]),gt=l.useCallback($=>{for(const ve of g)for(const ye of ve.clips)if(ye.keyframes?.find(Y=>Y.id===$)){const Y=ye.keyframes?.filter(je=>je.id!==$);Y&&A(ye.id,Y),Ke(je=>je.filter(Se=>Se!==$));return}},[g,A]),Ft=l.useCallback(async()=>{fe.length===1&&await c(fe[0],b)},[fe,b,c]),Qe=l.useCallback(async()=>{if(fe.length!==0){for(const $ of fe){if(de.find(we=>we.id===$)){h($);continue}const ye=Me.find(we=>we.id===$);if(ye){ye.type==="svg"?x($):m($);continue}d($)}D()}},[fe,d,D,de,Me,h,m,x]),Ds=l.useCallback(()=>{D()},[D]),Cs=l.useCallback($=>{if($.button!==0||$.target.closest(".clip-component"))return;const ve=s.current?.getBoundingClientRect();if(!ve)return;const ye=$.clientX-ve.left+w,we=$.clientY-ve.top+S;rt(!0),Ie({startX:ye,startY:we,currentX:ye,currentY:we})},[w,S]),Dt=l.useCallback($=>{if(!nt||!Pe)return;const ve=s.current?.getBoundingClientRect();if(!ve)return;const ye=$.clientX-ve.left+w,we=$.clientY-ve.top+S;Ie({...Pe,currentX:ye,currentY:we})},[nt,Pe,w,S]),us=l.useCallback(()=>{if(!nt||!Pe){rt(!1),Ie(null);return}const $=Math.min(Pe.startX,Pe.currentX),ve=Math.max(Pe.startX,Pe.currentX),ye=$/y,we=ve/y;let Y=0;const je=[];for(const Se of g){const Ae=P(Se.id),Be=Y,jt=Y+Ae,Gt=Math.min(Pe.startY,Pe.currentY),Kt=Math.max(Pe.startY,Pe.currentY);if(GtBe)for(const ma of Se.clips){const Dr=ma.startTime,wt=ma.startTime+ma.duration;yeDr&&je.push({type:"clip",id:ma.id,trackId:Se.id})}Y+=Ae}je.length>0&&U(je),rt(!1),Ie(null)},[nt,Pe,y,g,P,U]);l.useEffect(()=>{if(!nt)return;const $=()=>us();return document.addEventListener("mouseup",$),()=>document.removeEventListener("mouseup",$)},[nt,us]);const Ws=l.useCallback(async($,ve,ye)=>{const{addClip:we,addClipToNewTrack:Y}=F.getState();$?await we($,ve,ye):await Y(ve,ye)},[]),{moveClip:Qt}=F(),Lt=l.useCallback(async($,ve,ye)=>{const we=Me.find(Y=>Y.id===$);we&&Ne?(we.type==="sticker"||we.type==="emoji"?Ne.updateStickerClip($,{startTime:ve}):we.type==="svg"?Ne.updateSVGClip($,{startTime:ve}):Ne.updateShapeClip($,{startTime:ve}),F.setState(Y=>({project:{...Y.project,modifiedAt:Date.now()}}))):await Qt($,ve,ye)},[Qt,Me,Ne]),[ca,ms]=_e.useState(null),da=l.useCallback($=>{ms($)},[]),ss=l.useCallback(($,ve,ye)=>{if(!at)return;const we=de.find(Ae=>Ae.id===$);if(!we)return;const Y=we.duration,je=ve==="left"?Math.max(.1,we.startTime+we.duration-ye):Math.max(.1,ye-we.startTime),Se=we.keyframes.map(Ae=>{if(Ae.id.startsWith("kf-exit-")){const Be=Ae.time-Y;return{...Ae,time:je+Be}}return Ae});ve==="left"?at.updateTextClip($,{startTime:ye,duration:je}):at.updateTextClip($,{duration:je}),F.getState().updateTextClipKeyframes($,Se),F.setState(Ae=>({project:{...Ae.project,modifiedAt:Date.now()}}))},[at,de]),ps=l.useCallback(($,ve)=>{!at||!de.find(we=>we.id===$)||(at.updateTextClip($,{startTime:Math.max(0,ve)}),F.setState(we=>({project:{...we.project,modifiedAt:Date.now()}})))},[at,de]),Ss=l.useCallback(($,ve,ye)=>{if(!Ne)return;const we=Me.find(Be=>Be.id===$);if(!we)return;const Y=we.duration,je=ve==="left"?Math.max(.1,we.startTime+we.duration-ye):Math.max(.1,ye-we.startTime),Se=ve==="left"?{startTime:ye,duration:je}:{duration:je},Ae=we.keyframes.map(Be=>{if(Be.id.startsWith("kf-exit-")){const jt=Be.time-Y;return{...Be,time:je+jt}}return Be});we.type==="sticker"||we.type==="emoji"?Ne.updateStickerClip($,Se):we.type==="svg"?Ne.updateSVGClip($,Se):Ne.updateShapeClip($,Se),F.getState().updateClipKeyframes($,Ae),F.setState(Be=>({project:{...Be.project,modifiedAt:Date.now()}}))},[Ne,Me]),qs=l.useCallback(($,ve,ye)=>{const we=g.flatMap(Be=>Be.clips).find(Be=>Be.id===$);if(!we)return;const Y=we.duration,je=ve==="left"?Math.max(.1,we.startTime+we.duration-ye):Math.max(.1,ye-we.startTime),Se=ve==="left"?{startTime:ye,duration:je}:{duration:je},Ae=we.keyframes.map(Be=>{if(Be.id.startsWith("kf-exit-")){const jt=Be.time-Y;return{...Be,time:je+jt}}return Be});F.setState(Be=>({project:{...Be.project,timeline:{...Be.project.timeline,tracks:Be.project.timeline.tracks.map(jt=>({...jt,clips:jt.clips.map(Gt=>Gt.id===$?{...Gt,...Se,keyframes:Ae}:Gt)}))},modifiedAt:Date.now()}}))},[g]),ua=l.useMemo(()=>g,[g]),He=({onClick:$,disabled:ve,active:ye,title:we,children:Y,extra:je})=>e.jsxs("button",{onClick:$,disabled:ve,"data-tip":we,title:we,className:`w-[30px] h-[30px] grid place-items-center rounded-md transition-colors relative ${ye?"bg-accent-soft text-accent":ve?"text-fg-muted opacity-50 cursor-not-allowed":"text-fg-2 hover:bg-hover hover:text-fg"}`,children:[Y,je]});return e.jsxs("div",{"data-tour":"timeline",className:"h-full bg-tl-bg flex flex-col min-h-0 relative overflow-hidden",children:[e.jsxs("div",{className:"flex items-center px-3 py-1.5 gap-0.5 bg-bg-1 border-b border-border shrink-0 relative z-[100]",children:[e.jsx(He,{onClick:r,disabled:!i(),title:"Undo (⌘Z)",children:e.jsx(pn,{size:14})}),e.jsx(He,{onClick:n,disabled:!o(),title:"Redo (⇧⌘Z)",children:e.jsx(pl,{size:14})}),e.jsx("div",{className:"w-px h-4 bg-border mx-1.5"}),e.jsx(He,{onClick:Ft,disabled:fe.length!==1,title:"Split (S)",children:e.jsx(xl,{size:14})}),e.jsx(He,{onClick:Qe,disabled:fe.length===0,title:"Delete (Del)",children:e.jsx($t,{size:14})}),e.jsx("div",{className:"w-px h-4 bg-border mx-1.5"}),e.jsxs(Di,{children:[e.jsx(Ii,{asChild:!0,children:e.jsxs("button",{"data-tip":"Add track",title:"Add track",className:"w-[30px] h-[30px] grid place-items-center rounded-md text-fg-2 hover:bg-hover hover:text-fg transition-colors relative",children:[e.jsx(cs,{size:14}),e.jsx(qt,{size:8,className:"absolute bottom-0.5 right-0.5 text-fg-3"})]})}),e.jsxs(Bi,{side:"top",align:"start",sideOffset:8,className:"w-48",children:[e.jsxs(ws,{onClick:()=>u("video"),children:[e.jsx(lr,{size:16,className:"text-clip-video"}),e.jsx("span",{children:"Video Track"})]}),e.jsxs(ws,{onClick:()=>u("audio"),children:[e.jsx(Ps,{size:16,className:"text-clip-audio"}),e.jsx("span",{children:"Audio Track"})]}),e.jsx(wn,{}),e.jsxs(ws,{onClick:()=>u("image"),children:[e.jsx(va,{size:16,className:"text-clip-music"}),e.jsx("span",{children:"Image Track"})]}),e.jsxs(ws,{onClick:()=>u("text"),children:[e.jsx(Hs,{size:16,className:"text-clip-text"}),e.jsx("span",{children:"Text Track"})]}),e.jsxs(ws,{onClick:()=>u("graphics"),children:[e.jsx(mn,{size:16,className:"text-clip-music"}),e.jsx("span",{children:"Graphics Track"})]})]})]}),e.jsxs(Fn,{open:_,onOpenChange:se,children:[e.jsx(Ln,{asChild:!0,children:e.jsx("button",{"data-tip":"Track layers",title:"Manage track layers",className:`w-[30px] h-[30px] grid place-items-center rounded-md transition-colors ${_?"bg-accent-soft text-accent":"text-fg-2 hover:bg-hover hover:text-fg"}`,children:e.jsx(Os,{size:14})})}),e.jsxs($n,{side:"top",align:"start",sideOffset:8,className:"w-64 p-0 bg-bg-1 border-border",children:[e.jsx("div",{className:"flex items-center justify-between px-3 py-2.5 border-b border-border bg-bg-2",children:e.jsx("span",{className:"text-xs font-semibold text-fg",children:"Track Layers"})}),e.jsx("div",{className:"p-2 max-h-60 overflow-y-auto",children:g.length===0?e.jsx("p",{className:"text-xs text-fg-muted text-center py-6",children:"No tracks yet"}):e.jsx("div",{className:"space-y-0.5",children:g.map(($,ve)=>{const ye=zu($,ve);return e.jsxs("div",{className:"flex items-center gap-2.5 px-2 py-2 rounded-md hover:bg-hover group transition-colors cursor-default",children:[e.jsx("div",{className:`w-7 h-7 rounded-md flex items-center justify-center ${ye.bgLight}`,children:e.jsx(ye.icon,{size:14,className:ye.textColor})}),e.jsx("span",{className:"text-[11px] font-medium text-fg flex-1 truncate",children:$.name||ye.label}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>ve>0&&p($.id,ve-1),disabled:ve===0,className:"p-1.5 rounded-md hover:bg-hover disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Move up",children:e.jsx(dp,{size:12})}),e.jsx("button",{onClick:()=>ve{G(80),Et.setState({trackHeights:{}})},active:O>=60,title:"Large tracks",children:e.jsx(Vh,{size:14})}),e.jsx(He,{onClick:()=>{G(50),Et.setState({trackHeights:{}})},active:O<60,title:"Compact tracks",children:e.jsx($h,{size:14})}),e.jsx("div",{className:"w-px h-4 bg-border mx-1.5"}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-1",children:[e.jsx(He,{onClick:B,title:"Zoom out",children:e.jsx("span",{className:"text-[15px] font-medium leading-none",children:"−"})}),e.jsxs("span",{className:"text-[10px] w-12 text-center font-mono text-fg-3 tabular-nums",children:[Math.round(y),"px/s"]}),e.jsx(He,{onClick:L,title:"Zoom in",children:e.jsx("span",{className:"text-[15px] font-medium leading-none",children:"+"})})]}),e.jsx(He,{onClick:pe,active:Te,title:Te?"Restore layout":"Maximize timeline (more room)",children:Te?e.jsx(ml,{size:14}):e.jsx(zr,{size:14})})]})]}),e.jsxs("div",{ref:t,className:"flex-1 flex flex-col overflow-hidden relative",onClick:Ds,children:[e.jsxs("div",{className:"flex shrink-0",children:[e.jsx("div",{className:"w-32 h-[26px] bg-bg-1 border-b border-r border-border shrink-0"}),e.jsx("div",{className:"flex-1 overflow-hidden relative bg-bg-1 border-b border-border",children:e.jsx("div",{style:{width:`${Ee*y}px`,transform:`translateX(-${w}px)`},children:e.jsx(Qv,{duration:Ee,pixelsPerSecond:y,scrollX:w,viewportWidth:T,snapPoints:ae,onSeek:$=>{An().scrubTo($)},onScrubStart:()=>{An().startScrubbing()},onScrubEnd:()=>{An().endScrubbing()}})})})]}),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsx("div",{className:"w-32 bg-bg-1 border-r border-border shrink-0 z-20 overflow-hidden",children:e.jsx("div",{className:"flex flex-col",style:{transform:`translateY(-${S}px)`},children:ua.map(($,ve)=>{const ye=$.clips.reduce((we,Y)=>we+(Y.keyframes?.length||0),0);return e.jsx("div",{className:k===$.id?"opacity-50":"",children:e.jsx(Jv,{track:$,index:ve,onDragStart:be,onDragOver:Oe,onDrop:Ue,keyframeCount:ye})},$.id)})})}),e.jsx("div",{ref:s,className:"flex-1 bg-background relative overflow-auto custom-scrollbar",onScroll:$=>{C($.currentTarget.scrollLeft),M($.currentTarget.scrollTop)},onMouseDown:Cs,onMouseMove:Dt,onDragOver:$=>{$.preventDefault(),$.dataTransfer.dropEffect="copy"},onDrop:async $=>{$.preventDefault();const ve=s.current?.getBoundingClientRect();if(!ve)return;const ye=$.clientX-ve.left+(s.current?.scrollLeft??0),we=Math.max(0,ye/y),Y=a.timeline.tracks.flatMap(Se=>Se.clips);let je=we;if(K.enabled){const Se=K.snapThreshold/y;let Ae=1/0;for(const Be of Y){const jt=Be.startTime+Be.duration,Gt=Math.abs(we-jt),Kt=Math.abs(we-Be.startTime);Gt0){const{importMedia:Se,addClipToNewTrack:Ae}=F.getState();for(const Be of Array.from($.dataTransfer.files))try{const jt=new Set(F.getState().project.mediaLibrary.items.map(Kt=>Kt.id));if((await Se(Be)).success){const Kt=F.getState().project.mediaLibrary.items.find(ja=>!jt.has(ja.id));if(Kt){await Ae(Kt.id,je);const ja=F.getState().project.timeline.tracks.find(ma=>ma.clips.some(Dr=>Dr.mediaId===Kt.id));ja&&Fe.success(`Added to ${ja.name}`,Be.name)}}}catch(jt){console.error("[Timeline] External file drop failed:",jt)}return}try{const Se=$.dataTransfer.getData("application/json");if(!Se)return;const Ae=JSON.parse(Se);if(!Ae?.mediaId)return;Ws("",Ae.mediaId,je)}catch{}},children:e.jsxs("div",{style:{width:`${Ee*y}px`},className:"min-w-full",children:[ua.map($=>e.jsx(lj,{track:$,allTracks:ua,pixelsPerSecond:y,selectedClipIds:fe,textClips:Ce($.id),shapeClips:qe($.id),trackHeights:Q,timelineRef:s,onSelectClip:Le,onDropMedia:Ws,onMoveClip:Lt,onSnapIndicator:da,onTrimClip:$.type==="video"||$.type==="image"||$.type==="audio"?qs:void 0,onTrimTextClip:ss,onMoveTextClip:ps,onTrimShapeClip:Ss,scrollX:w,trackHeight:P($.id),onResizeTrack:V,onKeyframeSelect:mt,onKeyframeMove:Ge,onKeyframeDelete:gt,selectedKeyframeIds:Ye},$.id)),e.jsx(cj,{pixelsPerSecond:y,scrollX:w,viewportWidth:T,totalHeight:W}),a.timeline.markers.map($=>e.jsx(dj,{marker:$,pixelsPerSecond:y,scrollX:w,onSeek:ve=>{An().scrubTo(ve)},onRemove:f,onUpdate:v},$.id)),ca!==null&&e.jsx("div",{className:"absolute top-0 bottom-0 w-px bg-yellow-400 z-30 pointer-events-none",style:{left:`${ca*y}px`},children:e.jsx("div",{className:"absolute -top-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-yellow-400 rounded-full"})}),nt&&Pe&&e.jsx("div",{className:"absolute border-2 border-primary bg-primary/10 pointer-events-none z-40",style:{left:Math.min(Pe.startX,Pe.currentX)-w,top:Math.min(Pe.startY,Pe.currentY)-S,width:Math.abs(Pe.currentX-Pe.startX),height:Math.abs(Pe.currentY-Pe.startY)}})]})})]}),e.jsx(qv,{position:b,pixelsPerSecond:y,scrollX:w,headerOffset:128})]})]})},xd={"position.x":"#22d3ee","position.y":"#a78bfa","scale.x":"#4ade80","scale.y":"#86efac",rotation:"#f472b6",opacity:"#fbbf24",borderRadius:"#94a3b8",default:"#64748b"},mj=[{label:"Linear",value:"linear"},{label:"Ease In",value:"easeInQuad"},{label:"Ease Out",value:"easeOutQuad"},{label:"Ease In Out",value:"easeInOutQuad"},{label:"Ease In Cubic",value:"easeInCubic"},{label:"Ease Out Cubic",value:"easeOutCubic"},{label:"Ease In Out Cubic",value:"easeInOutCubic"},{label:"Ease In Quart",value:"easeInQuart"},{label:"Ease Out Quart",value:"easeOutQuart"},{label:"Ease In Out Quart",value:"easeInOutQuart"},{label:"Ease In Back",value:"easeInBack"},{label:"Ease Out Back",value:"easeOutBack"},{label:"Ease In Out Back",value:"easeInOutBack"},{label:"Ease In Elastic",value:"easeInElastic"},{label:"Ease Out Elastic",value:"easeOutElastic"},{label:"Ease In Out Elastic",value:"easeInOutElastic"},{label:"Ease In Bounce",value:"easeInBounce"},{label:"Ease Out Bounce",value:"easeOutBounce"},{label:"Ease In Out Bounce",value:"easeInOutBounce"}],es=40,aa=200,pj=({clip:t,onClose:s,onUpdateKeyframe:a,onDeleteKeyframe:r,onCopyKeyframes:n,onPasteKeyframes:i,selectedKeyframeIds:o,onSelectKeyframe:c,copiedKeyframes:d})=>{const[u,p]=l.useState(null),m=l.useRef(null),[x,h]=l.useState(!1),[f,v]=l.useState(null),A=600,g=l.useMemo(()=>{if(!t?.keyframes)return[];const V=new Map;for(const P of t.keyframes){const _=V.get(P.property)||[];_.push(P),V.set(P.property,_)}return Array.from(V.entries()).map(([P,_])=>({property:P,keyframes:_.sort((se,R)=>se.time-R.time),color:xd[P]||xd.default})).sort((P,_)=>P.property.localeCompare(_.property))},[t?.keyframes]);l.useEffect(()=>{g.length>0&&!u&&p(g[0].property)},[g,u]);const k=l.useMemo(()=>g.find(V=>V.property===u)||null,[g,u]),N=l.useMemo(()=>{if(!k||k.keyframes.length===0)return{min:0,max:t?.duration||1};const V=k.keyframes.map(P=>P.time);return{min:Math.min(0,...V),max:Math.max(t?.duration||1,...V)}},[k,t?.duration]),b=l.useMemo(()=>{if(!k||k.keyframes.length===0)return{min:0,max:1};const V=k.keyframes.map(R=>R.value),P=Math.min(...V),_=Math.max(...V),se=(_-P)*.1||.1;return{min:P-se,max:_+se}},[k]),j=l.useCallback(V=>{const P=N.max-N.min;return es+(V-N.min)/P*(A-es*2)},[N,A]),y=l.useCallback(V=>{const P=b.max-b.min;return es+(1-(V-b.min)/P)*(aa-es*2)},[b]),w=l.useCallback(V=>{const P=N.max-N.min;return N.min+(V-es)/(A-es*2)*P},[N,A]),S=l.useCallback(V=>{const P=b.max-b.min;return b.min+(1-(V-es)/(aa-es*2))*P},[b]),T=l.useCallback(()=>{const V=m.current;if(!V||!k)return;const P=V.getContext("2d");if(!P)return;const _=window.devicePixelRatio||1;V.width=A*_,V.height=aa*_,P.scale(_,_),P.fillStyle="#1a1a1a",P.fillRect(0,0,A,aa),P.strokeStyle="#333",P.lineWidth=1;for(let se=0;se<=10;se++){const R=es+se/10*(A-es*2);P.beginPath(),P.moveTo(R,es),P.lineTo(R,aa-es),P.stroke()}for(let se=0;se<=5;se++){const R=es+se/5*(aa-es*2);P.beginPath(),P.moveTo(es,R),P.lineTo(A-es,R),P.stroke()}P.strokeStyle="#555",P.lineWidth=2,P.beginPath(),P.moveTo(es,aa-es),P.lineTo(A-es,aa-es),P.lineTo(A-es,es),P.stroke(),P.fillStyle="#888",P.font="10px sans-serif",P.textAlign="center";for(let se=0;se<=5;se++){const R=N.min+se/5*(N.max-N.min),U=j(R);P.fillText(R.toFixed(2)+"s",U,aa-10)}P.textAlign="right";for(let se=0;se<=5;se++){const R=b.min+se/5*(b.max-b.min),U=y(R);P.fillText(R.toFixed(2),es-5,U+3)}if(k.keyframes.length>1){P.strokeStyle=k.color,P.lineWidth=2,P.beginPath();const se=100;for(let R=0;R<=se;R++){const U=R/se,D=Math.floor(U*(k.keyframes.length-1)),X=Math.min(D+1,k.keyframes.length-1),K=U*(k.keyframes.length-1)-D,ue=k.keyframes[D],Te=k.keyframes[X],fe=(Fi[ue.easing]||Fi.linear)(K),We=ue.time+(Te.time-ue.time)*K,Ze=ue.value+(Te.value-ue.value)*fe,at=j(We),de=y(Ze);R===0?P.moveTo(at,de):P.lineTo(at,de)}P.stroke()}for(const se of k.keyframes){const R=j(se.time),U=y(se.value),D=o.includes(se.id);P.save(),P.translate(R,U),P.rotate(Math.PI/4),P.fillStyle=k.color,P.fillRect(-6,-6,12,12),D&&(P.strokeStyle="#fff",P.lineWidth=2,P.strokeRect(-6,-6,12,12),P.shadowColor=k.color,P.shadowBlur=10,P.fillRect(-6,-6,12,12)),P.restore()}},[k,A,j,y,N,b,o]);l.useEffect(()=>{T()},[T]);const C=l.useCallback(V=>{if(!k)return;const P=m.current?.getBoundingClientRect();if(!P)return;const _=V.clientX-P.left,se=V.clientY-P.top;for(const R of k.keyframes){const U=j(R.time),D=y(R.value);if(Math.sqrt((_-U)**2+(se-D)**2)<10){c(R.id,V.shiftKey||V.metaKey),h(!0),v(R.id);return}}},[k,j,y,c]),M=l.useCallback(V=>{if(!x||!f||!k)return;const P=m.current?.getBoundingClientRect();if(!P)return;const _=V.clientX-P.left,se=V.clientY-P.top,R=Math.max(0,w(_)),U=S(se);a(f,{time:R,value:U})},[x,f,k,w,S,a]),z=l.useCallback(()=>{h(!1),v(null)},[]);l.useEffect(()=>{const V=()=>{h(!1),v(null)};return window.addEventListener("mouseup",V),()=>window.removeEventListener("mouseup",V)},[]);const L=l.useCallback(()=>{n(o)},[n,o]),B=l.useCallback(()=>{t&&i(t.id,0)},[t,i]),O=l.useCallback(()=>{for(const V of o)r(V)},[o,r]),G=l.useCallback(V=>{for(const P of o)a(P,{easing:V})},[o,a]);return t?e.jsxs("div",{className:"h-full flex flex-col bg-background-secondary border-l border-border",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Keyframe Editor"}),e.jsx("button",{onClick:s,className:"p-1 rounded hover:bg-background-elevated text-text-muted hover:text-text-primary transition-colors",children:e.jsx(Ls,{size:16})})]}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-background-tertiary",children:[e.jsxs(ot,{value:u||"",onValueChange:p,children:[e.jsx(lt,{className:"w-[180px] h-8",children:e.jsx(ct,{placeholder:"Select property"})}),e.jsx(dt,{children:g.map(V=>e.jsx(ge,{value:V.property,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:V.color}}),e.jsx("span",{children:V.property})]})},V.property))})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(zt,{variant:"ghost",size:"sm",onClick:L,disabled:o.length===0,className:"h-8 px-2",children:[e.jsx(dn,{size:14,className:"mr-1"}),"Copy"]}),e.jsxs(zt,{variant:"ghost",size:"sm",onClick:B,disabled:d.length===0,className:"h-8 px-2",children:[e.jsx(ix,{size:14,className:"mr-1"}),"Paste"]}),e.jsxs(zt,{variant:"ghost",size:"sm",onClick:O,disabled:o.length===0,className:"h-8 px-2 text-red-400 hover:text-red-300",children:[e.jsx($t,{size:14,className:"mr-1"}),"Delete"]})]}),e.jsx("div",{className:"flex-1 p-4 overflow-hidden",children:e.jsx("canvas",{ref:m,width:A,height:aa,className:"rounded border border-border cursor-crosshair",style:{width:A,height:aa},onMouseDown:C,onMouseMove:M,onMouseUp:z})}),e.jsx("div",{className:"px-4 py-3 border-t border-border bg-background-tertiary",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Easing:"}),e.jsxs(ot,{value:o.length>0?void 0:"",onValueChange:G,disabled:o.length===0,children:[e.jsx(lt,{className:"w-[160px] h-7 text-xs",children:e.jsx(ct,{placeholder:"Select easing"})}),e.jsx(dt,{children:mj.map(V=>e.jsx(ge,{value:V.value,children:V.label},V.value))})]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("span",{className:"text-xs text-text-muted",children:[o.length," keyframe",o.length!==1?"s":""," selected"]})]})}),k&&e.jsx(ia,{className:"max-h-32 border-t border-border",children:e.jsx("div",{className:"p-2",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-text-muted",children:[e.jsx("th",{className:"text-left py-1 px-2",children:"Time"}),e.jsx("th",{className:"text-left py-1 px-2",children:"Value"}),e.jsx("th",{className:"text-left py-1 px-2",children:"Easing"})]})}),e.jsx("tbody",{children:k.keyframes.map(V=>e.jsxs("tr",{className:`cursor-pointer hover:bg-background-elevated transition-colors ${o.includes(V.id)?"bg-primary/20":""}`,onClick:P=>c(V.id,P.shiftKey||P.metaKey),children:[e.jsxs("td",{className:"py-1 px-2",children:[V.time.toFixed(3),"s"]}),e.jsx("td",{className:"py-1 px-2",children:V.value.toFixed(3)}),e.jsx("td",{className:"py-1 px-2",children:V.easing})]},V.id))})]})})})]}):e.jsx("div",{className:"h-full flex items-center justify-center text-text-muted",children:e.jsx("p",{className:"text-sm",children:"Select a clip with keyframes to edit"})})};function Iu(t){return t<=0?-1/0:20*Math.log10(t)}function Bu(t){return t===-1/0||t<-60?"-∞":`${t>=0?"+":""}${t.toFixed(1)}`}function xj(t){return Math.abs(t)<.05?"C":t<0?`L${Math.round(Math.abs(t)*100)}`:`R${Math.round(t*100)}`}const hj=({level:t,peak:s})=>{const a=Math.min(100,Math.max(0,t*100)),r=Math.min(100,Math.max(0,s*100)),n=i=>i>90?"bg-red-500":i>75?"bg-yellow-500":"bg-green-500";return e.jsxs("div",{className:"flex gap-0.5 h-32 w-4",children:[e.jsxs("div",{className:"flex-1 bg-gray-800 rounded-sm overflow-hidden relative",children:[e.jsx("div",{className:`absolute bottom-0 left-0 right-0 transition-all duration-75 ${n(a)}`,style:{height:`${a}%`}}),e.jsx("div",{className:"absolute left-0 right-0 h-0.5 bg-white",style:{bottom:`${r}%`}})]}),e.jsxs("div",{className:"flex-1 bg-gray-800 rounded-sm overflow-hidden relative",children:[e.jsx("div",{className:`absolute bottom-0 left-0 right-0 transition-all duration-75 ${n(a)}`,style:{height:`${a}%`}}),e.jsx("div",{className:"absolute left-0 right-0 h-0.5 bg-white",style:{bottom:`${r}%`}})]})]})},fj=({value:t,onChange:s,disabled:a})=>{const r=l.useCallback(i=>{s(parseFloat(i.target.value))},[s]),n=Iu(t);return e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-xs text-gray-400 font-mono w-12 text-center",children:[Bu(n)," dB"]}),e.jsx("input",{type:"range",min:"0",max:"4",step:"0.01",value:t,onChange:r,disabled:a,className:`h-24 w-2 appearance-none bg-gray-700 rounded-full cursor-pointer\r + [writing-mode:vertical-lr] [direction:rtl]\r + disabled:opacity-50 disabled:cursor-not-allowed\r + [&::-webkit-slider-thumb]:appearance-none\r + [&::-webkit-slider-thumb]:w-4\r + [&::-webkit-slider-thumb]:h-6\r + [&::-webkit-slider-thumb]:bg-gray-300\r + [&::-webkit-slider-thumb]:rounded\r + [&::-webkit-slider-thumb]:cursor-pointer\r + [&::-webkit-slider-thumb]:shadow-md\r + [&::-moz-range-thumb]:w-4\r + [&::-moz-range-thumb]:h-6\r + [&::-moz-range-thumb]:bg-gray-300\r + [&::-moz-range-thumb]:rounded\r + [&::-moz-range-thumb]:cursor-pointer\r + [&::-moz-range-thumb]:border-0`,"aria-label":"Volume fader"})]})},gj=({value:t,onChange:s,disabled:a})=>{const r=l.useCallback(n=>{s(parseFloat(n.target.value))},[s]);return e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-xs text-gray-400 font-mono",children:xj(t)}),e.jsx("input",{type:"range",min:"-1",max:"1",step:"0.01",value:t,onChange:r,disabled:a,className:`w-16 h-2 appearance-none bg-gray-700 rounded-full cursor-pointer\r + disabled:opacity-50 disabled:cursor-not-allowed\r + [&::-webkit-slider-thumb]:appearance-none\r + [&::-webkit-slider-thumb]:w-3\r + [&::-webkit-slider-thumb]:h-3\r + [&::-webkit-slider-thumb]:bg-blue-500\r + [&::-webkit-slider-thumb]:rounded-full\r + [&::-webkit-slider-thumb]:cursor-pointer\r + [&::-moz-range-thumb]:w-3\r + [&::-moz-range-thumb]:h-3\r + [&::-moz-range-thumb]:bg-blue-500\r + [&::-moz-range-thumb]:rounded-full\r + [&::-moz-range-thumb]:cursor-pointer\r + [&::-moz-range-thumb]:border-0`,"aria-label":"Pan control"})]})},bj=({channel:t,onVolumeChange:s,onPanChange:a,onMuteToggle:r,onSoloToggle:n,hasSoloedTracks:i})=>{const o=l.useCallback(x=>{s(t.trackId,x)},[t.trackId,s]),c=l.useCallback(x=>{a(t.trackId,x)},[t.trackId,a]),d=l.useCallback(()=>{r(t.trackId)},[t.trackId,r]),u=l.useCallback(()=>{n(t.trackId)},[t.trackId,n]),p=l.useMemo(()=>!!(t.muted||i&&!t.solo),[t.muted,t.solo,i]),m=t.trackType==="audio"?"🎵":"🎬";return e.jsxs("div",{className:`flex flex-col items-center gap-2 p-3 bg-gray-800 rounded-lg min-w-[80px] + ${p?"opacity-60":""}`,"data-testid":`channel-strip-${t.trackId}`,children:[e.jsxs("div",{className:"text-xs text-gray-300 font-medium truncate w-full text-center",title:t.trackName,children:[e.jsx("span",{className:"mr-1",children:m}),t.trackName]}),e.jsx(hj,{level:t.rmsLevel,peak:t.peakLevel}),e.jsx(gj,{value:t.pan,onChange:c,disabled:p}),e.jsx(fj,{value:t.volume,onChange:o,disabled:t.muted}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:d,className:`px-2 py-1 text-xs font-bold rounded transition-colors + ${t.muted?"bg-red-600 text-white":"bg-gray-700 text-gray-400 hover:bg-gray-600"}`,"aria-label":t.muted?"Unmute track":"Mute track","aria-pressed":t.muted,children:"M"}),e.jsx("button",{onClick:u,className:`px-2 py-1 text-xs font-bold rounded transition-colors + ${t.solo?"bg-yellow-500 text-black":"bg-gray-700 text-gray-400 hover:bg-gray-600"}`,"aria-label":t.solo?"Unsolo track":"Solo track","aria-pressed":t.solo,children:"S"})]})]})},yj=({volume:t,peakLevel:s,rmsLevel:a,onVolumeChange:r})=>{const n=l.useCallback(u=>{r(parseFloat(u.target.value))},[r]),i=Iu(t),o=Math.min(100,Math.max(0,a*100)),c=Math.min(100,Math.max(0,s*100)),d=u=>u>90?"bg-red-500":u>75?"bg-yellow-500":"bg-green-500";return e.jsxs("div",{className:"flex flex-col items-center gap-2 p-3 bg-gray-900 rounded-lg min-w-[100px] border border-gray-700",children:[e.jsx("div",{className:"text-xs text-gray-300 font-bold",children:"MASTER"}),e.jsxs("div",{className:"flex gap-1 h-32 w-6",children:[e.jsxs("div",{className:"flex-1 bg-gray-800 rounded-sm overflow-hidden relative",children:[e.jsx("div",{className:`absolute bottom-0 left-0 right-0 transition-all duration-75 ${d(o)}`,style:{height:`${o}%`}}),e.jsx("div",{className:"absolute left-0 right-0 h-0.5 bg-white",style:{bottom:`${c}%`}})]}),e.jsxs("div",{className:"flex-1 bg-gray-800 rounded-sm overflow-hidden relative",children:[e.jsx("div",{className:`absolute bottom-0 left-0 right-0 transition-all duration-75 ${d(o)}`,style:{height:`${o}%`}}),e.jsx("div",{className:"absolute left-0 right-0 h-0.5 bg-white",style:{bottom:`${c}%`}})]})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-xs text-gray-400 font-mono w-12 text-center",children:[Bu(i)," dB"]}),e.jsx("input",{type:"range",min:"0",max:"4",step:"0.01",value:t,onChange:n,className:`h-24 w-2 appearance-none bg-gray-700 rounded-full cursor-pointer\r + [writing-mode:vertical-lr] [direction:rtl]\r + [&::-webkit-slider-thumb]:appearance-none\r + [&::-webkit-slider-thumb]:w-4\r + [&::-webkit-slider-thumb]:h-6\r + [&::-webkit-slider-thumb]:bg-orange-500\r + [&::-webkit-slider-thumb]:rounded\r + [&::-webkit-slider-thumb]:cursor-pointer\r + [&::-webkit-slider-thumb]:shadow-md\r + [&::-moz-range-thumb]:w-4\r + [&::-moz-range-thumb]:h-6\r + [&::-moz-range-thumb]:bg-orange-500\r + [&::-moz-range-thumb]:rounded\r + [&::-moz-range-thumb]:cursor-pointer\r + [&::-moz-range-thumb]:border-0`,"aria-label":"Master volume fader"})]})]})},vj=({visible:t=!0,onClose:s})=>{const a=F(C=>C.project),r=F(C=>C.muteTrack),n=F(C=>C.soloTrack),i=l.useRef(null),[o,c]=l.useState(1),[d,u]=l.useState(0),[p,m]=l.useState(0),[x,h]=l.useState({}),[f,v]=l.useState({}),[A,g]=l.useState({}),k=l.useMemo(()=>(a?.timeline?.tracks??[]).filter(M=>M.type==="audio"||M.type==="video"),[a?.timeline?.tracks]);l.useEffect(()=>{try{i.current=Nn()}catch{i.current=null}},[]),l.useEffect(()=>{if(!t||!i.current)return;const C=i.current;try{typeof C.getMasterVolume=="function"&&c(C.getMasterVolume()),typeof C.getTrackVolume=="function"&&typeof C.getTrackPan=="function"&&(h(M=>{const z={...M};return k.forEach(L=>{z[L.id]=C.getTrackVolume(L.id)}),z}),v(M=>{const z={...M};return k.forEach(L=>{z[L.id]=C.getTrackPan(L.id)}),z}))}catch{}},[t,k]);const N=l.useMemo(()=>k.some(C=>C.solo),[k]),b=l.useMemo(()=>k.map(C=>({trackId:C.id,trackName:C.name,trackType:C.type,volume:x[C.id]??1,pan:f[C.id]??0,muted:C.muted,solo:C.solo,peakLevel:A[C.id]?.peak??0,rmsLevel:A[C.id]?.rms??0})),[k,x,f,A]),j=l.useCallback((C,M)=>{h(z=>({...z,[C]:M})),i.current?.updateTrackVolume(C,M)},[]),y=l.useCallback((C,M)=>{v(z=>({...z,[C]:M})),i.current?.updateTrackPan(C,M)},[]),w=l.useCallback(async C=>{const M=k.find(z=>z.id===C);M&&await r(C,!M.muted)},[k,r]),S=l.useCallback(async C=>{const M=k.find(z=>z.id===C);M&&await n(C,!M.solo)},[k,n]),T=l.useCallback(C=>{c(C),i.current?.setMasterVolume(C)},[]);return l.useEffect(()=>{if(!t)return;const C=setInterval(()=>{const M={};k.forEach(L=>{const B=!L.muted&&(!N||L.solo),O=x[L.id]??1;if(B&&O>0){const G=O*.4;M[L.id]={peak:Math.min(1,G*1.2),rms:G}}else M[L.id]={peak:0,rms:0}}),g(M);const z=Object.values(M).filter(L=>L.rms>0);if(z.length>0){const L=z.reduce((O,G)=>O+G.rms,0)/z.length,B=Math.max(...z.map(O=>O.peak));m(Math.min(1,L*o)),u(Math.min(1,B*o))}else m(0),u(0)},100);return()=>clearInterval(C)},[t,k,N,o,x]),t?e.jsxs("div",{className:"bg-gray-900 border-t border-gray-700 p-4","data-testid":"audio-mixer",role:"region","aria-label":"Audio Mixing Console",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Audio Mixer"}),s&&e.jsx("button",{onClick:s,className:"text-gray-400 hover:text-white transition-colors","aria-label":"Close mixer",children:"✕"})]}),e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[b.length>0?b.map(C=>e.jsx(bj,{channel:C,onVolumeChange:j,onPanChange:y,onMuteToggle:w,onSoloToggle:S,hasSoloedTracks:N},C.trackId)):e.jsx("div",{className:"text-gray-500 text-sm py-8 px-4",children:"No audio tracks in timeline. Add audio or video tracks to see channel strips."}),b.length>0&&e.jsx("div",{className:"w-px bg-gray-700 mx-2 self-stretch"}),e.jsx(yj,{volume:o,peakLevel:d,rmsLevel:p,onVolumeChange:T})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-800 flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("span",{children:[b.length," channel",b.length!==1?"s":"",N&&e.jsx("span",{className:"ml-2 text-yellow-500",children:"• Solo active"})]}),e.jsxs("span",{children:["Sample Rate: ",a.settings.sampleRate,"Hz | Channels:"," ",a.settings.channels]})]})]}):null},hd="openreel_shortcuts",fd="openreel_shortcut_preset";function rl(t){const s=t.toLowerCase().split("+");return{key:s[s.length-1],meta:s.includes("cmd")||s.includes("meta"),ctrl:s.includes("ctrl"),shift:s.includes("shift"),alt:s.includes("alt")||s.includes("option")}}function Fu(t){const s=[];(t.meta||t.ctrl)&&s.push("⌘"),t.shift&&s.push("⇧"),t.alt&&s.push("⌥");const a={space:"Space",arrowleft:"←",arrowright:"→",arrowup:"↑",arrowdown:"↓",delete:"⌫",backspace:"⌫",escape:"Esc",enter:"↵",tab:"⇥",home:"Home",end:"End"};return s.push(a[t.key]||t.key.toUpperCase()),s.join("")}const jj=[{id:"playback.playPause",name:"Play/Pause",description:"Toggle playback",category:"playback",defaultKey:"space",currentKey:"space",action:"playback.playPause",enabled:!0},{id:"playback.frameBack",name:"Frame Back",description:"Move back one frame",category:"playback",defaultKey:"arrowleft",currentKey:"arrowleft",action:"playback.frameBack",enabled:!0},{id:"playback.frameForward",name:"Frame Forward",description:"Move forward one frame",category:"playback",defaultKey:"arrowright",currentKey:"arrowright",action:"playback.frameForward",enabled:!0},{id:"playback.secondBack",name:"Second Back",description:"Move back one second",category:"playback",defaultKey:"shift+arrowleft",currentKey:"shift+arrowleft",action:"playback.secondBack",enabled:!0},{id:"playback.secondForward",name:"Second Forward",description:"Move forward one second",category:"playback",defaultKey:"shift+arrowright",currentKey:"shift+arrowright",action:"playback.secondForward",enabled:!0},{id:"playback.jump5Back",name:"Jump 5s Back",description:"Move back 5 seconds",category:"playback",defaultKey:"arrowup",currentKey:"arrowup",action:"playback.jump5Back",enabled:!0},{id:"playback.jump5Forward",name:"Jump 5s Forward",description:"Move forward 5 seconds",category:"playback",defaultKey:"arrowdown",currentKey:"arrowdown",action:"playback.jump5Forward",enabled:!0},{id:"playback.goToStart",name:"Go to Start",description:"Jump to timeline start",category:"playback",defaultKey:"home",currentKey:"home",action:"playback.goToStart",enabled:!0},{id:"playback.goToEnd",name:"Go to End",description:"Jump to timeline end",category:"playback",defaultKey:"end",currentKey:"end",action:"playback.goToEnd",enabled:!0},{id:"playback.prevClip",name:"Previous Clip",description:"Jump to previous clip edge",category:"playback",defaultKey:"[",currentKey:"[",action:"playback.prevClip",enabled:!0},{id:"playback.nextClip",name:"Next Clip",description:"Jump to next clip edge",category:"playback",defaultKey:"]",currentKey:"]",action:"playback.nextClip",enabled:!0},{id:"editing.undo",name:"Undo",description:"Undo last action",category:"editing",defaultKey:"cmd+z",currentKey:"cmd+z",action:"editing.undo",enabled:!0},{id:"editing.redo",name:"Redo",description:"Redo last undone action",category:"editing",defaultKey:"cmd+shift+z",currentKey:"cmd+shift+z",action:"editing.redo",enabled:!0},{id:"editing.cut",name:"Cut",description:"Cut selected clips",category:"editing",defaultKey:"cmd+x",currentKey:"cmd+x",action:"editing.cut",enabled:!0},{id:"editing.copy",name:"Copy",description:"Copy selected clips",category:"editing",defaultKey:"cmd+c",currentKey:"cmd+c",action:"editing.copy",enabled:!0},{id:"editing.paste",name:"Paste",description:"Paste clips at playhead",category:"editing",defaultKey:"cmd+v",currentKey:"cmd+v",action:"editing.paste",enabled:!0},{id:"editing.duplicate",name:"Duplicate",description:"Duplicate selected clip",category:"editing",defaultKey:"cmd+d",currentKey:"cmd+d",action:"editing.duplicate",enabled:!0},{id:"editing.delete",name:"Delete",description:"Delete selected clips",category:"editing",defaultKey:"delete",currentKey:"delete",action:"editing.delete",enabled:!0},{id:"editing.rippleDelete",name:"Ripple Delete",description:"Delete and close gap",category:"editing",defaultKey:"shift+delete",currentKey:"shift+delete",action:"editing.rippleDelete",enabled:!0},{id:"editing.split",name:"Split",description:"Split clip at playhead",category:"editing",defaultKey:"s",currentKey:"s",action:"editing.split",enabled:!0},{id:"editing.trimStart",name:"Trim Start",description:"Trim clip start to playhead",category:"editing",defaultKey:"q",currentKey:"q",action:"editing.trimStart",enabled:!0},{id:"editing.trimEnd",name:"Trim End",description:"Trim clip end to playhead",category:"editing",defaultKey:"w",currentKey:"w",action:"editing.trimEnd",enabled:!0},{id:"selection.selectAll",name:"Select All",description:"Select all clips",category:"selection",defaultKey:"cmd+a",currentKey:"cmd+a",action:"selection.selectAll",enabled:!0},{id:"selection.deselect",name:"Deselect",description:"Clear selection",category:"selection",defaultKey:"escape",currentKey:"escape",action:"selection.deselect",enabled:!0},{id:"timeline.toggleSnap",name:"Toggle Snap",description:"Toggle snapping",category:"timeline",defaultKey:"n",currentKey:"n",action:"timeline.toggleSnap",enabled:!0},{id:"timeline.zoomIn",name:"Zoom In",description:"Zoom in timeline",category:"timeline",defaultKey:"cmd+=",currentKey:"cmd+=",action:"timeline.zoomIn",enabled:!0},{id:"timeline.zoomOut",name:"Zoom Out",description:"Zoom out timeline",category:"timeline",defaultKey:"cmd+-",currentKey:"cmd+-",action:"timeline.zoomOut",enabled:!0},{id:"timeline.fitTimeline",name:"Fit Timeline",description:"Fit timeline to view",category:"timeline",defaultKey:"cmd+0",currentKey:"cmd+0",action:"timeline.fitTimeline",enabled:!0},{id:"view.showShortcuts",name:"Show Shortcuts",description:"Show keyboard shortcuts",category:"view",defaultKey:"?",currentKey:"?",action:"view.showShortcuts",enabled:!0},{id:"file.save",name:"Save",description:"Save project",category:"file",defaultKey:"cmd+s",currentKey:"cmd+s",action:"file.save",enabled:!0},{id:"file.export",name:"Export",description:"Export video",category:"file",defaultKey:"cmd+e",currentKey:"cmd+e",action:"file.export",enabled:!0},{id:"tools.addText",name:"Add Text",description:"Add text clip",category:"tools",defaultKey:"t",currentKey:"t",action:"tools.addText",enabled:!0},{id:"tools.addMarker",name:"Add Marker",description:"Add marker at playhead",category:"tools",defaultKey:"m",currentKey:"m",action:"tools.addMarker",enabled:!0}],gd=[{id:"openreel",name:"OpenReel Default",description:"Default OpenReel shortcuts",shortcuts:{}},{id:"capcut",name:"CapCut",description:"CapCut-style shortcuts",shortcuts:{"editing.split":"ctrl+b","playback.playPause":"space","editing.delete":"delete"}},{id:"premiere",name:"Adobe Premiere",description:"Premiere Pro-style shortcuts",shortcuts:{"editing.split":"cmd+k","playback.playPause":"space","playback.frameBack":"arrowleft","playback.frameForward":"arrowright","editing.rippleDelete":"shift+delete"}},{id:"finalcut",name:"Final Cut Pro",description:"Final Cut Pro-style shortcuts",shortcuts:{"editing.split":"cmd+b","playback.playPause":"space","editing.trimStart":"[","editing.trimEnd":"]"}},{id:"davinci",name:"DaVinci Resolve",description:"DaVinci Resolve-style shortcuts",shortcuts:{"editing.split":"cmd+\\","playback.playPause":"space","editing.rippleDelete":"shift+backspace"}}];class wj{shortcuts=new Map;handlers=new Map;activePreset="openreel";isListening=!1;constructor(){this.loadShortcuts(),this.loadPreset()}loadShortcuts(){const s=localStorage.getItem(hd),a=s?JSON.parse(s):{};jj.forEach(r=>{const n=a[r.id];this.shortcuts.set(r.id,{...r,currentKey:n||r.defaultKey})})}loadPreset(){const s=localStorage.getItem(fd);s&&(this.activePreset=s)}saveShortcuts(){const s={};this.shortcuts.forEach((a,r)=>{a.currentKey!==a.defaultKey&&(s[r]=a.currentKey)}),localStorage.setItem(hd,JSON.stringify(s))}savePreset(){localStorage.setItem(fd,this.activePreset)}startListening(){this.isListening||(this.isListening=!0,window.addEventListener("keydown",this.handleKeyDown))}stopListening(){this.isListening&&(this.isListening=!1,window.removeEventListener("keydown",this.handleKeyDown))}handleKeyDown=s=>{if(s.target instanceof HTMLInputElement||s.target instanceof HTMLTextAreaElement)return;const a=this.findMatchingShortcut(s);a&&(s.preventDefault(),s.stopPropagation(),this.executeAction(a.action,s))};findMatchingShortcut(s){const a=s.metaKey||s.ctrlKey;for(const r of this.shortcuts.values()){if(!r.enabled)continue;const n=rl(r.currentKey),i=s.key.toLowerCase()===n.key||s.code.toLowerCase()===n.key,o=(n.meta||n.ctrl)===a,c=n.shift===s.shiftKey,d=n.alt===s.altKey;if(i&&o&&c&&d)return r}return null}executeAction(s,a){const r=this.handlers.get(s);r&&r.forEach(n=>n(a))}registerHandler(s,a){return this.handlers.has(s)||this.handlers.set(s,new Set),this.handlers.get(s).add(a),()=>{this.handlers.get(s)?.delete(a)}}getShortcut(s){return this.shortcuts.get(s)}getAllShortcuts(){return Array.from(this.shortcuts.values())}getShortcutsByCategory(s){return this.getAllShortcuts().filter(a=>a.category===s)}setShortcut(s,a){const r=this.shortcuts.get(s);return!r||this.findConflict(a,s)?!1:(this.shortcuts.set(s,{...r,currentKey:a}),this.saveShortcuts(),!0)}resetShortcut(s){const a=this.shortcuts.get(s);a&&(this.shortcuts.set(s,{...a,currentKey:a.defaultKey}),this.saveShortcuts())}resetAllShortcuts(){this.shortcuts.forEach((s,a)=>{this.shortcuts.set(a,{...s,currentKey:s.defaultKey})}),this.saveShortcuts()}findConflict(s,a){for(const[r,n]of this.shortcuts)if(r!==a&&n.currentKey.toLowerCase()===s.toLowerCase())return n;return null}getPresets(){return gd}getActivePreset(){return this.activePreset}applyPreset(s){const a=gd.find(r=>r.id===s);a&&(this.resetAllShortcuts(),Object.entries(a.shortcuts).forEach(([r,n])=>{const i=this.shortcuts.get(r);i&&this.shortcuts.set(r,{...i,currentKey:n})}),this.activePreset=s,this.saveShortcuts(),this.savePreset())}formatShortcut(s){const a=this.shortcuts.get(s);if(!a)return"";const r=rl(a.currentKey);return Fu(r)}getCategories(){return["playback","editing","selection","timeline","view","file","tools"]}getCategoryName(s){return{playback:"Playback",editing:"Editing",selection:"Selection",timeline:"Timeline",view:"View",file:"File",tools:"Tools"}[s]}}const hs=new wj;function kj(t){const s=rl(t);return Fu(s)}const Nj=({isOpen:t,onClose:s})=>{const[a,r]=l.useState(""),[n,i]=l.useState("all"),[o,c]=l.useState([]),[d,u]=l.useState(null),[p,m]=l.useState(!1),[x,h]=l.useState(hs.getActivePreset());l.useEffect(()=>{c(hs.getAllShortcuts())},[]),l.useEffect(()=>{const y=w=>{w.key==="Escape"&&t&&(d?u(null):s())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t,s,d]);const f=o.filter(y=>{const w=n==="all"||y.category===n,S=a===""||y.name.toLowerCase().includes(a.toLowerCase())||y.description.toLowerCase().includes(a.toLowerCase());return w&&S}),v=f.reduce((y,w)=>(y[w.category]||(y[w.category]=[]),y[w.category].push(w),y),{}),A=l.useCallback((y,w)=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){u(null);return}if(["Shift","Control","Alt","Meta"].includes(y.key))return;const S=[];(y.metaKey||y.ctrlKey)&&S.push("cmd"),y.shiftKey&&S.push("shift"),y.altKey&&S.push("alt"),S.push(y.key.toLowerCase());const T=S.join("+"),C=hs.findConflict(T,w);if(C){alert(`This shortcut conflicts with "${C.name}". Choose a different key.`);return}hs.setShortcut(w,T),c(hs.getAllShortcuts()),u(null)},[]),g=y=>{hs.resetShortcut(y),c(hs.getAllShortcuts())},k=()=>{confirm("Reset all shortcuts to defaults?")&&(hs.resetAllShortcuts(),c(hs.getAllShortcuts()))},N=y=>{hs.applyPreset(y),c(hs.getAllShortcuts()),h(y),m(!1)},b=hs.getCategories(),j=hs.getPresets();return t?e.jsx(ur,{open:!0,onOpenChange:y=>!y&&s(),children:e.jsxs(mr,{className:"max-w-3xl max-h-[80vh] p-0 gap-0 bg-background-secondary border-border overflow-hidden flex flex-col",children:[e.jsx(pr,{className:"p-4 border-b border-border bg-background-tertiary space-y-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rc,{size:20,className:"text-primary"}),e.jsx(xr,{className:"text-lg font-bold text-text-primary",children:"Keyboard Shortcuts"})]})}),e.jsxs("div",{className:"flex items-center gap-3 p-4 border-b border-border",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(la,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-muted z-10"}),e.jsx(ts,{type:"text",value:a,onChange:y=>r(y.target.value),placeholder:"Search shortcuts...",className:"pl-9 bg-background-tertiary border-border text-text-primary"})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>m(!p),className:"flex items-center gap-2 px-3 py-2 bg-background-tertiary border border-border rounded-lg text-sm text-text-secondary hover:text-text-primary transition-colors",children:[e.jsx("span",{children:j.find(y=>y.id===x)?.name||"Preset"}),e.jsx(qt,{size:14})]}),p&&e.jsx("div",{className:"absolute top-full right-0 mt-1 w-48 bg-background-secondary border border-border rounded-lg shadow-lg z-10",children:j.map(y=>e.jsxs("button",{onClick:()=>N(y.id),className:`w-full text-left px-3 py-2 text-sm transition-colors ${x===y.id?"bg-primary/10 text-primary":"text-text-secondary hover:bg-background-tertiary hover:text-text-primary"}`,children:[e.jsx("div",{className:"font-medium",children:y.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:y.description})]},y.id))})]}),e.jsxs("button",{onClick:k,className:"flex items-center gap-1 px-3 py-2 text-sm text-text-muted hover:text-text-primary transition-colors",children:[e.jsx(Ns,{size:14}),"Reset All"]})]}),e.jsxs("div",{className:"flex gap-2 px-4 py-2 border-b border-border overflow-x-auto",children:[e.jsx("button",{onClick:()=>i("all"),className:`px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-colors ${n==="all"?"bg-primary text-white":"text-text-secondary hover:text-text-primary hover:bg-background-tertiary"}`,children:"All"}),b.map(y=>e.jsx("button",{onClick:()=>i(y),className:`px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-colors ${n===y?"bg-primary text-white":"text-text-secondary hover:text-text-primary hover:bg-background-tertiary"}`,children:hs.getCategoryName(y)},y))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[Object.entries(v).map(([y,w])=>e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-bold text-text-muted uppercase tracking-wider mb-3",children:hs.getCategoryName(y)}),e.jsx("div",{className:"space-y-1",children:w.map(S=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-background-tertiary group",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm text-text-primary",children:S.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:S.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d===S.id?e.jsx("input",{autoFocus:!0,onKeyDown:T=>A(T,S.id),placeholder:"Press keys...",className:"w-32 px-2 py-1 bg-primary/20 border border-primary rounded text-sm text-center text-text-primary focus:outline-none"}):e.jsx("button",{onClick:()=>u(S.id),className:"min-w-[80px] px-3 py-1.5 bg-background-tertiary border border-border rounded text-sm font-mono text-text-primary hover:border-primary transition-colors",children:kj(S.currentKey)}),S.currentKey!==S.defaultKey&&e.jsx("button",{onClick:()=>g(S.id),className:"p-1 text-text-muted hover:text-text-primary opacity-0 group-hover:opacity-100 transition-opacity",title:"Reset to default",children:e.jsx(Ns,{size:12})})]})]},S.id))})]},y)),f.length===0&&e.jsxs("div",{className:"text-center py-8 text-text-muted",children:[e.jsx(rc,{size:32,className:"mx-auto mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:"No shortcuts found"})]})]}),e.jsx("div",{className:"p-3 border-t border-border bg-background-tertiary text-center",children:e.jsxs("p",{className:"text-[10px] text-text-muted",children:["Click a shortcut key to customize • Press"," ",e.jsx("kbd",{className:"px-1.5 py-0.5 bg-background-secondary border border-border rounded text-[10px]",children:"?"})," ","to toggle this overlay"]})})]})}):null};class Cj extends _e.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("[ErrorBoundary] Component error:",s,a),this.props.onError?.(s,a)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center bg-background-secondary/50 rounded-lg m-2",children:[e.jsx("div",{className:"text-red-400 text-sm font-medium mb-2",children:"Something went wrong"}),e.jsx("div",{className:"text-text-muted text-xs mb-4 max-w-xs",children:this.state.error?.message||"An unexpected error occurred"}),e.jsx("button",{onClick:this.handleRetry,className:"px-4 py-2 bg-primary/20 hover:bg-primary/30 text-primary text-xs rounded transition-colors",children:"Retry"})]}):this.props.children}}const Qr=({name:t,children:s})=>e.jsx(Cj,{fallback:e.jsx("div",{className:"flex-1 flex items-center justify-center p-4 text-center",children:e.jsxs("div",{className:"text-text-muted text-xs",children:[t," failed to load. Please refresh the page."]})}),children:s});function Sj(){const[t,s]=l.useState(!1),{undo:a,redo:r,splitClip:n,removeClip:i,rippleDeleteClip:o,copyClips:c,pasteClips:d,duplicateClip:u,getClip:p,project:m,addMarker:x}=F(),{getSelectedClipIds:h,clearSelection:f,toggleSnap:v,select:A}=vt(),{togglePlayback:g,seekRelative:k,seekTo:N,playheadPosition:b,zoomIn:j,zoomOut:y,zoomToFit:w}=Et(),S=l.useCallback(()=>{g()},[g]),T=l.useCallback(()=>{k(-1/30)},[k]),C=l.useCallback(()=>{k(1/30)},[k]),M=l.useCallback(()=>{k(-1)},[k]),z=l.useCallback(()=>{k(1)},[k]),L=l.useCallback(()=>{k(-5)},[k]),B=l.useCallback(()=>{k(5)},[k]),O=l.useCallback(()=>{N(0)},[N]),G=l.useCallback(()=>{let Ie=0;for(const Ee of m.timeline.tracks)for(const ae of Ee.clips){const W=ae.startTime+ae.duration;W>Ie&&(Ie=W)}N(Ie)},[N,m.timeline.tracks]),V=l.useCallback(()=>{const Ie=b;let Ee=0;for(const ae of m.timeline.tracks)for(const W of ae.clips){const Q=W.startTime+W.duration;W.startTimeEe&&(Ee=W.startTime),QEe&&(Ee=Q)}N(Ee)},[N,m.timeline.tracks,b]),P=l.useCallback(()=>{const Ie=b;let Ee=1/0;for(const ae of m.timeline.tracks)for(const W of ae.clips){const Q=W.startTime+W.duration;W.startTime>Ie+.001&&W.startTimeIe+.001&&Q{a()},[a]),se=l.useCallback(()=>{r()},[r]),R=l.useCallback(()=>{const Ie=h();Ie.length>0&&c(Ie)},[h,c]),U=l.useCallback(()=>{const Ie=h();Ie.length>0&&(c(Ie),Ie.forEach(Ee=>i(Ee)))},[h,c,i]),D=l.useCallback(()=>{const Ie=b,Ee=m.timeline.tracks[0];Ee&&d(Ee.id,Ie)},[d,b,m.timeline.tracks]),X=l.useCallback(()=>{const Ie=h();Ie.length===1&&u(Ie[0])},[h,u]),K=l.useCallback(()=>{h().forEach(Ee=>i(Ee)),f()},[h,i,f]),ue=l.useCallback(()=>{h().forEach(Ee=>o(Ee)),f()},[h,o,f]),Te=l.useCallback(()=>{const Ie=h();if(Ie.length===1){const Ee=b,ae=p(Ie[0]);ae&&Ee>ae.startTime&&Ee{const Ie=h();if(Ie.length===1){const Ee=b;F.getState().trimToPlayhead(Ie[0],Ee,!0)}},[h,b]),fe=l.useCallback(()=>{const Ie=h();if(Ie.length===1){const Ee=b;F.getState().trimToPlayhead(Ie[0],Ee,!1)}},[h,b]),We=l.useCallback(()=>{for(const Ie of m.timeline.tracks)for(const Ee of Ie.clips)A({id:Ee.id,type:"clip"})},[A,m.timeline.tracks]),Ze=l.useCallback(()=>{f()},[f]),at=l.useCallback(()=>{v()},[v]),de=l.useCallback(()=>{j()},[j]),Ce=l.useCallback(()=>{y()},[y]),Ne=l.useCallback(()=>{let Ie=0;for(const Ee of m.timeline.tracks)for(const ae of Ee.clips){const W=ae.startTime+ae.duration;W>Ie&&(Ie=W)}w(Ie||60)},[w,m.timeline.tracks]),Me=l.useCallback(()=>{s(!0)},[]),qe=l.useCallback(()=>{},[]),nt=l.useCallback(()=>{},[]),rt=l.useCallback(()=>{},[]),Pe=l.useCallback(()=>{const Ie=b,Ee=m.timeline.markers.length;x(Ie,`Marker ${Ee+1}`,"#3b82f6")},[b,m.timeline.markers.length,x]);return l.useEffect(()=>{const Ee=[["playback.playPause",S],["playback.frameBack",T],["playback.frameForward",C],["playback.secondBack",M],["playback.secondForward",z],["playback.jump5Back",L],["playback.jump5Forward",B],["playback.goToStart",O],["playback.goToEnd",G],["playback.prevClip",V],["playback.nextClip",P],["editing.undo",_],["editing.redo",se],["editing.cut",U],["editing.copy",R],["editing.paste",D],["editing.duplicate",X],["editing.delete",K],["editing.rippleDelete",ue],["editing.split",Te],["editing.trimStart",pe],["editing.trimEnd",fe],["selection.selectAll",We],["selection.deselect",Ze],["timeline.toggleSnap",at],["timeline.zoomIn",de],["timeline.zoomOut",Ce],["timeline.fitTimeline",Ne],["view.showShortcuts",Me],["file.save",qe],["file.export",nt],["tools.addText",rt],["tools.addMarker",Pe]].map(([ae,W])=>hs.registerHandler(ae,W));return hs.startListening(),()=>{Ee.forEach(ae=>ae()),hs.stopListening()}},[S,T,C,M,z,L,B,O,G,V,P,_,se,U,R,D,X,K,ue,Te,pe,fe,We,Ze,at,de,Ce,Ne,Me,qe,nt,rt,Pe]),{showShortcutsOverlay:t,setShowShortcutsOverlay:s}}const Aj=42,Tj=22,Mj=70,bd=80,Ej=460,Rj=320,Pj=640,zj=360,Dj=280,Ij=560,yd=380,_o=4,Vo=(t,s,a)=>Math.min(Math.max(t,s),a),Bj=()=>{const{initializeAutoSave:t}=F();l.useEffect(()=>{t().catch(console.error)},[t])},Fj=()=>{const{initialize:t,initialized:s,initializing:a,initError:r}=Ct(),[n,i]=l.useState(!1),[o,c]=l.useState("Starting..."),[d,u]=l.useState(null);return l.useEffect(()=>{let p=!0;return(async()=>{try{const x=Ct.getState();if(!x.initialized&&!x.initializing?(c("Initializing video engine..."),await t()):x.initializing&&await new Promise(g=>{const k=Ct.subscribe(N=>{(N.initialized||N.initError)&&(k(),g())})}),!p)return;const h=Ct.getState();if(!h.initialized)throw new Error(h.initError||"Engine initialization failed");if(c("Initializing media bridge..."),await xp(),!p||(c("Initializing playback bridge..."),await R1(),!p)||(c("Initializing render bridge..."),await kb(),!p))return;c("Initializing effects bridge...");const f=F.getState(),{width:v,height:A}=f.project.settings;try{await hp(v,A)}catch(g){console.error("[EditorInterface] EffectsBridge initialization failed:",g)}if(!p)return;c("Initializing transition bridge...");try{fp(v,A)}catch(g){console.error("[EditorInterface] TransitionBridge initialization failed:",g)}if(!p)return;i(!0)}catch(x){console.error("Failed to initialize engines/bridges:",x),p&&(u(x instanceof Error?x.message:"Unknown error"),c(`Error: ${x instanceof Error?x.message:"Unknown error"}`))}})(),()=>{p=!1,P1(),up(),Nb(),mp(),pp()}},[t,s,a]),{initialized:s&&n,initializing:a||!n&&s,initError:r||d,initStatus:o}},vd=()=>{const{initialized:t,initializing:s,initError:a,initStatus:r}=Fj(),{showShortcutsOverlay:n,setShowShortcutsOverlay:i}=Sj();Bj();const{keyframeEditorOpen:o,setKeyframeEditorOpen:c,getSelectedClipIds:d,panels:u,setPanelVisible:p,timelineMaximized:m}=vt(),{project:x,updateClipKeyframes:h}=F(),f=x.timeline.tracks,[v,A]=_e.useState([]),[g,k]=_e.useState([]),N=_e.useMemo(()=>{const U=d();if(U.length===0)return null;const D=U[0];for(const X of f){const K=X.clips.find(ue=>ue.id===D);if(K)return K}return null},[d,f]),b=_e.useCallback((U,D)=>{if(!N?.keyframes)return;const X=N.keyframes.map(K=>K.id===U?{...K,...D}:K);h(N.id,X)},[N,h]),j=_e.useCallback(U=>{if(!N?.keyframes)return;const D=N.keyframes.filter(X=>X.id!==U);h(N.id,D),A(X=>X.filter(K=>K!==U))},[N,h]),y=_e.useCallback(U=>{if(!N?.keyframes)return;const D=N.keyframes.filter(X=>U.includes(X.id));k(D)},[N]),w=_e.useCallback((U,D)=>{const X=f.flatMap(ue=>ue.clips).find(ue=>ue.id===U);if(!X)return;const K=g.map(ue=>({...ue,id:`kf-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,time:ue.time+D}));h(U,[...X.keyframes||[],...K])},[g,f,h]),S=_e.useCallback((U,D)=>{A(D?X=>X.includes(U)?X.filter(K=>K!==U):[...X,U]:[U])},[]),T=l.useRef(null),C=l.useRef(null),[M,z]=l.useState(Ej),[L,B]=l.useState(zj),[O,G]=l.useState(Aj),V=l.useRef(M),P=l.useRef(L);l.useEffect(()=>{V.current=M},[M]),l.useEffect(()=>{P.current=L},[L]);const _=l.useCallback(U=>D=>{D.preventDefault(),C.current=U,document.body.style.cursor=U==="timeline"?"row-resize":"col-resize",document.body.style.userSelect="none"},[]);if(l.useEffect(()=>{const U=X=>{const K=T.current,ue=C.current;if(!K||!ue)return;const Te=K.getBoundingClientRect();if(ue==="media"){const fe=Te.width-P.current-yd;z(Vo(X.clientX-Te.left,Rj,Math.min(Pj,fe)));return}if(ue==="inspector"){const fe=Te.width-V.current-yd;B(Vo(Te.right-X.clientX,Dj,Math.min(Ij,fe)));return}const pe=(window.innerHeight-X.clientY)/window.innerHeight*100;G(Vo(pe,Tj,Mj))},D=()=>{C.current=null,document.body.style.cursor="",document.body.style.userSelect=""};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",D),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",D)}},[]),l.useEffect(()=>{const U=T.current;if(!U)return;const D=m?bd:O;U.style.setProperty("--media-w",`${M}px`),U.style.setProperty("--inspector-w",`${L}px`),U.style.setProperty("--tl-height",`${D}vh`)},[M,L,O,m]),s||!t)return e.jsx("div",{className:"w-full h-full bg-bg flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-fg-2 text-sm",children:"Initializing editor…"}),e.jsx("p",{className:"text-fg-muted text-xs mt-2",children:r}),a&&e.jsx("p",{className:"text-status-error text-xs mt-2",children:a})]})});const se=m?bd:O,R={gridTemplateColumns:`${M}px ${_o}px 1fr ${_o}px ${L}px`,gridTemplateRows:`1fr ${_o}px ${se}vh`,gridTemplateAreas:"'media mh stage ih inspector' 'th th th th th' 'timeline timeline timeline timeline timeline'"};return e.jsxs("div",{ref:T,className:"w-full h-full bg-bg text-fg overflow-hidden font-sans select-none relative z-20 flex flex-col",children:[e.jsx(b0,{}),e.jsxs("div",{className:"flex-1 min-h-0 grid gap-px bg-border",style:R,children:[e.jsx("div",{className:"bg-bg-1 min-w-0 min-h-0 overflow-hidden",style:{gridArea:"media"},children:e.jsx(Qr,{name:"Media",children:e.jsx(jb,{})})}),e.jsx("div",{className:"bg-border hover:bg-accent/50 cursor-col-resize transition-colors",style:{gridArea:"mh"},onMouseDown:_("media")}),e.jsx("div",{className:"bg-stage-bg min-w-0 min-h-0 overflow-hidden",style:{gridArea:"stage"},children:e.jsx(Qr,{name:"Stage",children:e.jsx(ey,{})})}),e.jsx("div",{className:"bg-border hover:bg-accent/50 cursor-col-resize transition-colors",style:{gridArea:"ih"},onMouseDown:_("inspector")}),e.jsx("div",{className:"bg-bg-1 min-w-0 min-h-0 overflow-hidden",style:{gridArea:"inspector"},children:e.jsx(Qr,{name:"Inspector",children:e.jsx(Gv,{})})}),e.jsx("div",{className:"bg-border hover:bg-accent/50 cursor-row-resize transition-colors",style:{gridArea:"th"},onMouseDown:_("timeline")}),e.jsxs("div",{className:"bg-tl-bg min-w-0 min-h-0 overflow-hidden flex flex-col",style:{gridArea:"timeline"},children:[u.audioMixer?.visible&&e.jsx("div",{className:"shrink-0 border-b border-border",children:e.jsx(Qr,{name:"Audio Mixer",children:e.jsx(vj,{visible:!0,onClose:()=>p("audioMixer",!1)})})}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[e.jsx("div",{className:"flex-1 min-w-0 min-h-0",children:e.jsx(Qr,{name:"Timeline",children:e.jsx(uj,{})})}),o&&e.jsx("div",{className:"shrink-0 min-w-0 border-l border-border",children:e.jsx(Qr,{name:"Keyframe Editor",children:e.jsx(pj,{clip:N,onClose:()=>c(!1),onUpdateKeyframe:b,onDeleteKeyframe:j,onCopyKeyframes:y,onPasteKeyframes:w,selectedKeyframeIds:v,onSelectKeyframe:S,copiedKeyframes:g})})})]})]})]}),e.jsx(Nj,{isOpen:n,onClose:()=>i(!1)}),e.jsx(m0,{}),e.jsx(g0,{})]})},Uj=Object.freeze(Object.defineProperty({__proto__:null,EditorInterface:vd,default:vd},Symbol.toStringTag,{value:"Module"}));export{If as A,Jf as B,mu as C,Df as D,mg as E,lu as F,Vs as G,pu as H,bg as I,yg as J,Ag as K,Yo as L,Rf as M,fc as N,Mg as O,oi as P,Eg as Q,xu as R,Pf as S,fl as T,zg as U,Dg as V,Uj as W,zf as a,Ff as b,Lf as c,oc as d,$f as e,Of as f,Bf as g,cc as h,_f as i,Qf as j,gl as k,Zf as l,eg as m,tg as n,du as o,uu as p,cg as q,lg as r,dg as s,uc as t,ug as u,Jr as v,pg as w,xg as x,mc as y,hg as z}; diff --git a/resources/video-editor/assets/canvas2d-fallback-renderer-CT8Dcn23.js b/resources/video-editor/assets/canvas2d-fallback-renderer-CT8Dcn23.js new file mode 100644 index 00000000..1aeb5b60 --- /dev/null +++ b/resources/video-editor/assets/canvas2d-fallback-renderer-CT8Dcn23.js @@ -0,0 +1 @@ +class u{type="canvas2d";canvas;ctx=null;width;height;deviceLostCallbacks=[];layers=[];constructor(e){this.width=e.width,this.height=e.height,this.canvas=new OffscreenCanvas(e.width,e.height)}async initialize(){try{return this.ctx=this.canvas.getContext("2d"),this.ctx!==null}catch{return!1}}isSupported(){return!0}destroy(){this.ctx=null,this.deviceLostCallbacks=[],this.layers=[]}beginFrame(){this.ctx&&(this.ctx.clearRect(0,0,this.width,this.height),this.layers=[])}renderLayer(e){this.layers.push(e)}async endFrame(){if(!this.ctx)throw new Error("Canvas2D context not initialized");for(const e of this.layers)await this.renderLayerToCanvas(e);return createImageBitmap(this.canvas)}async renderLayerToCanvas(e){if(!this.ctx)return;const t=this.ctx,{transform:a,opacity:i,borderRadius:s}=e;let n;if(e.texture instanceof ImageBitmap)n=e.texture;else return;t.save(),t.globalAlpha=i*a.opacity;const r=this.width/2+a.position.x,h=this.height/2+a.position.y;t.translate(r,h),t.rotate(a.rotation*Math.PI/180),t.scale(a.scale.x,a.scale.y);const c=-n.width*a.anchor.x,o=-n.height*a.anchor.y;s>0&&(t.beginPath(),this.roundRect(t,c,o,n.width,n.height,s),t.clip()),t.drawImage(n,c,o),t.restore()}roundRect(e,t,a,i,s,n){const r=Math.min(n,i/2,s/2);e.moveTo(t+r,a),e.lineTo(t+i-r,a),e.quadraticCurveTo(t+i,a,t+i,a+r),e.lineTo(t+i,a+s-r),e.quadraticCurveTo(t+i,a+s,t+i-r,a+s),e.lineTo(t+r,a+s),e.quadraticCurveTo(t,a+s,t,a+s-r),e.lineTo(t,a+r),e.quadraticCurveTo(t,a,t+r,a),e.closePath()}createTextureFromImage(e){return e}releaseTexture(e){}applyEffects(e,t){return e}onDeviceLost(e){this.deviceLostCallbacks.push(e)}async recreateDevice(){return!0}resize(e,t){this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t}getMemoryUsage(){return this.width*this.height*4}getDevice(){return null}}export{u as Canvas2DFallbackRenderer}; diff --git a/resources/video-editor/assets/fft-_Y3kmDnt.wasm b/resources/video-editor/assets/fft-_Y3kmDnt.wasm new file mode 100644 index 0000000000000000000000000000000000000000..a150af79285dd7bc0b6f3cd8ce3ff4edf7b97636 GIT binary patch literal 8359 zcmeHLd03Oz(m(H(?F}TLXq8q^f{NCOwY81Dv{!3gi(2Uv9IpvYf&StWs8RaXJ$%H2qjerAuctETl!^I}1 z3o(!$wYv8KTdYu_?1-kya0*BVwk5WZKkNq-)unloF?odNT&3 z^g+{7l4drFHS+xoF|%eRy!CQSV&eE2iBpp@kiQs{kdQPbCN*|Q?_S8zNR0)`sG1o& zGb!aQ7HOCOJ!8-ncMUkmFsf{fq#GWOhx-R_m6mIzGOct9N$rdXi7;Y}GxJj2Z--6N zb96L>H*q1n#K)Og%u6leq*=)lA8!U)AjqtejH!}=GRUat4#7TC0X0l{V zH>-iG9v*B(5_%a#)V>EKiXs*|@R-AVUlw7Os^uiqmjxF6(ZC4Pm({}$P(~0i#)XtifW$hqmL})uh<)YGY zvcu`vnP(8Nz-NL*pS@b*08ClBM%F1bGC`oYi7%QsPzyjrlsrycYz%mtI3qGP9(rZ$ z*nLzh9RZ`%>V_dNw4C=^1QDjj+=UCXPyl#ZN7Bs(o^_<(b56gI`v2j6-Fx!BAX5FoG)5;iwCs9GQgMf z{ehW1qsoc%-zGo+Ac68Q>anSoIE#UpGP!Nc4&&%S&f*RNX6t;p&^k?8#l*w@A;}v} z8my93X%d$z*>!PdRToZUQa9l764+P|CL!mzWSVAt%0{ymgAl@+g;*U{3ct48`B_*K zhR5+)SWO>n3#o)L%aan%FpK17ZZPxl zn8!k}XyQWz69a~sWZp(WrrAsrjHb(fNd_2!RC2=j)008)YN4uVr2b?=i)NGupuh^_ zBsMu1Hr=1rxJ~na-|-kKFwKL;tz_b!zTN507a*3u*?>w||Du583C(oNj=!{eh`yTk zUu)I-e+oh^##!%%WYPbOxwEHi?srzJJSCFfKQ`Iau%sSds z6*o-=QRKYcy-uhY2&b|J>x!}9a6oxfMU=l*Jt`sNIH(|*RK;o8p{VX#vA11%%t7G) zvMl|gcK=c3K&LZ?2UovxZ2n#tS+ilPiv;cW&6sv;V&@*)OM!3c_riwq#oy8y^zEP( zj|uCUy8${lW4z?{FmPfvdJM}z&JRI=Svbm%X$zz`Oc1Gu9yA(Q5(7P7wTDTjUqj&8 zZU=0nj~6 zQ;1yo*E()t^M(VZ1tF-U(5yCc;HlCxt1#D@<>RoX9}69WkvGx4 zo>y3E%7UIc&cr|>h#}|;qfp11RG^d%p-sPpOmLwxA;pS{-U3*R(xJ7Wvro;s~pz(TNWum9BLR4=;XGM+U&6){y44rkHRAUlT|F>8kI`35dB`TG*w9}-&M z?3seedt=H|@4;vAq5(_|)>8^1(Hu+-7JXa=Y6w;yb(c1qCjK{=`Zr=~0IUF0tq)T_ z#Uv06*k`bTVoFV!HP`?&U<%jn0Jf^18nW@F%2q!#nZ)r7=^JVAf_ZEC0YQc zt+A0Rfz7C3+DgGxqsRv0)(UELI;N)L0MTavPQWV&Fm0iX(nV2BL0Z93kp{XIZlTak zI~!`mQ!rKTyx6~_&=d%s>b#NG(KUIqDGsJ7F@_c6zycaa9gU-o#!(#0GBz&TTdq_J zQc8hPkP;d(forHYv*X~($hnN?6Xm3w>*y~leWl`B1!k+Mw!EM|#`rhwhp7{JR*$pX&mHy zjA#Y0<`)VQV}d!&xOS3XC<@B7YCGH?ZBQ7z5~aR*rKCWKCY{Zh1Z6Hpg`%kZ(ScEc z;w@aB5QG65&hU;KGY1xg`#lI4lwT13$)}&fkHQ}scy4z=_^N}Ed-4nN3t$4=^JoGB zBJ>h#ZF*zDpGOSK@nU$tDK`g!&KWOm+y-u}TnSqixaSPR2yovtnYTA^IWc_Fs=1WA z!_cyk%lbk|Wu1*&hW-Np$HOY|D95rkp&8Wle<4_tnx+bzr;vt921EJrmQqN3z5s|u zsNppALd`<(v5*gGAiPecUQh8uZ87gMYXKd59XABj3PuqU3~Qx!>2N>9g3GLf|8P>^ zJkvGggAQs=LnN>U;y?odClGb}ykVGC501ibDKsAtGf?IG>qk4-4*^9@si`Sl!=o*{ z{7@?^okM61O%68md9XeW9Cg8hq7ooQ&^i2WOr-5igBGvmN)(56!@w^upOV^Pl5Z++ zQ}lrQm@iyng#6$e{D5^*PZUHkuNNSz^BVlYe0cZWU-!;m363>9D-Py^eMEgdAk#0p zcvvxLRStaxp*YObJ*K8RSFP+^nPK^C&IYZ7au9+~@DG`?g9VyuzFOM=D;#CMbCVV> zosla5B-B2jm8L?Abw=LHZPscuE4hsC7**6O#~cI25XIB{feOyRIRj4&O(LZnD2w-w zD4C^{@TN{foXT?0LD9scYd3SyMU^NXz>NSrpt}!pT@-C^czFzTI|s}+0DnVsPy!OR4dgr>lpRIru=b}&38!JFEp`lf>p$))vL)ruYI z+;+dQngTO=fQ3}BIk~}_T_@r$K@tB<%&B#jUhMPW*!a*oX?eJ1b>ZamG5fy0^x2fr zPY^WeqFwWFLdgNA=_KIA5`1rJ%E58y{mcF}SzFU6h$DaNJi-CSvxjCG1 z%L@|9dfkWt+A8+l_vDiNa8*FzqY$9oU$i}2e^E|ge^~cg#RGzt@7HhkT#&yUX__c( z1lmy_(2u_$w@YkgxS0&JdqA)0;(7V+55-rt{ej-vZDNn0bMnPaF*iptKu15Em~A>M zm(6{7>6ZuZgTCagBYK{ZZ;kA|qkkdL?oVnLOQ+=-C%0Ta6ivt5eBO2JDS6DU@_$b2 z2DEXFGbH|`y#CB{0nFojU_Z(boAaaGcY^+l!UL54^~I_WPRPUScMgAcHPF%Tjw$}? zxcvEQw|?mipsfe3IcJZ_B^52^l@9>gZ5^=SQJK7L_kuQU{DAIR(QEB&{kQ!JtVwpM9SxSprf-#9l!7mnUdyzp=8|+h~Fjdv-G`W^r2IgO9{~Ur;Kp*eiEr? zM|Qn<9p-clX4;n9@hL=;j|K{YQ1_G;7~Aus?l= z?yWL%@o%9nW+u?3%$vf-V`Rx4;yTd^X!nyJ1I`~Oo1RP`cI?|Kkl**uA*vqFAITQZdzJ8OwZpmY9v-d4&5FF#km2Gkea#`ddC@-UPJUvH5P)aOzlz~7f150(g0ujDSgq;zp&-lfb^?k3qNsJKjgkjI<1^NF4vQ5`MF@V+ta>+Y?~JqYOR0AV)TDC2t`*ADJNt{ zT78P^qap0qNL)iJQ z|I|I|hN3G;`}glU@7K(OQ*@17Y7zPQ zf%)@X*SJj=J(sT$OZVt&-v>^xj2P&5$J72gSvx0m)5S+iT@zcGj(Vc5lNSTOYt#DB z7)$EaQD;3xkTypPq_Z`%En7Zb+XA_-lhQSBnD*+@EUPaMc@5zkfv_>kVz>SW>wft}@t=7~2 zCfRc(YMSPS39gmTj&pjVZjyV2$Jcb`=eqPu%pZ7)Zj!!EL!Z&?B1@|*S1fYhB>FS! zTD4=+Tq}nD3XR4s;+}k4+rz%ta%TPM@hJKhc~qmHkS1oi^rbgLk>eH#ST$IiGe6Ij zdFVj`a^E8N(}M~_?aN$;ZC&Ree48vAlbUk&?PV_AV0|YPeVbhHgodJItE>0Pyh=~e zZL;;_`YRWLC%6_bG@SHYzD*LBt~k`Tc9CUzNEaUAYV!7wUa|MG*I3>>_4Ci3sA@8| zaPvjYqlK378y4u0qnfOEe8PU|r}3`CB&scPSCf|2`-I-}R=6H~wdJ9w{T=e{SN3UN zKU(72v|_|Bo~S$IcEyXW1G7JHUFo|q06Fdu&x2Ni4z0Dk9QJ)1iRCoahL2{GAVgBJImF7P#3r7 z@?BE9zT{m0%r%yI)fZ|!?eCFS{^vqs?>jb2^pc6yo~V1|`rnR3j^qCAI=tDxJ96A3 z8S75`qoO*^(zoO#9=Y$4-nk#NJY-vI@hmz9@xM%^vo&e?Tt0k}>~G&MHgN z_C@ucs0T#dx$JKh+C{FfYM#66DSANIxhZcJ)hx2S-KXxl=kfzGsH$i8<@OaWByDUf zGMPyFvaJ|PyNpTj84DdrESiI6!S@vCFk+RCC=|G9O79X1eM)Dbl3)x&zcL%%GoWXo zvuN*>1RV^9J}3sbw2z`Z+U?M8r3+XL7MVz}7%YZUix&9Ih8a_!pUF_9X2KKgqiBcY Z)gFsxLYI>OJys9UnFt!``jj5)e*wxj{5Ajp literal 0 HcmV?d00001 diff --git a/resources/video-editor/assets/index-C7tVZKMU.js b/resources/video-editor/assets/index-C7tVZKMU.js new file mode 100644 index 00000000..6d00475f --- /dev/null +++ b/resources/video-editor/assets/index-C7tVZKMU.js @@ -0,0 +1 @@ +import{v as r,A as o,x as E,B as T,s as c,C as S,D as g,j as l,q as A,G as m,w as d,E as _,h as u,F as I,a as b,M as R,e as f,H as P,P as F,S as p,d as O,u as D,T as L,m as C,l as U,J as N,K as G,R as M,Q as B,p as h,g as v,y,b as k,k as V,t as z,c as x,N as Y,L as H,f as W,I as j,i as K,n as X,z as w,o as Q,r as q,U as J,O as Z,V as $}from"./EditorInterface-C-F8FyLk.js";import{f as ea,h as sa,A as ia,aI as ta,a0 as na,bi as ra,a_ as oa,aW as Ea,c4 as Ta,bX as ca,c7 as Sa,bK as ga,as as la,Z as Aa,aD as ma,j as da,i as _a,aS as ua,a as Ia,c6 as ba,bT as Ra,aq as fa,U as Pa,X as Fa,bM as pa,Y as Oa,b as Da,bU as La,bS as Ca,b9 as Ua,bp as Na,bL as Ga,ah as Ma,bB as Ba,bv as ha,bw as va,D as ya,cd as ka,cc as Va,bP as za,E as xa,aV as Ya,F as Ha,af as Wa,ab as ja,aC as Ka,aF as Xa,ce as wa,bN as Qa,ag as qa,I as Ja,ao as Za,a6 as $a,bs as ae,M as ee,z as se,aH as ie,N as te,ae as ne,ad as re,x as oe,y as Ee,ax as Te,ck as ce,ca as Se,bV as ge,bq as le,P as Ae,bj as me,av as de,n as _e,c as ue,S as Ie,a8 as be,a7 as Re,ai as fe,k as Pe,bC as Fe,r as pe,t as Oe,q as De,bn as Le,bm as Ce,ba as Ue,bI as Ne,a9 as Ge,aj as Me,bQ as Be,l as he,bH as ve,c5 as ye,bz as ke,bx as Ve,_ as ze,aJ as xe,V as Ye,bf as He,be as We,R as je,O as Ke,am as Xe,bh as we,H as Qe,W as qe,a5 as Je,bd as Ze,a3 as $e,bJ as as,ch as es,bg as ss,aA as is,aB as ts,ar as ns,a2 as rs,aQ as os,J as Es,aP as Ts,aZ as cs,aY as Ss,o as gs,aR as ls,m as As,$ as ms,az as ds,e as _s,bb as us,aM as Is,aN as bs,bG as Rs,bc as fs,bE as Ps,ci as Fs,cj as ps,d as Os,a$ as Ds,aX as Ls,c8 as Cs,au as Us,bZ as Ns,bY as Gs,aE as Ms,b$ as Bs,g as hs,w as vs,ac as ys,cf as ks,K as Vs,b5 as zs,bt as xs,p as Ys,B as Hs,b3 as Ws,ay as js,cl as Ks,cb as Xs,bW as ws,br as Qs,b2 as qs,bk as Js,aw as Zs,bo as $s,aa as ai,ak as ei,al as si,aK as ii,T as ti,Q as ni,an as ri,aT as oi,G as Ei,bO as Ti,v as ci,b0 as Si,c9 as gi,aG as li,bu as Ai,C as mi,bl as di,a4 as _i,L as ui,b_ as Ii,b1 as bi,u as Ri,at as fi,ap as Pi,aL as Fi,bF as pi,bD as Oi,b8 as Di,b6 as Li,b7 as Ci,c1 as Ui,c0 as Ni,c3 as Gi,c2 as Mi,cg as Bi,aU as hi,s as vi,a1 as yi,aO as ki,b4 as Vi,bR as zi,bA as xi,by as Yi}from"./index-Dws9LQij.js";import{T as Wi,a as ji,W as Ki,i as Xi,d as wi,c as Qi,b as qi,k as Ji,l as Zi,j as $i,e as at,g as et,f as st,h as it,t as tt}from"./webgpu-renderer-impl-DhZn-Lwe.js";import{Canvas2DFallbackRenderer as rt}from"./canvas2d-fallback-renderer-CT8Dcn23.js";import"./react-kyfdMflE.js";import"./zustand-CnPgS7xu.js";import"./three-D1sxpTQl.js";import"./radix-DNxS_rDm.js";export{r as ASPECT_RATIO_PRESETS,ea as ActionExecutor,sa as ActionHistory,ia as ActionValidator,ta as AdjustmentLayerEngine,na as AnimationEngine,ra as AudioDucker,oa as AudioEffectsEngine,Ea as AudioEngine,o as AutoEditService,E as AutoReframeEngine,Ta as BUILTIN_TEMPLATES,ca as BUILT_IN_EDITING_TEMPLATES,Sa as BackgroundRemovalEngine,T as BeatDetectionEngine,c as BeatSyncEngine,S as CAPTION_ANIMATION_STYLES,rt as Canvas2DFallbackRenderer,ga as CharacterAnimator,la as ChromaKeyEngine,Aa as ColorGradingEngine,ma as CompositeFrameBuffer,da as DB_NAME,_a as DB_VERSION,ua as DEFAULT_AUDIO_CONFIG,Ia as DEFAULT_AUDIO_SETTINGS,g as DEFAULT_AUTO_EDIT_OPTIONS,ba as DEFAULT_BACKGROUND_SETTINGS,l as DEFAULT_BEAT_DETECTION_CONFIG,A as DEFAULT_BEAT_SYNC_CONFIG,Ra as DEFAULT_BLEND_MODE,fa as DEFAULT_CHROMA_KEY_SETTINGS,Pa as DEFAULT_COLOR_WHEELS,Fa as DEFAULT_CURVES,pa as DEFAULT_GRAPHIC_TRANSFORM,Oa as DEFAULT_HSL,Da as DEFAULT_IMAGE_SETTINGS,La as DEFAULT_LAYER_OPACITY,Ca as DEFAULT_LAYER_TRANSFORM,Ua as DEFAULT_NOISE_REDUCTION_CONFIG,m as DEFAULT_PARTICLE_CONFIG,Na as DEFAULT_PLAYBACK_CONFIG,d as DEFAULT_REFRAME_SETTINGS,Ga as DEFAULT_SHAPE_STYLE,Ma as DEFAULT_STABILIZATION_CONFIG,Ba as DEFAULT_SUBTITLE_STYLE,ha as DEFAULT_TEXT_STYLE,va as DEFAULT_TEXT_TRANSFORM,ya as DEFAULT_VIDEO_SETTINGS,ka as EASING_CATEGORIES,Va as EASING_FUNCTIONS,_ as EDITING_TEMPLATE_CATEGORIES,za as EMOJI_CATEGORIES,xa as ExportEngine,Ya as FFT,Ha as FFmpegFallback,u as FILTER_CATEGORIES,I as FILTER_PRESETS,Wa as FlowFieldCache,ja as FrameInterpolationEngine,Ka as FrameRingBuffer,Xa as GPUCompositor,wa as GSAPAnimationEngine,Qa as GraphicsEngine,qa as INTERPOLATION_QUALITY_PRESETS,Ja as InverseActionGenerator,Za as KeyframeEngine,b as MOOD_TAGS,R as MUSIC_GENRES,$a as MaskEngine,ae as MasterTimelineClock,ee as MediaBunnyEngine,se as MediaImportService,f as MotionTrackingEngine,ie as MultiCamEngine,te as NestedSequenceEngine,ne as OpticalFlowCPU,re as OpticalFlowGPU,P as PARTICLE_PRESETS,F as PLATFORM_PRESETS,oe as PROXY_PRESETS,Ee as PROXY_THRESHOLDS,Te as ParallelFrameDecoder,ce as ParticleEngine,Se as PersonSegmentationEngine,ge as PhotoEngine,le as PlaybackController,Ae as ProjectSerializer,me as RealtimeAudioGraph,de as RendererFactory,_e as SCHEMA_VERSION,p as SFX_CATEGORIES,ue as SOCIAL_MEDIA_CATEGORY_INFO,Ie as SOCIAL_MEDIA_PRESETS,O as SPEED_CURVE_PRESETS,be as SPEED_MAX,Re as SPEED_MIN,fe as STABILIZATION_ANALYSIS_VERSION,Pe as STORES,Fe as SUBTITLE_STYLE_PRESETS,pe as SUPPORTED_AUDIO_FORMATS,Oe as SUPPORTED_IMAGE_FORMATS,De as SUPPORTED_VIDEO_FORMATS,D as SVG_ANIMATION_PRESETS,Le as SoundGenerator,Ce as SoundLibraryEngine,Ue as SpectralNoiseReducer,Ne as SpeechToTextEngine,Ge as SpeedEngine,Me as StabilizationEngine,Be as StickerLibrary,he as StorageEngine,ve as SubtitleEngine,L as TEMPLATE_CATEGORIES,ye as TemplateEngine,ke as TextAnimationEngine,Wi as TextureCache,Ve as TitleEngine,C as TranscriptionService,ze as TransitionEngine,xe as UpscalingEngine,Ye as VIDEO_QUALITY_PRESETS,He as VOLUME_MAX,We as VOLUME_MIN,je as VideoEffectsEngine,Ke as VideoEngine,Xe as VidstabEngine,we as VolumeAutomation,Qe as WAVEFORM_RESOLUTIONS,qe as WaveformGenerator,ji as WebGPUEffectsProcessor,Ki as WebGPURenderer,U as analyzeAudioForHighlights,Je as applyEasing,Ze as autoLearnNoiseProfile,Xi as blurComputeShaderSource,wi as borderRadiusShaderSource,$e as boundsPathFromTransform,Qi as calculateTextureSize,as as calculateUnitAnimationState,es as catmullRomInterpolate,ss as clampVolume,qi as compositeShaderSource,Ji as createBlurUniformsBuffer,is as createDecodeWorkerBlob,ts as createDecodeWorkerUrl,ns as createDefaultChromaKeySettings,rs as createDefaultPath,Zi as createDimensionsBuffer,os as createEdgeDimensionsBuffer,N as createEffectFromPreset,$i as createEffectUniformsBuffer,Es as createGifFrameCache,Ts as createLanczosDimensionsBuffer,at as createLayerUniformsBuffer,cs as createNoiseReductionNodeChain,Ss as createProfileBasedNoiseReductionFilters,gs as createProjectSerializer,ls as createSharpenUniformsBuffer,As as createStorageEngine,et as createTransformMatrix,st as createTransformUniformsBuffer,ms as createTransitionEngine,ds as decodeWorkerCode,_s as deserializeProject,G as detectDeviceCapabilities,us as detectNoiseSegments,Is as edgeDetectShaderSource,bs as edgeDirectedShaderSource,it as effectsComputeShaderSource,M as estimateExportTime,Rs as exportSRT,fs as extractAudioSegment,B as formatDeviceSummary,Ps as formatSRTTimestamp,Fs as generateBezierPath,ps as generateDefaultControlPoints,Os as generateId,h as getAnimationStyleDisplayName,Ds as getAudioEffectsEngine,Ls as getAudioEngine,v as getAutoEditService,y as getAutoReframeEngine,k as getAvailableBlendModes,Cs as getBackgroundRemovalEngine,V as getBeatDetectionEngine,z as getBeatSyncEngine,Us as getBestRendererType,x as getBlendModeName,Ns as getBuiltInEditingTemplate,Gs as getBuiltInEditingTemplates,Y as getCodecRecommendations,Ms as getCompositeFrameBuffer,H as getDeviceProfile,Bs as getEditingTemplateDefaultControlValues,hs as getExportEngine,vs as getFFmpegFallback,ys as getFrameInterpolationEngine,ks as getGSAPEngine,Vs as getGifFrameAtTime,zs as getLinkedAudioClips,xs as getMasterClock,Ys as getMediaEngine,Hs as getMediaImportService,W as getMotionTrackingEngine,Ws as getPanFromAudioEffects,js as getParallelFrameDecoder,Ks as getParticleEngine,j as getParticlePresetById,Xs as getPersonSegmentationEngine,ws as getPhotoEngine,Qs as getPlaybackController,K as getPresetsByCategory,qs as getPreviewAudioEffects,Js as getRealtimeAudioGraph,Zs as getRendererFactory,$s as getSoundGenerator,ai as getSpeedEngine,ei as getStabilizationEngine,si as getStabilizedTransform,X as getTranscriptionService,ii as getUpscalingEngine,ti as getVideoEffectsEngine,ni as getVideoEngine,ri as getVidstabEngine,oi as getVolumeAutomationPointsForRange,Ei as getWaveformGenerator,Ti as graphicsEngine,ci as inferMediaType,Si as initializeAudioEffectsEngine,w as initializeAutoReframeEngine,gi as initializeBackgroundRemovalEngine,li as initializeGPUCompositor,Ai as initializeMasterClock,mi as initializeMediaImportService,di as initializeRealtimeAudioGraph,Q as initializeTranscriptionService,_i as interpolatePaths,ui as isAnimatedGif,Ii as isEditingTemplateBinding,bi as isSerializedNoiseProfile,Ri as isSupportedFormat,fi as isWebGPUSupported,Pi as keyframeEngine,Fi as lanczosShaderSource,pi as parseSRT,Oi as parseSRTTimestamp,q as renderAnimatedCaption,Di as resolveAudibleAudioTarget,Li as resolveClipAudioEffects,Ci as resolveClipVolumeAutomation,Ui as resolveEditingTemplate,Ni as resolveEditingTemplateControlValues,Gi as resolveOverlayTiming,Mi as resolveTemplateVariables,J as runBenchmark,Bi as sampleMotionPath,Z as saveBenchmarkResult,hi as scheduleVolumeAutomationOnGain,vi as serializeProject,yi as shapeToPath,ki as sharpenShaderSource,$ as shouldRecommendBenchmark,Vi as splitProfileAwareNoiseReductionEffects,zi as stickerLibrary,xi as textAnimationEngine,Yi as titleEngine,tt as transformShaderSource}; diff --git a/resources/video-editor/assets/index-CiM7N5zy.js b/resources/video-editor/assets/index-CiM7N5zy.js new file mode 100644 index 00000000..63e708ef --- /dev/null +++ b/resources/video-editor/assets/index-CiM7N5zy.js @@ -0,0 +1 @@ +const w=new Error("failed to get response body reader"),R=new Error("failed to complete download"),g="Content-Length",y=async(o,e)=>{const r=await fetch(o);let n;try{const t=parseInt(r.headers.get(g)||"-1"),d=r.body?.getReader();if(!d)throw w;const l=[];let s=0;for(;;){const{done:a,value:c}=await d.read(),f=c?c.length:0;if(a){if(t!=-1&&t!==s)throw R;e&&e({url:o,total:t,received:s,delta:f,done:a});break}l.push(c),s+=f,e&&e({url:o,total:t,received:s,delta:f,done:a})}const i=new Uint8Array(s);let h=0;for(const a of l)i.set(a,h),h+=a.length;n=i.buffer}catch(t){console.log("failed to send download progress event: ",t),n=await r.arrayBuffer(),e&&e({url:o,total:n.byteLength,received:n.byteLength,delta:0,done:!0})}return n},E=async(o,e,r=!1,n)=>{const t=r?await y(o,n):await(await fetch(o)).arrayBuffer(),d=new Blob([t],{type:e});return URL.createObjectURL(d)};export{y as downloadWithProgress,E as toBlobURL}; diff --git a/resources/video-editor/assets/index-DfgTfcu_.js b/resources/video-editor/assets/index-DfgTfcu_.js new file mode 100644 index 00000000..073d93e9 --- /dev/null +++ b/resources/video-editor/assets/index-DfgTfcu_.js @@ -0,0 +1 @@ +var E;(function(i){i.LOAD="LOAD",i.EXEC="EXEC",i.FFPROBE="FFPROBE",i.WRITE_FILE="WRITE_FILE",i.READ_FILE="READ_FILE",i.DELETE_FILE="DELETE_FILE",i.RENAME="RENAME",i.CREATE_DIR="CREATE_DIR",i.LIST_DIR="LIST_DIR",i.DELETE_DIR="DELETE_DIR",i.ERROR="ERROR",i.DOWNLOAD="DOWNLOAD",i.PROGRESS="PROGRESS",i.LOG="LOG",i.MOUNT="MOUNT",i.UNMOUNT="UNMOUNT"})(E||(E={}));const h=(()=>{let i=0;return()=>i++})(),d=new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),D=new Error("called FFmpeg.terminate()");class O{#e=null;#i={};#E={};#s=[];#r=[];loaded=!1;#n=()=>{this.#e&&(this.#e.onmessage=({data:{id:t,type:e,data:s}})=>{switch(e){case E.LOAD:this.loaded=!0,this.#i[t](s);break;case E.MOUNT:case E.UNMOUNT:case E.EXEC:case E.FFPROBE:case E.WRITE_FILE:case E.READ_FILE:case E.DELETE_FILE:case E.RENAME:case E.CREATE_DIR:case E.LIST_DIR:case E.DELETE_DIR:this.#i[t](s);break;case E.LOG:this.#s.forEach(r=>r(s));break;case E.PROGRESS:this.#r.forEach(r=>r(s));break;case E.ERROR:this.#E[t](s);break}delete this.#i[t],delete this.#E[t]})};#t=({type:t,data:e},s=[],r)=>this.#e?new Promise((o,R)=>{const n=h();this.#e&&this.#e.postMessage({id:n,type:t,data:e},s),this.#i[n]=o,this.#E[n]=R,r?.addEventListener("abort",()=>{R(new DOMException(`Message # ${n} was aborted`,"AbortError"))},{once:!0})}):Promise.reject(d);on(t,e){t==="log"?this.#s.push(e):t==="progress"&&this.#r.push(e)}off(t,e){t==="log"?this.#s=this.#s.filter(s=>s!==e):t==="progress"&&(this.#r=this.#r.filter(s=>s!==e))}load=({classWorkerURL:t,...e}={},{signal:s}={})=>(this.#e||(this.#e=t?new Worker(new URL(t,import.meta.url),{type:"module"}):new Worker(new URL("/assets/worker-DYSz7Krg.js",import.meta.url),{type:"module"}),this.#n()),this.#t({type:E.LOAD,data:e},void 0,s));exec=(t,e=-1,{signal:s}={})=>this.#t({type:E.EXEC,data:{args:t,timeout:e}},void 0,s);ffprobe=(t,e=-1,{signal:s}={})=>this.#t({type:E.FFPROBE,data:{args:t,timeout:e}},void 0,s);terminate=()=>{const t=Object.keys(this.#E);for(const e of t)this.#E[e](D),delete this.#E[e],delete this.#i[e];this.#e&&(this.#e.terminate(),this.#e=null,this.loaded=!1)};writeFile=(t,e,{signal:s}={})=>{const r=[];return e instanceof Uint8Array&&r.push(e.buffer),this.#t({type:E.WRITE_FILE,data:{path:t,data:e}},r,s)};mount=(t,e,s)=>{const r=[];return this.#t({type:E.MOUNT,data:{fsType:t,options:e,mountPoint:s}},r)};unmount=t=>{const e=[];return this.#t({type:E.UNMOUNT,data:{mountPoint:t}},e)};readFile=(t,e="binary",{signal:s}={})=>this.#t({type:E.READ_FILE,data:{path:t,encoding:e}},void 0,s);deleteFile=(t,{signal:e}={})=>this.#t({type:E.DELETE_FILE,data:{path:t}},void 0,e);rename=(t,e,{signal:s}={})=>this.#t({type:E.RENAME,data:{oldPath:t,newPath:e}},void 0,s);createDir=(t,{signal:e}={})=>this.#t({type:E.CREATE_DIR,data:{path:t}},void 0,e);listDir=(t,{signal:e}={})=>this.#t({type:E.LIST_DIR,data:{path:t}},void 0,e);deleteDir=(t,{signal:e}={})=>this.#t({type:E.DELETE_DIR,data:{path:t}},void 0,e)}var a;(function(i){i.MEMFS="MEMFS",i.NODEFS="NODEFS",i.NODERAWFS="NODERAWFS",i.IDBFS="IDBFS",i.WORKERFS="WORKERFS",i.PROXYFS="PROXYFS"})(a||(a={}));export{a as FFFSType,O as FFmpeg}; diff --git a/resources/video-editor/assets/index-DjtrfS0G.js b/resources/video-editor/assets/index-DjtrfS0G.js new file mode 100644 index 00000000..716a4c17 --- /dev/null +++ b/resources/video-editor/assets/index-DjtrfS0G.js @@ -0,0 +1,414 @@ +/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */function m(r){if(!r)throw new Error("Assertion failed.")}const yr=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},X=r=>r&&r[r.length-1],_t=r=>r>=0&&r<2**32;class W{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),s=(t&1<>i;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i>i-s-1<{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const e=E(r);return e&1?e+1>>1:-(e>>1)},jn=(r,e,t,i)=>{for(let s=e;s>t-s-1<r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),L=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),ke=new TextDecoder,j=new TextEncoder,mt=r=>{for(let e=0;e255)return!1;return!0},wi=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),vt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},vs=wi(vt),It={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Is=wi(It),Et={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Es=wi(Et),As=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Sr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class At{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(s=>{e=s}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const Hi=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),qi=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),bi=(r,e,t)=>{let i=0,s=r.length-1,n=-1;for(;i<=s;){const a=i+s>>1,o=t(r[a]);o===e?(n=a,s=a-1):o{let i=0,s=r.length-1,n=-1;for(;i<=s;){const a=i+(s-i+1)/2|0;t(r[a])<=e?(n=a,i=a+1):s=a-1}return n},ji=(r,e,t)=>{const i=H(r,t(e),t);r.splice(i+1,0,e)},G=()=>{let r,e;return{promise:new Promise((i,s)=>{r=i,e=s}),resolve:r,reject:e}},Fs=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Bs=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},$n=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Qn=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},ae=r=>{throw new Error(`Unexpected value: ${r}`)},xr=(r,e,t)=>{const i=r.getUint8(e),s=r.getUint8(e+1),n=r.getUint8(e+2);return t?i|s<<8|n<<16:i<<16|s<<8|n},Kn=(r,e,t)=>xr(r,e,t)<<8>>8,zs=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},Gn=(r,e,t,i)=>{t=J(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),zs(r,e,t,i)},Xn=(r,e,t,i)=>{r.setUint32(e+0,t,!0),r.setInt32(e+4,Math.floor(t/2**32),!0)},lr=(r,e)=>({async next(){const t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),J=(r,e,t)=>Math.max(e,Math.min(t,r)),me="und",ur=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Qr=(r,e)=>Math.round(r/e)*e,Yn=r=>{let e=0;for(;r;)e++,r>>=1;return e},Zn=/^[a-z]{3}$/,jt=r=>Zn.test(r),Ke=1e6*(1+Number.EPSILON),$i=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const i=r.headers?Qi(r.headers):{},s=e.headers?Qi(e.headers):{},n={...i};Object.entries(s).forEach(([a,o])=>{const c=Object.keys(n).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),t.headers=n}return t},Qi=r=>{if(r instanceof Headers){const e={};return r.forEach((t,i)=>{e[i]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,i])=>{e[t]=i}),e}return r},Ki=async(r,e,t,i,s)=>{let n=0;for(;;)try{return await r(e,t)}catch(a){if(s())throw a;n++;const o=i(n,a,e);if(o===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await new Promise(c=>setTimeout(c,1e3*o)),s())throw a}},Jn=(r,e)=>{const t=r<0?-1:1;r=Math.abs(r);let i=0,s=1,n=1,a=0,o=r;for(;;){const c=Math.floor(o),l=c*n+i,u=c*a+s;if(u>e)return{numerator:t*n,denominator:a};if(i=n,s=a,n=l,a=u,o=1/(o-c),!isFinite(o))break}return{numerator:t*n,denominator:a}};class Cr{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let vr=null;const nr=()=>vr!==null?vr:vr=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i));let Ir=null;const Pt=()=>Ir!==null?Ir:Ir=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let Er=null;const ea=()=>Er!==null?Er:Er=!!(typeof navigator<"u"&&navigator.vendor?.includes("Google Inc")),pt=(r,e)=>r!==-1?r:e,Kr=(r,e,t,i)=>r<=i&&t<=e,Ft=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},ta=r=>{switch(r.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},ra=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let i=0;i{let e="";for(let t=0;t{if(r.length!==e.length)return!1;for(let t=0;t{Symbol.dispose??=Symbol("Symbol.dispose")},Bt=r=>typeof r=="number"&&!Number.isNaN(r);/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class yt{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class ki{constructor(e,t,i,s){if(this.data=e,this.mimeType=t,this.name=i,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}}const Gr=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof yt)&&!(e instanceof ki))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},dr=r=>r.title===void 0&&r.description===void 0&&r.artist===void 0&&r.album===void 0&&r.albumArtist===void 0&&r.trackNumber===void 0&&r.tracksTotal===void 0&&r.discNumber===void 0&&r.discsTotal===void 0&&r.genre===void 0&&r.date===void 0&&r.lyrics===void 0&&(!r.images||r.images.length===0)&&r.comment===void 0&&(r.raw===void 0||Object.keys(r.raw).length===0),nt={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},na=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const ce=["avc","hevc","vp9","av1","vp8"],Z=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],St=["aac","opus","mp3","vorbis","flac"],pe=[...St,...Z],Ve=["webvtt"],Gi=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],Xi=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Ge=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Yi=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Zi=".01.01.01.01.00",Ji=".0.110.01.01.01.0",aa=(r,e,t,i)=>{if(r==="avc"){const n=Math.ceil(e/16)*Math.ceil(t/16),a=Gi.find(d=>n<=d.maxMacroblocks&&i<=d.maxBitrate)??X(Gi),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){const s="",a="6",o=e*t,c=Xi.find(u=>o<=u.maxPictureSize&&i<=u.maxBitrate)??X(Xi);return`hev1.${s}1.${a}.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const s="00",n=e*t,a=Ge.find(c=>n<=c.maxPictureSize&&i<=c.maxBitrate)??X(Ge);return`vp09.${s}.${a.level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const n=e*t,a=Yi.find(l=>n<=l.maxPictureSize&&i<=l.maxBitrate)??X(Yi);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)},oa=r=>{const e=r.split("."),t=Number(e[1]),i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,s,4,1,n]},Ms=r=>{const e=r.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,T=(l<<7)+(d<<6)+(h<<5)+(f<<4)+(p<<3)+(g<<2)+w;return[s,c,T,0]},Ds=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(m(r.avcType!==null),s){const c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${r.avcType}.${Hi(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Hi(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,h,f;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,u=qi(n.generalProfileCompatibilityFlags),d=n.generalTierFlag,h=n.generalLevelIdc,f=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const g=L(t),w=g.getUint8(1);c=w>>6&3,l=w&31,u=qi(g.getUint32(2)),d=w>>5&1,h=g.getUint8(12),f=[];for(let T=0;T<6;T++)f.push(g.getUint8(6+T))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const T=r.width*r.height;let k=X(Ge).level;for(const S of Ge)if(T<=S.maxPictureSize){k=S.level;break}return`vp09.00.${k.toString().padStart(2,"0")}.08`}const c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${c}.${l}.${u}.${d}`;return w+=`.${h}.${f}.${p}.${g}`,w.endsWith(Zi)&&(w=w.slice(0,-Zi.length)),w}else if(e==="av1"){if(!o){const S=r.width*r.height;let y=X(Ge).level;for(const x of Ge)if(S<=x.maxPictureSize){y=x.level;break}return`av01.0.${y.toString().padStart(2,"0")}M.08`}const c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=i?.primaries?vt[i.primaries]:1,g=i?.transfer?It[i.transfer]:1,w=i?.matrix?Et[i.matrix]:1,T=i?.fullRange?1:0;let k=`av01.${c}.${l}${u}.${d}`;return k+=`.${h}.${f.toString().padStart(3,"0")}`,k+=`.${p.toString().padStart(2,"0")}`,k+=`.${g.toString().padStart(2,"0")}`,k+=`.${w.toString().padStart(2,"0")}`,k+=`.${T}`,k.endsWith(Ji)&&(k=k.slice(0,-Ji.length)),k}}throw new TypeError(`Unhandled codec '${e}'.`)},ca=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(Z.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Us=r=>{const{codec:e,codecDescription:t,aacCodecInfo:i}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":`mp4a.40.${_r(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Z.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},$t=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ti=[-1,1,2,3,4,5,6,8],_r=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new W(r);let t=e.readBits(5);t===31&&(t=32+e.readBits(6));const i=e.readBits(4);let s=null;i===15?s=e.readBits(24):i<$t.length&&(s=$t[i]);const n=e.readBits(4);let a=null;return n>=1&&n<=7&&(a=Ti[n]),{objectType:t,frequencyIndex:i,sampleRate:s,channelConfiguration:n,numberOfChannels:a}},la=r=>{let e=$t.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);const i=Ti.indexOf(r.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let s=13;r.objectType>=32&&(s+=6),e===15&&(s+=24);const n=Math.ceil(s/8),a=new Uint8Array(n),o=new W(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,i),a},zt=48e3,Ns=/^pcm-([usf])(\d+)+(be)?$/,Ae=r=>{if(m(Z.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Ns.exec(r);m(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,s=e[3]!=="be",n=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:s,silentValue:n}},Os=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r.startsWith("mp4a.40")||r==="mp4a.67"?"aac":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"?"mp3":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Ns.test(r)?r:r==="webvtt"?"webvtt":null,ua=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},da=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},ha=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],fa=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ma=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pa=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ga=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Vs=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ha.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.description!==void 0&&!Sr(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(vt);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const i=Object.keys(It);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const s=Object.keys(Et);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!fa.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!ma.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!pa.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!ga.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},wa=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Rt=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!wa.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!Sr(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!Z.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Z.join(", ")}).`)},Ws=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class at{constructor(e){this.mutex=new At,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let s=this.trackTimestampInfo.get(e);if(!s){if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,s)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),t{const e=[];let t=0;for(;t0&&i>t){const n=r.subarray(t,i);n.length>0&&e.push(n)}t=i+s}if(t0&&e.push(i)}return e},Ls=(r,e)=>{const t=[];let i=0;const s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;i+e<=r.length;){let n;e===1?n=s.getUint8(i):e===2?n=s.getUint16(i,!1):e===3?n=xr(s,i,!1):e===4?n=s.getUint32(i,!1):(ae(e),m(!1)),i+=e;const a=r.subarray(i,i+n);t.push(a),i+=n}return t},Xr=r=>{const e=[],t=r.length;for(let i=0;i{const t=Yt(r);if(t.length===0)return null;let i=0;for(const o of t)i+=4+o.byteLength;const s=new Uint8Array(i),n=new DataView(s.buffer);let a=0;for(const o of t){const c=o.byteLength;n.setUint32(a,c,!1),a+=4,s.set(o,a),a+=o.byteLength}return s},Ta=(r,e)=>{if(e.description){const s=(K(e.description)[4]&3)+1;return Ls(r,s)}else return Yt(r)},ar=r=>r[0]&31,Hs=r=>{try{const e=Yt(r),t=e.filter(c=>ar(c)===xt.SPS),i=e.filter(c=>ar(c)===xt.PPS),s=e.filter(c=>ar(c)===xt.SPS_EXT);if(t.length===0||i.length===0)return null;const n=t[0],a=qs(n);m(a!==null);const o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?s:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},ya=r=>{const e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(const t of r.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s>8),e.push(i&255);for(let s=0;s>8),e.push(i&255);for(let s=0;s{try{const e=L(r);let t=0;const i=e.getUint8(t++),s=e.getUint8(t++),n=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let f=0;f{try{const e=new W(Xr(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();E(e);let a=null,o=null,c=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=E(e),a===3&&e.skipBits(1),o=E(e),c=E(e),e.skipBits(1),e.readBits(1))){for(let h=0;h<(a!==3?8:12);h++)if(e.readBits(1)){const p=h<6?16:64;let g=8,w=8;for(let T=0;T{if(e.description){const s=(K(e.description)[21]&3)+1;return Ls(r,s)}else return Yt(r)},je=r=>r[0]>>1&63,$s=r=>{try{const e=Yt(r),t=e.filter(M=>je(M)===oe.VPS_NUT),i=e.filter(M=>je(M)===oe.SPS_NUT),s=e.filter(M=>je(M)===oe.PPS_NUT),n=e.filter(M=>je(M)===oe.PREFIX_SEI_NUT||je(M)===oe.SUFFIX_SEI_NUT);if(i.length===0||s.length===0)return null;const a=i[0],o=new W(Xr(a));o.skipBits(16),o.readBits(4);const c=o.readBits(3),l=o.readBits(1),{general_profile_space:u,general_tier_flag:d,general_profile_idc:h,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=xa(o,c);E(o);const w=E(o);w===3&&o.skipBits(1),E(o),E(o),o.readBits(1)&&(E(o),E(o),E(o),E(o));const T=E(o),k=E(o);E(o);const y=o.readBits(1)?0:c;for(let M=y;M<=c;M++)E(o),E(o),E(o);E(o),E(o),E(o),E(o),E(o),E(o),o.readBits(1)&&o.readBits(1)&&Ca(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),E(o),E(o),o.skipBits(1));const x=E(o);if(_a(o,x),o.readBits(1)){const M=E(o);for(let z=0;z0){const M=s[0],z=new W(Xr(M));z.skipBits(16),E(z),E(z),z.skipBits(1),z.skipBits(1),z.skipBits(3),z.skipBits(1),z.skipBits(1),E(z),E(z),Ue(z),z.skipBits(1),z.skipBits(1),z.readBits(1)&&E(z),Ue(z),Ue(z),z.skipBits(1),z.skipBits(1),z.skipBits(1),z.skipBits(1);const U=z.readBits(1),q=z.readBits(1);!U&&!q?C=0:U&&!q?C=2:!U&&q?C=3:C=0}const P=[...t.length?[{arrayCompleteness:1,nalUnitType:oe.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:oe.SPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:oe.PPS_NUT,nalUnits:s}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:je(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:d,generalProfileIdc:h,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:I,parallelismType:C,chromaFormatIdc:w,bitDepthLumaMinus8:T,bitDepthChromaMinus8:k,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:P}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},xa=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),s=r.readBits(5);let n=0;for(let u=0;u<32;u++)n=n<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))E(r);else{const s=Math.min(64,1<<4+(e<<1));e>1&&Ue(r);for(let n=0;n{const t=[];for(let i=0;i{let s=0,n=0,a=0;if(e!==0&&(n=r.readBits(1)),n){if(e===t){const c=E(r);a=e-(c+1)}else a=e-1;r.readBits(1),E(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);s=i[a]}else{const o=E(r),c=E(r);for(let l=0;l{if(r.readBits(1)&&r.readBits(8)===255&&(r.readBits(16),r.readBits(16)),r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),r.readBits(1),r.readBits(1)&&(r.readBits(8),r.readBits(8),r.readBits(8))),r.readBits(1)&&(E(r),E(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(E(r),E(r),E(r),E(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&E(r),r.readBits(1)&&Ia(r,!0,e)),r.readBits(1)){r.readBits(1),r.readBits(1),r.readBits(1);const t=E(r);return E(r),E(r),E(r),E(r),t}return 0},Ia=(r,e,t)=>{let i=!1,s=!1,n=!1;i=r.readBits(1)===1,s=r.readBits(1)===1,(i||s)&&(n=r.readBits(1)===1,n&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),n&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let l=!1;c?E(r):l=r.readBits(1)===1;let u=1;l||(u=E(r)+1),i&&es(r,u,n),s&&es(r,u,n)}},es=(r,e,t)=>{for(let i=0;i{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let s=0;s{const e=new W(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),n=(e.readBits(1)<<1)+i;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,h=0;if(u!==7)if(h=e.readBits(1),n===1||n===3){const C=e.readBits(1),P=e.readBits(1);d=!C&&!P?3:C&&!P?2:1,e.skipBits(1)}else d=1;else d=3,h=1;const f=e.readBits(16),p=e.readBits(16),g=f+1,w=p+1,T=g*w;let k=X(Ge).level;for(const I of Ge)if(T<=I.maxPictureSize){k=I.level;break}return{profile:n,level:k,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Ks=function*(r){const e=new W(r),t=()=>{let i=0;for(let s=0;s<8;s++){const n=e.readAlignedByte();if(i|=(n&127)<=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Gs=r=>{for(const{type:e,data:t}of Ks(r)){if(e!==1)continue;const i=new W(t),s=i.readBits(3);i.readBits(1);const n=i.readBits(1);let a=0,o=0,c=0;if(n)a=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;const w=i.readBits(1);w&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));const T=i.readBits(5);for(let k=0;k<=T;k++){i.skipBits(12);const S=i.readBits(5);if(k===0&&(a=S),S>7){const x=i.readBits(1);k===0&&(o=x)}if(w&&i.readBits(1)){const I=c+1;i.skipBits(I),i.skipBits(I),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(1);let u=8;s===2&&l?u=i.readBits(1)?12:10:s<=2&&(u=l?10:8);let d=0;s!==1&&(d=i.readBits(1));let h=1,f=1,p=0;return d||(s===0?(h=1,f=1):s===1?(h=0,f=0):u===12&&(h=i.readBits(1),h&&(f=i.readBits(1))),h&&f&&(p=i.readBits(2))),{profile:s,level:a,tier:o,bitDepth:u,monochrome:d,chromaSubsamplingX:h,chromaSubsamplingY:f,chromaSamplePosition:p}}return null},Pr=r=>{const e=L(r),t=e.getUint8(9),i=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},Aa=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Fa=r=>{const e=r[0]>>3;return{durationInSamples:Aa[e]}},Xs=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=r.length,i=new Uint8Array(t);for(let d=0;d97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){const d=s.pos,h=s.readBits(8),f=s.readBits(16),p=s.readBits(16);if(h>63||f!==0||p!==0){s.pos=d;break}if(s.skipBits(1),a++,a>64)break;s.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const l=c;s.pos=0,s.skipBits(n);const u=Array(l).fill(0);for(let d=l-1;d>=0;d--)s.skipBits(40),u[d]=s.readBits(1);return{modeBlockflags:u}},Ys=(r,e,t)=>{switch(r){case"avc":return Ta(t,e).some(n=>ar(n)===xt.IDR)?"key":"delta";case"hevc":return js(t,e).some(n=>{const a=je(n);return oe.BLA_W_LP<=a&&a<=oe.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new W(t);if(i.readBits(2)!==2)return null;const s=i.readBits(1);return(i.readBits(1)<<1)+s===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:s,data:n}of Ks(t))if(s===1){const a=new W(n);a.skipBits(4),i=!!a.readBits(1)}else if(s===3||s===6||s===7){if(i)return"key";const a=new W(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:ae(r),m(!1)}};var Ne;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Ne||(Ne={}));const Yr=(r,e)=>{const t=L(r);let i=0;const s=t.getUint32(i,!0);i+=4;const n=ke.decode(r.subarray(i,i+s));i+=s,s>0&&(e.raw??={},e.raw.vendor??=n);const a=t.getUint32(i,!0);i+=4;for(let o=0;o0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{const f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{const f=h.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{const f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{const f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{const f=ra(h),p=L(f),g=p.getUint32(0,!1),w=p.getUint32(4,!1),T=String.fromCharCode(...f.subarray(8,8+w)),k=p.getUint32(8+w,!1),S=ke.decode(f.subarray(12+w,12+w+k)),y=p.getUint32(w+k+28),x=f.subarray(w+k+32,w+k+32+y);e.images??=[],e.images.push({data:x,mimeType:T,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:S||void 0})}break}}},Zr=(r,e,t)=>{const i=[r],n=j.encode("Mediabunny");let a=new Uint8Array(4+n.length),o=new DataView(a.buffer);o.setUint32(0,n.length,!0),a.set(n,4),i.push(a);const c=new Set,l=(p,g)=>{const w=`${p}=${g}`,T=j.encode(w);a=new Uint8Array(4+T.length),o=new DataView(a.buffer),o.setUint32(0,T.length,!0),a.set(T,4),i.push(a),c.add(p)};for(const{key:p,value:g}of Ft(e))switch(p){case"title":l("TITLE",g);break;case"description":l("DESCRIPTION",g);break;case"artist":l("ARTIST",g);break;case"album":l("ALBUM",g);break;case"albumArtist":l("ALBUMARTIST",g);break;case"genre":l("GENRE",g);break;case"date":{const w=e.raw?.DATE??e.raw?.date;w&&typeof w=="string"?l("DATE",w):l("DATE",g.toISOString().slice(0,10))}break;case"comment":l("COMMENT",g);break;case"lyrics":l("LYRICS",g);break;case"trackNumber":l("TRACKNUMBER",g.toString());break;case"tracksTotal":l("TRACKTOTAL",g.toString());break;case"discNumber":l("DISCNUMBER",g.toString());break;case"discsTotal":l("DISCTOTAL",g.toString());break;case"images":{if(!t)break;for(const w of g){const T=w.kind==="coverFront"?3:w.kind==="coverBack"?4:0,k=new Uint8Array(w.mimeType.length);for(let C=0;Cp+g.length,0),h=new Uint8Array(d);let f=0;for(const p of i)h.set(p,f),f+=p.length;return h};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class ot{constructor(e){this.input=e}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Ba{static supports(e,t){return!1}}class za{static supports(e,t){return!1}}class Ra{static supports(e,t){return!1}}class Ma{static supports(e,t){return!1}}const hr=[],fr=[],Qt=[],Kt=[],Ql=r=>{if(r.prototype instanceof Ba){const e=r;if(hr.includes(e)){console.warn("Video decoder already registered.");return}hr.push(e)}else if(r.prototype instanceof za){const e=r;if(fr.includes(e)){console.warn("Audio decoder already registered.");return}fr.push(e)}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},Kl=r=>{if(r.prototype instanceof Ra){const e=r;if(Qt.includes(e)){console.warn("Video encoder already registered.");return}Qt.push(e)}else if(r.prototype instanceof Ma){const e=r;if(Kt.includes(e)){console.warn("Audio encoder already registered.");return}Kt.push(e)}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Te=new Uint8Array(0);class ${constructor(e,t,i,s,n=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=s,this.sequenceNumber=n,e===Te&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Te}get microsecondTimestamp(){return Math.trunc(Ke*this.timestamp)}get microsecondDuration(){return Math.trunc(Ke*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new $(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new $(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Da=r=>{let i=r,s=4096,n=0,a=12,o=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&s)!==s&&a>=5;)s>>=1,a--;return o=i>>a-4&15,~(n|a-5<<4|o)&255},Ua=r=>{let t=0,i=0,s=~r;s&128&&(s&=-129,t=-1),i=((s&240)>>4)+5;const n=(1<{let t=2048,i=0,s=11,n=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(i|s-4<<4|n)^85},Oa=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let s=0;return t!==4?s=1<e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const Mt=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,yi=(r,e,t)=>{r.left=Math.min(r.left,e),r.top=Math.min(r.top,t),r.width=Math.min(r.width,e-r.left),r.height=Math.min(r.height,t-r.top),m(r.width>=0),m(r.height>=0)},Si=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ar=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ne{get microsecondTimestamp(){return Math.trunc(Ke*this.timestamp)}get microsecondDuration(){return Math.trunc(Ke*this.duration)}constructor(e){if(this._closed=!1,Ut(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ar.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Dt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const s=this.numberOfFrames*this.numberOfChannels*Dt(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(s>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const n=Dt(t),a=ir(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?s:s*this.numberOfChannels)*n}copyTo(e,t){if(!Sr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Ar.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:s,frameCount:n,frameOffset:a}=t,o=s??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const d=n!==void 0?n:c-u;if(d>c-u)throw new RangeError("frameCount out of range");const h=Dt(o),f=ir(o);if(f&&i>=l)throw new RangeError("planeIndex out of range");if(!f&&i!==0)throw new RangeError("planeIndex out of range");const g=(f?d:d*l)*h;if(e.byteLength0;){const u=Math.min(o,l),d=new Float32Array(s*u);for(let h=0;h0;){const d=Math.min(o,l),h=new Float32Array(s*d);for(let p=0;p{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ir=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Va=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Wa=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,J((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,J(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,J(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ut=r=>typeof AudioData<"u"&&r instanceof AudioData;/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const dt=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Oe=r=>{if(!Bt(r))throw new TypeError("timestamp must be a number.")},Fr=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const s=await r.determinePacketType(i);return s&&(i.type=s),i}):e;class Gt{constructor(e){if(!(e instanceof Ci))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(dt(e),this._track.input._disposed)throw new fe;return Fr(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Oe(e),dt(t),this._track.input._disposed)throw new fe;return Fr(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(dt(t),this._track.input._disposed)throw new fe;return Fr(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Oe(e),dt(t),this._track.input._disposed)throw new fe;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);return!i||i.type==="delta"?i:await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(dt(t),this._track.input._disposed)throw new fe;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return!i||i.type==="delta"?i:await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(e!==void 0&&!(e instanceof $))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof $))throw new TypeError("endPacket must be an EncodedPacket.");if(dt(i),this._track.input._disposed)throw new fe;const s=[];let{promise:n,resolve:a}=G(),{promise:o,resolve:c}=G(),l=!1,u=!1,d=null;const h=[],f=()=>Math.max(2,h.length);(async()=>{let g=e??await this.getFirstPacket(i);for(;g&&!u&&!this._track.input._disposed&&!(t&&g.sequenceNumber>=t?.sequenceNumber);){if(s.length>f()){({promise:o,resolve:c}=G()),await o;continue}s.push(g),a(),{promise:n,resolve:a}=G(),g=await this.getNextPacket(g,i)}l=!0,a()})().catch(g=>{d||(d=g,a())});const p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new fe;if(u)return{value:void 0,done:!0};if(d)throw d;if(s.length>0){const g=s.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}class xi{constructor(e,t){this.onSample=e,this.onError=t}}class Zs{mediaSamplesInRange(e=0,t=1/0){Oe(e),Oe(t);const i=[];let s=!1,n=null,{promise:a,resolve:o}=G(),{promise:c,resolve:l}=G(),u=!1,d=!1,h=!1,f=null;(async()=>{const w=new Error,T=await this._createDecoder(C=>{if(l(),C.timestamp>=t&&(d=!0),d){C.close();return}n&&(C.timestamp>e?(i.push(n),s=!0):n.close()),C.timestamp>=e&&(i.push(C),s=!0),n=s?null:C,i.length>0&&(o(),{promise:a,resolve:o}=G())},C=>{f||(C.stack=w.stack,f=C,o())}),k=this._createPacketSink(),S=await k.getKeyPacket(e,{verifyKeyPackets:!0})??await k.getFirstPacket();if(!S)return;let y=S,x;if(t<1/0){const C=await k.getPacket(t),P=C?C.type==="key"&&C.timestamp===t?C:await k.getNextKeyPacket(C,{verifyKeyPackets:!0}):null;P&&(x=P)}const I=k.packets(S,x);for(await I.next();y&&!d&&!this._track.input._disposed;){const C=ts(i.length);if(i.length+T.getDecodeQueueSize()>C){({promise:c,resolve:l}=G()),await c;continue}T.decode(y);const P=await I.next();if(P.done)break;y=P.value}await I.return(),!h&&!this._track.input._disposed&&await T.flush(),T.close(),!s&&n&&i.push(n),u=!0,o()})().catch(w=>{f||(f=w,o())});const p=this._track,g=()=>{n?.close();for(const w of i)w.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new fe;if(h)return{value:void 0,done:!0};if(f)throw g(),f;if(i.length>0){const w=i.shift();return l(),{value:w,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return h=!0,d=!0,l(),o(),g(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Qn(e);const t=$n(e),i=[],s=[];let{promise:n,resolve:a}=G(),{promise:o,resolve:c}=G(),l=!1,u=!1,d=null;const h=g=>{s.push(g),a(),{promise:n,resolve:a}=G()};(async()=>{const g=new Error,w=await this._createDecoder(C=>{if(c(),u){C.close();return}let P=0;for(;i.length>0&&C.timestamp-i[0]>-1e-10;)P++,i.shift();if(P>0)for(let A=0;A{d||(C.stack=g.stack,d=C,a())}),T=this._createPacketSink();let k=null,S=null,y=-1;const x=async()=>{m(S);let C=S;for(w.decode(C);C.sequenceNumberP&&!u;)({promise:o,resolve:c}=G()),await o;if(u)break;const A=await T.getNextPacket(C);m(A),w.decode(A),C=A}y=-1},I=async()=>{await w.flush();for(let C=0;C{d||(d=g,a())});const f=this._track,p=()=>{for(const g of s)g?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new fe;if(u)return{value:void 0,done:!0};if(d)throw p(),d;if(s.length>0){const g=s.shift();return m(g!==void 0),c(),{value:g,done:!1}}else if(!l)await n;else return{value:void 0,done:!0}}},async return(){return u=!0,c(),a(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}const ts=r=>r===0?40:8;class La extends xi{constructor(e,t,i,s,n,a){super(e,t),this.codec=i,this.decoderConfig=s,this.rotation=n,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Cr,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const o=hr.find(c=>c.supports(i,s));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof ee))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const c=l=>{if(this.alphaQueue.length>0){const u=this.alphaQueue.shift();m(u!==void 0),this.mergeAlpha(l,u)}else this.colorQueue.push(l)};if(i==="avc"&&this.decoderConfig.description&&ea()){const l=Sa(K(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const u=qs(l.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}this.decoder=new VideoDecoder({output:l=>{try{c(l)}catch(u){this.onError(u)}},error:t}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}this.currentPacketIndex++,this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),nr()||ji(this.inputTimestamps,e.timestamp,t=>t),this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e))}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new Ha}catch(i){console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){const i=s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const n=this.colorQueue.shift();m(n!==void 0),this.mergeAlpha(n,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const n=this.colorQueue.shift();m(n!==void 0),this.mergeAlpha(n,null)}else this.alphaQueue.push(null)};this.alphaDecoder=new VideoDecoder({output:s=>{try{i(s)}catch(n){this.onError(n)}},error:this.onError}),this.alphaDecoder.configure(this.decoderConfig)}const t=Ys(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return js(e,this.decoderConfig).some(i=>{const s=je(i);return s===oe.RASL_N||s===oe.RASL_R})}sampleHandler(e){if(nr()){if(this.sampleQueue.length>0&&e.timestamp>=X(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ji(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();m(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){const n=new ee(e);this.sampleHandler(n);return}m(this.merger),this.merger.update(e,t),e.close(),t.close();const i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),s=new ee(i);this.sampleHandler(s)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),nr()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}class Ha{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es + in vec2 a_position; + in vec2 a_texCoord; + out vec2 v_texCoord; + + void main() { + gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; + } + `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es + precision highp float; + + uniform sampler2D u_colorTexture; + uniform sampler2D u_alphaTexture; + in vec2 v_texCoord; + out vec4 fragColor; + + void main() { + vec3 color = texture(u_colorTexture, v_texCoord).rgb; + float alpha = texture(u_alphaTexture, v_texCoord).r; + fragColor = vec4(color, alpha); + } + `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Jr extends Zs{constructor(e){if(!(e instanceof Zt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,s=this._track.rotation,n=await this._track.getDecoderConfig(),a=this._track.timeResolution;return m(i&&n),new La(e,t,i,n,s,a)}_createPacketSink(){return new Gt(this._track)}async getSample(e){Oe(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class qa{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Zt))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Si(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");const i=t.rotation??e.rotation,[s,n]=i%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],a=t.crop;a&&yi(a,s,n);let[o,c]=a?[a.width,a.height]:[s,n];const l=o/c;t.width!==void 0&&t.height===void 0?(o=t.width,c=Math.round(o/l)):t.width===void 0&&t.height!==void 0?(c=t.height,o=Math.round(c*l)):t.width!==void 0&&t.height!==void 0&&(o=t.width,c=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=o,this._height=c,this._rotation=i,this._crop=a,this._fit=t.fit??"fill",this._videoSampleSink=new Jr(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],i=!1;t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=t.getContext("2d",{alpha:this._alpha||Pt()});m(s),s.resetTransform(),i||(!this._alpha&&Pt()?(s.fillStyle="black",s.fillRect(0,0,this._width,this._height)):s.clearRect(0,0,this._width,this._height)),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation,crop:this._crop});const n={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e){Oe(e);const t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return lr(this._videoSampleSink.samples(e,t),i=>this._videoSampleToWrappedCanvas(i))}canvasesAtTimestamps(e){return lr(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}}class ja extends xi{constructor(e,t,i,s){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Cr,this.customDecoderQueueSize=0,this.currentTimestamp=null;const n=o=>{(this.currentTimestamp===null||Math.abs(o.timestamp-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=o.timestamp);const c=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const l=s.sampleRate;o.setTimestamp(Math.round(c*l)/l),e(o)},a=fr.find(o=>o.supports(i,s));a?(this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=o=>{if(!(o instanceof ne))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:o=>{try{n(new ne(o))}catch(c){this.onError(c)}},error:t}),this.decoder.configure(s))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}}class $a extends xi{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,m(Z.includes(i.codec)),this.codec=i.codec;const{dataType:s,sampleSize:n,littleEndian:a}=Ae(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>Ua(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>Oa(o.getUint8(c)):m(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):m(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>xr(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>Kn(o,c,a):m(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):m(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):m(!1);break;default:ae(n),m(!1)}switch(n){case 1:s==="ulaw"||s==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,s==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:ae(n),m(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=L(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,s=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let u=0;u=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const l=new ne({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class ei extends Zs{constructor(e){if(!(e instanceof Fe))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,s=await this._track.getDecoderConfig();return m(i&&s),Z.includes(s.codec)?new $a(e,t,s):new ja(e,t,i,s)}_createPacketSink(){return new Gt(this._track)}async getSample(e){Oe(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class Gl{constructor(e){if(!(e instanceof Fe))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new ei(e)}_audioSampleToWrappedArrayBuffer(e){return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}async getBuffer(e){Oe(e);const t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return lr(this._audioSampleSink.samples(e,t),i=>this._audioSampleToWrappedArrayBuffer(i))}buffersAtTimestamps(e){return lr(this._audioSampleSink.samplesAtTimestamps(e),t=>t&&this._audioSampleToWrappedArrayBuffer(t))}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Ci{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Zt}isAudioTrack(){return this instanceof Fe}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){const t=new Gt(this);let i=1/0,s=-1/0,n=0,a=0;for await(const o of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&o.timestamp>=s)break;i=Math.min(i,o.timestamp),s=Math.max(s,o.timestamp+o.duration),n++,a+=o.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(s-i)).toPrecision(16)):0,averageBitrate:n?Number((8*a/(s-i)).toPrecision(16)):0}}}class Zt extends Ci{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();return m(t!==null),hr.some(s=>s.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;const t=await this.getDecoderConfig();return m(t),Ys(this.codec,t,e.data)}}class Fe extends Ci{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();return m(t!==null),fr.some(i=>i.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Js=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Me=8,et=16,$e=r=>{let e=v(r);const t=te(r,4);let i=8;e===1&&(e=xe(r),i=16);const n=e-i;return n<0?null:{name:t,totalSize:e,headerSize:i,contentSize:n}},Je=r=>rt(r)/65536,Br=r=>rt(r)/1073741824,zr=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=F(r);if(e|=i&127,!(i&128))break}return e},Pe=r=>{let e=re(r);return r.skip(2),e=Math.min(e,r.remainingLength),ke.decode(D(r,e))},Qa=r=>{const e=$e(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=v(r);r.skip(4);const i=D(r,e.contentSize-8);switch(t){case 1:return ke.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new yt(i,"image/jpeg");case 14:return new yt(i,"image/png");case 27:return new yt(i,"image/bmp");default:return i}};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Ka extends ot{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return Js({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(t=>t.info?.type==="video"),hasAudio:this.tracks.some(t=>t.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Me,et);if(t instanceof Promise&&(t=await t),!t)break;const i=e,s=$e(t);if(!s)break;if(s.name==="ftyp"){const n=te(t,4);this.isQuickTime=n==="qt "}else if(s.name==="moov"){let n=this.reader.requestSlice(t.filePos,s.contentSize);if(n instanceof Promise&&(n=await n),!n)break;this.moovSlice=n,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((a,o)=>Number(o.disposition.default)-Number(a.disposition.default));for(const a of this.tracks){const o=a.editListPreviousSegmentDurations/this.movieTimescale;a.editListOffset-=Math.round(o*a.timescale)}break}e=i+s.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),m(t);const i=v(t),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-et){let n=this.reader.requestSliceRange(s,Me,et);if(n instanceof Promise&&(n=await n),n){const a=$e(n);if(a&&a.name==="mfra"){let o=this.reader.requestSlice(n.filePos,a.contentSize);o instanceof Promise&&(o=await o),o&&this.readContiguousBoxes(o)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,m(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Z.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){m(e.info?.type==="audio");const n=Ae(e.info.codec),a=[],o=[];for(let c=0;cP.startIndex),w=t.sampleTimingEntries[g],T=H(t.sampleTimingEntries,p,P=>P.startIndex),k=t.sampleTimingEntries[T],S=w.startDecodeTimestamp+(f-w.startIndex)*w.delta,x=k.startDecodeTimestamp+(p-k.startIndex)*k.delta-S,I=X(a);I&&I.delta===x?I.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:S,count:1,delta:x});const C=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;o.push(C)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const n of t.sampleTimingEntries)for(let a=0;an.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let n=0;nd.moofOffset===n.moofOffset);if(u)Rr(a,u.timestamp);else{const d=H(c,n.moofOffset-1,h=>h.moofOffset);if(d!==-1){const h=c[d];Rr(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}const l=H(c,a.startTimestamp,u=>u.startTimestamp);(l===-1||c[l].moofOffset!==n.moofOffset)&&c.splice(l+1,0,{moofOffset:n.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp})}return n}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Me&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Me;){const i=e.filePos,s=$e(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=i+s.totalSize}}traverseBox(e){const t=e.filePos,i=$e(e);if(!i)return!1;const s=e.filePos,n=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mvhd":{const a=F(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=v(e),this.movieDurationInTimescale=xe(e)):(e.skip(8),this.movieTimescale=v(e),this.movieDurationInTimescale=v(e))}break;case"trak":{const a={id:-1,demuxer:this,inputTrack:null,disposition:{...nt},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:me,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(s,i.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.inputTrack=new Zt(this.input,new Ga(o)),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.inputTrack=new Fe(this.input,new Xa(o)),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=F(e),l=!!(wt(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=v(e),e.skip(4),a.durationInMovieTimescale=v(e);else if(o===1)e.skip(16),a.id=v(e),e.skip(4),a.durationInMovieTimescale=xe(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(2*4+2+2+2+2);const u=[Je(e),Je(e),Br(e),Je(e),Je(e),Br(e),Je(e),Je(e),Br(e)],d=yr(Qr(eo(u),90));m(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=F(e);e.skip(3);let c=!1,l=0;const u=v(e);for(let d=0;d0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;jt(a.languageCode)||(a.languageCode=me)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=te(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,i.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=F(e);e.skip(3);const c=v(e);for(let l=0;l0){if(f===1)e.skip(4),g=8*v(e),e.skip(2*4);else if(f===2){e.skip(4),w=_n(e),p=v(e),e.skip(4),g=v(e);const T=v(e);if(e.skip(2*4),h==="lpcm"){const k=g+7>>3,S=!!(T&1),y=!!(T&2),x=T&4?-1:0;g>0&&g<=64&&(S?g===32&&(a.info.codec=y?"pcm-f32be":"pcm-f32"):x&1<>4,d=l>>1&7,h=l&1,f=F(e),p=F(e),g=F(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="video"),e.skip(1);const o=F(e),c=o>>5,l=o&31,u=F(e),d=u>>7,h=u>>6&1,f=u>>5&1,p=u>>4&1,g=u>>3&1,w=u>>2&1,T=u&3,k=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:k,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:w,chromaSamplePosition:T}}break;case"colr":{const a=this.currentTrack;if(!a||(m(a.info?.type==="video"),te(e,4)!=="nclx"))break;const c=re(e),l=re(e),u=re(e),d=!!(F(e)&128);a.info.colorSpace={primaries:vs[c],transfer:Is[l],matrix:Es[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"esds":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);const o=F(e);m(o===3),zr(e),e.skip(2);const c=F(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){const w=F(e);e.skip(w)}d&&e.skip(2);const h=F(e);m(h===4);const f=zr(e),p=e.filePos,g=F(e);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),f>e.filePos-p){const w=F(e);m(w===5);const T=zr(e);if(a.info.codecDescription=D(e,T),a.info.codec==="aac"){const k=_r(a.info.codecDescription);k.numberOfChannels!==null&&(a.info.numberOfChannels=k.numberOfChannels),k.sampleRate!==null&&(a.info.sampleRate=k.sampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),re(e)&255&&(a.info.codec==="pcm-s16be"?a.info.codec="pcm-s16":a.info.codec==="pcm-s24be"?a.info.codec="pcm-s24":a.info.codec==="pcm-s32be"?a.info.codec="pcm-s32":a.info.codec==="pcm-f32be"?a.info.codec="pcm-f32":a.info.codec==="pcm-f64be"&&(a.info.codec="pcm-f64"))}break;case"pcmC":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);const c=!!(F(e)&1),l=F(e);a.info.codec==="pcm-s16be"?c?l===16?a.info.codec="pcm-s16":l===24?a.info.codec="pcm-s24":l===32?a.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),a.info.codec=null):l===16?a.info.codec="pcm-s16be":l===24?a.info.codec="pcm-s24be":l===32?a.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),a.info.codec=null):a.info.codec==="pcm-f32be"&&(c?l===32?a.info.codec="pcm-f32":l===64?a.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),a.info.codec=null):l===32?a.info.codec="pcm-f32be":l===64?a.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),a.info.codec=null));break}case"dOps":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(1);const o=F(e),c=re(e),l=v(e),u=di(e),d=F(e);let h;d!==0?h=D(e,2+o):h=new Uint8Array(0);const f=new Uint8Array(19+h.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,u,!0),p.setUint8(18,d),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);const o=127,c=128,l=e.filePos;for(;e.filePos>>12,S=(T>>9&7)+1;a.info.sampleRate=k,a.info.numberOfChannels=S,e.skip(20)}else e.skip(g);if(p&c)break}const u=e.filePos;e.filePos=l;const d=D(e,u-l),h=new Uint8Array(4+d.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(d,4),a.info.codecDescription=h}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=v(e);let c=0,l=0;for(let u=0;uk.id===o);if(!c)break;const l=v(e),u=(l&48)>>4,d=(l&12)>>2,h=l&3,f=[F,re,wt,v],p=f[u],g=f[d],w=f[h],T=v(e);for(let k=0;kk.timestamp-S.timestamp);for(let k=0;kT.id===p);if(!g)break;const w=this.fragmentTrackDefaults.find(T=>T.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:w?.defaultSampleDescriptionIndex??null,defaultSampleDuration:w?.defaultSampleDuration??null,defaultSampleSize:w?.defaultSampleSize??null,defaultSampleFlags:w?.defaultSampleFlags??null,startTimestamp:null},o?g.currentFragmentState.baseDataOffset=xe(e):f&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=v(e)),l&&(g.currentFragmentState.defaultSampleDuration=v(e)),u&&(g.currentFragmentState.defaultSampleSize=v(e)),d&&(g.currentFragmentState.defaultSampleFlags=v(e)),h&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;m(a.currentFragmentState);const o=F(e);e.skip(3);const c=o===0?v(e):xe(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;if(m(this.currentFragment),m(a.currentFragmentState),this.currentFragment.trackData.has(a.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const o=F(e),c=wt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),h=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=v(e);let w=a.currentFragmentState.baseDataOffset;l&&(w+=rt(e));let T=null;u&&(T=v(e));let k=w;if(g===0){this.currentFragment.implicitBaseDataOffset=k;break}let S=0;const y={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(a.id,y);for(let C=0;C({presentationTimestamp:C.presentationTimestamp,sampleIndex:P})).sort((C,P)=>C.presentationTimestamp-P.presentationTimestamp);for(let C=0;C0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const h=L(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const h=L(d),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=n,!0}}class en{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return ur(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=rs(s,i),a=await this.fetchPacketForSampleIndex(n,t);return!is(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=H(c.presentationTimestamps,i,h=>h.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i{if(n===s.fragment){const a=n.trackData.get(this.internalTrack.id);if(s.sampleIndex+1{const l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};const u=Bs(l.presentationTimestamps,f=>l.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),d=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,h=u!==-1&&i{if(n===s.fragment){const o=n.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return m(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Ya(i,e);if(!s)return null;let n;if(t.metadataOnly)n=Te;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);l instanceof Promise&&(l=await l),m(l),n=D(l,s.sampleSize)}const a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,c=new $(n,s.isKeyFrame?"key":"delta",a,o,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).samples[t];m(n);let a;if(i.metadataOnly)a=Te;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);u instanceof Promise&&(u=await u),m(u),a=D(u,n.byteSize)}const o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=new $(a,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,i,s,n){const a=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:w,correctSampleFound:T}=t(e);if(T)return this.fetchPacketInFragment(e,w,n);w!==-1&&(c=e,l=w)}const u=H(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,h=H(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null;let g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,o=e):g=p:g=p??0;;){if(o){const S=o.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>s)break}let w=a.reader.requestSliceRange(g,Me,et);if(w instanceof Promise&&(w=await w),!w)break;const T=g,k=$e(w);if(!k)break;if(k.name==="moof"){o=await a.readFragment(T);const{sampleIndex:S,correctSampleFound:y}=t(o);if(y)return this.fetchPacketInFragment(o,S,n);S!==-1&&(c=o,l=S)}g=T+k.totalSize}if(d&&(!c||c.moofOffset{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Qs(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Gs(e.data)}return{codec:Ds(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class Xa extends en{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Us(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const rs=(r,e)=>{if(r.presentationTimestamps){const t=H(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=H(r.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Ya=(r,e)=>{const t=H(r.sampleTimingEntries,e,T=>T.startIndex),i=r.sampleTimingEntries[t];if(!i||i.startIndex+i.count<=e)return null;let n=i.startDecodeTimestamp+(e-i.startIndex)*i.delta;const a=H(r.sampleCompositionTimeOffsets,e,T=>T.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndexT.startSampleIndex),u=r.sampleToChunk[l];m(u);const d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),h=r.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let p=0,g=h;if(r.sampleSizes.length===1)g+=c*(e-f),p+=c*u.samplesPerChunk;else for(let T=f;TT)!==-1:!0}},Za=(r,e)=>{if(!r.keySampleIndices)return e;const t=H(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t]??-1},Ja=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=H(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Rr=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(const t of r.samples)t.presentationTimestamp+=e;for(const t of r.presentationTimestamps)t.presentationTimestamp+=e},eo=r=>{const[e,,,t]=r,i=Math.hypot(e,t),s=e/i,n=t/i,a=-Math.atan2(n,s)*(180/Math.PI);return Number.isFinite(a)?a:0},is=r=>r.sampleSizes.length===0;/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class ti{constructor(e){this.value=e}}class ri{constructor(e){this.value=e}}class tn{constructor(e){this.value=e}}class He{constructor(e){this.value=e}}var b;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(b||(b={}));const to=[b.EBML,b.Segment],Xt=[b.SeekHead,b.Info,b.Cluster,b.Tracks,b.Cues,b.Attachments,b.Chapters,b.Tags],or=[...to,...Xt],ss=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,ns=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,as=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6,ro=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)};class io{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=ss(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=ns(e)){let i=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(i++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=as(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=ro(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){const n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,i),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??ss(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??ns(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ti)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof ri)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof tn){const t=e.size??as(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof He){const t=j.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else ae(e.data)}}const ii=8,Ce=2,De=2*ii,rn=r=>{const e=F(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;!(e&i);)t++,i>>=1;return t},Lt=r=>{const e=F(r);if(e===0)return null;let t=1,i=128;for(;!(e&i);)t++,i>>=1;let s=e&i-1;for(let n=1;n{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i{const e=rn(r);return e===null?null:N(r,e)},sn=r=>{let e=F(r);return e===255?e=null:(r.skip(-1),e=Lt(r),e===72057594037927940&&(e=null)),e},ze=r=>{const e=_i(r);if(e===null)return null;const t=sn(r);return{id:e,size:t}},gt=(r,e)=>{const t=D(r,e);let i=0;for(;i{const t=D(r,e);let i=0;for(;i{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?ec(r):_n(r)},si=async(r,e,t,i)=>{const s=new Set(t);let n=e;for(;i===null||nn?i:n,found:!1}},nn=async(r,e,t,i)=>{const n=new Set(t);let a=e;for(;a{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */var Be;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Be||(Be={}));var mr;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(mr||(mr={}));var Ht;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(Ht||(Ht={}));const Dr=[{id:b.SeekHead,flag:"seekHeadSeen"},{id:b.Info,flag:"infoSeen"},{id:b.Tracks,flag:"tracksSeen"},{id:b.Cues,flag:"cuesSeen"}],on=10*2**20;class no extends ot{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.inputTrack))}async getMimeType(){await this.readMetadata();const e=await this.getTracks(),t=await Promise.all(e.map(i=>i.getCodecParameterString()));return an({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Ce,De);if(t instanceof Promise&&(t=await t),!t)break;const i=ze(t);if(!i)break;const s=i.id;let n=i.size;const a=t.filePos;if(s===b.EBML){qe(n);let o=this.reader.requestSlice(a,n);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===b.Segment){if(await this.readSegment(a,n),n===null||this.reader.fileSize===null)break}else if(s===b.Cluster){if(this.reader.fileSize===null)break;n===null&&(n=(await si(this.reader,a,or,this.reader.fileSize)).pos-a);const o=X(this.segments);o&&(o.elementEndPos=a+n)}qe(n),e=a+n}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===null?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||ip.id===u);if(f!==-1){const p=Dr[f].flag;this.currentSegment[p]=!0,qe(d);let g=this.reader.requestSlice(h,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(u===b.Tags||u===b.Attachments){u===b.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,qe(d);let p=this.reader.requestSlice(h,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===b.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===null)break;i=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Dr.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Ce,De);if(l instanceof Promise&&(l=await l),!l)continue;const u=ze(l);if(!u)continue;const{id:d,size:h}=u;if(d!==c.id)continue;qe(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((o,c)=>Number(c.disposition.default)-Number(o.disposition.default));const s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=s.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;ca&&(a=o.cuePoints.length,n=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,Ce,De);i instanceof Promise&&(i=await i),m(i);const s=e,n=ze(i);m(n);const a=n.id;m(a===b.Cluster);let o=n.size;const c=i.filePos;o===null&&(o=(await si(this.reader,c,or,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const d=this.readContiguousElements(l,or);u.elementEndPos=d}for(const[,d]of u.trackData){const h=d.track;m(d.blocks.length>0);let f=!1;for(let T=0;T({timestamp:T.timestamp,blockIndex:k})).sort((T,k)=>T.timestamp-k.timestamp);for(let T=0;T({timestamp:T.timestamp,blockIndex:k})).sort((T,k)=>T.timestamp-k.timestamp));const p=d.blocks[d.presentationTimestamps[0].blockIndex],g=d.blocks[X(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=g.timestamp+g.duration;const w=H(h.clusterPositionCache,d.startTimestamp,T=>T.startTimestamp);(w===-1||h.clusterPositionCache[w].elementStartPos!==s)&&h.clusterPositionCache.splice(w+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const s=e.segment.tracks.find(n=>n.id===t);if(!s)return null;i={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;io.data?.type!=="decompress"||o.scope!==mr.Block||o.data.algorithm!==Ht.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===Se.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Se.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.vp8?this.currentTrack.info.codec="vp8":c===Se.vp9?this.currentTrack.info.codec="vp9":c===Se.av1&&(this.currentTrack.info.codec="av1");const l=this.currentTrack,u=new Zt(this.input,new ao(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Se.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Se.mp3?this.currentTrack.info.codec="mp3":c===Se.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=zt):c===Se.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Se.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const l=this.currentTrack,u=new Fe(this.input,new oo(l));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case b.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=N(e,n)}break;case b.TrackType:{if(!this.currentTrack)break;const o=N(e,n);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case b.FlagEnabled:{if(!this.currentTrack)break;N(e,n)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case b.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!N(e,n)}break;case b.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!N(e,n)}break;case b.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!N(e,n)}break;case b.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!N(e,n)}break;case b.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!N(e,n)}break;case b.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!N(e,n)}break;case b.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=gt(e,n)}break;case b.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=D(e,n)}break;case b.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*N(e,n)/1e9}break;case b.Name:{if(!this.currentTrack)break;this.currentTrack.name=Nt(e,n)}break;case b.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==me)break;this.currentTrack.languageCode=gt(e,n),jt(this.currentTrack.languageCode)||(this.currentTrack.languageCode=me)}break;case b.LanguageBCP47:{if(!this.currentTrack)break;const c=gt(e,n).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=me}break;case b.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case b.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=N(e,n)}break;case b.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=N(e,n)}break;case b.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=N(e,n)===1}break;case b.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,n))}break;case b.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=N(e,n),c=Es[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case b.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=N(e,n)===2}break;case b.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=N(e,n),c=Is[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case b.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=N(e,n),c=vs[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case b.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case b.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Mr(e,n);try{this.currentTrack.info.rotation=yr(c)}catch{}}break;case b.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case b.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Mr(e,n)}break;case b.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=N(e,n)}break;case b.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=N(e,n)}break;case b.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case b.CueTime:this.currentCueTime=N(e,n);break;case b.CueTrackPositions:{if(this.currentCueTime===null)break;m(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,n)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case b.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=N(e,n)}break;case b.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;m(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+N(e,n)}break;case b.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=N(e,n)}break;case b.SimpleBlock:{if(!this.currentCluster)break;const o=Lt(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=di(e),u=F(e),d=u>>1&3;let h=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);const f=D(e,n-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:d,decoded:!p,mainAdditional:null})}break;case b.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case b.Block:{if(!this.currentCluster)break;const o=Lt(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=di(e),d=F(e)>>1&3,h=D(e,n-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case b.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case b.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case b.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=D(e,n)}break;case b.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=N(e,n)}break;case b.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=N(e,n)}break;case b.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case b.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case b.Targets:this.readContiguousElements(e.slice(a,n));break;case b.TargetTypeValue:N(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case b.TagTrackUID:case b.TagEditionUID:case b.TagChapterUID:case b.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case b.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case b.TagName:this.currentSimpleTagName=Nt(e,n);break;case b.TagString:{if(!this.currentSimpleTagName)break;const o=Nt(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case b.TagBinary:{if(!this.currentSimpleTagName)break;const o=D(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case b.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new ki(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const c=this.currentAttachedFile.fileName;let l="unknown";if(c){const u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case b.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=so(e,n)}break;case b.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Nt(e,n)}break;case b.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=gt(e,n)}break;case b.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=D(e,n)}break;case b.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Nt(e,n)}break;case b.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case b.ContentEncoding:this.currentDecodingInstruction={order:0,scope:mr.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case b.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=N(e,n)}break;case b.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=N(e,n)}break;case b.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ht.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case b.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=N(e,n)}break;case b.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=D(e,n)}break;case b.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){m(e.decodingInstructions.length>0);let i=t;for(const s of e.decodingInstructions)switch(m(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case Ht.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){const n=s.data.settings,a=new Uint8Array(n.length+i.length);a.set(n,0),a.set(i,n.length),i=a}break}break}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{const s=new Date(t);Number.isNaN(s.getTime())||(i.date??=s)}break;case"track_number":case"part_number":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.trackNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.discNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}}class cn{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return ur(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=H(n.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i{if(s===i.cluster){const n=s.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=Bs(n.presentationTimestamps,l=>n.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i{if(s===i.cluster){const a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){const a=n.blocks.findIndex(o=>o.isKeyFrame);return m(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];m(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const a=i.metadataOnly?Te:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Te:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const u=new $(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,i,s,n){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:T,correctBlockFound:k}=t(e);if(k)return this.fetchPacketInCluster(e,T,n);T!==-1&&(l=e,u=T)}const d=H(this.internalTrack.cuePoints,i,T=>T.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,f=H(this.internalTrack.clusterPositionCache,i,T=>T.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,g=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null;let w;for(e?g===null||e.elementStartPos>=g?(w=e.elementEndPos,c=e):w=g:w=g??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-Ce;){if(c){const P=c.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>s)break}let T=a.reader.requestSliceRange(w,Ce,De);if(T instanceof Promise&&(T=await T),!T)break;const k=w,S=ze(T);if(!S||!Xt.includes(S.id)&&S.id!==b.Void){const P=await nn(a.reader,k,Xt,Math.min(o.elementEndPos??1/0,k+on));if(P){w=P;continue}else break}const y=S.id;let x=S.size;const I=T.filePos;if(y===b.Cluster){c=await a.readCluster(k,o),x=c.elementEndPos-I;const{blockIndex:P,correctBlockFound:A}=t(c);if(A)return this.fetchPacketInCluster(c,P,n);P!==-1&&(l=c,u=P)}x===null&&(m(y!==b.Cluster),x=(await si(a.reader,I,or,o.elementEndPos)).pos-I);const C=I+x;if(o.elementEndPos===null){let P=a.reader.requestSliceRange(C,Ce,De);if(P instanceof Promise&&(P=await P),!P)break;if(_i(P)===b.Segment){o.elementEndPos=C;break}}w=C}if(h&&(!l||l.elementStartPos{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:Ds({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Hs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?$s(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Qs(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Gs(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class oo extends cn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Us({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const ln=4,co=[44100,48e3,32e3],ni=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Pi=1483304551,un=1231971951,ai=(r,e,t,i,s)=>e===0?0:e===1?Math.floor(144*t/(i<r===3?e===3?21:36:e===3?13:21,dn=(r,e)=>{const t=r>>>24,i=r>>>16&255,s=r>>>8&255,n=r&255;if(t!==255&&i!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);const c=i>>3&3,l=i>>1&3,u=s>>4&15,d=(s>>2&3)%3,h=s>>1&1,f=n>>6&3,p=n>>4&3,g=n>>3&1,w=n>>2&1,T=n&3,k=ni[a*16*4+l*16+u];if(k===-1)return{header:null,bytesAdvanced:1};const S=k*1e3,y=co[d]>>a+o,x=ai(a,l,S,y,h);if(e!==null&&e{let e=127,t=0,i=r;for(;e^2147483647;)t=i&~e,t<<=1,t|=i&e,e=(e+1<<8)-1,i=t;return t},oi=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */var bt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(bt||(bt={}));var se;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(se||(se={}));const cr=128,pr=10,kt=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],uo=(r,e)=>{const t=r.filePos;e.raw??={},e.raw.TAG??=D(r,cr-3),r.filePos=t;const i=ht(r,30);i&&(e.title??=i);const s=ht(r,30);s&&(e.artist??=s);const n=ht(r,30);n&&(e.album??=n);const a=ht(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(o,0,1));const c=D(r,30);let l;if(c[28]===0&&c[29]!==0){const d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=ht(r,28),r.skip(2)}else r.skip(-30),l=ht(r,30);l&&(e.comment??=l);const u=F(r);u{const t=D(r,e),i=pt(t.indexOf(0),t.length),s=t.subarray(0,i);let n="";for(let a=0;a{const e=r.filePos,t=te(r,3),i=F(r),s=F(r),n=F(r),a=v(r);if(t!=="ID3"||i===255||s===255||a&2155905152)return r.filePos=e,null;const o=oi(a);return{majorVersion:i,revision:s,flags:n,size:o}},hn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=D(r,e.size),s=new ho(e,i);if(e.flags&bt.Footer&&s.removeFooter(),e.flags&bt.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&bt.ExtendedHeader){const n=s.readU32();e.majorVersion===3?s.pos+=n:s.pos+=n-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const n=s.readId3V2Frame();if(!n)break;const a=s.pos,o=s.pos+n.size;let c=!1,l=!1,u=!1;if(e.majorVersion===3?(c=!!(n.flags&64),l=!!(n.flags&128)):e.majorVersion===4&&(c=!!(n.flags&4),l=!!(n.flags&8),u=!!(n.flags&2)||!!(e.flags&bt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${n.id}`),s.pos=o;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${n.id}`),s.pos=o;continue}switch(u&&s.ununsynchronizeRegion(s.pos,o),t.raw??={},n.id[0]==="T"?t.raw[n.id]??=s.readId3V2EncodingAndText(o):t.raw[n.id]??=s.readBytes(n.size),s.pos=a,n.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(o);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(o);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(o);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(o);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(o);break;case"TRCK":case"TRK":{const h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.tracksTotal??=p)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(t.discsTotal??=p)}break;case"TCON":case"TCO":{const d=s.readId3V2EncodingAndText(o);let h=/^\((\d+)\)/.exec(d);if(h){const f=Number.parseInt(h[1]);if(kt[f]!==void 0){t.genre??=kt[f];break}}if(h=/^\d+$/.exec(d),h){const f=Number.parseInt(h[0]);if(kt[f]!==void 0){t.genre??=kt[f];break}}t.genre??=d}break;case"TDRC":case"TDAT":{const d=s.readId3V2EncodingAndText(o),h=new Date(d);Number.isNaN(h.getTime())||(t.date??=h)}break;case"TYER":case"TYE":{const d=s.readId3V2EncodingAndText(o),h=Number.parseInt(d,10);Number.isInteger(h)&&(t.date??=new Date(h,0,1))}break;case"USLT":case"ULT":{const d=s.readU8();s.pos+=3,s.readId3V2Text(d,o),t.lyrics??=s.readId3V2Text(d,o)}break;case"COMM":case"COM":{const d=s.readU8();s.pos+=3,s.readId3V2Text(d,o),t.comment??=s.readId3V2Text(d,o)}break;case"APIC":case"PIC":{const d=s.readId3V2TextEncoding();let h;if(e.majorVersion===2){const w=s.readAscii(3);h=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(d,o);const f=s.readU8(),p=s.readId3V2Text(d,o).trimEnd(),g=o-s.pos;if(g>=0){const w=s.readBytes(g);t.images||(t.images=[]),t.images.push({data:w,mimeType:h,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:s.pos+=n.size;break}s.pos=o}};class ho{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(i)){const o=this.header.majorVersion===4?t:oi(t);a(o)&&(i=o)}return this.pos=n,{id:e,size:i,flags:s}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,s=this.readBytes(t-this.pos);switch(e){case se.ISO_8859_1:{let n="";for(let a=0;ao===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){const n=new TextDecoder("utf-16be"),a=pt(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{const n=pt(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),ke.decode(s.subarray(0,n))}case se.UTF_16_BE_NO_BOM:{const n=new TextDecoder("utf-16be"),a=pt(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case se.UTF_8:{const n=pt(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),ke.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class fn{constructor(e){this.helper=new Uint8Array(8),this.helperView=L(this.helper),this.writer=e}writeId3V2Tag(e){const t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);const i=this.writer.getPos(),s=new Set;for(const{key:o,value:c}of Ft(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),s.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),s.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),s.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),s.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),s.add("TPE2");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),s.add("TRCK")}break;case"discNumber":{const l=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),s.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),s.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),s.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(c),s.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),s.add("COMM");break;case"images":{const l={coverFront:3,coverBack:4,unknown:0};for(const u of c){const d=l[u.kind]??0,h=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,h,u.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||s.has(o))continue;let l;if(typeof c=="string"){const u=j.encode(c);l=new Uint8Array(u.byteLength+2),l[0]=se.UTF_8,l.set(u,1)}else if(c instanceof Uint8Array)l=c;else continue;this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}const n=this.writer.getPos(),a=n-i;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(n),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t{let i=e;for(;t===null||i{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Fe(this.input,new mo(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,pr);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=gr(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await ci(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=vi(t.mpegVersionId,t.channel);let s=this.reader.requestSlice(e.startPos+i,4);if(s instanceof Promise&&(s=await s),s){const o=v(s);if(o===Pi||o===un)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return m(e),e.computeDuration()}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,i=!1;for(;;){let s=this.reader.requestSlice(t,pr);if(s instanceof Promise&&(s=await s),!s)break;const n=gr(s);if(!n)break;i=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(a instanceof Promise&&(a=await a),!a)break;hn(a,n,this.metadataTags),t=s.filePos+n.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=cr){let s=this.reader.requestSlice(this.reader.fileSize-cr,cr);s instanceof Promise&&(s=await s),m(s),te(s,3)==="TAG"&&uo(s,this.metadataTags)}return this.metadataTags}finally{e()}}}class mo{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return me}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...nt}}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Te;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=D(n,i.dataSize)}return new $(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=bi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=H(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1>>0&4294967295}const pn=r=>{const e=L(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let s=0;s>>24^n])>>>0}return e.setUint32(22,t,!0),i},gn=(r,e,t)=>{let i=0,s=null;if(r.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);const n=e.vorbisInfo.modeBlockflags.length,o=(1<>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t;const u=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[u],u===1){const d=(o|1)+1,h=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[h]}i=l!==null?l+s>>2:0}else e.codec==="opus"&&(i=Fa(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:s}},wn=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const tt=27,Ct=282,bn=Ct+255*255,qt=r=>{const e=r.filePos;if(Tt(r)!==Ii)return null;r.skip(1);const i=F(r),s=Jo(r),n=Tt(r),a=Tt(r),o=Tt(r),c=F(r),l=new Uint8Array(c);for(let f=0;ff+p,0),h=u+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+u,dataSize:d,headerType:i,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:l}},go=(r,e)=>{for(;r.filePos>>8&255,n=t>>>16&255,a=t>>>24&255,o=79;if(!(i!==o&&s!==o&&n!==o&&a!==o)){if(r.skip(-4),t===Ii)return!0;r.skip(1)}}return!1};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class wo extends ot{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,tt,Ct);if(t instanceof Promise&&(t=await t),!t)break;const i=qt(t);if(!i||!!!(i.headerType&2))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.tracks.push(new Fe(this.input,new bo(t,this))))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||(i=await this.findNextPacketStart(s),!i))return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(s.data.length);const c=new Uint8Array(1+a.length+e.data.length+s.data.length+n.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(s.data,1+a.length+e.data.length),c.set(n.data,1+a.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;const l=L(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Xs(n.data).modeBlockflags},Yr(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;const n=Pr(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=zt,t.codecInfo.opusInfo={preSkip:n.preSkip},Yr(s.data.subarray(8),this.metadataTags)}async readPacket(e,t){m(td+h.length,0),l=new Uint8Array(c);let u=0;for(let d=0;dt.getCodecParameterString()));return wn({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class bo{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new At,this.internalSampleRate=e.codecInfo.codec==="opus"?zt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return m(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return me}getDisposition(){return{...nt}}async getFirstTimestamp(){return 0}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(m(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:s,vorbisBlockSize:n}=gn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new $(i.metadataOnly?Te:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),a}async getFirstPacket(e){m(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const s=await this.demuxer.findNextPacketStart(i.packet);if(!s)return null;const n=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const i=ur(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;m(this.bitstream.lastMetadataPacket);const s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,a=this.demuxer.reader.fileSize;const o=[n];e:for(;n.headerStartPos+n.totalSizei?a=A.headerStartPos:(n=A,o.push(A));continue e}}let c=s.startPage;for(const k of o){if(k.granulePosition===n.granulePosition)break;(!c||k.headerStartPos>c.headerStartPos)&&(c=k)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){const k=l.headerStartPos+l.totalSize;let S=this.demuxer.reader.requestSliceRange(k,tt,Ct);S instanceof Promise&&(S=await S),m(S);const y=qt(S);m(y),l=y,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}m(l.granulePosition!==-1);let d=null,h,f,p=l,g=0;if(l.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,d=0;else{h=0,f=!1;for(let y=l.lacingValues.length-1;y>=0;y--)if(l.lacingValues[y]<255){d=y+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=d-1;const k={data:Te,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(k)){const y=cs(u,l,d);m(y);const x=os(u,y.page,y.segmentIndex);x&&(l=x.page,d=x.segmentIndex)}else for(;;){const y=cs(u,l,d);if(!y)break;const x=os(u,y.page,y.segmentIndex);if(!x)break;if(l=x.page,d=x.segmentIndex,y.page.headerStartPos!==p.headerStartPos){p=y.page,g=y.segmentIndex;break}}}let w=null,T=null;for(;l!==null;){m(d!==null);const k=await this.demuxer.readPacket(l,d);if(!k)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&di||Math.max(I.timestampInSamples,0)===i))break}const y=await this.demuxer.findNextPacketStart(k);if(!y)break;l=y.startPage,d=y.startSegmentIndex}return w}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const s=ur(e*this.internalSampleRate);e=s/this.internalSampleRate;const n=H(this.sequentialScanCache,s,c=>c.timestampInSamples);let a;if(n!==-1){const c=this.sequentialScanCache[n];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestampe)break;if(a=c,o++,o===100){o=0;const l=this.encodedPacketToMetadata.get(a);m(l),this.sequentialScanCache.length>0&&m(X(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const os=(r,e,t)=>{let i=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(i.lacingValues[s]<255){s++;break e}if(m(s===-1),!(i.headerType&1)){s=0;break}const a=Fs(r,o=>o.headerStartPos{if(t>0)return{page:e,segmentIndex:t-1};const i=Fs(r,s=>s.headerStartPos{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),m(e);const t=te(e,4),i=t!=="RIFX",s=t==="RF64",n=Xe(e,i);let a=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(te(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u=18&&n!==357){const u=Ot(s,i),d=t-18;if(Math.min(d,u)>=22&&n===he.EXTENSIBLE){s.skip(6);const f=D(s,16);n=f[0]|f[1]<<8}}(n===he.MULAW||n===he.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,i){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;const n=te(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+t-8;){s.filePos=a;const o=te(s,4),c=Xe(s,i),l=D(s,c);let u=0;for(let h=0;h0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{const h=new Date(d);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{const h=Number.parseInt(d,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const s=gr(i);if(s){const n=i.slice(e+10,s.size);hn(n,s,this.metadataTags)}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===he.MULAW)return"ulaw";if(this.audioInfo.format===he.ALAW)return"alaw";if(this.audioInfo.format===he.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===he.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return m(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const ft=2048;class To{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(m(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return me}getDisposition(){return{...nt}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){m(this.demuxer.audioInfo);const i=e*ft*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const s=Math.min(ft*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=Te;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);c instanceof Promise&&(c=await c),m(c),n=D(c,s)}const a=e*ft/this.demuxer.audioInfo.sampleRate,o=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,a),new $(n,"key",a,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){m(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ft,(this.demuxer.dataSize-1)/(ft*this.demuxer.audioInfo.blockSizeInBytes))),s=await this.getPacketAtIndex(i,t);if(s)return s;if(i===0)return null;m(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const a=await this.getNextPacket(n,t);if(!a)break;n=a}return n}getNextPacket(e,t){m(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ft);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const wr=7,br=9,li=r=>{const e=r.filePos,t=D(r,9),i=new W(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);const l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const u=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:h,startPos:e}};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const ui=1024;class yo extends ot{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new At,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();m(this.firstFrameHeader),this.tracks=[new Fe(this.input,new So(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,wr,br);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=li(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const i=$t[t.samplingFrequencyIndex];m(i!==void 0);const s=ui/i,n=t.crcCheck?br:wr,a={timestamp:this.nextTimestampInSamples/i,duration:s,dataStart:t.startPos+n,dataSize:t.frameLength-n};this.loadedSamples.push(a),this.nextTimestampInSamples+=ui,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return m(e),e.computeDuration()}async getMetadataTags(){return{}}}class So{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/ui}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return me}getCodec(){return"aac"}getInternalCodecId(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){m(this.demuxer.firstFrameHeader);const e=Ti[this.demuxer.firstFrameHeader.channelConfiguration];return m(e!==void 0),e}getSampleRate(){m(this.demuxer.firstFrameHeader);const e=$t[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return m(e!==void 0),e}getDisposition(){return{...nt}}async getDecoderConfig(){m(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),t=new W(e),{objectType:i,samplingFrequencyIndex:s,channelConfiguration:n}=this.demuxer.firstFrameHeader;return i>31?(t.writeBits(5,31),t.writeBits(6,i-32)):t.writeBits(5,i),t.writeBits(4,s),t.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Te;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=D(n,i.dataSize)}return new $(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=bi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=H(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,xo=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Tn=r=>{let e=0;const t=new W(D(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],s=e-1,n=new W(D(r,s)),a=8-e-1;for(let c=0;cc|l<{if(e==="uncommon-u16")return re(r)+1;if(e==="uncommon-u8")return F(r)+1;if(typeof e=="number")return e;ae(e),m(!1)},Co=(r,e)=>e==="uncommon-u16"?re(r):e==="uncommon-u16-10"?re(r)*10:e==="uncommon-u8"?F(r):typeof e=="number"?e:null,_o=r=>{let t=0;for(const i of r){t^=i;for(let s=0;s<8;s++)t&128?t=t<<1^7:t<<=1,t&=255}return t};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Po extends ot{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new At,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),m(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),m(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||ea.end-i)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:a.end-e,isLastFrame:!0};if(F(a)===255){const l=a.filePos,u=F(a),d=this.blockingBit===1?249:248;if(u!==d){a.filePos=l;continue}a.skip(-2);const h=a.filePos-e,f=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!f){a.filePos=l;continue}if(this.blockingBit===0){if(f.num-o.num!==1){a.filePos=l;continue}}else if(f.num-o.num!==o.blockSize){a.filePos=l;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:h,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,s=D(e,4),n=new W(s);if(n.readBits(15)!==32764)return null;if(this.blockingBit===null){m(t);const w=n.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(m(!t),n.readBits(1)!==1)return null}else if(this.blockingBit===0){if(m(!t),n.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=kn(n.readBits(4));if(!o)return null;m(this.audioInfo);const c=xo(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;const u=Tn(e),d=yn(e,o),h=Co(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;const f=e.filePos-i,p=F(e);e.skip(-f),e.skip(-1);const g=_o(D(e,f));return p!==g?null:{num:u,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),m(this.lastLoadedPos!==null),m(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const i=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(n),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class vo{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return me}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...nt}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return m(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(m(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=H(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(s===-1){await this.demuxer.advanceReader();continue}const n=this.demuxer.loadedSamples[s],a=n.blockOffset/this.demuxer.audioInfo.sampleRate,o=n.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(s,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Te;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;s=D(o,i.byteSize)}m(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new $(s,"key",n,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Ye{}class Sn extends Ye{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),te(t,4)!=="ftyp")?null:te(t,4)}_createDemuxer(e){return new Ka(e)}}class Io extends Sn{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Eo extends Sn{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class xn extends Ye{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,De);if(i instanceof Promise&&(i=await i),!i)return!1;const s=rn(i);if(s===null||s<1||s>8||N(i,s)!==b.EBML)return!1;const a=sn(i);if(a===null)return!1;let o=e._reader.requestSlice(i.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-Ce;){const l=ze(o);if(!l)break;const{id:u,size:d}=l,h=o.filePos;if(d===null)return!1;switch(u){case b.EBMLVersion:if(N(o,d)!==1)return!1;break;case b.EBMLReadVersion:if(N(o,d)!==1)return!1;break;case b.DocType:if(gt(o,d)!==t)return!1;break;case b.DocTypeVersion:if(N(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new no(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ao extends xn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Fo extends Ye{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let i=0,s=!1;for(;;){let l=e._reader.requestSlice(i,pr);if(l instanceof Promise&&(l=await l),!l)break;const u=gr(l);if(!u)break;s=!0,i=l.filePos+u.size}const n=await ci(e._reader,i,i+4096);if(!n)return!1;if(s)return!0;i=n.startPos+n.header.totalSize;const a=await ci(e._reader,i,i+ln);if(!a)return!1;const o=n.header,c=a.header;return!(o.channel!==c.channel||o.sampleRate!==c.sampleRate)}_createDemuxer(e){return new fo(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Bo extends Ye{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=te(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),te(t,4)==="WAVE")}_createDemuxer(e){return new ko(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class zo extends Ye{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?te(t,4)==="OggS":!1}_createDemuxer(e){return new wo(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ro extends Ye{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?te(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Po(e)}}class Mo extends Ye{async _canReadInput(e){let t=e._reader.requestSliceRange(0,wr,br);if(t instanceof Promise&&(t=await t),!t)return!1;const i=li(t);if(!i||(t=e._reader.requestSliceRange(i.frameLength,wr,br),t instanceof Promise&&(t=await t),!t))return!1;const s=li(t);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new yo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const Do=new Io,Uo=new Eo,No=new xn,Oo=new Ao,Vo=new Fo,Wo=new Bo,Lo=new zo,Ho=new Mo,qo=new Ro,Xl=[Do,Uo,No,Oo,Wo,Lo,qo,Vo,Ho],jo={},kr=Object.freeze(Object.defineProperty({__proto__:null,default:jo},Symbol.toStringTag,{value:"Module"}));/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const $o=typeof kr<"u"?kr:void 0;class ct{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new fe;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new fe;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}}class Yl extends ct{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=K(e),this._view=L(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class Zl extends ct{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Bt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Ai({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Ei.fileSystem})}_retrieveSize(){const e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!nr()?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)};class Jl extends ct{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Bt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Qo,this._orchestrator=new Ai({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Ei.network})}async _retrieveSize(){const e=new AbortController,t=await Ki(this._options.fetchFn??fetch,this._url,$i(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let i,s;if(t.status===206)s=this._getTotalLengthFromRangeResponse(t),i=this._orchestrator.createWorker(0,Math.min(s,Cn));else{const n=t.headers.get("Content-Length");if(n)s=Number(n),i=this._orchestrator.createWorker(0,s),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=s,this._existingResponses.set(i,{response:t,abortController:e}),this._orchestrator.runWorker(i),s}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const t=this._existingResponses.get(e);this._existingResponses.delete(e);let i=t?.abortController,s=t?.response;if(i||(i=new AbortController,s=await Ki(this._options.fetchFn??fetch,this._url,$i(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed)),m(s),!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(e.currentPos>0&&s.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const n=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){i.abort(),e.running=!1;return}let a;try{a=await n.read()}catch(l){if(this._disposed)throw l;const u=this._getRetryDelay(1,l,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(d=>setTimeout(d,1e3*u));break}else throw l}if(e.aborted)break;const{done:o,value:c}=a;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}if(e.aborted)break}e.running=!1}_getTotalLengthFromRangeResponse(e){const t=e.headers.get("Content-Range");if(t){const s=/\/(\d+)/.exec(t);if(s)return Number(s[1])}const i=e.headers.get("Content-Length");if(i)return Number(i);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class eu extends ct{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Bt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._fileHandle=null,this._streamSource=new Ko({getSize:async()=>(this._fileHandle=await $o.fs.open(e,"r"),(await this._fileHandle.stat()).size),read:async(i,s)=>{m(this._fileHandle);const n=new Uint8Array(s-i);return await this._fileHandle.read(n,0,s-i,i),n},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t){return this._streamSource._read(e,t)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class Ko extends ct{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Bt(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Ai({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Ei[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then(t=>{if(!Number.isInteger(t)||t<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=t,t});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPosthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=H(this._cache,e,u=>u.start),s=i!==-1?this._cache[i]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e;const a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u=t)break;const h=Math.max(e,d.start);h>n&&this._throwDueToCacheMiss();const f=Math.min(t,d.end);hn&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=G();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex0;){const n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}const Ei={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const s of t){const a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(Kr(r,e,a,s.targetPos)){const o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,s.startPos+u)}}return e=Math.max(e,r+Cn),{start:r,end:e}}};class Ai{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){m(this.fileSize!==null);const i=this.options.prefetchProfile(e,t,this.workers),s=Math.max(i.start,0),n=Math.min(i.end,this.fileSize);m(s<=e&&t<=n);let a=null;const o=H(this.cache,e,k=>k.start),c=o!==-1?this.cache[o]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,a={bytes:c.bytes,view:c.view,offset:c.start});const l=H(this.cache,s,k=>k.start),u=a?null:new Uint8Array(t-e);let d=0,h=s;const f=[];if(l!==-1){for(let k=l;k=n)break;if(S.end<=s)continue;const y=Math.max(s,S.start),x=Math.min(n,S.end);if(m(y<=x),h=u.length&&(a={bytes:u,view:L(u),offset:e}),f.length===0)return m(a),a;const{promise:p,resolve:g,reject:w}=G(),T=[];for(const k of f){const S=Math.max(e,k.start),y=Math.min(t,k.end);S===k.start&&y===k.end?T.push(k):S({bytes:k,view:L(k),offset:e}))),a}createWorker(e,t){const i={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(i);this.workers.length>this.options.maxWorkerCount;){let s=0,n=this.workers[0];for(let a=1;a0)break;n.aborted=!0,this.workers.splice(s,1)}return i}runWorker(e){m(!e.running),m(e.currentPos{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){m(!e.aborted);const i=e.currentPos,s=i+t.length;this.insertIntoCache({start:i,end:s,bytes:t,view:L(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let n=0;nu.start&&(u.start=s),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;ni.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const s=new Uint8Array(e.end-i.start);s.set(i.bytes,0),s.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=s,i.view=L(s),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i=s.end){this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length,i--;continue}const n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=L(n),e.end=s.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,s=this.cache[0];for(let n=1;n!(t instanceof Ye)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ct))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Xo(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class fe extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Xo{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new fe;if(this.fileSize!==null&&e+t>this.fileSize)return null;const i=e+t,s=this.source._read(e,i);return s instanceof Promise?s.then(n=>n?new it(n.bytes,n.view,n.offset,e,i):null):s?new it(s.bytes,s.view,s.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new fe;if(this.fileSize!==null)return this.requestSlice(e,J(this.fileSize-e,t,i));{const s=this.requestSlice(e,i),n=a=>{if(a)return a;const o=l=>(m(l!==null),this.requestSlice(e,J(l-e,t,i))),c=this.source._retrieveSize();return c instanceof Promise?c.then(o):o(c)};return s instanceof Promise?s.then(n):n(s)}}}class it{constructor(e,t,i,s,n){this.bytes=e,this.view=t,this.offset=i,this.start=s,this.end=n,this.bufferPos=s-i}static tempFromBytes(e){return new it(e,L(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(ethis.end)throw new RangeError("Slicing outside of original slice.");return new it(this.bytes,this.view,this.offset,e,e+t)}}const le=(r,e)=>{if(r.filePosr.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=(r,e)=>{le(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},F=r=>(le(r,1),r.view.getUint8(r.bufferPos++)),Ot=(r,e)=>{le(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},re=r=>{le(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},wt=r=>{le(r,3);const e=xr(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},di=r=>{le(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Xe=(r,e)=>{le(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},v=r=>{le(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Tt=r=>{le(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},rt=r=>{le(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},Yo=r=>{le(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},ls=(r,e)=>{let t,i;return e?(t=Xe(r,!0),i=Xe(r,!0)):(i=Xe(r,!1),t=Xe(r,!1)),i*4294967296+t},xe=r=>{const e=v(r),t=v(r);return e*4294967296+t},Zo=r=>{const e=rt(r),t=v(r);return e*4294967296+t},Jo=r=>{const e=Tt(r);return Yo(r)*4294967296+e},ec=r=>{le(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},_n=r=>{le(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},te=(r,e)=>{le(r,e);let t="";for(let i=0;i=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){const t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,i=new Uint8Array(t);let s=0;const n=L(i);n.setUint32(s,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),s+=4,n.setUint32(s,e.mimeType.length),s+=4,i.set(j.encode(e.mimeType),8),s+=e.mimeType.length,n.setUint32(s,e.description?.length??0),s+=4,i.set(j.encode(e.description??""),s),s+=e.description?.length??0,s+=16,n.setUint32(s,e.data.length),s+=4,i.set(e.data,s),s+=e.data.length,m(s===t);const a=new W(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,Ne.PICTURE),a.writeBits(24,t),this.writer.write(a.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.writer.seek(tc+us.byteLength),dr(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const s of e)this.writePictureBlock(s);const t=Zr(new Uint8Array(0),this.output._metadataTags,!1),i=new W(new Uint8Array(4));i.writeBits(1,1),i.writeBits(7,Ne.VORBIS_COMMENT),i.writeBits(24,t.length),this.writer.write(i.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();Rt(i),m(i),m(i.decoderConfig),m(i.decoderConfig.description);try{if(this.validateAndNormalizeTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null&&(this.sampleRate=i.decoderConfig.sampleRate),this.channels===null&&(this.channels=i.decoderConfig.numberOfChannels),this.bitsPerSample===null){const d=new W(K(i.decoderConfig.description));d.skipBits(167);const h=d.readBits(5)+1;this.bitsPerSample=h}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const n=it.tempFromBytes(t.data);D(n,2);const a=D(n,2),o=new W(a),c=kn(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");Tn(n);const l=yn(n,c);this.blockSizes.push(l),this.frameSizes.push(t.data.length);const u=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,u),await this.writer.flush()}finally{s()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();let t=1/0,i=0,s=1/0,n=0,a=0;for(let o=0;o\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,sc=/^WEBVTT(.|\n)*?\n{2}/,Tr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class nc{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r +`,` +`).replaceAll("\r",` +`),Vt.lastIndex=0;let t;if(!this.preambleText){if(!sc.test(e))throw new Error("WebVTT preamble incorrect.");t=Vt.exec(e);const i=e.slice(0,t?.index??e.length).trimEnd();if(!i)throw new Error("No WebVTT preamble provided.");this.preambleText=i,t&&(e=e.slice(t.index),Vt.lastIndex=0)}for(;t=Vt.exec(e);){const i=e.slice(0,t.index),s=t[1],n=t.index+t[0].length,a=e.indexOf(` +`,n)+1,o=e.slice(n,a).trim();let c=e.indexOf(` + +`,n);c===-1&&(c=e.length);const l=hi(t[2]),d=hi(t[3])-l,h=e.slice(a,c).trim();e=e.slice(c).trimStart(),Vt.lastIndex=0;const f={timestamp:l/1e3,duration:d/1e3,text:h,identifier:s,settings:o,notes:i},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}}const ac=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,hi=r=>{const e=ac.exec(r);if(!e)throw new Error("Expected match.");return 60*60*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},Pn=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(60*60*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),s=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class ds{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t[(r%256+256)%256],B=r=>(Ee.setUint16(0,r,!1),[O[0],O[1]]),vn=r=>(Ee.setInt16(0,r,!1),[O[0],O[1]]),In=r=>(Ee.setUint32(0,r,!1),[O[1],O[2],O[3]]),_=r=>(Ee.setUint32(0,r,!1),[O[0],O[1],O[2],O[3]]),Qe=r=>(Ee.setInt32(0,r,!1),[O[0],O[1],O[2],O[3]]),st=r=>(Ee.setUint32(0,Math.floor(r/2**32),!1),Ee.setUint32(4,r,!1),[O[0],O[1],O[2],O[3],O[4],O[5],O[6],O[7]]),En=r=>(Ee.setInt16(0,2**8*r,!1),[O[0],O[1]]),Re=r=>(Ee.setInt32(0,2**16*r,!1),[O[0],O[1],O[2],O[3]]),Ur=r=>(Ee.setInt32(0,2**30*r,!1),[O[0],O[1],O[2],O[3]]),Nr=(r,e)=>{const t=[];let i=r;do{let s=i&127;i>>=7,t.length>0&&(s|=128),t.push(s)}while(i>0||e);return t.reverse()},ie=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,s)=>r.charCodeAt(s));return e&&t.push(0),t},Fi=r=>{let e=null;for(const t of r)(!e||t.timestamp>e.timestamp)&&(e=t);return e},An=r=>{const e=r*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Fn=An(0),Bn=r=>[Re(r[0]),Re(r[1]),Ur(r[2]),Re(r[3]),Re(r[4]),Ur(r[5]),Re(r[6]),Re(r[7]),Ur(r[8])],R=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),V=(r,e,t,i,s)=>R(r,[Q(e),In(t),i??[]],s),oc=r=>r.isQuickTime?R("ftyp",[ie("qt "),_(512),ie("qt ")]):r.fragmented?R("ftyp",[ie("iso5"),_(512),ie("iso5"),ie("iso6"),ie("mp41")]):R("ftyp",[ie("isom"),_(512),ie("isom"),r.holdsAvc?ie("avc1"):[],ie("mp41")]),sr=r=>({type:"mdat",largeSize:r}),cc=r=>({type:"free",size:r}),Wt=r=>R("moov",void 0,[lc(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>uc(e,r.creationTime)),r.isFragmented?jc(r.trackDatas):null,sl(r)]),lc=(r,e)=>{const t=Y(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=Fi(a.samples);return o.timestamp+o.duration})),fi),i=Math.max(0,...e.map(a=>a.track.id))+1,s=!_t(r)||!_t(t),n=s?st:_;return V("mvhd",+s,0,[n(r),n(r),_(fi),n(t),Re(1),En(1),Array(10).fill(0),Bn(Fn),Array(24).fill(0),_(i)])},uc=(r,e)=>{const t=Sl(r);return R("trak",void 0,[dc(r,e),hc(r,e),t.name!==void 0?R("udta",void 0,[R("name",[...j.encode(t.name)])]):null])},dc=(r,e)=>{const t=Fi(r.samples),i=Y(t?t.timestamp+t.duration:0,fi),s=!_t(e)||!_t(i),n=s?st:_;let a;if(r.type==="video"){const c=r.track.metadata.rotation;a=An(c??0)}else a=Fn;let o=2;return r.track.metadata.disposition?.default!==!1&&(o|=1),V("tkhd",+s,o,[n(e),n(e),_(r.track.id),_(0),n(i),Array(8).fill(0),B(0),B(r.track.id),En(r.type==="audio"?1:0),B(0),Bn(a),Re(r.type==="video"?r.info.width:0),Re(r.type==="video"?r.info.height:0)])},hc=(r,e)=>R("mdia",void 0,[fc(r,e),Bi(!0,mc[r.type],pc[r.type]),gc(r)]),fc=(r,e)=>{const t=Fi(r.samples),i=Y(t?t.timestamp+t.duration:0,r.timescale),s=!_t(e)||!_t(i),n=s?st:_;return V("mdhd",+s,0,[n(e),n(e),_(r.timescale),n(i),B(Dn(r.track.metadata.languageCode??me)),B(0)])},mc={video:"vide",audio:"soun",subtitle:"text"},pc={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Bi=(r,e,t,i="\0\0\0\0")=>V("hdlr",0,0,[r?ie("mhlr"):_(0),ie(e),ie(i),_(0),_(0),ie(t,!0)]),gc=r=>R("minf",void 0,[Tc[r.type](),yc(),Cc(r)]),wc=()=>V("vmhd",0,1,[B(0),B(0),B(0),B(0)]),bc=()=>V("smhd",0,0,[B(0),B(0)]),kc=()=>V("nmhd",0,0),Tc={video:wc,audio:bc,subtitle:kc},yc=()=>R("dinf",void 0,[Sc()]),Sc=()=>V("dref",0,0,[_(1)],[xc()]),xc=()=>V("url ",0,1),Cc=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return R("stbl",void 0,[_c(r),Nc(r),e?Hc(r):null,e?qc(r):null,Vc(r),Wc(r),Lc(r),Oc(r)])},_c=r=>{let e;if(r.type==="video")e=Pc(cl(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=Mn(r.track.source._codec,r.muxer.isQuickTime);m(t),e=Fc(t,r)}else r.type==="subtitle"&&(e=Dc(dl[r.track.source._codec],r));return m(e),V("stsd",0,0,[_(1)],[e])},Pc=(r,e)=>R(r,[Array(6).fill(0),B(1),B(0),B(0),Array(12).fill(0),B(e.info.width),B(e.info.height),_(4718592),_(4718592),_(0),B(1),Array(32).fill(0),B(24),vn(65535)],[ll[e.track.source._codec](e),As(e.info.decoderConfig.colorSpace)?vc(e):null]),vc=r=>R("colr",[ie("nclx"),B(vt[r.info.decoderConfig.colorSpace.primaries]),B(It[r.info.decoderConfig.colorSpace.transfer]),B(Et[r.info.decoderConfig.colorSpace.matrix]),Q((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ic=r=>r.info.decoderConfig&&R("avcC",[...K(r.info.decoderConfig.description)]),Ec=r=>r.info.decoderConfig&&R("hvcC",[...K(r.info.decoderConfig.description)]),hs=r=>{if(!r.info.decoderConfig)return null;const e=r.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),s=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?vt[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):e.colorSpace?.transfer?It[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Et[e.colorSpace.matrix]:2;return V("vpcC",1,0,[Q(i),Q(s),Q(c),Q(l),Q(u),Q(d),B(0)])},Ac=r=>R("av1C",Ms(r.info.decoderConfig.codec)),Fc=(r,e)=>{let t=0,i,s=16;if(Z.includes(e.track.source._codec)){const n=e.track.source._codec,{sampleSize:a}=Ae(n);s=8*a,s>16&&(t=1)}return t===0?i=[Array(6).fill(0),B(1),B(t),B(0),_(0),B(e.info.numberOfChannels),B(s),B(0),B(0),B(e.info.sampleRate<2**16?e.info.sampleRate:0),B(0)]:i=[Array(6).fill(0),B(1),B(t),B(0),_(0),B(e.info.numberOfChannels),B(Math.min(s,16)),B(0),B(0),B(e.info.sampleRate<2**16?e.info.sampleRate:0),B(0),_(1),_(s/8),_(e.info.numberOfChannels*s/8),_(2)],R(r,i,[ul(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Or=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...Q(e),...Q(21),...In(0),..._(0),..._(0)];if(r.info.decoderConfig.description){const i=K(r.info.decoderConfig.description);t=[...t,...Q(5),...Nr(i.byteLength),...i]}return t=[...B(1),...Q(0),...Q(4),...Nr(t.length),...t,...Q(6),...Q(1),...Q(2)],t=[...Q(3),...Nr(t.length),...t],V("esds",0,0,t)},Le=r=>R("wave",void 0,[Bc(r),zc(r),R("\0\0\0\0")]),Bc=r=>R("frma",[ie(Mn(r.track.source._codec,r.muxer.isQuickTime))]),zc=r=>{const{littleEndian:e}=Ae(r.track.source._codec);return R("enda",[B(+e)])},Rc=r=>{let e=r.info.numberOfChannels,t=3840,i=r.info.sampleRate,s=0,n=0,a=new Uint8Array(0);const o=r.info.decoderConfig?.description;if(o){m(o.byteLength>=18);const c=K(o),l=Pr(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return R("dOps",[Q(0),Q(e),B(t),_(i),vn(s),Q(n),...a])},Mc=r=>{const e=r.info.decoderConfig?.description;m(e);const t=K(e);return V("dfLa",0,0,[...t.subarray(4)])},ve=r=>{const{littleEndian:e,sampleSize:t}=Ae(r.track.source._codec),i=+e;return V("pcmC",0,0,[Q(i),Q(8*t)])},Dc=(r,e)=>R(r,[Array(6).fill(0),B(1)],[hl[e.track.source._codec](e)]),Uc=r=>R("vttC",[...j.encode(r.info.config.description)]),Nc=r=>V("stts",0,0,[_(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[_(e.sampleCount),_(e.sampleDelta)])]),Oc=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return V("stss",0,0,[_(e.length),e.map(([t])=>_(t+1))])},Vc=r=>V("stsc",0,0,[_(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[_(e.firstChunk),_(e.samplesPerChunk),_(1)])]),Wc=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=Ae(r.track.source._codec);return V("stsz",0,0,[_(e*r.info.numberOfChannels),_(r.samples.reduce((t,i)=>t+Y(i.duration,r.timescale),0))])}return V("stsz",0,0,[_(0),_(r.samples.length),r.samples.map(e=>_(e.size))])},Lc=r=>r.finalizedChunks.length>0&&X(r.finalizedChunks).offset>=2**32?V("co64",0,0,[_(r.finalizedChunks.length),r.finalizedChunks.map(e=>st(e.offset))]):V("stco",0,0,[_(r.finalizedChunks.length),r.finalizedChunks.map(e=>_(e.offset))]),Hc=r=>V("ctts",1,0,[_(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[_(e.sampleCount),Qe(e.sampleCompositionTimeOffset)])]),qc=r=>{let e=1/0,t=-1/0,i=1/0,s=-1/0;m(r.compositionTimeOffsetTable.length>0),m(r.samples.length>0);for(let a=0;a=2**31?null:V("cslg",0,0,[Qe(n),Qe(e),Qe(t),Qe(i),Qe(s)])},jc=r=>R("mvex",void 0,r.map($c)),$c=r=>V("trex",0,0,[_(r.track.id),_(1),_(0),_(0),_(0)]),fs=(r,e)=>R("moof",void 0,[Qc(r),...e.map(Kc)]),Qc=r=>V("mfhd",0,0,[_(r)]),zn=r=>{let e=0,t=0;const i=0,s=0,n=r.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|i<<8|s},Kc=r=>R("traf",void 0,[Gc(r),Xc(r),Yc(r)]),Gc=r=>{m(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:zn(t)};return V("tfhd",0,e,[_(r.track.id),_(i.duration),_(i.size),_(i.flags)])},Xc=r=>(m(r.currentChunk),V("tfdt",1,0,[st(Y(r.currentChunk.startTimestamp,r.timescale))])),Yc=r=>{m(r.currentChunk);const e=r.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(g=>g.size),i=r.currentChunk.samples.map(zn),s=r.currentChunk.samples.map(g=>Y(g.timestamp-g.decodeTimestamp,r.timescale)),n=new Set(e),a=new Set(t),o=new Set(i),c=new Set(s),l=o.size===2&&i[0]!==i[1],u=n.size>1,d=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(g=>g!==0);let p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+h,p|=2048*+f,V("trun",1,p,[_(r.currentChunk.samples.length),_(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?_(i[0]):[],r.currentChunk.samples.map((g,w)=>[u?_(e[w]):[],d?_(t[w]):[],h?_(i[w]):[],f?Qe(s[w]):[]])])},Zc=r=>R("mfra",void 0,[...r.map(Jc),el()]),Jc=(r,e)=>V("tfra",1,0,[_(r.track.id),_(63),_(r.finalizedChunks.length),r.finalizedChunks.map(i=>[st(Y(i.samples[0].timestamp,r.timescale)),st(i.moofOffset),_(e+1),_(1),_(1)])]),el=()=>V("mfro",0,0,[_(0)]),tl=()=>R("vtte"),rl=(r,e,t,i,s)=>R("vttc",void 0,[s!==null?R("vsid",[Qe(s)]):null,t!==null?R("iden",[...j.encode(t)]):null,e!==null?R("ctim",[...j.encode(Pn(e))]):null,i!==null?R("sttg",[...j.encode(i)]):null,R("payl",[...j.encode(r)])]),il=r=>R("vtta",[...j.encode(r)]),sl=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const s=al(i);s&&e.push(s)}else if(t==="mdta"){const s=ol(i);s&&e.push(s)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&nl(e,r.output._metadataTags);return e.length===0?null:R("udta",void 0,e)},nl=(r,e)=>{for(const{key:t,value:i}of Ft(e))switch(t){case"title":r.push(Ie("©nam",i));break;case"description":r.push(Ie("©des",i));break;case"artist":r.push(Ie("©ART",i));break;case"album":r.push(Ie("©alb",i));break;case"albumArtist":r.push(Ie("albr",i));break;case"genre":r.push(Ie("©gen",i));break;case"date":r.push(Ie("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(Ie("©cmt",i));break;case"lyrics":r.push(Ie("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ae(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||r.some(s=>s.type===t)||(typeof i=="string"?r.push(Ie(t,i)):i instanceof Uint8Array&&r.push(R(t,Array.from(i))))}},Ie=(r,e)=>{const t=j.encode(e);return R(r,[B(t.length),B(Dn("und")),Array.from(t)])},ms={"image/jpeg":13,"image/png":14,"image/bmp":27},Rn=(r,e)=>{const t=[];for(const{key:i,value:s}of Ft(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:ye(s)});break;case"description":t.push({key:e?"description":"©des",value:ye(s)});break;case"artist":t.push({key:e?"artist":"©ART",value:ye(s)});break;case"album":t.push({key:e?"album":"©alb",value:ye(s)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:ye(s)});break;case"comment":t.push({key:e?"comment":"©cmt",value:ye(s)});break;case"genre":t.push({key:e?"genre":"©gen",value:ye(s)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:ye(s)});break;case"date":t.push({key:e?"date":"©day",value:ye(s.toISOString().slice(0,10))});break;case"images":for(const n of s)n.kind==="coverFront"&&t.push({key:"covr",value:R("data",[_(ms[n.mimeType]??0),_(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=r.tracksTotal!==void 0?`${s}/${r.tracksTotal}`:s.toString();t.push({key:"track",value:ye(n)})}else t.push({key:"trkn",value:R("data",[_(0),_(0),B(0),B(s),B(r.tracksTotal??0),B(0)])});break;case"discNumber":e||t.push({key:"disc",value:R("data",[_(0),_(0),B(0),B(s),B(r.discsTotal??0),B(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(i)}if(r.raw)for(const i in r.raw){const s=r.raw[i];s==null||!e&&i.length!==4||t.some(n=>n.key===i)||(typeof s=="string"?t.push({key:i,value:ye(s)}):s instanceof Uint8Array?t.push({key:i,value:R("data",[_(0),_(0),Array.from(s)])}):s instanceof yt&&t.push({key:i,value:R("data",[_(ms[s.mimeType]??0),_(0),Array.from(s.data)])}))}return t},al=r=>{const e=Rn(r,!1);return e.length===0?null:V("meta",0,0,void 0,[Bi(!1,"mdir","","appl"),R("ilst",void 0,e.map(t=>R(t.key,void 0,[t.value])))])},ol=r=>{const e=Rn(r,!0);return e.length===0?null:R("meta",void 0,[Bi(!1,"mdta",""),V("keys",0,0,[_(e.length)],e.map(t=>R("mdta",[...j.encode(t.key)]))),R("ilst",void 0,e.map((t,i)=>{const s=String.fromCharCode(..._(i+1));return R(s,void 0,[t.value])}))])},ye=r=>R("data",[_(1),_(0),...j.encode(r)]),cl=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},ll={avc:Ic,hevc:Ec,vp8:hs,vp9:hs,av1:Ac},Mn=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},ul=(r,e)=>{switch(r){case"aac":return Or;case"mp3":return Or;case"opus":return Rc;case"vorbis":return Or;case"flac":return Mc}if(e)switch(r){case"pcm-s24":return Le;case"pcm-s24be":return Le;case"pcm-s32":return Le;case"pcm-s32be":return Le;case"pcm-f32":return Le;case"pcm-f32be":return Le;case"pcm-f64":return Le;case"pcm-f64be":return Le}else switch(r){case"pcm-s16":return ve;case"pcm-s16be":return ve;case"pcm-s24":return ve;case"pcm-s24be":return ve;case"pcm-s32":return ve;case"pcm-s32be":return ve;case"pcm-f32":return ve;case"pcm-f32be":return ve;case"pcm-f64":return ve;case"pcm-f64be":return ve}return null},dl={webvtt:"wvtt"},hl={webvtt:Uc},Dn=r=>{m(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class zi{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(tWr)throw new Error(`ArrayBuffer exceeded maximum size of ${Wr} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{const i=new ArrayBuffer(t),s=new Uint8Array(i);s.set(this.bytes,0),this.buffer=i,this.bytes=s}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}const fl=2**24,ml=2;class pl extends zi{constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??fl}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){const t=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(t))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){const i=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(i))}if(m(this.writer),this.sections.length===0)return;const e=[],t=[...this.sections].sort((i,s)=>i.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;ic.start<=t&&tml){for(let c=0;c=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}createChunk(e){const i={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(i),this.chunks.sort((s,n)=>s.start-n.start),this.chunks.indexOf(i)}tryToFlushChunks(e=!1){m(this.writer);for(let t=0;t{this._fileHandle=await wl.fs.open(e,"w")},write:async s=>{m(this._fileHandle),await this._fileHandle.write(s.data,0,s.data.byteLength,s.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new kl(i,{chunked:!0,...t}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}}class Tl extends Jt{_createWriter(){return new gl(this)}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const fi=1e3,yl=2082844800,Sl=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},Y=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i};class xl extends at{constructor(e,t){super(e),this.auxTarget=new bl,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ds(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=G(),this.creationTime=Math.floor(Date.now()/1e3)+yl,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new ds(this.writer),this.isQuickTime=t instanceof Vn;const i=this.writer instanceof Un?"in-memory":!1;this.fastStart=t._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(oc({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,s)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=sr(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Js({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const s=this.trackDatas.find(l=>l.track===e);if(s)return s;Vs(i),m(i),m(i.decoderConfig);const n={...i.decoderConfig};m(n.codedWidth!==void 0),m(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){const l=Hs(t.data);if(!l)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=ya(l),a=!0}else if(e.source._codec==="hevc"&&!n.description){const l=$s(t.data);if(!l)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Ea(l),a=!0}const o=Jn(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Rt(t),m(t),m(t.decoderConfig);const s={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Z.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Ws(t),m(t),m(t.config);const s={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i);let a=t.data;if(n.info.requiresAnnexBTransformation){const l=ka(a);if(!l)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=l}const o=this.validateAndNormalizeTimestamp(n.track,t.timestamp,t.type==="key"),c=this.createSampleForTrack(n,a,o,t.duration,t.type);await this.registerSample(n,c)}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(n.track,t.timestamp,t.type==="key"),o=this.createSampleForTrack(n,t.data,a,t.duration,t.type);n.info.requiresPcmTransformation&&await this.maybePadWithSilence(n,a),await this.registerSample(n,o)}finally{s()}}async maybePadWithSilence(e,t){const i=X(e.samples),s=i?i.timestamp+i.duration:0,n=t-s,a=Y(n,e.timescale);if(a>0){const{sampleSize:o,silentValue:c}=Ae(e.info.decoderConfig.codec),l=a*e.info.numberOfChannels,u=new Uint8Array(o*l).fill(c),d=this.createSampleForTrack(e,new Uint8Array(u.buffer),s,n,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,t,i){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(t),await this.processWebVTTCues(n,t.timestamp))}finally{s()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const l of e.cueQueue)m(l.timestamp<=t),m(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);const s=[...i].sort((l,u)=>l-u),n=s[0],a=s[1]??n;if(t=a)break;Tr.lastIndex=0;const d=Tr.test(u.text),h=u.timestamp+u.duration;let f=e.cueToSourceId.get(u);if(f===void 0&&as.timestamp).sort((s,n)=>s-n);for(let s=0;s=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=X(e.timeToSampleTable);if(m(u),u.sampleCount===1){u.sampleDelta=l;const h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),u=h)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=X(e.compositionTimeOffsetTable);m(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=Y(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,m(e.lastSample),m(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){m(t.type==="key");const s=Y(t.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const s=e.track.metadata.maximumPacketCount;if(m(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const s=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});s>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=s>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),m(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(m(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,s)=>i+Y(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||X(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)m(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(m(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.track.source._closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestampf.currentChunk),s=fs(t,i),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s);let o=a+Me,c=1/0;for(const f of i){f.currentChunk.offset=o,f.currentChunk.moofOffset=n;for(const p of f.currentChunk.samples)o+=p.size;c=Math.min(c,f.currentChunk.startTimestamp)}const l=o-a,u=l>=2**32;if(u)for(const f of i)f.currentChunk.offset+=et-Me;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=fs(t,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,p,c)}m(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=sr(u);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(u?et:Me));for(const f of i)for(const p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){const{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,p)}for(const f of i)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const i=Wt(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;m(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=sr(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){m(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;m(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(s=>s.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const t of this.trackDatas)this.processTimestamps(t);await this.finalizeFragment(!1)}else for(const t of this.trackDatas)this.processTimestamps(t),await this.finalizeCurrentChunk(t);if(this.fastStart==="in-memory"){this.mdat=sr(!1);let t;for(let s=0;s<2;s++){const n=Wt(this),a=this.boxWriter.measureBox(n);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:l}of c.samples)m(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=Wt(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const s of this.finalizedChunks)for(const n of s.samples)m(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,n)}}else if(this.isFragmented){const t=this.writer.getPos(),i=Zc(this.trackDatas);this.boxWriter.writeBox(i);const s=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{m(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);m(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,a)}const s=Wt(this);if(this.fastStart==="reserve"){m(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(cc(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,a)}}e()}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Cl=-32768,_l=2**15-1,ps="Mediabunny",gs=6,ws=5,Pl={video:1,audio:2,subtitle:17};class vl extends at{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=G(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new io(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:b.EBML,data:[{id:b.EBMLVersion,data:1},{id:b.EBMLReadVersion,data:1},{id:b.EBMLMaxIDLength,data:4},{id:b.EBMLMaxSizeLength,data:8},{id:b.DocType,data:this.format instanceof ks?"webm":"matroska"},{id:b.DocTypeVersion,data:2},{id:b.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:b.SeekHead,data:[{id:b.Seek,data:[{id:b.SeekID,data:t},{id:b.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:b.Seek,data:[{id:b.SeekID,data:i},{id:b.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:b.Seek,data:[{id:b.SeekID,data:s},{id:b.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:b.Seek,data:[{id:b.SeekID,data:n},{id:b.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:b.Seek,data:[{id:b.SeekID,data:a},{id:b.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:b.Duration,data:new ri(0)};this.segmentDuration=e;const t={id:b.Info,data:[{id:b.TimestampScale,data:1e6},{id:b.MuxingApp,data:ps},{id:b.WritingApp,data:ps},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:b.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const i=Se[t.track.source._codec];m(i);let s=0;if(t.type==="audio"&&t.track.source._codec==="opus"){s=1e6*80;const n=t.info.decoderConfig.description;if(n){const a=K(n),o=Pr(a);s=Math.round(1e9*(o.preSkip/zt))}}e.data.push({id:b.TrackEntry,data:[{id:b.TrackNumber,data:t.track.id},{id:b.TrackUID,data:t.track.id},{id:b.TrackType,data:Pl[t.type]},t.track.metadata.disposition?.default===!1?{id:b.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:b.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:b.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:b.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:b.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:b.FlagCommentary,data:1}:null,{id:b.FlagLacing,data:0},{id:b.Language,data:t.track.metadata.languageCode??me},{id:b.CodecID,data:i},{id:b.CodecDelay,data:0},{id:b.SeekPreRoll,data:s},t.track.metadata.name!==void 0?{id:b.Name,data:new He(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,s=[e.info.decoderConfig.description?{id:b.CodecPrivate,data:K(e.info.decoderConfig.description)}:null,t?{id:b.DefaultDuration,data:1e9/t}:null],n=i?yr(-i):0,a=e.info.decoderConfig.colorSpace,o={id:b.Video,data:[{id:b.PixelWidth,data:e.info.width},{id:b.PixelHeight,data:e.info.height},e.info.alphaMode?{id:b.AlphaMode,data:1}:null,As(a)?{id:b.Colour,data:[{id:b.MatrixCoefficients,data:Et[a.matrix]},{id:b.TransferCharacteristics,data:It[a.transfer]},{id:b.Primaries,data:vt[a.primaries]},{id:b.Range,data:a.fullRange?2:1}]}:null,n?{id:b.Projection,data:[{id:b.ProjectionType,data:0},{id:b.ProjectionPoseRoll,data:new ti((n+180)%360-180)}]}:null]};return s.push(o),s}audioSpecificTrackInfo(e){const t=Z.includes(e.track.source._codec)?Ae(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:b.CodecPrivate,data:K(e.info.decoderConfig.description)}:null,{id:b.Audio,data:[{id:b.SamplingFrequency,data:new ti(e.info.sampleRate)},{id:b.Channels,data:e.info.numberOfChannels},t?{id:b.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:b.CodecPrivate,data:j.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(n,a)=>{e.push({id:b.SimpleTag,data:[{id:b.TagName,data:new He(n)},typeof a=="string"?{id:b.TagString,data:new He(a)}:{id:b.TagBinary,data:a}]})},i=this.output._metadataTags,s=new Set;for(const{key:n,value:a}of Ft(i))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{const o=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{const o=i.discsTotal!==void 0?`${a}/${i.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ae(n)}if(i.raw)for(const n in i.raw){const a=i.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:b.Tags,data:[{id:b.Tag,data:[{id:b.Targets,data:[{id:b.TargetTypeValue,data:50},{id:b.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,s=e.images??[];for(const n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(ta(n.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!i.has(o))break}i.add(o),t.push({id:b.AttachedFile,data:[n.description!==void 0?{id:b.FileDescription,data:new He(n.description)}:null,{id:b.FileName,data:new He(a)},{id:b.FileMediaType,data:n.mimeType},{id:b.FileData,data:n.data},{id:b.FileUID,data:o}]})}for(const[n,a]of Object.entries(e.raw??{}))!(a instanceof ki)||!/^\d+$/.test(n)||s.find(c=>c.mimeType===a.mimeType&&sa(c.data,a.data))||t.push({id:b.AttachedFile,data:[a.description!==void 0?{id:b.FileDescription,data:new He(a.description)}:null,{id:b.FileName,data:new He(a.name??"")},{id:b.FileMediaType,data:a.mimeType??""},{id:b.FileData,data:a.data},{id:b.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:b.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:b.Segment,size:this.format._options.appendOnly?-1:gs,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:b.Cues,data:[]}}get segmentDataOffset(){return m(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return an({isWebM:this.format instanceof ks,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const s=this.trackDatas.find(a=>a.track===e);if(s)return s;Vs(i),m(i),m(i.decoderConfig),m(i.decoderConfig.codedWidth!==void 0),m(i.decoderConfig.codedHeight!==void 0);const n={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,decoderConfig:i.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return e.source._codec==="vp9"?n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(oa(n.info.decoderConfig.codec))}:e.source._codec==="av1"&&(n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(Ms(n.info.decoderConfig.codec))}),this.trackDatas.push(n),this.trackDatas.sort((a,o)=>a.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getAudioTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Rt(t),m(t),m(t.decoderConfig);const s={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Ws(t),m(t),m(t.config);const s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i),a=t.type==="key";let o=this.validateAndNormalizeTimestamp(n.track,t.timestamp,a),c=t.duration;e.metadata.frameRate!==void 0&&(o=Qr(o,1/e.metadata.frameRate),c=Qr(c,1/e.metadata.frameRate));const l=n.info.alphaMode?t.sideData.alpha??null:null,u=this.createInternalChunk(t.data,o,c,t.type,l);e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,u),n.chunkQueue.push(u),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i),a=t.type==="key",o=this.validateAndNormalizeTimestamp(n.track,t.timestamp,a),c=this.createInternalChunk(t.data,o,t.duration,t.type);n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,i){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i),a=this.validateAndNormalizeTimestamp(n.track,t.timestamp,!0);let o=t.text;const c=Math.round(a*1e3);Tr.lastIndex=0,o=o.replace(Tr,h=>{const p=hi(h.slice(1,-1))-c;return`<${Pn(p)}>`});const l=j.encode(o),u=`${t.settings??""} +${t.identifier??""} +${t.notes??""}`,d=this.createInternalChunk(l,a,t.duration,"key",u.trim()?j.encode(u):null);n.chunkQueue.push(d),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!n.track.source._closed)break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp=2&&i.skipBits(1);const u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];jn(t.data,i.pos,i.pos+3,u)}createInternalChunk(e,t,i,s,n=null){return{data:e,type:s,timestamp:t,duration:i,additions:n}}writeBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),s=this.trackDatas.every(u=>{if(e===u)return t.type==="key";const d=u.chunkQueue[0];return d?d.type==="key":u.track.source._closed});let n=!1;if(!this.currentCluster)n=!0;else{m(this.currentClusterStartMsTimestamp!==null),m(this.currentClusterMaxMsTimestamp!==null);const u=i-this.currentClusterStartMsTimestamp;n=s&&i>this.currentClusterMaxMsTimestamp&&u>=1e3*(this.format._options.minimumClusterDuration??1)||u>_l}n&&this.createNewCluster(i);const a=i-this.currentClusterStartMsTimestamp;if(a0?{id:b.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(u)}else{c.setUint8(3,+(t.type==="key")<<7);const u={id:b.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(u)}this.duration=Math.max(this.duration,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:b.Cluster,size:this.format._options.appendOnly?-1:ws,data:[{id:b.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(m(this.currentCluster),!this.format._options.appendOnly){const s=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),n=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(s,ws),this.writer.seek(n)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(s,n,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[s,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(s);const i=[...t.entries()].sort((s,n)=>s[0]-n[0]);for(const[s,n]of i)m(this.cues),this.cues.data.push({id:b.CuePoint,data:[{id:b.CueTime,data:s},...n.map(a=>({id:b.CueTrackPositions,data:[{id:b.CueTrack,data:a.track.id},{id:b.CueClusterPosition,data:e}]}))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),m(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos(),i=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(i,gs),this.segmentDuration.data=new ri(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),m(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(t)}e()}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Il{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos(),i=255,s=224|e.mpegVersionId<<3|e.layer<<1;let n;e.mpegVersionId&2?n=e.mpegVersionId&1?0:1:n=1;const a=0,o=155;let c=-1;const l=n*16*4+e.layer*16;for(let w=0;w<16;w++){const T=ni[l+w];if(ai(n,e.layer,1e3*T,e.sampleRate,a)>=o){c=w;break}}if(c===-1)throw new Error("No suitable bitrate found.");const u=c<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=i,this.helper[1]=s,this.helper[2]=u,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));const h=vi(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(Pi);let f=0;e.frameCount!==null&&(f|=1),e.fileSize!==null&&(f|=2),e.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const p=ni[l+c],g=ai(n,e.layer,1e3*p,e.sampleRate,a);this.writer.seek(t+g)}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class El extends at{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writer=e._writer,this.mp3Writer=new Il(e._writer)}async start(){dr(this.output._metadataTags)||new fn(this.writer).writeId3V2Tag(this.output._metadataTags)}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const i=await this.mutex.acquire();try{const s=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&s){const n=L(t.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=n.getUint32(0,!1),o=dn(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");const c=vi(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){const l=n.getUint32(c,!1);if(l===Pi||l===un)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(e,t.timestamp,t.type==="key"),this.writer.write(t.data),this.frameCount++,await this.writer.flush(),s&&this.framePositions.push(this.writer.getPos())}finally{i()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;const e=await this.mutex.acquire(),t=this.writer.getPos();this.writer.seek(this.xingFramePos);const i=new Uint8Array(100);for(let s=0;s<100;s++){const n=Math.floor(this.framePositions.length*(s/100));m(n!==-1&&ne.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const i=this.trackDatas.find(a=>a.track===e);if(i)return i;let s;do s=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===s));m(e.source._codec==="vorbis"||e.source._codec==="opus"),Rt(t),m(t),m(t.decoderConfig);const n={track:e,serialNumber:s,internalSampleRate:e.source._codec==="opus"?zt:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};return this.queueHeaderPackets(n,t),this.trackDatas.push(n),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}queueHeaderPackets(e,t){if(m(t.decoderConfig),e.track.source._codec==="vorbis"){m(t.decoderConfig.description);const i=K(t.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let s=1;const n=()=>{let g=0;for(;;){const w=i[s++];if(w===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=w,w<255)return g}},a=n(),o=n();if(i.length-s<=0)throw new TypeError("Vorbis decoder description is too short.");const l=i.subarray(s,s+=a);s+=o;const u=i.subarray(s),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;const h=Zr(d,this.output._metadataTags,!0);e.packetQueue.push({data:l,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:h,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:u,endGranulePosition:0,timestamp:0,forcePageFlush:!0});const p=L(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(p&15),1<<(p>>4)],modeBlockflags:Xs(u).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const i=K(t.decoderConfig.description),s=new Uint8Array(8),n=L(s);n.setUint32(0,1332770163,!1),n.setUint32(4,1415669619,!1);const a=Zr(s,this.output._metadataTags,!0);e.packetQueue.push({data:i,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:a,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Pr(i).preSkip}}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,t.timestamp,t.type==="key");const a=n.currentTimestampInSamples,{durationInSamples:o,vorbisBlockSize:c}=gn(t.data,n.codecInfo,n.vorbisLastBlocksize);n.currentTimestampInSamples+=o,n.vorbisLastBlocksize=c,n.packetQueue.push({data:t.data,endGranulePosition:n.currentTimestampInSamples,timestamp:a/n.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{s()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(const t of this.trackDatas)for(;t.packetQueue.length>0;){const i=t.packetQueue.shift();if(this.writePacket(t,i,!1),i.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!a.track.source._closed)break e;a.packetQueue.length>0&&a.packetQueue[0].timestamp0&&(e.currentPageStartsWithFreshPacket=!1);const c=Math.min(255,s);e.currentLacingValues.push(c),e.currentPageSize++,a+=c;const l=s<255;if(e.currentLacingValues.length===255){const u=t.data.subarray(n,a);if(n=a,e.currentPageData.push(u),e.currentPageSize+=u.length,this.writePage(e,i&&l),l)return}if(l)break;s-=255}const o=t.data.subarray(n);e.currentPageData.push(o),e.currentPageSize+=o.length,e.currentGranulePosition=t.endGranulePosition,(e.currentPageSize>=Al||t.forcePageFlush)&&this.writePage(e,i)}writePage(e,t){this.pageView.setUint32(0,Ii,!0),this.pageView.setUint8(4,0);let i=0;e.currentPageStartsWithFreshPacket||(i|=1),e.pagesWritten===0&&(i|=2),t&&(i|=4),this.pageView.setUint8(5,i);const s=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;Xn(this.pageView,6,s),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let n=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,n),n+=c.length;const a=this.pageBytes.subarray(0,n),o=pn(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){const{data:c,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(c,l,e.track.source)}}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),e()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(const t of this.trackDatas)t.currentLacingValues.length>0&&this.writePage(t,!0);e()}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Bl{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class zl extends at{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.writer=e._writer,this.riffWriter=new Bl(e._writer),this.isRf64=!!t._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{if(this.headerWritten||(Rt(i),m(i),m(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let i;const s=e.source._codec,n=Ae(s);n.dataType==="ulaw"?i=he.MULAW:n.dataType==="alaw"?i=he.ALAW:n.dataType==="float"?i=he.IEEE_FLOAT:i=he.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=n.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(i),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*n.sampleSize),!dr(this.output._metadataTags)){const l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){const{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,u)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const i=new Set,s=(o,c)=>{if(!mt(c)){console.warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const l=c.length+1,u=new Uint8Array(l);for(let d=0;dce.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>pe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ve.includes(e))}_codecUnsupportedHint(e){return""}}class Nn extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new xl(e,this)}}class On extends Nn{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ce,...St,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ve]}_codecUnsupportedHint(e){return new Vn().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Vn extends Nn{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ce,...pe]}_codecUnsupportedHint(e){return new On().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class bs extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new vl(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...ce,...St,...Z.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Ve]}get supportsVideoRotationMetadata(){return!1}}class ks extends bs{constructor(e){super(e)}getSupportedCodecs(){return[...ce.filter(e=>["vp8","vp9","av1"].includes(e)),...pe.filter(e=>["opus","vorbis"].includes(e)),...Ve]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new bs().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class iu extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new El(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}}class su extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new zl(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...Z.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}}class nu extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Fl(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:1/0},subtitle:{min:0,max:0},total:{min:1,max:2**32}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...pe.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}}class au extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new ba(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoRotationMetadata(){return!1}}class ou extends Ze{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");super(),this._options=e}_createMuxer(e){return new ic(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoRotationMetadata(){return!1}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Ri=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!ce.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${ce.join(", ")}.`);if(!(r.bitrate instanceof ge)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Wn(r.codec,r)},Wn=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Os(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},mi=r=>{const e=r.bitrate instanceof ge?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??aa(r.codec,r.width,r.height,e),width:r.width,height:r.height,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...ua(r.codec)}},Mi=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!pe.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${pe.join(", ")}.`);if(r.bitrate===void 0&&(!Z.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof ge)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Ln(r.codec,r)},Ln=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Os(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},pi=r=>{const e=r.bitrate instanceof ge?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??ca(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...da(r.codec)}};class ge{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const s=t*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(s/a,.95),d=o*c*n[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(Z.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let s=i*this._factor;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-s)Math.abs(o-s){if(ce.includes(r))return Di(r);if(pe.includes(r))return Ui(r);if(Ve.includes(r))return Ni(r);throw new TypeError(`Unknown codec '${r}'.`)},Di=async(r,e={})=>{const{width:t=1280,height:i=720,bitrate:s=1e6,...n}=e;if(!ce.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(s instanceof ge)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Wn(r,n);let a=null;return Qt.length>0&&(a??=mi({codec:r,width:t,height:i,bitrate:s,framerate:void 0,...n}),Qt.some(l=>l.supports(r,a)))?!0:typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(r==="avc"||r==="hevc")||(a??=mi({codec:r,width:t,height:i,bitrate:s,framerate:void 0,...n,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(a)).supported)?!1:Pt()?new Promise(async l=>{try{const u=new VideoEncoder({output:()=>{},error:()=>l(!1)});u.configure(a);const d=new Uint8Array(t*i*4),h=new VideoFrame(d,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});u.encode(h),h.close(),await u.flush(),l(!0)}catch{l(!1)}}):!0},Ui=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,bitrate:s=128e3,...n}=e;if(!pe.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(s instanceof ge)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");Ln(r,n);let a=null;return Kt.length>0&&(a??=pi({codec:r,numberOfChannels:t,sampleRate:i,bitrate:s,...n}),Kt.some(c=>c.supports(r,a)))||Z.includes(r)?!0:typeof AudioEncoder>"u"?!1:(a??=pi({codec:r,numberOfChannels:t,sampleRate:i,bitrate:s,...n}),(await AudioEncoder.isConfigSupported(a)).supported===!0)},Ni=async r=>!!Ve.includes(r),fu=async()=>{const[r,e,t]=await Promise.all([Rl(),gi(),Ml()]);return[...r,...e,...t]},Rl=async(r=ce,e)=>{const t=await Promise.all(r.map(i=>Di(i,e)));return r.filter((i,s)=>t[s])},gi=async(r=pe,e)=>{const t=await Promise.all(r.map(i=>Ui(i,e)));return r.filter((i,s)=>t[s])},Ml=async(r=Ve)=>{const e=await Promise.all(r.map(Ni));return r.filter((t,i)=>e[i])},Dl=async(r,e)=>{for(const t of r)if(await Di(t,e))return t;return null},mu=async(r,e)=>{for(const t of r)if(await Ui(t,e))return t;return null},pu=async r=>{for(const e of r)if(await Ni(e))return e;return null};/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */class Oi{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class er extends Oi{constructor(e){if(super(),this._connectedTrack=null,!ce.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ce.join(", ")}.`);this._codec=e}}class Ul extends er{constructor(e){super(e)}add(e,t){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Vi{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Cr,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,t,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(o==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let c=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),c=!0);const l=this.resizeCanvas.getContext("2d",{alpha:Pt()});m(l),c||(Pt()?(l.fillStyle="black",l.fillRect(0,0,this.codedWidth,this.codedHeight)):l.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(l,{fit:o}),t&&e.close(),e=new ee(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);const s=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/s),a={...i,keyFrame:i?.keyFrame||s===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(l=>this.error??=l).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await c}else{m(this.encoder);const o=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(o,a),o.close();else if(!!o.format&&!o.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close();else{const l=o.displayWidth,u=o.displayHeight;if(!this.splitter)try{this.splitter=new Nl(l,u)}catch(d){console.error("Due to an error, only color data will be encoded.",d),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close()}if(this.splitter){const d=this.splitter.extractColor(o),h=this.splitter.extractAlpha(o);this.alphaFrameQueue.push(h),this.encoder.encode(d,a),d.close(),o.close()}}t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){const t=new Error;this.ensureEncoderPromise=(async()=>{const i=mi({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const s=Qt.find(n=>n.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(n,a)=>{if(!(n instanceof $))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,a).catch(o=>{this.error??=o,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const o=[],c=[];let l=0,u=0;const d=(h,f,p)=>{const g={};if(f){const T=new Uint8Array(f.byteLength);f.copyTo(T),g.alpha=T}const w=$.fromEncodedChunk(h,g);this.encodingConfig.onEncodedPacket?.(w,p),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,p).catch(T=>{this.error??=T,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){d(h,null,f);return}const p=this.alphaFrameQueue.shift();m(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),u++,p.close(),o.push({chunk:h,meta:f})):u===0?d(h,null,f):(c.push(l+u),o.push({chunk:h,meta:f}))},error:h=>{h.stack=t.stack,this.error??=h}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(h,f)=>{u--;const p=o.shift();for(m(p!==void 0),d(p.chunk,h,p.meta),l++;c.length>0&&c[0]===l;){c.shift();const g=o.shift();m(g!==void 0),d(g.chunk,null,g.meta)}},error:h=>{h.stack=t.stack,this.error??=h}}),this.alphaEncoder.configure(i))}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class Nl{constructor(e,t){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es + in vec2 a_position; + in vec2 a_texCoord; + out vec2 v_texCoord; + + void main() { + gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; + } + `)}createColorProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es + precision highp float; + + uniform sampler2D u_sourceTexture; + in vec2 v_texCoord; + out vec4 fragColor; + + void main() { + vec4 source = texture(u_sourceTexture, v_texCoord); + fragColor = vec4(source.rgb, 1.0); + } + `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createAlphaProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es + precision highp float; + + uniform sampler2D u_sourceTexture; + uniform vec2 u_resolution; // The width and height of the canvas + in vec2 v_texCoord; + out vec4 fragColor; + + // This function determines the value for a single byte in the YUV stream + float getByteValue(float byteOffset) { + float width = u_resolution.x; + float height = u_resolution.y; + + float yPlaneSize = width * height; + + if (byteOffset < yPlaneSize) { + // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from + float y = floor(byteOffset / width); + float x = mod(byteOffset, width); + + // Add 0.5 to sample the center of the texel + vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution; + + // The luma value is the alpha from the source texture + return texture(u_sourceTexture, sampleCoord).a; + } else { + // Write a fixed value for chroma and beyond + return 128.0 / 255.0; + } + } + + void main() { + // Each fragment writes 4 bytes (R, G, B, A) + float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x); + float baseByteOffset = pixelIndex * 4.0; + + vec4 result; + for (int i = 0; i < 4; i++) { + float currentByteOffset = baseByteOffset + float(i); + result[i] = getByteValue(currentByteOffset); + } + + fragColor = result; + } + `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:i}=this.canvas,s=Math.ceil(t/2)*Math.ceil(i/2),n=t*i+s*2,a=Math.ceil(n/(t*4));let o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,n),m(o[t*i]===128),m(o[o.length-1]===128);const c={format:"I420",codedWidth:t,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class ys extends er{constructor(e){Ri(e),super(e.codec),this._encoder=new Vi(this,e)}add(e,t){if(!(e instanceof ee))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class gu extends er{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Ri(t),super(t.codec),this._encoder=new Vi(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const s=new ee(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class wu extends er{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}constructor(e,t){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");Ri(t),t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=G(),this._errorPromiseAccessed=!1,this._encoder=new Vi(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1;const i=s=>{if(t){s.close();return}if(e===null){e=s.timestamp/1e6;const n=this._connectedTrack.output._muxer;n.firstMediaStreamTimestamp===null?(n.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-e):this._timestampOffset=performance.now()/1e3-n.firstMediaStreamTimestamp-e}if(this._encoder.getQueueSize()>=4){s.close();return}this._encoder.add(new ee(s),!0).catch(n=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(n),this._workerTrackId!==null&&Hr({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const s=new MediaStreamTrackProcessor({track:this._track}),n=new WritableStream({write:i});s.readable.pipeTo(n,{signal:this._abortController.signal}).catch(a=>{a instanceof DOMException&&a.name==="AbortError"||this._promiseWithResolvers.reject(a)})}else if(await Hl())this._workerTrackId=Wl++,Hr({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=n=>{const a=n.data;a.type==="videoFrame"&&a.trackId===this._workerTrackId?i(a.videoFrame):a.type==="error"&&a.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(a.error)},_e.addEventListener("message",this._workerListener);else throw new Error("MediaStreamTrackProcessor is required but not supported by this browser.")}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._workerTrackId!==null&&(m(this._workerListener),Hr({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(t=>{const i=s=>{const n=s.data;n.type==="trackStopped"&&n.trackId===this._workerTrackId&&(m(this._workerListener),_e.removeEventListener("message",this._workerListener),_e.removeEventListener("message",i),t())};_e.addEventListener("message",i)})),await this._encoder.flushAndClose(e)}}class tr extends Oi{constructor(e){if(super(),this._connectedTrack=null,!pe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${pe.join(", ")}.`);this._codec=e}}class Ol extends tr{constructor(e){super(e)}add(e,t){if(!(e instanceof $))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class Wi{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Cr,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);{const i=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex!==null&&i>this.lastEndSampleIndex){const n=i-this.lastEndSampleIndex,a=new ne({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(a,!0)}this.lastEndSampleIndex=s}if(this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??=n).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await s,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{m(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){m(this.outputSampleSize),m(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let h=0;h{const{numberOfChannels:i,sampleRate:s}=e,n=pi({numberOfChannels:i,sampleRate:s,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);const a=Kt.find(o=>o.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof $))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(l=>{this.error??=l,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(Z.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=_r(K(l.decoderConfig.description)).objectType===0,d){const h=Number(X(n.codec.split(".")));l.decoderConfig.description=la({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}const u=$.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(u,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d,this.errorNeedsNewStack=!1})},error:c=>{c.stack=t.stack,this.error??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:s}=Ae(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,J((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,J(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{const c=J(Math.floor(o*32767),-32768,32767);n.setUint8(a,Da(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{const c=J(Math.floor(o*32767),-32768,32767);n.setUint8(a,Na(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,J((o+1)*32767.5,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,J(Math.round(o*32767),-32768,32767),s):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>zs(n,a,J((o+1)*83886075e-1,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>Gn(n,a,J(Math.round(o*8388607),-8388608,8388607),s):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,J((o+1)*21474836475e-1,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,J(Math.round(o*2147483647),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):m(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):m(!1);break;default:ae(i),m(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class Ss extends tr{constructor(e){Mi(e),super(e.codec),this._encoder=new Wi(this,e)}add(e){if(!(e instanceof ne))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class bu extends tr{constructor(e){Mi(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Wi(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=ne._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class ku extends tr{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}constructor(e,t){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");Mi(t),super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=G(),this._errorPromiseAccessed=!1,this._encoder=new Wi(this,t),this._track=e}async _start(){if(this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController,typeof MediaStreamTrackProcessor<"u"){let e=null;const t=new MediaStreamTrackProcessor({track:this._track}),i=new WritableStream({write:s=>{if(e===null){e=s.timestamp/1e6;const n=this._connectedTrack.output._muxer;n.firstMediaStreamTimestamp===null?(n.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-e):this._timestampOffset=performance.now()/1e3-n.firstMediaStreamTimestamp-e}if(this._encoder.getQueueSize()>=4){s.close();return}this._encoder.add(new ne(s),!0).catch(n=>{this._abortController?.abort(),this._promiseWithResolvers.reject(n)})}});t.readable.pipeTo(i,{signal:this._abortController.signal}).catch(s=>{s instanceof DOMException&&s.name==="AbortError"||this._promiseWithResolvers.reject(s)})}else{const e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});const t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let i=!1,s=0;this._scriptProcessorNode.onaudioprocess=n=>{const a=ne._fromAudioBuffer(n.inputBuffer,s);s+=n.inputBuffer.duration;for(const o of a){if(!i){i=!0;const c=this._connectedTrack.output._muxer;c.firstMediaStreamTimestamp===null?c.firstMediaStreamTimestamp=performance.now()/1e3:this._timestampOffset=performance.now()/1e3-c.firstMediaStreamTimestamp}if(this._encoder.getQueueSize()>=4){o.close();continue}this._encoder.add(o,!0).catch(c=>{this._audioContext.suspend(),this._promiseWithResolvers.reject(c)})}}}}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(m(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}const Vl=()=>{const r=(i,s)=>{s?self.postMessage(i,{transfer:s}):self.postMessage(i)};r({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",i=>{const s=i.data;switch(s.type){case"videoTrack":{t.set(s.trackId,s.track);const n=new MediaStreamTrackProcessor({track:s.track}),a=new WritableStream({write:c=>{if(!t.has(s.trackId)){c.close();return}r({type:"videoFrame",trackId:s.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(s.trackId,o),n.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||r({type:"error",trackId:s.trackId,error:c})})}break;case"stopTrack":{const n=e.get(s.trackId);n&&(n.abort(),e.delete(s.trackId)),t.get(s.trackId)?.stop(),t.delete(s.trackId),r({type:"trackStopped",trackId:s.trackId})}break;default:ae(s)}})};let Wl=0,_e=null;const Ll=()=>{const r=new Blob([`(${Vl.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(r);_e=new Worker(e)};let Lr=null;const Hl=async()=>Lr!==null?Lr:(_e||Ll(),new Promise(r=>{m(_e);const e=t=>{const i=t.data;i.type==="support"&&(Lr=i.supported,_e.removeEventListener("message",e),r(i.supported))};_e.addEventListener("message",e)})),Hr=(r,e)=>{m(_e),_e.postMessage(r)};class Hn extends Oi{constructor(e){if(super(),this._connectedTrack=null,!Ve.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ve.join(", ")}.`);this._codec=e}}class Tu extends Hn{constructor(e){super(e),this._error=null,this._parser=new nc({codec:e,output:(t,i)=>{this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,t,i).catch(s=>{this._error??=s})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._connectedTrack.output._muxer.mutex.currentPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose(e){e||this._checkForError()}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const ql=["video","audio","subtitle"],qr=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!jt(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&na(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class xs{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new At,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ze))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Jt))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof er))throw new TypeError("source must be a VideoSource.");if(qr(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof tr))throw new TypeError("source must be an AudioSource.");qr(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Hn))throw new TypeError("source must be a SubtitleSource.");qr(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if(Gr(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const s=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((l,u)=>l+(u.type===e?1:0),0),a=s[e].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?"":"s"}.`);const o=s.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);const c={id:this._tracks.length+1,output:this,type:e,source:t,metadata:i};if(c.type==="video"){const l=this.format.getSupportedVideoCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){const l=this.format.getSupportedAudioCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){const l=this.format.getSupportedSubtitleCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${l.map(u=>`'${u}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),t._connectedTrack=c}async start(){const e=this.format.getSupportedTrackCounts();for(const i of ql){const s=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s{this.state="started",this._writer.start();const i=await this._mutex.acquire();await this._muxer.start();const s=this._tracks.map(n=>n.source._start());await Promise.all(s),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}/*! + * Copyright (c) 2025-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */const Cs=r=>{if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!ce.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ce.join(", ")}.`);if(r?.bitrate!==void 0&&!(r.bitrate instanceof ge)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(r?.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(r?.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(r?.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(r?.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(r?.rotate!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(r?.crop!==void 0&&Si(r.crop,"options.video."),r?.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(r?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(r?.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(r?.processedWidth!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(r?.processedHeight!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.")},_s=r=>{if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!pe.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${pe.join(", ")}.`);if(r?.bitrate!==void 0&&!(r.bitrate instanceof ge)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(r?.numberOfChannels!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(r?.sampleRate!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(r?.processedNumberOfChannels!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(r?.processedSampleRate!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},jr=2,$r=48e3;class qn{static async init(e){const t=new qn(e);return await t._init(),t}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new jl,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof Go))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof xs))throw new TypeError("options.output must be an Output.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(typeof e.video!="function"&&Cs(e.video),typeof e.audio!="function"&&_s(e.audio),e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&(!Number.isFinite(e.trim.start)||e.trim.start<0))throw new TypeError("options.trim.start, when provided, must be a non-negative number.");if(e.trim?.end!==void 0&&(!Number.isFinite(e.trim.end)||e.trim.end<0))throw new TypeError("options.trim.end, when provided, must be a non-negative number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&Gr(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output,this._startTimestamp=e.trim?.start??0,this._endTimestamp=e.trim?.end??1/0;const{promise:t,resolve:i}=G();this._started=t,this._start=i}async _init(){const e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts();let i=1,s=1;for(const l of e){let u;if(l.isVideoTrack()?this._options.video&&(typeof this._options.video=="function"?(u=await this._options.video(l,i),Cs(u),i++):u=this._options.video):l.isAudioTrack()?this._options.audio&&(typeof this._options.audio=="function"?(u=await this._options.audio(l,s),_s(u),s++):u=this._options.audio):m(!1),u?.discard){this.discardedTracks.push({track:l,reason:"discarded_by_user"});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:l,reason:"max_track_count_reached"});continue}if(this._addedCounts[l.type]===t[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached"});continue}l.isVideoTrack()?await this._processVideoTrack(l,u??{}):l.isAudioTrack()&&await this._processAudioTrack(l,u??{})}const n=await this.input.getMetadataTags();let a;if(this._options.tags){const l=typeof this._options.tags=="function"?await this._options.tags(n):this._options.tags;Gr(l),a=l}else a=n;const o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,c=n.raw===a.raw;if(n.raw&&c&&!o&&delete a.raw,this.output.setMetadataTags(a),this.isValid=this._totalTrackCount>=t.total.min&&this._addedCounts.video>=t.video.min&&this._addedCounts.audio>=t.audio.min&&this._addedCounts.subtitle>=t.subtitle.min,this._options.showWarnings??!0){const l=[],u=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");u.length>0&&l.push("Some tracks had to be discarded from the conversion:",u),this.isValid||l.push(` + +`+this._getInvalidityExplanation().join("")),l.length>0&&console.warn(...l)}}_getInvalidityExplanation(){const e=[];if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(i=>i.reason==="discarded_by_user"||i.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const i=this.discardedTracks.flatMap(s=>s.reason==="discarded_by_user"?[]:s.track.type==="video"?this.output.format.getSupportedVideoCodecs():s.track.type==="audio"?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs());i.length===1?e.push(` +Tracks were discarded because your environment is not able to encode '${i[0]}'.`):e.push(` +Tracks were discarded because your environment is not able to encode any of the following codecs: ${i.map(s=>`'${s}'`).join(", ")}.`),i.includes("mp3")&&e.push(` +The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`)}else e.push(` +Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion. +`+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}this._canceled&&await new Promise(()=>{}),await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){const i=e.codec;if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let s;const n=yr(e.rotation+(t.rotate??0)),a=this.output.format.supportsVideoRotationMetadata,[o,c]=n%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],l=t.crop;l&&yi(l,o,c);const[u,d]=l?[l.width,l.height]:[o,c];let h=u,f=d;const p=h/f,g=x=>Math.ceil(x/2)*2;t.width!==void 0&&t.height===void 0?(h=g(t.width),f=g(Math.round(h/p))):t.width===void 0&&t.height!==void 0?(f=g(t.height),h=g(Math.round(f*p))):t.width!==void 0&&t.height!==void 0&&(h=g(t.width),f=g(t.height));const w=await e.getFirstTimestamp(),T=!!t.forceTranscode||this._startTimestamp>0||w<0||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0;let k=h!==u||f!==d||n!==0&&(!a||t.process!==void 0)||!!l;const S=t.alpha??"discard";let y=this.output.format.getSupportedVideoCodecs();if(!T&&!t.bitrate&&!k&&y.includes(i)&&(!t.codec||t.codec===i)){const x=new Ul(i);s=x,this._trackPromises.push((async()=>{await this._started;const I=new Gt(e),P={decoderConfig:await e.getDecoderConfig()??void 0},A=Number.isFinite(this._endTimestamp)?await I.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const M of I.packets(void 0,A,{verifyKeyPackets:!0})){if(this._canceled)return;S==="discard"&&(delete M.sideData.alpha,delete M.sideData.alphaByteLength),this._reportProgress(e.id,M.timestamp),await x.add(M,P),this._synchronizer.shouldWait(e.id,M.timestamp)&&await this._synchronizer.wait(M.timestamp)}x.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}t.codec&&(y=y.filter(M=>M===t.codec));const I=t.bitrate??Ts,C=await Dl(y,{width:t.process&&t.processedWidth?t.processedWidth:h,height:t.process&&t.processedHeight?t.processedHeight:f,bitrate:I});if(!C){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}const P={codec:C,bitrate:I,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:S},A=new ys(P);if(s=A,!k){const M=new xs({format:new On,target:new Tl}),z=new ys(P);M.addVideoTrack(z),await M.start();const q=await new Jr(e).getSample(w);if(q)try{await z.add(q),q.close(),await M.finalize()}catch(we){console.info("Error when probing encoder support. Falling back to rerender path.",we),k=!0,M.cancel()}else await M.cancel()}k?this._trackPromises.push((async()=>{await this._started;const z=new qa(e,{width:h,height:f,fit:t.fit??"fill",rotation:n,crop:t.crop,poolSize:1,alpha:S==="keep"}).canvases(this._startTimestamp,this._endTimestamp),U=t.frameRate;let q=null,we=null,lt=null;const ue=async de=>{m(q),m(U!==void 0);const be=Math.round((de-we)*U);for(let ut=1;ut{await this._started;const M=new Jr(e),z=t.frameRate;let U=null,q=null,we=null;const lt=async ue=>{m(U),m(z!==void 0);const de=Math.round((ue-q)*z);for(let be=1;beo instanceof ee?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new ee(o):new ee(o,{timestamp:s.timestamp,duration:s.duration}))}for(const a of n){if(this._canceled)break;await i.add(a),this._synchronizer.shouldWait(e.id,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}for(const a of n)a!==s&&a.close()}async _processAudioTrack(e,t){const i=e.codec;if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let s;const n=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp();let c=t.numberOfChannels??n,l=t.sampleRate??a,u=c!==n||l!==a||this._startTimestamp>0||o<0,d=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!u&&d.includes(i)&&(!t.codec||t.codec===i)&&!t.process){const h=new Ol(i);s=h,this._trackPromises.push((async()=>{await this._started;const f=new Gt(e),g={decoderConfig:await e.getDecoderConfig()??void 0},w=Number.isFinite(this._endTimestamp)?await f.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const T of f.packets(void 0,w)){if(this._canceled)return;this._reportProgress(e.id,T.timestamp),await h.add(T,g),this._synchronizer.shouldWait(e.id,T.timestamp)&&await this._synchronizer.wait(T.timestamp)}h.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}let f=null;t.codec&&(d=d.filter(w=>w===t.codec));const p=t.bitrate??Ts,g=await gi(d,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:l,bitrate:p});if(!g.some(w=>St.includes(w))&&d.some(w=>St.includes(w))&&(c!==jr||l!==$r)){const T=(await gi(d,{numberOfChannels:jr,sampleRate:$r,bitrate:p})).find(k=>St.includes(k));T&&(u=!0,f=T,c=jr,l=$r)}else f=g[0]??null;if(f===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}if(u)s=this._resampleAudio(e,t,f,c,l,p);else{const w=new Ss({codec:f,bitrate:p});s=w,this._trackPromises.push((async()=>{await this._started;const T=new ei(e);for await(const k of T.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample(e,t,w,k),k.close()}w.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(s,{languageCode:jt(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,i,s){if(this._canceled)return;this._reportProgress(e.id,s.timestamp);let n;if(!t.process)n=[s];else{let a=t.process(s);if(a instanceof Promise&&(a=await a),Array.isArray(a)||(a=a===null?[]:[a]),!a.every(o=>o instanceof ne))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");n=a}for(const a of n){if(this._canceled)break;await i.add(a),this._synchronizer.shouldWait(e.id,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}for(const a of n)a!==s&&a.close()}_resampleAudio(e,t,i,s,n,a){const o=new Ss({codec:i,bitrate:a});return this._trackPromises.push((async()=>{await this._started;const c=new $l({targetNumberOfChannels:s,targetSampleRate:n,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:d=>this._registerAudioSample(e,t,o,d)}),u=new ei(e).samples(this._startTimestamp,this._endTimestamp);for await(const d of u){if(this._canceled)return;await c.add(d)}await c.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),s=J(i/this._totalDuration,0,1);s!==this._lastProgress&&(this._lastProgress=s,this.onProgress?.(s))}}const Ps=5;class jl{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t=Ps}wait(e){const{promise:t,resolve:i}=G();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}}class $l{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){m(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,s)=>i[s*e]:e===1&&t===4?this.channelMixer=(i,s,n)=>i[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(i,s,n)=>i[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .5*(i[n]+i[n+1])}:e===2&&t===4?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .25*(i[n]+i[n+1]+i[n+2]+i[n+3])}:e===4&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return .5*(i[a+n]+i[a+n+2])}:e===4&&t===6?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]:n===2||n===3?0:i[a+n-2]}:e===6&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return Math.SQRT1_2*(i[n]+i[n+1])+i[n+2]+.5*(i[n+4]+i[n+5])}:e===6&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return i[a+n]+Math.SQRT1_2*(i[a+2]+i[a+n+4])}:e===6&&t===4?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]+Math.SQRT1_2*i[a+2]:i[a+n+2]}:this.channelMixer=(i,s,n)=>n=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const d=u-this.bufferStartFrame;m(d=0&&g=0&&wi.map(i=>d[i]); +import{r as F,d as Xn,j as x,_ as ii,S as Bk,e as R5,v as D5,f as F5}from"./react-kyfdMflE.js";import{c as Yl,s as ty,p as $k}from"./zustand-CnPgS7xu.js";import{S as L5,C as jk,a as O5,P as B5,b as Nk,R as $5,T as j5,c as Vk,d as N5,e as V5,f as U5,g as z5,h as G5,i as W5,j as Uk,k as zk,l as q5,m as Gk,I as Wk,n as qk,o as Hk,p as Yk,L as Xk,q as Kk,r as H5,s as Y5,t as X5,O as Qk,u as K5,v as Jk,w as Q5,x as Zk,D as eA,y as J5,z as tA,A as iA,B as Z5,E as sA,F as nA,G as rA,H as aA,J as oA,K as cA,M as lA,N as eR,Q as tR,U as uA,V as dA,W as iR,X as hA,Y as sR,Z as fA,_ as pA,$ as nR,a0 as mA,a1 as rR,a2 as gA,a3 as yA,a4 as aR,a5 as oR,a6 as vA,a7 as cR,a8 as lR,a9 as uR,aa as bA,ab as dR,ac as hR,ad as xA,ae as fR,af as wA,ag as pR,ah as mR,ai as _A,aj as TA,ak as kA,al as AA,am as SA,an as CA,ao as EA,ap as gR,aq as yR,ar as vR}from"./radix-DNxS_rDm.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();var G=typeof window<"u"?window:void 0,Wt=typeof globalThis<"u"?globalThis:G;typeof self>"u"&&(Wt.self=Wt),typeof File>"u"&&(Wt.File=function(){});var MA=Array.prototype,gb=MA.forEach,yb=MA.indexOf,Li=Wt?.navigator,Y=Wt?.document,gi=Wt?.location,Pm=Wt?.fetch,Rm=Wt!=null&&Wt.XMLHttpRequest&&"withCredentials"in new Wt.XMLHttpRequest?Wt.XMLHttpRequest:void 0,vb=Wt?.AbortController,mi=Li?.userAgent,ce=G??{},dn={DEBUG:!1,LIB_VERSION:"1.335.2"};function bb(s,e,t,i,n,r,a){try{var o=s[r](a),c=o.value}catch(l){return void t(l)}o.done?e(c):Promise.resolve(c).then(i,n)}function $a(s){return function(){var e=this,t=arguments;return new Promise(function(i,n){var r=s.apply(e,t);function a(c){bb(r,i,n,a,o,"next",c)}function o(c){bb(r,i,n,a,o,"throw",c)}a(void 0)})}}function K(){return K=Object.assign?Object.assign.bind():function(s){for(var e=1;e{var n=i.toLowerCase();return t.indexOf(n)!==-1})},xR=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function we(s,e){return s.indexOf(e)!==-1}var Mh=function(s){return s.trim()},Dm=function(s){return s.replace(/^\$/,"")},wR=Array.isArray,PA=Object.prototype,RA=PA.hasOwnProperty,Ih=PA.toString,Me=wR||function(s){return Ih.call(s)==="[object Array]"},ir=s=>typeof s=="function",Mt=s=>s===Object(s)&&!Me(s),ja=s=>{if(Mt(s)){for(var e in s)if(RA.call(s,e))return!1;return!0}return!1},H=s=>s===void 0,It=s=>Ih.call(s)=="[object String]",Fm=s=>It(s)&&s.trim().length===0,Is=s=>s===null,Ce=s=>H(s)||Is(s),kn=s=>Ih.call(s)=="[object Number]"&&s==s,Fa=s=>kn(s)&&s>0,_n=s=>Ih.call(s)==="[object Boolean]",_R=s=>s instanceof FormData,TR=s=>we(xR,s);function Lm(s){return s===null||typeof s!="object"}function Id(s,e){return Object.prototype.toString.call(s)==="[object "+e+"]"}function DA(s){return!H(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(s,Event)}var kR=[!0,"true",1,"1","yes"],wf=s=>we(kR,s),AR=[!1,"false",0,"0","no"];function zs(s,e,t,i,n){return e>t&&(i.warn("min cannot be greater than max."),e=t),kn(s)?s>t?(i.warn(" cannot be greater than max: "+t+". Using max value instead."),t):s0){var r=n*this.m;e.tokens=Math.min(e.tokens+r,this.o),e.lastAccess=e.lastAccess+n*this.$}}consumeRateLimit(e){var t,i=Date.now(),n=String(e),r=this.t[n];return r?this.S(r,i):(r={tokens:this.o,lastAccess:i},this.t[n]=r),r.tokens===0||(r.tokens--,r.tokens===0&&((t=this.i)==null||t.call(this,e)),r.tokens===0)}stop(){this.t={}}};var fs="Mobile",Pd="iOS",xn="Android",gl="Tablet",FA=xn+" "+gl,LA="iPad",OA="Apple",BA=OA+" Watch",yl="Safari",yo="BlackBerry",$A="Samsung",jA=$A+"Browser",NA=$A+" Internet",ga="Chrome",CR=ga+" OS",VA=ga+" "+Pd,iy="Internet Explorer",UA=iy+" "+fs,sy="Opera",ER=sy+" Mini",ny="Edge",zA="Microsoft "+ny,to="Firefox",GA=to+" "+Pd,vl="Nintendo",bl="PlayStation",io="Xbox",WA=xn+" "+fs,qA=fs+" "+yl,Pc="Windows",Om=Pc+" Phone",wb="Nokia",Bm="Ouya",HA="Generic",MR=HA+" "+fs.toLowerCase(),YA=HA+" "+gl.toLowerCase(),$m="Konqueror",ri="(\\d+(\\.\\d+)?)",_f=new RegExp("Version/"+ri),IR=new RegExp(io,"i"),PR=new RegExp(bl+" \\w+","i"),RR=new RegExp(vl+" \\w+","i"),ry=new RegExp(yo+"|PlayBook|BB10","i"),DR={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},wu,_b,Tf,FR=(s,e)=>e&&we(e,OA)||function(t){return we(t,yl)&&!we(t,ga)&&!we(t,xn)}(s),XA=function(s,e){return e=e||"",we(s," OPR/")&&we(s,"Mini")?ER:we(s," OPR/")?sy:ry.test(s)?yo:we(s,"IE"+fs)||we(s,"WPDesktop")?UA:we(s,jA)?NA:we(s,ny)||we(s,"Edg/")?zA:we(s,"FBIOS")?"Facebook "+fs:we(s,"UCWEB")||we(s,"UCBrowser")?"UC Browser":we(s,"CriOS")?VA:we(s,"CrMo")||we(s,ga)?ga:we(s,xn)&&we(s,yl)?WA:we(s,"FxiOS")?GA:we(s.toLowerCase(),$m.toLowerCase())?$m:FR(s,e)?we(s,fs)?qA:yl:we(s,to)?to:we(s,"MSIE")||we(s,"Trident/")?iy:we(s,"Gecko")?to:""},LR={[UA]:[new RegExp("rv:"+ri)],[zA]:[new RegExp(ny+"?\\/"+ri)],[ga]:[new RegExp("("+ga+"|CrMo)\\/"+ri)],[VA]:[new RegExp("CriOS\\/"+ri)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ri)],[yl]:[_f],[qA]:[_f],[sy]:[new RegExp("(Opera|OPR)\\/"+ri)],[to]:[new RegExp(to+"\\/"+ri)],[GA]:[new RegExp("FxiOS\\/"+ri)],[$m]:[new RegExp("Konqueror[:/]?"+ri,"i")],[yo]:[new RegExp(yo+" "+ri),_f],[WA]:[new RegExp("android\\s"+ri,"i")],[NA]:[new RegExp(jA+"\\/"+ri)],[iy]:[new RegExp("(rv:|MSIE )"+ri)],Mozilla:[new RegExp("rv:"+ri)]},OR=function(s,e){var t=XA(s,e),i=LR[t];if(H(i))return null;for(var n=0;n[io,s&&s[1]||""]],[new RegExp(vl,"i"),[vl,""]],[new RegExp(bl,"i"),[bl,""]],[ry,[yo,""]],[new RegExp(Pc,"i"),(s,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Om,""];if(new RegExp(fs).test(e)&&!/IEMobile\b/.test(e))return[Pc+" "+fs,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var i=t[1],n=DR[i]||"";return/arm/i.test(e)&&(n="RT"),[Pc,n]}return[Pc,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,s=>{if(s&&s[3]){var e=[s[3],s[4],s[5]||"0"];return[Pd,e.join(".")]}return[Pd,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,s=>{var e="";return s&&s.length>=3&&(e=H(s[2])?s[3]:s[2]),["watchOS",e]}],[new RegExp("("+xn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+xn+")","i"),s=>{if(s&&s[2]){var e=[s[2],s[3],s[4]||"0"];return[xn,e.join(".")]}return[xn,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,s=>{var e=["Mac OS X",""];if(s&&s[1]){var t=[s[1],s[2],s[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[CR,""]],[/Linux|debian/i,["Linux",""]]],kb=function(s){return RR.test(s)?vl:PR.test(s)?bl:IR.test(s)?io:new RegExp(Bm,"i").test(s)?Bm:new RegExp("("+Om+"|WPDesktop)","i").test(s)?Om:/iPad/.test(s)?LA:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?BA:ry.test(s)?yo:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(wb,"i").test(s)?wb:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":/(Android|ZTE)/i.test(s)?new RegExp(fs).test(s)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)||/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?xn:FA:new RegExp("(pda|"+fs+")","i").test(s)?MR:new RegExp(gl,"i").test(s)&&!new RegExp(gl+" pc","i").test(s)?YA:""},BR=s=>s instanceof Error;function $R(s){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return Tf&&t.length===_b||(_b=t.length,Tf=t.reduce((i,n)=>{wu||(wu={});var r=wu[n];if(r)i[r[0]]=r[1];else for(var a=s(n),o=a.length-1;o>=0;o--){var c=a[o],l=c?.filename,u=e[n];if(l&&u){i[l]=u,wu[n]=[l,u];break}}return i},{})),Tf}}let jR=class{constructor(e,t,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t){t===void 0&&(t={});var i=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(),a=this.parseStacktrace(n,r);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}modifyFrames(e){var t=this;return $a(function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&Me(i.stacktrace.frames)&&(i.stacktrace.frames=yield t.applyModifiers(i.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var i,n;return e.cause!=null&&(i=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),K({},e,{cause:i,stack:n})}applyChunkIds(e,t){return e.map(i=>(i.filename&&t&&(i.chunk_id=t[i.filename]),i))}applyCoercers(e,t){for(var i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return $a(function*(){var i=e;for(var n of t.modifiers)i=yield n(i);return i})()}convertToExceptionList(e,t){var i,n,r,a={type:e.type,value:e.value,mechanism:{type:(i=t.type)!==null&&i!==void 0?i:"generic",handled:(n=t.handled)===null||n===void 0||n,synthetic:(r=e.synthetic)!==null&&r!==void 0&&r}};e.stack&&(a.stacktrace={type:"raw",frames:e.stack});var o=[a];return e.cause!=null&&o.push(...this.convertToExceptionList(e.cause,K({},t,{handled:!0}))),o}buildParsingContext(){return{chunkIdMap:$R(this.stackParser)}}buildCoercingContext(e,t,i){i===void 0&&(i=0);var n=(r,a)=>{if(a<=4){var o=this.buildCoercingContext(e,t,a);return this.applyCoercers(r,o)}};return K({},t,{syntheticException:i==0?t.syntheticException:void 0,mechanism:e,apply:r=>n(r,i),next:r=>n(r,i+1)})}};var vo="?";function jm(s,e,t,i,n){var r={platform:s,filename:e,function:t===""?vo:t,in_app:!0};return H(i)||(r.lineno=i),H(n)||(r.colno=n),r}var KA=(s,e)=>{var t=s.indexOf("safari-extension")!==-1,i=s.indexOf("safari-web-extension")!==-1;return t||i?[s.indexOf("@")!==-1?s.split("@")[0]:vo,t?"safari-extension:"+e:"safari-web-extension:"+e]:[s,e]},NR=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,VR=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,UR=/\((\S*)(?::(\d+))(?::(\d+))\)/,zR=(s,e)=>{var t=NR.exec(s);if(t){var[,i,n,r]=t;return jm(e,i,vo,+n,+r)}var a=VR.exec(s);if(a){if(a[2]&&a[2].indexOf("eval")===0){var o=UR.exec(a[2]);o&&(a[2]=o[1],a[3]=o[2],a[4]=o[3])}var[c,l]=KA(a[1]||vo,a[2]);return jm(e,l,c,a[3]?+a[3]:void 0,a[4]?+a[4]:void 0)}},GR=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,WR=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,qR=(s,e)=>{var t=GR.exec(s);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var i=WR.exec(t[3]);i&&(t[1]=t[1]||"eval",t[3]=i[1],t[4]=i[2],t[5]="")}var n=t[3],r=t[1]||vo;return[r,n]=KA(r,n),jm(e,n,r,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Ab=/\(error: (.*)\)/,Sb=50;function HR(){return function(s){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i1024)){var u=Ab.test(l)?l.replace(Ab,"$1"):l;if(!u.match(/\S*Error: /)){for(var d of t){var h=d(u,s);if(h){a.push(h);break}}if(a.length>=Sb)break}}}return function(f){if(!f.length)return[];var p=Array.from(f);return p.reverse(),p.slice(0,Sb).map(m=>{return K({},m,{filename:m.filename||(g=p,g[g.length-1]||{}).filename,function:m.function||vo});var g})}(a)}}("web:javascript",zR,qR)}let YR=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var i=It(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Id(e,"DOMException")}isDOMError(e){return Id(e,"DOMError")}},XR=class{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var i=e.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(e){return e.stacktrace||e.stack||void 0}},KR=class{constructor(){}match(e){return Id(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var i,n=t.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:(i=t.syntheticException)==null?void 0:i.stack,synthetic:!0}}};var QR=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;let JR=class{match(e){return typeof e=="string"}coerce(e,t){var i,[n,r]=this.getInfos(e);return{type:n??"Error",value:r??e,stack:(i=t.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var t="Error",i=e,n=e.match(QR);return n&&(t=n[1],i=n[2]),[t,i]}};var ZR=["fatal","error","warning","log","info","debug"];function QA(s,e){e===void 0&&(e=40);var t=Object.keys(s);if(t.sort(),!t.length)return"[object has no keys]";for(var i=t.length;i>0;i--){var n=t.slice(0,i).join(", ");if(!(n.length>e))return i===t.length||n.length<=e?n:n.slice(0,e)+"..."}return""}let eD=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var i,n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(i=t.syntheticException)==null?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return DA(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+QA(e)}isSeverityLevel(e){return It(e)&&!Fm(e)&&ZR.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var i=e[t];if(BR(i))return i}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},tD=class{match(e){return DA(e)}coerce(e,t){var i,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+QA(e),stack:(i=t.syntheticException)==null?void 0:i.stack,synthetic:!0}}},iD=class{match(e){return Lm(e)}coerce(e,t){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=t.syntheticException)==null?void 0:i.stack,synthetic:!0}}},sD=class{match(e){return Id(e,"PromiseRejectionEvent")}coerce(e,t){var i,n=this.getUnhandledRejectionReason(e);return Lm(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(i=t.syntheticException)==null?void 0:i.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){if(Lm(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var JA=function(s,e){var{debugEnabled:t}=e===void 0?{}:e,i={k:function(n){if(G&&(dn.DEBUG||ce.POSTHOG_DEBUG||t)&&!H(G.console)&&G.console){for(var r=("__rrweb_original__"in G.console[n])?G.console[n].__rrweb_original__:G.console[n],a=arguments.length,o=new Array(a>1?a-1:0),c=1;c{i.error("You must initialize PostHog before calling "+n)},createLogger:(n,r)=>JA(s+" "+n,r)};return i},X=JA("[PostHog.js]"),ut=X.createLogger,nD=ut("[ExternalScriptsLoader]"),Cb=(s,e,t)=>{if(s.config.disable_external_dependency_loading)return nD.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var i=Y?.querySelectorAll("script");if(i){for(var n,r=function(){if(i[a].src===e){var c=i[a];return c.__posthog_loading_callback_fired?{v:t()}:(c.addEventListener("load",l=>{c.__posthog_loading_callback_fired=!0,t(void 0,l)}),c.onerror=l=>t(l),{v:void 0})}},a=0;a{if(!Y)return t("document not found");var c=Y.createElement("script");if(c.type="text/javascript",c.crossOrigin="anonymous",c.src=e,c.onload=d=>{c.__posthog_loading_callback_fired=!0,t(void 0,d)},c.onerror=d=>t(d),s.config.prepare_external_dependency_script&&(c=s.config.prepare_external_dependency_script(c)),!c)return t("prepare_external_dependency_script returned null");if(s.config.external_scripts_inject_target==="head")Y.head.appendChild(c);else{var l,u=Y.querySelectorAll("body > script");u.length>0?(l=u[0].parentNode)==null||l.insertBefore(c,u[0]):Y.body.appendChild(c)}};Y!=null&&Y.body?o():Y?.addEventListener("DOMContentLoaded",o)};ce.__PosthogExtensions__=ce.__PosthogExtensions__||{},ce.__PosthogExtensions__.loadExternalDependency=(s,e,t)=>{var i="/static/"+e+".js?v="+s.version;if(e==="remote-config"&&(i="/array/"+s.config.token+"/config.js"),e==="toolbar"){var n=3e5;i=i+"&t="+Math.floor(Date.now()/n)*n}var r=s.requestRouter.endpointFor("assets",i);Cb(s,r,t)},ce.__PosthogExtensions__.loadSiteApp=(s,e,t)=>{var i=s.requestRouter.endpointFor("api",e);Cb(s,i,t)};var Rd={};function sr(s,e,t){if(Me(s)){if(gb&&s.forEach===gb)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(var i=0,n=s.length;i1?e-1:0),i=1;i1?e-1:0),i=1;i0||kn(t))&&(e[i]=t)}),e};function aD(s,e){return t=s,i=r=>It(r)&&!Is(e)?r.slice(0,e):r,n=new Set,function r(a,o){return a!==Object(a)?i?i(a,o):a:n.has(a)?void 0:(n.add(a),Me(a)?(c=[],sr(a,l=>{c.push(r(l))})):(c={},Be(a,(l,u)=>{n.has(l)||(c[u]=r(l,u))})),c);var c}(t);var t,i,n}var oD=["herokuapp.com","vercel.app","netlify.app"];function cD(s){var e=s?.hostname;if(!It(e))return!1;var t=e.split(".").slice(-2).join(".");for(var i of oD)if(t===i)return!1;return!0}function ZA(s,e){for(var t=0;te.match(t)))}function Bd(s){var e="";switch(typeof s.className){case"string":e=s.className;break;case"object":e=(s.className&&"baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";break;default:e=""}return oy(e)}function aS(s){return Ce(s)?null:Mh(s).split(/(\s+)/).filter(e=>xl(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Xl(s){var e="";return Ym(s)&&!dS(s)&&s.childNodes&&s.childNodes.length&&Be(s.childNodes,function(t){var i;nS(t)&&t.textContent&&(e+=(i=aS(t.textContent))!==null&&i!==void 0?i:"")}),Mh(e)}function oS(s){return H(s.target)?s.srcElement||null:(e=s.target)!=null&&e.shadowRoot?s.composedPath()[0]||null:s.target||null;var e}var cy=["a","button","form","input","select","textarea","label"];function cS(s,e){if(H(e))return!0;var t,i=function(r){if(e.some(a=>r.matches(a)))return{v:!0}};for(var n of s)if(t=i(n))return t.v;return!1}function lS(s){var e=s.parentNode;return!(!e||!Ph(e))&&e}var uD=["next","previous","prev",">","<"],Bb=10,$b=[".ph-no-rageclick",".ph-no-capture"];function dD(s,e){if(!G||ly(s))return!1;var t,i,n;if(_n(e)?(t=!!e&&$b,i=void 0):(t=(n=e?.css_selector_ignorelist)!==null&&n!==void 0?n:$b,i=e?.content_ignorelist),t===!1)return!1;var{targetElementList:r}=uS(s,!1);return!function(a,o){if(a===!1||H(a))return!1;var c;if(a===!0)c=uD;else{if(!Me(a))return!1;if(a.length>Bb)return X.error("[PostHog] content_ignorelist array cannot exceed "+Bb+" items. Use css_selector_ignorelist for more complex matching."),!1;c=a.map(l=>l.toLowerCase())}return o.some(l=>{var{safeText:u,ariaLabel:d}=l;return c.some(h=>u.includes(h)||d.includes(h))})}(i,r.map(a=>{var o;return{safeText:Xl(a).toLowerCase(),ariaLabel:((o=a.getAttribute("aria-label"))==null?void 0:o.toLowerCase().trim())||""}}))&&!cS(r,t)}var ly=s=>!s||nr(s,"html")||!Ph(s),uS=(s,e)=>{if(!G||ly(s))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,i=[s],n=s;n.parentNode&&!nr(n,"body");)if(rS(n.parentNode))i.push(n.parentNode.host),n=n.parentNode.host;else{var r=lS(n);if(!r)break;if(e||cy.indexOf(r.tagName.toLowerCase())>-1)t=!0;else{var a=G.getComputedStyle(r);a&&a.getPropertyValue("cursor")==="pointer"&&(t=!0)}i.push(r),n=r}return{parentIsUsefulElement:t,targetElementList:i}};function hD(s,e,t,i,n){var r,a,o,c;if(t===void 0&&(t=void 0),!G||ly(s)||(r=t)!=null&&r.url_allowlist&&!Ob(t.url_allowlist)||(a=t)!=null&&a.url_ignorelist&&Ob(t.url_ignorelist))return!1;if((o=t)!=null&&o.dom_event_allowlist){var l=t.dom_event_allowlist;if(l&&!l.some(p=>e.type===p))return!1}var{parentIsUsefulElement:u,targetElementList:d}=uS(s,i);if(!function(p,m){var g=m?.element_allowlist;if(H(g))return!0;var v,w=function(k){if(g.some(A=>k.tagName.toLowerCase()===A))return{v:!0}};for(var b of p)if(v=w(b))return v.v;return!1}(d,t)||!cS(d,(c=t)==null?void 0:c.css_selector_allowlist))return!1;var h=G.getComputedStyle(s);if(h&&h.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var f=s.tagName.toLowerCase();switch(f){case"html":return!1;case"form":return(n||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(n||["change","click"]).indexOf(e.type)>=0;default:return u?(n||["click"]).indexOf(e.type)>=0:(n||["click"]).indexOf(e.type)>=0&&(cy.indexOf(f)>-1||s.getAttribute("contenteditable")==="true")}}function Ym(s){for(var e=s;e.parentNode&&!nr(e,"body");e=e.parentNode){var t=Bd(e);if(we(t,"ph-sensitive")||we(t,"ph-no-capture"))return!1}if(we(Bd(s),"ph-include"))return!0;var i=s.type||"";if(It(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var n=s.name||s.id||"";return!(It(n)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(n.replace(/[^a-zA-Z0-9]/g,"")))}function dS(s){return!!(nr(s,"input")&&!["button","checkbox","submit","reset"].includes(s.type)||nr(s,"select")||nr(s,"textarea")||s.getAttribute("contenteditable")==="true")}var hS="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",fD=new RegExp("^(?:"+hS+")$"),pD=new RegExp(hS),fS="\\d{3}-?\\d{2}-?\\d{4}",mD=new RegExp("^("+fS+")$"),gD=new RegExp("("+fS+")");function xl(s,e){return e===void 0&&(e=!0),!(Ce(s)||It(s)&&(s=Mh(s),(e?fD:pD).test((s||"").replace(/[- ]/g,""))||(e?mD:gD).test(s)))}function pS(s){var e=Xl(s);return xl(e=(e+" "+mS(s)).trim())?e:""}function mS(s){var e="";return s&&s.childNodes&&s.childNodes.length&&Be(s.childNodes,function(t){var i;if(t&&((i=t.tagName)==null?void 0:i.toLowerCase())==="span")try{var n=Xl(t);e=(e+" "+n).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+mS(t)).trim())}catch(r){X.error("[AutoCapture]",r)}}),e}function yD(s){return function(e){var t=e.map(i=>{var n,r,a="";if(i.tag_name&&(a+=i.tag_name),i.attr_class)for(var o of(i.attr_class.sort(),i.attr_class))a+="."+o.replace(/"/g,"");var c=K({},i.text?{text:i.text}:{},{"nth-child":(n=i.nth_child)!==null&&n!==void 0?n:0,"nth-of-type":(r=i.nth_of_type)!==null&&r!==void 0?r:0},i.href?{href:i.href}:{},i.attr_id?{attr_id:i.attr_id}:{},i.attributes),l={};return od(c).sort((u,d)=>{var[h]=u,[f]=d;return h.localeCompare(f)}).forEach(u=>{var[d,h]=u;return l[jb(d.toString())]=jb(h.toString())}),a+=":",a+=od(l).map(u=>{var[d,h]=u;return d+'="'+h+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var i,n,r={text:(i=t.$el_text)==null?void 0:i.slice(0,400),tag_name:t.tag_name,href:(n=t.attr__href)==null?void 0:n.slice(0,2048),attr_class:vD(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return od(t).filter(a=>{var[o]=a;return o.indexOf("attr__")===0}).forEach(a=>{var[o,c]=a;return r.attributes[o]=c}),r})}(s))}function jb(s){return s.replace(/"|\\"/g,'\\"')}function vD(s){var e=s.attr__class;return e?Me(e)?e:oy(e):void 0}let gS=class{constructor(e){this.disabled=e===!1;var t=Mt(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(t-n.y){var e=Y?.createElement("a");return H(e)?null:(e.href=s,e)},bD=function(s,e){var t,i;e===void 0&&(e="&");var n=[];return Be(s,function(r,a){H(r)||H(a)||a==="undefined"||(t=encodeURIComponent((o=>o instanceof File)(r)?r.name:r.toString()),i=encodeURIComponent(a),n[n.length]=i+"="+t)}),n.join(e)},jd=function(s,e){for(var t,i=((s.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;ns?e.slice(0,s)+"...":e}function xD(s){if(s.previousElementSibling)return s.previousElementSibling;var e=s;do e=e.previousSibling;while(e&&!Ph(e));return e}function wD(s,e,t,i){var n=s.tagName.toLowerCase(),r={tag_name:n};cy.indexOf(n)>-1&&!t&&(n.toLowerCase()==="a"||n.toLowerCase()==="button"?r.$el_text=Sf(1024,pS(s)):r.$el_text=Sf(1024,Xl(s)));var a=Bd(s);a.length>0&&(r.classes=a.filter(function(u){return u!==""})),Be(s.attributes,function(u){var d;if((!dS(s)||["name","id","class","aria-label"].indexOf(u.name)!==-1)&&(i==null||!i.includes(u.name))&&!e&&xl(u.value)&&(d=u.name,!It(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var h=u.value;u.name==="class"&&(h=oy(h).join(" ")),r["attr__"+u.name]=Sf(1024,h)}});for(var o=1,c=1,l=s;l=xD(l);)o++,l.tagName===s.tagName&&c++;return r.nth_child=o,r.nth_of_type=c,r}function _D(s,e){for(var t,i,{e:n,maskAllElementAttributes:r,maskAllText:a,elementAttributeIgnoreList:o,elementsChainAsString:c}=e,l=[s],u=s;u.parentNode&&!nr(u,"body");)rS(u.parentNode)?(l.push(u.parentNode.host),u=u.parentNode.host):(l.push(u.parentNode),u=u.parentNode);var d,h=[],f={},p=!1,m=!1;if(Be(l,k=>{var A=Ym(k);k.tagName.toLowerCase()==="a"&&(p=k.getAttribute("href"),p=A&&p&&xl(p)&&p),we(Bd(k),"ph-no-capture")&&(m=!0),h.push(wD(k,r,a,o));var M=function(R){if(!Ym(R))return{};var I={};return Be(R.attributes,function(D){if(D.name&&D.name.indexOf("data-ph-capture-attribute")===0){var B=D.name.replace("data-ph-capture-attribute-",""),$=D.value;B&&$&&xl($)&&(I[B]=$)}}),I}(k);gt(f,M)}),m)return{props:{},explicitNoCapture:m};if(a||(s.tagName.toLowerCase()==="a"||s.tagName.toLowerCase()==="button"?h[0].$el_text=pS(s):h[0].$el_text=Xl(s)),p){var g,v;h[0].attr__href=p;var w=(g=$d(p))==null?void 0:g.host,b=G==null||(v=G.location)==null?void 0:v.host;w&&b&&w!==b&&(d=p)}return{props:gt({$event_type:n.type,$ce_version:1},c?{}:{$elements:h},{$elements_chain:yD(h)},(t=h[0])!=null&&t.$el_text?{$el_text:(i=h[0])==null?void 0:i.$el_text}:{},d&&n.type==="click"?{$external_click_url:d}:{},f)}}let TD=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new gS(e.config.rageclick),this.C=null}get R(){var e,t,i=Mt(this.instance.config.autocapture)?this.instance.config.autocapture:{};return i.url_allowlist=(e=i.url_allowlist)==null?void 0:e.map(n=>new RegExp(n)),i.url_ignorelist=(t=i.url_ignorelist)==null?void 0:t.map(n=>new RegExp(n)),i}F(){if(this.isBrowserSupported()){if(G&&Y){var e=i=>{i=i||G?.event;try{this.M(i)}catch(n){Nb.error("Failed to capture event",n)}};if(_t(Y,"submit",e,{capture:!0}),_t(Y,"change",e,{capture:!0}),_t(Y,"click",e,{capture:!0}),this.R.capture_copied_text){var t=i=>{i=i||G?.event,this.M(i,Af)};_t(Y,"copy",t,{capture:!0}),_t(Y,"cut",t,{capture:!0})}}}else Nb.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Mb]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,i=[];return(t=this.C)==null||t.forEach(n=>{var r=Y?.querySelectorAll(n);r?.forEach(a=>{e===a&&i.push(n)})}),i}get isEnabled(){var e,t,i=(e=this.instance.persistence)==null?void 0:e.props[Mb],n=this.T;if(Is(n)&&!_n(i)&&!this.instance.O())return!1;var r=(t=this.T)!==null&&t!==void 0?t:!!i;return!!this.instance.config.autocapture&&!r}M(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var i,n=oS(e);nS(n)&&(n=n.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(i=this.rageclicks)!=null&&i.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&dD(n,this.instance.config.rageclick)&&this.M(e,"$rageclick");var r=t===Af;if(n&&hD(n,e,this.R,r,r?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:o}=_D(n,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(o)return!1;var c=this.getElementSelectors(n);if(c&&c.length>0&&(a.$element_selectors=c),t===Af){var l,u=aS(G==null||(l=G.getSelection())==null?void 0:l.toString()),d=e.type||"clipboard";if(!u)return!1;a.$selected_content=u,a.$copy_type=d}return this.instance.capture(t,a),!0}}}isBrowserSupported(){return ir(Y?.querySelectorAll)}};Math.trunc||(Math.trunc=function(s){return s<0?Math.ceil(s):Math.floor(s)}),Number.isInteger||(Number.isInteger=function(s){return kn(s)&&isFinite(s)&&Math.floor(s)===s});var Vb="0123456789abcdef";let kD=class Xm{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(n)||e<0||t<0||i<0||n<0||e>0xffffffffffff||t>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/Math.pow(2,8),r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new Xm(r)}toString(){for(var e="",t=0;t>>4)+Vb.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Xm(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var i=this.bytes[t]-e.bytes[t];if(i!==0)return Math.sign(i)}return 0}},AD=class{constructor(){this.A=0,this.D=0,this.j=new SD}generate(){var e=this.generateOrAbort();if(H(e)){this.A=0;var t=this.generateOrAbort();if(H(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.D++,this.D>4398046511103&&(this.A++,this.L())}return kD.fromFieldsV7(this.A,Math.trunc(this.D/Math.pow(2,30)),this.D&Math.pow(2,30)-1,this.j.nextUint32())}L(){this.D=1024*this.j.nextUint32()+(1023&this.j.nextUint32())}};var Ub,yS=s=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;ecrypto.getRandomValues(s));let SD=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(yS(this.N),this.U=0),this.N[this.U++]}};var Qn=()=>CD().toString(),CD=()=>(Ub||(Ub=new AD)).generate(),hc="",ED=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function MD(s,e){if(e){var t=function(n,r){if(r===void 0&&(r=Y),hc)return hc;if(!r||["localhost","127.0.0.1"].includes(n))return"";for(var a=n.split("."),o=Math.min(a.length,8),c="dmn_chk_"+Qn();!hc&&o--;){var l=a.slice(o).join("."),u=c+"=1;domain=."+l+";path=/";r.cookie=u+";max-age=3",r.cookie.includes(c)&&(r.cookie=u+";max-age=0",hc=l)}return hc}(s);if(!t){var i=(n=>{var r=n.match(ED);return r?r[0]:""})(s);i!==t&&X.info("Warning: cookie subdomain discovery mismatch",i,t),t=i}return t?"; domain=."+t:""}return""}var js={H:()=>!!Y,B:function(s){X.error("cookieStore error: "+s)},q:function(s){if(Y){try{for(var e=s+"=",t=Y.cookie.split(";").filter(r=>r.length),i=0;i3686.4&&X.warn("cookieStore warning: large cookie, len="+l.length),Y.cookie=l,l}catch{return}},V:function(s,e){if(Y!=null&&Y.cookie)try{js.G(s,"",-1,e)}catch{return}}},Cf=null,Xe={H:function(){if(!Is(Cf))return Cf;var s=!0;if(H(G))s=!1;else try{var e="__mplssupport__";Xe.G(e,"xyz"),Xe.q(e)!=='"xyz"'&&(s=!1),Xe.V(e)}catch{s=!1}return s||X.error("localStorage unsupported; falling back to cookie store"),Cf=s,s},B:function(s){X.error("localStorage error: "+s)},q:function(s){try{return G?.localStorage.getItem(s)}catch(e){Xe.B(e)}return null},W:function(s){try{return JSON.parse(Xe.q(s))||{}}catch{}return null},G:function(s,e){try{G?.localStorage.setItem(s,JSON.stringify(e))}catch(t){Xe.B(t)}},V:function(s){try{G?.localStorage.removeItem(s)}catch(e){Xe.B(e)}}},ID=["$device_id","distinct_id",Dd,iS,Od,Ld],_u={},PD={H:function(){return!0},B:function(s){X.error("memoryStorage error: "+s)},q:function(s){return _u[s]||null},W:function(s){return _u[s]||null},G:function(s,e){_u[s]=e},V:function(s){delete _u[s]}},Cr=null,zt={H:function(){if(!Is(Cr))return Cr;if(Cr=!0,H(G))Cr=!1;else try{var s="__support__";zt.G(s,"xyz"),zt.q(s)!=='"xyz"'&&(Cr=!1),zt.V(s)}catch{Cr=!1}return Cr},B:function(s){X.error("sessionStorage error: ",s)},q:function(s){try{return G?.sessionStorage.getItem(s)}catch(e){zt.B(e)}return null},W:function(s){try{return JSON.parse(zt.q(s))||null}catch{}return null},G:function(s,e){try{G?.sessionStorage.setItem(s,JSON.stringify(e))}catch(t){zt.B(t)}},V:function(s){try{G?.sessionStorage.removeItem(s)}catch(e){zt.B(e)}}},fn=function(s){return s[s.PENDING=-1]="PENDING",s[s.DENIED=0]="DENIED",s[s.GRANTED=1]="GRANTED",s}({});let RD=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?fn.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===fn.DENIED||this.consent===fn.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===fn.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:i}=this._instance.config;return i||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return wf(e)?fn.GRANTED:we(AR,e)?fn.DENIED:fn.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?Xe:js;var t=e==="localStorage"?js:Xe;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(wf(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!ZA([Li?.doNotTrack,Li?.msDoNotTrack,ce.doNotTrack],e=>wf(e))}};var Tu=ut("[Dead Clicks]"),DD=()=>!0,FD=s=>{var e,t=!((e=s.instance.persistence)==null||!e.get_property(tS)),i=s.instance.config.capture_dead_clicks;return _n(i)?i:!!Mt(i)||t};let vS=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[tS]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it(()=>{this.et()})}it(e){var t,i;(t=ce.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(i=ce.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",n=>{n?Tu.error("failed to load script",n):e()})}et(){var e;if(Y){if(!this.tt&&(e=ce.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=Mt(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=ce.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(Y),Tu.info("starting...")}}else Tu.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Tu.info("stopping..."))}};var fc=ut("[ExceptionAutocapture]");let LD=class{constructor(e){var t,i,n;this.rt=()=>{var r;if(G&&this.isEnabled&&(r=ce.__PosthogExtensions__)!=null&&r.errorWrappingFunctions){var a=ce.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,o=ce.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,c=ce.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=a(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=o(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=c(this.captureException.bind(this)))}catch(l){fc.error("failed to start",l),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[Ib]),this.dt=new SR({refillRate:(i=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(n=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10,refillInterval:1e4,h:fc}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Mt(e)?t=K({},t,e):(H(e)?this.ht:e)&&(t=K({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(fc.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,i;(t=ce.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(i=ce.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"exception-autocapture",n=>{if(n)return fc.error("failed to load script",n);e()})}ut(){var e,t,i;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(i=this.ot)==null||i.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Ib]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,i,n=(t=e==null||(i=e.$exception_list)==null||(i=i[0])==null?void 0:i.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(n)?fc.info("Skipping exception capture because of client rate limiting.",{exception:n}):this._instance.exceptions.sendExceptionEvent(e)}};function zb(s,e,t){try{if(!(e in s))return()=>{};var i=s[e],n=t(i);return ir(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0}})),s[e]=n,()=>{s[e]=i}}catch{return()=>{}}}let OD=class{constructor(e){var t;this._instance=e,this.ct=(G==null||(t=G.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(X.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,X.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(G&&G.history){var i=this;(e=G.history.pushState)!=null&&e.__posthog_wrapped__||zb(G.history,"pushState",n=>function(r,a,o){n.call(this,r,a,o),i._t("pushState")}),(t=G.history.replaceState)!=null&&t.__posthog_wrapped__||zb(G.history,"replaceState",n=>function(r,a,o){n.call(this,r,a,o),i._t("replaceState")}),this.yt()}}_t(e){try{var t,i=G==null||(t=G.location)==null?void 0:t.pathname;if(!i)return;i!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=i}catch(n){X.error("Error capturing "+e+" pageview",n)}}yt(){if(!this.ft){var e=()=>{this._t("popstate")};_t(G,"popstate",e),this.ft=()=>{G&&G.removeEventListener("popstate",e)}}}};var Ef=ut("[SegmentIntegration]");function BD(s,e){var t=s.config.segment;if(!t)return e();(function(i,n){var r=i.config.segment;if(!r)return n();var a=c=>{var l=()=>c.anonymousId()||Qn();i.config.get_device_id=l,c.id()&&(i.register({distinct_id:c.id(),$device_id:l()}),i.persistence.set_property(hn,"identified")),n()},o=r.user();"then"in o&&ir(o.then)?o.then(a):a(o)})(s,()=>{t.register((i=>{Promise&&Promise.resolve||Ef.warn("This browser does not have Promise support, and can not use the segment integration");var n=(r,a)=>{if(!a)return r;r.event.userId||r.event.anonymousId===i.get_distinct_id()||(Ef.info("No userId set, resetting PostHog"),i.reset()),r.event.userId&&r.event.userId!==i.get_distinct_id()&&(Ef.info("UserId set, identifying with PostHog"),i.identify(r.event.userId));var o=i.calculateEventProperties(a,r.event.properties);return r.event.properties=Object.assign({},o,r.event.properties),r};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:r=>n(r,r.event.event),page:r=>n(r,"$pageview"),identify:r=>n(r,"$identify"),screen:r=>n(r,"$screen")}})(s)).then(()=>{e()})})}var bS="posthog-js";function xS(s,e){var{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:a=!0}=e===void 0?{}:e;return o=>{var c,l,u,d,h;if(!(r==="*"||r.includes(o.level))||!s.__loaded)return o;o.tags||(o.tags={});var f=s.requestRouter.endpointFor("ui","/project/"+s.config.token+"/person/"+s.get_distinct_id());o.tags["PostHog Person URL"]=f,s.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=s.get_session_replay_url({withTimestamp:!0}));var p=((c=o.exception)==null?void 0:c.values)||[],m=p.map(v=>K({},v,{stacktrace:v.stacktrace?K({},v.stacktrace,{type:"raw",frames:(v.stacktrace.frames||[]).map(w=>K({},w,{platform:"web:javascript"}))}):void 0})),g={$exception_message:((l=p[0])==null?void 0:l.value)||o.message,$exception_type:(u=p[0])==null?void 0:u.type,$exception_level:o.level,$exception_list:m,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:((d=p[0])==null?void 0:d.value)||o.message,$sentry_exception_type:(h=p[0])==null?void 0:h.type,$sentry_tags:o.tags};return t&&i&&(g.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+o.event_id),a&&s.exceptions.sendExceptionEvent(g),o}}let $D=class{constructor(e,t,i,n,r,a){this.name=bS,this.setupOnce=function(o){o(xS(e,{organization:t,projectId:i,prefix:n,severityAllowList:r,sendExceptionsToPostHog:a==null||a}))}}};var jD=G!=null&&G.location?Nd(G.location.hash,"__posthog")||Nd(location.hash,"state"):null,Gb="_postHogToolbarParams",Wb=ut("[Toolbar]"),Wn=function(s){return s[s.UNINITIALIZED=0]="UNINITIALIZED",s[s.LOADING=1]="LOADING",s[s.LOADED=2]="LOADED",s}(Wn||{});let ND=class{constructor(e){this.instance=e}bt(e){ce.ph_toolbar_state=e}wt(){var e;return(e=ce.ph_toolbar_state)!==null&&e!==void 0?e:Wn.UNINITIALIZED}maybeLoadToolbar(e,t,i){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),i===void 0&&(i=void 0),!G||!Y)return!1;e=e??G.location,i=i??G.history;try{if(!t){try{G.localStorage.setItem("test","test"),G.localStorage.removeItem("test")}catch{return!1}t=G?.localStorage}var n,r=jD||Nd(e.hash,"__posthog")||Nd(e.hash,"state"),a=r?Eb(()=>JSON.parse(atob(decodeURIComponent(r))))||Eb(()=>JSON.parse(decodeURIComponent(r))):null;return a&&a.action==="ph_authorize"?((n=a).source="url",n&&Object.keys(n).length>0&&(a.desiredHash?e.hash=a.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):((n=JSON.parse(t.getItem(Gb)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token)&&(this.loadToolbar(n),!0)}catch{return!1}}xt(e){var t=ce.ph_load_toolbar||ce.ph_load_editor;!Ce(t)&&ir(t)?t(e,this.instance):Wb.warn("No toolbar load function found")}loadToolbar(e){var t=!(Y==null||!Y.getElementById(sS));if(!G||t)return!1;var i=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=K({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},i?{instrument:!1}:{});if(G.localStorage.setItem(Gb,JSON.stringify(K({},n,{source:void 0}))),this.wt()===Wn.LOADED)this.xt(n);else if(this.wt()===Wn.UNINITIALIZED){var r;this.bt(Wn.LOADING),(r=ce.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",a=>{if(a)return Wb.error("[Toolbar] Failed to load",a),void this.bt(Wn.UNINITIALIZED);this.bt(Wn.LOADED),this.xt(n)}),_t(G,"turbolinks:load",()=>{this.bt(Wn.UNINITIALIZED),this.loadToolbar(n)})}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,i){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),i===void 0&&(i=void 0),this.maybeLoadToolbar(e,t,i)}};var VD=ut("[TracingHeaders]");let UD=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var t,i;H(this.$t)&&((t=ce.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),H(this.St)&&((i=ce.__PosthogExtensions__)==null||(i=i.tracingHeadersPatchFns)==null||i._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,i;(t=ce.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(i=ce.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"tracing-headers",n=>{if(n)return VD.error("failed to load script",n);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(t=this.St)==null||t.call(this),this.$t=void 0,this.St=void 0)}};var ku="https?://(.*)",zo=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],zD=Uo(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],zo),Ql="",GD=["li_fat_id"];function wS(s,e,t){if(!Y)return{};var i,n=e?Uo([],zo,t||[]):[],r=_S(Kl(Y.URL,n,Ql),s),a=(i={},Be(GD,function(o){var c=js.q(o);i[o]=c||null}),i);return gt(a,r)}function _S(s,e){var t=zD.concat(e||[]),i={};return Be(t,function(n){var r=jd(s,n);i[n]=r||null}),i}function TS(s){var e=function(r){return r?r.search(ku+"google.([^/?]*)")===0?"google":r.search(ku+"bing.com")===0?"bing":r.search(ku+"yahoo.com")===0?"yahoo":r.search(ku+"duckduckgo.com")===0?"duckduckgo":null:null}(s),t=e!="yahoo"?"q":"p",i={};if(!Is(e)){i.$search_engine=e;var n=Y?jd(Y.referrer,t):"";n.length&&(i.ph_keyword=n)}return i}function qb(){return navigator.language||navigator.userLanguage}function kS(){return Y?.referrer||"$direct"}function AS(s,e){var t=s?Uo([],zo,e||[]):[],i=gi?.href.substring(0,1e3);return{r:kS().substring(0,1e3),u:i?Kl(i,t,Ql):void 0}}function SS(s){var e,{r:t,u:i}=s,n={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=$d(t))==null?void 0:e.host};if(i){n.$current_url=i;var r=$d(i);n.$host=r?.host,n.$pathname=r?.pathname;var a=_S(i);gt(n,a)}if(t){var o=TS(t);gt(n,o)}return n}function CS(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function WD(){try{return new Date().getTimezoneOffset()}catch{return}}function qD(s,e){if(!mi)return{};var t,i,n,r=s?Uo([],zo,e||[]):[],[a,o]=function(c){for(var l=0;l1e3?mi.substring(0,997)+"...":mi,$browser_version:OR(mi,navigator.vendor),$browser_language:qb(),$browser_language_prefix:(t=qb(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:G?.screen.height,$screen_width:G?.screen.width,$viewport_height:G?.innerHeight,$viewport_width:G?.innerWidth,$lib:"web",$lib_version:dn.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var Bn=ut("[Web Vitals]"),Hb=9e5;let HD=class{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((i,n)=>K({},i,{["$web_vitals_"+n.name+"_event"]:K({},n),["$web_vitals_"+n.name+"_value"]:n.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=i=>{var n,r=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0);if(H(r))Bn.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var a=this.Ct();H(a)||(Ce(i?.name)||Ce(i?.value)?Bn.error("Invalid metric received",i):this.Rt&&i.value>=this.Rt?Bn.error("Ignoring metric with value >= "+this.Rt,i):(this.N.url!==a&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),H(this.N.url)&&(this.N.url=a),this.N.firstMetricTimestamp=H(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,i.attribution&&i.attribution.interactionTargetElement&&(i.attribution.interactionTargetElement=void 0),this.N.metrics.push(K({},i,{$current_url:a,$session_id:r.sessionId,$window_id:r.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var i,n,r,a,o=ce.__PosthogExtensions__;H(o)||H(o.postHogWebVitalsCallbacks)||({onLCP:i,onCLS:n,onFCP:r,onINP:a}=o.postHogWebVitalsCallbacks),i&&n&&r&&a?(this.allowedMetrics.indexOf("LCP")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&r(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&a(this.It.bind(this)),this.P=!0):Bn.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[Rb]),this.startIfEnabled()}get allowedMetrics(){var e,t,i=Mt(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return H(i)?((t=this._instance.persistence)==null?void 0:t.props[Fb])||["CLS","FCP","INP","LCP"]:i}get flushToCaptureTimeoutMs(){return(Mt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=Mt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e==null||e}get Rt(){var e=Mt(this._instance.config.capture_performance)&&kn(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:Hb;return 0{var r;if(n)Bn.error("failed to load script",n);else{var a=(r=ce.__PosthogExtensions__)==null?void 0:r.loadWebVitalsCallbacks;a&&a(this.useAttribution),e()}})}Ct(){var e=G?G.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,i=this._instance.config.custom_personal_data_properties,n=t?Uo([],zo,i||[]):[];return Kl(e,n,Ql)}Bn.error("Could not determine current URL")}};var YD=ut("[Heatmaps]");function Yb(s){return Mt(s)&&"clientX"in s&&"clientY"in s&&kn(s.clientX)&&kn(s.clientY)}let XD=class{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[Nm]),this.rageclicks=new gS(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return Mt(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return H(this.instance.config.capture_heatmaps)?H(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;YD.info("starting..."),this.Mt(),this.Ot()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Nm]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}Dt(e){this.jt(e.originalEvent,"deadclick")}Ot(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return e?.visibilityState==="visible"}(Y)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Mt(){G&&Y&&(this.Nt=this.Lt.bind(this),_t(G,"beforeunload",this.Nt),this.Ut=e=>this.jt(e||G?.event),_t(Y,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||G?.event),_t(Y,"mousemove",this.zt,{capture:!0}),this.Bt=new vS(this.instance,DD,this.Dt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Ot.bind(this),_t(Y,"visibilitychange",this.qt),this.P=!0)}At(){var e;G&&Y&&(this.Nt&&G.removeEventListener("beforeunload",this.Nt),this.Ut&&Y.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&Y.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&Y.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var i=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),a=function(o,c,l){for(var u=o;u&&Ph(u)&&!nr(u,"body");){if(u===l)return!1;if(we(c,G?.getComputedStyle(u).position))return!0;u=lS(u)}return!1}(oS(e),["fixed","sticky"],r);return{x:e.clientX+(a?0:n),y:e.clientY+(a?0:i),target_fixed:a,type:t}}jt(e,t){var i;if(t===void 0&&(t="click"),!Lb(e.target)&&Yb(e)){var n=this.Gt(e,t);(i=this.rageclicks)!=null&&i.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(K({},n,{type:"rageclick"})),this.Vt(n)}}Ht(e){!Lb(e.target)&&Yb(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(G){var t=G.location.href,i=this.instance.config.mask_personal_data_properties,n=this.instance.config.custom_personal_data_properties,r=i?Uo([],zo,n||[]):[],a=Kl(t,r,Ql);this.N=this.N||{},this.N[a]||(this.N[a]=[]),this.N[a].push(e)}}Lt(){this.N&&!ja(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},Xb=class{constructor(e){this.Jt=(t,i,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength)&&(X.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:n}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var i,n=this.Qt(e,t);return this.Kt={pathname:(i=G?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var i=this.Kt;if(!i)return{$pageview_id:t};var n={$pageview_id:t,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:a,lastScrollY:o,maxScrollY:c,maxContentHeight:l,lastContentY:u,maxContentY:d}=r;if(!(H(a)||H(o)||H(c)||H(l)||H(u)||H(d))){a=Math.ceil(a),o=Math.ceil(o),c=Math.ceil(c),l=Math.ceil(l),u=Math.ceil(u),d=Math.ceil(d);var h=a<=1?1:zs(o/a,0,1,X),f=a<=1?1:zs(c/a,0,1,X),p=l<=1?1:zs(u/l,0,1,X),m=l<=1?1:zs(d/l,0,1,X);n=gt(n,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:c,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:m})}}return i.pathname&&(n.$prev_pageview_pathname=i.pathname),i.timestamp&&(n.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),n}};var yn=function(s){return s.GZipJS="gzip-js",s.Base64="base64",s}({}),ps=Uint8Array,vi=Uint16Array,bo=Uint32Array,uy=new ps([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),dy=new ps([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Kb=new ps([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ES=function(s,e){for(var t=new vi(31),i=0;i<31;++i)t[i]=e+=1<>>1|(21845&je)<<1;Er=(61680&(Er=(52428&Er)>>>2|(13107&Er)<<2))>>>4|(3855&Er)<<4,IS[je]=((65280&Er)>>>8|(255&Er)<<8)>>>1}var Kc=function(s,e,t){for(var i=s.length,n=0,r=new vi(e);n>>15-s[n];return a},ya=new ps(288);for(je=0;je<144;++je)ya[je]=8;for(je=144;je<256;++je)ya[je]=9;for(je=256;je<280;++je)ya[je]=7;for(je=280;je<288;++je)ya[je]=8;var Vd=new ps(32);for(je=0;je<32;++je)Vd[je]=5;var QD=Kc(ya,9),JD=Kc(Vd,5),PS=function(s){return(s/8>>0)+(7&s&&1)},RS=function(s,e,t){(t==null||t>s.length)&&(t=s.length);var i=new(s instanceof vi?vi:s instanceof bo?bo:ps)(t-e);return i.set(s.subarray(e,t)),i},an=function(s,e,t){t<<=7&e;var i=e/8>>0;s[i]|=t,s[i+1]|=t>>>8},pc=function(s,e,t){t<<=7&e;var i=e/8>>0;s[i]|=t,s[i+1]|=t>>>8,s[i+2]|=t>>>16},Mf=function(s,e){for(var t=[],i=0;ih&&(h=r[i].s);var f=new vi(h+1),p=Qm(t[u-1],f,0);if(p>e){i=0;var m=0,g=p-e,v=1<e))break;m+=v-(1<>>=g;m>0;){var b=r[i].s;f[b]=0&&m;--i){var k=r[i].s;f[k]==e&&(--f[k],++m)}p=e}return[new ps(f),p]},Qm=function(s,e,t){return s.s==-1?Math.max(Qm(s.l,e,t+1),Qm(s.r,e,t+1)):e[s.s]=t},Jb=function(s){for(var e=s.length;e&&!s[--e];);for(var t=new vi(++e),i=0,n=s[0],r=1,a=function(c){t[i++]=c},o=1;o<=e;++o)if(s[o]==n&&o!=e)++r;else{if(!n&&r>2){for(;r>138;r-=138)a(32754);r>2&&(a(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(a(n),--r;r>6;r-=6)a(8304);r>2&&(a(r-3<<5|8208),r=0)}for(;r--;)a(n);r=1,n=s[o]}return[t.subarray(0,i),e]},mc=function(s,e){for(var t=0,i=0;i>>8,s[n+2]=255^s[n],s[n+3]=255^s[n+1];for(var r=0;r4&&!B[Kb[V-1]];--V);var y,_,T,S,C=l+5<<3,E=mc(n,ya)+mc(r,Vd)+a,P=mc(n,h)+mc(r,m)+a+14+3*V+mc(R,B)+(2*R[16]+3*R[17]+7*R[18]);if(C<=E&&C<=P)return Jm(e,u,s.subarray(c,c+l));if(an(e,u,1+(P15&&(an(e,u,j[I]>>>5&127),u+=j[I]>>>12)}}}else y=QD,_=ya,T=JD,S=Vd;for(I=0;I255){N=i[I]>>>18&31,pc(e,u,y[N+257]),u+=_[N+257],N>7&&(an(e,u,i[I]>>>23&31),u+=uy[N]);var z=31&i[I];pc(e,u,T[z]),u+=S[z],z>3&&(pc(e,u,i[I]>>>5&8191),u+=dy[z])}else pc(e,u,y[i[I]]),u+=_[i[I]];return pc(e,u,y[256]),u+_[256]},ZD=new bo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),eF=function(){for(var s=new bo(256),e=0;e<256;++e){for(var t=e,i=9;--i;)t=(1&t&&3988292384)^t>>>1;s[e]=t}return s}(),tF=function(s,e,t,i,n){return function(r,a,o,c,l,u){var d=r.length,h=new ps(c+d+5*(1+Math.floor(d/7e3))+l),f=h.subarray(c,h.length-l),p=0;if(!a||d<8)for(var m=0;m<=d;m+=65535){var g=m+65535;g>>13,b=8191&v,k=(1<7e3||T>24576)&&O>423){p=Zb(r,f,0,B,$,V,_,T,C,m-C,p),T=y=_=0,C=m;for(var U=0;U<286;++U)$[U]=0;for(U=0;U<30;++U)V[U]=0}var j=2,N=0,z=b,W=P-L&32767;if(O>2&&E==D(m-W))for(var Q=Math.min(w,O)-1,fe=Math.min(32767,m),ye=Math.min(258,O);W<=fe&&--z&&P!=L;){if(r[m+j]==r[m+j-W]){for(var le=0;lej){if(j=le,N=W,le>Q)break;var Le=Math.min(W,le-2),Oe=0;for(U=0;UOe&&(Oe=dt,L=jt)}}}W+=(P=L)-(L=A[P])+32768&32767}if(N){B[T++]=268435456|Km[j]<<18|Qb[N];var ht=31&Km[j],Si=31&Qb[N];_+=uy[ht]+dy[Si],++$[257+ht],++V[Si],S=m+j,++y}else B[T++]=r[m],++$[r[m]]}}p=Zb(r,f,u,B,$,V,_,T,C,m-C,p)}return RS(h,0,c+PS(p)+l)}(s,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+e.mem,t,i,!0)},If=function(s,e,t){for(;t;++e)s[e]=t,t>>>=8};function iF(s,e){e===void 0&&(e={});var t=function(){var o=4294967295;return{p:function(c){for(var l=o,u=0;u>>8;o=l},d:function(){return 4294967295^o}}}(),i=s.length;t.p(s);var n,r=tF(s,e,10+((n=e).filename&&n.filename.length+1||0),8),a=r.length;return function(o,c){var l=c.filename;if(o[0]=31,o[1]=139,o[2]=8,o[8]=c.level<2?4:c.level==9?2:0,o[9]=3,c.mtime!=0&&If(o,4,Math.floor(new Date(c.mtime||Date.now())/1e3)),l){o[3]=8;for(var u=0;u<=l.length;++u)o[u+10]=l.charCodeAt(u)}}(r,e),If(r,a-8,t.d()),If(r,a-4,i),r}var sF=function(s){var e,t,i,n,r="";for(e=t=0,i=(s=(s+"").replace(/\r\n/g,` +`).replace(/\r/g,` +`)).length,n=0;n127&&a<2048?String.fromCharCode(a>>6|192,63&a|128):String.fromCharCode(a>>12|224,a>>6&63|128,63&a|128),Is(o)||(t>e&&(r+=s.substring(e,t)),r+=o,e=t=n+1)}return t>e&&(r+=s.substring(e,s.length)),r},nF=!!Rm||!!Pm,ex="text/plain",Ud=function(s,e,t){var i;t===void 0&&(t=!0);var[n,r]=s.split("?"),a=K({},e),o=(i=r?.split("&").map(l=>{var u,[d,h]=l.split("="),f=t&&(u=a[d])!==null&&u!==void 0?u:h;return delete a[d],d+"="+f}))!==null&&i!==void 0?i:[],c=bD(a);return c&&o.push(c),n+"?"+o.join("&")},Oc=(s,e)=>JSON.stringify(s,(t,i)=>typeof i=="bigint"?i.toString():i,e),Pf=s=>{var{data:e,compression:t}=s;if(e){if(t===yn.GZipJS){var i=iF(function(c,l){var u=c.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(c);for(var d=new ps(c.length+(c.length>>>1)),h=0,f=function(v){d[h++]=v},p=0;pd.length){var m=new ps(h+8+(u-p<<1));m.set(d),d=m}var g=c.charCodeAt(p);g<128||l?f(g):g<2048?(f(192|g>>>6),f(128|63&g)):g>55295&&g<57344?(f(240|(g=65536+(1047552&g)|1023&c.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return RS(d,0,h)}(Oc(e)),{mtime:0}),n=new Blob([i],{type:ex});return{contentType:ex,body:n,estimatedSize:n.size}}if(t===yn.Base64){var r=function(c){var l,u,d,h,f,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",m=0,g=0,v="",w=[];if(!c)return c;c=sF(c);do l=(f=c.charCodeAt(m++)<<16|c.charCodeAt(m++)<<8|c.charCodeAt(m++))>>18&63,u=f>>12&63,d=f>>6&63,h=63&f,w[g++]=p.charAt(l)+p.charAt(u)+p.charAt(d)+p.charAt(h);while(m"data="+encodeURIComponent(typeof c=="string"?c:Oc(c)))(r);return{contentType:"application/x-www-form-urlencoded",body:a,estimatedSize:new Blob([a]).size}}var o=Oc(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},cd=[];Pm&&cd.push({transport:"fetch",method:s=>{var e,t,{contentType:i,body:n,estimatedSize:r}=(e=Pf(s))!==null&&e!==void 0?e:{},a=new Headers;Be(s.headers,function(u,d){a.append(d,u)}),i&&a.append("Content-Type",i);var o=s.url,c=null;if(vb){var l=new vb;c={signal:l.signal,timeout:setTimeout(()=>l.abort(),s.timeout)}}Pm(o,K({method:s?.method||"GET",headers:a,keepalive:s.method==="POST"&&(r||0)<52428.8,body:n,signal:(t=c)==null?void 0:t.signal},s.fetchOptions)).then(u=>u.text().then(d=>{var h={statusCode:u.status,text:d};if(u.status===200)try{h.json=JSON.parse(d)}catch(f){X.error(f)}s.callback==null||s.callback(h)})).catch(u=>{X.error(u),s.callback==null||s.callback({statusCode:0,text:u})}).finally(()=>c?clearTimeout(c.timeout):null)}}),Rm&&cd.push({transport:"XHR",method:s=>{var e,t=new Rm;t.open(s.method||"GET",s.url,!0);var{contentType:i,body:n}=(e=Pf(s))!==null&&e!==void 0?e:{};Be(s.headers,function(r,a){t.setRequestHeader(a,r)}),i&&t.setRequestHeader("Content-Type",i),s.timeout&&(t.timeout=s.timeout),s.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var r={statusCode:t.status,text:t.responseText};if(t.status===200)try{r.json=JSON.parse(t.responseText)}catch{}s.callback==null||s.callback(r)}},t.send(n)}}),Li!=null&&Li.sendBeacon&&cd.push({transport:"sendBeacon",method:s=>{var e=Ud(s.url,{beacon:"1"});try{var t,{contentType:i,body:n}=(t=Pf(s))!==null&&t!==void 0?t:{},r=typeof n=="string"?new Blob([n],{type:i}):n;Li.sendBeacon(e,r)}catch{}}});var zd=function(s,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(s)}catch{return!1}};function tx(s,e,t){return Oc({distinct_id:s,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var DS={exact:(s,e)=>e.some(t=>s.some(i=>t===i)),is_not:(s,e)=>e.every(t=>s.every(i=>t!==i)),regex:(s,e)=>e.some(t=>s.some(i=>zd(t,i))),not_regex:(s,e)=>e.every(t=>s.every(i=>!zd(t,i))),icontains:(s,e)=>e.map(Au).some(t=>s.map(Au).some(i=>t.includes(i))),not_icontains:(s,e)=>e.map(Au).every(t=>s.map(Au).every(i=>!t.includes(i))),gt:(s,e)=>e.some(t=>{var i=parseFloat(t);return!isNaN(i)&&s.some(n=>i>parseFloat(n))}),lt:(s,e)=>e.some(t=>{var i=parseFloat(t);return!isNaN(i)&&s.some(n=>is.toLowerCase();function FS(s,e){return!s||Object.entries(s).every(t=>{var[i,n]=t,r=e?.[i];if(H(r)||Is(r))return!1;var a=[String(r)],o=DS[n.operator];return!!o&&o(n.values,a)})}var Rf=ut("[Error tracking]");let rF=class{constructor(e){var t,i;this.Zt=[],this.ti=new jR([new YR,new sD,new KR,new XR,new tD,new eD,new JR,new iD],HR()),this._instance=e,this.Zt=(t=(i=this._instance.persistence)==null?void 0:i.get_property(Vm))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,i,n,r=(t=(i=e.errorTracking)==null?void 0:i.suppressionRules)!==null&&t!==void 0?t:[],a=(n=e.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Zt=r,this._instance.persistence&&this._instance.persistence.register({[Vm]:this.Zt,[Pb]:a})}get ii(){var e,t=!!this._instance.get_property(Pb),i=this._instance.config.error_tracking.captureExtensionExceptions;return(e=i??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void Rf.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void Rf.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void Rf.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var t=e.reduce((i,n)=>{var{type:r,value:a}=n;return It(r)&&r.length>0&&i.$exception_types.push(r),It(a)&&a.length>0&&i.$exception_values.push(a),i},{$exception_types:[],$exception_values:[]});return this.Zt.some(i=>{var n=i.values.map(r=>{var a,o=DS[r.operator],c=Me(r.value)?r.value:[r.value],l=(a=t[r.key])!==null&&a!==void 0?a:[];return c.length>0&&o(c,l)});return i.type==="OR"?n.some(Boolean):n.every(Boolean)})}si(e){return e.flatMap(t=>{var i,n;return(i=(n=t.stacktrace)==null?void 0:n.frames)!==null&&i!==void 0?i:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,i,n,r,a=(t=(i=e[0].stacktrace)==null?void 0:i.frames)!==null&&t!==void 0?t:[],o=a[a.length-1];return(n=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}ei(e){return!Ce(e)&&Me(e)}};var ts=ut("[FeatureFlags]"),gc=ut("[FeatureFlags]",{debugEnabled:!0}),Df="$active_feature_flags",Sa="$override_feature_flags",ix="$feature_flag_payloads",yc="$override_feature_flag_payloads",sx="$feature_flag_request_id",nx="$feature_flag_evaluated_at",rx=s=>{var e={};for(var[t,i]of od(s||{}))i&&(e[t]=i);return e},aF=s=>{var e=s.flags;return e?(s.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var i;return[t,(i=e[t].variant)!==null&&i!==void 0?i:e[t].enabled]})),s.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var i;return(i=e[t].metadata)==null?void 0:i.payload}).map(t=>{var i;return[t,(i=e[t].metadata)==null?void 0:i.payload]}))):ts.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),s},oF=function(s){return s.FeatureFlags="feature_flags",s.Recordings="recordings",s}({});let cF=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(ts.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(i=>{var n=i&&typeof i=="string"&&i.trim().length>0;return n||ts.error("Invalid evaluation context found:",i,"Expected non-empty string"),n}):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Um),t=this._instance.get_property(Sa),i=this._instance.get_property(yc);if(!i&&!t)return e||{};var n=gt({},e||{}),r=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(var a of r){var o,c,l=n[a],u=t?.[a],d=H(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,h=H(u)?l.variant:typeof u=="string"?u:void 0,f=i?.[a],p=K({},l,{enabled:d,variant:d?h??l?.variant:void 0});d!==l?.enabled&&(p.original_enabled=l?.enabled),h!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=K({},l?.metadata,{payload:f,original_payload:l==null||(c=l.metadata)==null?void 0:c.payload})),n[a]=p}return this.oi||(ts.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:n}),this.oi=!0),n}getFlagVariants(){var e=this._instance.get_property(Na),t=this._instance.get_property(Sa);if(!t)return e||{};for(var i=gt({},e),n=Object.keys(t),r=0;r{this.mi()},5))}yi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.yi(),!this._instance.O())if(this.li)this.hi=!0;else{var i=this._instance.config.token,n=this._instance.get_property("$device_id"),r={token:i,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:K({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(Lc)||{}),group_properties:this._instance.get_property($r)};Is(n)||H(n)||(r.$device_id=n),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0),this.pi()&&(r.evaluation_contexts=this.fi());var a=this._instance.config.__preview_remote_config,o=a?"/flags/?v=2":"/flags/?v=2&config=true",c=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",l=this._instance.requestRouter.endpointFor("flags",o+c);a&&(r.timezone=CS()),this.li=!0,this._instance._send_request({method:"POST",url:l,data:r,compression:this._instance.config.disable_compression?void 0:yn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:u=>{var d,h,f=!0;if(u.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),f=!1),this.li=!1,this.di||(this.di=!0,this._instance.bi((h=u.json)!==null&&h!==void 0?h:{})),!r.disable_flags||this.hi)if(this.vi=!f,u.json&&(d=u.json.quotaLimited)!=null&&d.includes(oF.FeatureFlags))ts.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var p;r.disable_flags||this.receivedFeatureFlags((p=u.json)!==null&&p!==void 0?p:{},f),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFlagVariants()[e],n=""+i,r=this._instance.get_property(sx)||void 0,a=this._instance.get_property(nx)||void 0,o=this._instance.get_property(Fd)||{};if((t.send_event||!("send_event"in t))&&(!(e in o)||!o[e].includes(n))){var c,l,u,d,h,f,p,m,g;Me(o[e])?o[e].push(n):o[e]=[n],(c=this._instance.persistence)==null||c.register({[Fd]:o});var v=this.getFeatureFlagDetails(e),w={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:r,$feature_flag_evaluated_at:a,$feature_flag_bootstrapped_response:((l=this._instance.config.bootstrap)==null||(l=l.featureFlags)==null?void 0:l[e])||null,$feature_flag_bootstrapped_payload:((u=this._instance.config.bootstrap)==null||(u=u.featureFlagPayloads)==null?void 0:u[e])||null,$used_bootstrap_value:!this.vi};H(v==null||(d=v.metadata)==null?void 0:d.version)||(w.$feature_flag_version=v.metadata.version);var b,k=(h=v==null||(f=v.reason)==null?void 0:f.description)!==null&&h!==void 0?h:v==null||(p=v.reason)==null?void 0:p.code;k&&(w.$feature_flag_reason=k),v!=null&&(m=v.metadata)!=null&&m.id&&(w.$feature_flag_id=v.metadata.id),H(v?.original_variant)&&H(v?.original_enabled)||(w.$feature_flag_original_response=H(v.original_variant)?v.original_enabled:v.original_variant),v!=null&&(g=v.metadata)!=null&&g.original_payload&&(w.$feature_flag_original_payload=v==null||(b=v.metadata)==null?void 0:b.original_payload),this._instance.capture("$feature_flag_called",w)}return i}ts.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,t){var i=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:i};this.pi()&&(n.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:yn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:r=>{var a,o=(a=r.json)==null?void 0:a.featureFlagPayloads;t(o?.[e]||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlag(e,t);return H(i)?void 0:!!i}ts.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var i=this.getFlagVariants(),n=this.getFlagPayloads(),r=this.getFlagsWithDetails();(function(a,o,c,l,u){c===void 0&&(c={}),l===void 0&&(l={}),u===void 0&&(u={});var d=aF(a),h=d.flags,f=d.featureFlags,p=d.featureFlagPayloads;if(f){var m=a.requestId,g=a.evaluatedAt;if(Me(f)){ts.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var v={};if(f)for(var w=0;wthis.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,i){var n,r=(this._instance.get_property(Fc)||[]).find(l=>l.flagKey===e),a={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:a};r&&(o.$early_access_feature_name=r.name),i&&(o.$feature_enrollment_stage=i),this._instance.capture("$feature_enrollment_update",o),this.setPersonPropertiesForFlags(a,!1);var c=K({},this.getFlagVariants(),{[e]:t});(n=this._instance.persistence)==null||n.register({[Df]:Object.keys(rx(c)),[Na]:c}),this.wi()}getEarlyAccessFeatures(e,t,i){t===void 0&&(t=!1);var n=this._instance.get_property(Fc),r=i?"&"+i.map(a=>"stage="+a).join("&"):"";if(n&&!t)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+r),method:"GET",callback:a=>{var o,c;if(a.json){var l=a.json.earlyAccessFeatures;return(o=this._instance.persistence)==null||o.unregister(Fc),(c=this._instance.persistence)==null||c.register({[Fc]:l}),e(l)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(i=>t[i]),flagVariants:Object.keys(t).filter(i=>t[i]).reduce((i,n)=>(i[n]=t[n],i),{})}}wi(e){var{flags:t,flagVariants:i}=this.xi();this.featureFlagEventHandlers.forEach(n=>n(t,i,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var i=this._instance.get_property(Lc)||{};this._instance.register({[Lc]:K({},i,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Lc)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var i=this._instance.get_property($r)||{};Object.keys(i).length!==0&&Object.keys(i).forEach(n=>{i[n]=K({},i[n],e[n]),delete e[n]}),this._instance.register({[$r]:K({},i,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property($r)||{};this._instance.register({[$r]:K({},t,{[e]:{}})})}else this._instance.unregister($r)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.yi(),this.oi=!1}};var lF=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];let Ff=class{constructor(e,t){this.R=e,this.props={},this.Ei=!1,this.$i=(i=>{var n="";return i.token&&(n=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+n+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&X.info("Persistence loaded",e.persistence,K({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){lF.indexOf(e.persistence.toLowerCase())===-1&&(X.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(n){n===void 0&&(n=[]);var r=[...ID,...n];return K({},Xe,{W:function(a){try{var o={};try{o=js.W(a)||{}}catch{}var c=gt(o,JSON.parse(Xe.q(a)||"{}"));return Xe.G(a,c),c}catch{}return null},G:function(a,o,c,l,u,d){try{Xe.G(a,o,void 0,void 0,d);var h={};r.forEach(f=>{o[f]&&(h[f]=o[f])}),Object.keys(h).length&&js.G(a,h,c,l,u,d)}catch(f){Xe.B(f)}},V:function(a,o){try{G?.localStorage.removeItem(a),js.V(a,o)}catch(c){Xe.B(c)}}})}(e.cookie_persisted_properties||[]),i=e.persistence.toLowerCase();return i==="localstorage"&&Xe.H()?Xe:i==="localstorage+cookie"&&t.H()?t:i==="sessionstorage"&&zt.H()?zt:i==="memory"?PD:i==="cookie"?js:t.H()?t:js}properties(){var e={};return Be(this.props,function(t,i){if(i===Na&&Mt(t))for(var n=Object.keys(t),r=0;r{this.props.hasOwnProperty(a)&&this.props[a]!==t||(this.props[a]=r,n=!0)}),n)return this.save(),!0}return!1}register(e,t){if(Mt(e)){this.Pi=H(t)?this.Ci:t;var i=!1;if(Be(e,(n,r)=>{e.hasOwnProperty(r)&&this.props[r]!==n&&(this.props[r]=n,i=!0)}),i)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=wS(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);ja(ay(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=Y?.referrer)?TS(e):{})}update_referrer_info(){var e;this.register_once({$referrer:kS(),$referring_domain:Y!=null&&Y.referrer&&((e=$d(Y.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[qm]||this.props[Hm]||this.register_once({[Ld]:AS(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Be([Hm,qm],a=>{var o=this.props[a];o&&Be(o,function(c,l){e["$initial_"+Dm(l)]=c})});var t,i,n=this.props[Ld];if(n){var r=(t=SS(n),i={},Be(t,function(a,o){i["$initial_"+Dm(o)]=a}),i);gt(e,r)}return e}safe_merge(e){return Be(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,i){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((a,o)=>{if(a.length!==o.length)return!1;var c=[...a].sort(),l=[...o].sort();return c.every((u,d)=>u===l[d])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var n=this.Si(e),r=this.props;this.clear(),this.Y=n,this.props=r,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var i=this.props[Dc]||{};i[e]=t,this.props[Dc]=i,this.save()}remove_event_timer(e){var t=(this.props[Dc]||{})[e];return H(t)||(delete this.props[Dc][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}};var ax=ut("[Product Tours]"),Lf="ph_product_tours";let uF=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[Db]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Db)||this.it(()=>this.Mi())}it(e){var t,i;(t=ce.__PosthogExtensions__)!=null&&t.generateProductTours?e():(i=ce.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"product-tours",n=>{n?ax.error("Could not load product tours script",n):e()})}Mi(){var e;!this.Ri&&(e=ce.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=ce.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!Me(this.Fi)||t){var i=this._instance.persistence;if(i){var n=i.props[Lf];if(Me(n)&&!t)return this.Fi=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:r=>{var a=r.statusCode;if(a!==200||!r.json){var o="Product Tours API could not be loaded, status: "+a;return ax.error(o),void e([],{isLoaded:!1,error:o})}var c=Me(r.json.product_tours)?r.json.product_tours:[];this.Fi=c,i&&i.register({[Lf]:c}),e(c,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){Ce(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Mi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(Lf)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}};var vc=function(s){return s.Activation="events",s.Cancellation="cancelEvents",s}({});(function(s){return s.Button="button",s.Tab="tab",s.Selector="selector",s})({});(function(s){return s.TopLeft="top_left",s.TopRight="top_right",s.TopCenter="top_center",s.MiddleLeft="middle_left",s.MiddleRight="middle_right",s.MiddleCenter="middle_center",s.Left="left",s.Center="center",s.Right="right",s.NextToTrigger="next_to_trigger",s})({});(function(s){return s.Top="top",s.Left="left",s.Right="right",s.Bottom="bottom",s})({});var Of=function(s){return s.Popover="popover",s.API="api",s.Widget="widget",s.ExternalSurvey="external_survey",s}({});(function(s){return s.Open="open",s.MultipleChoice="multiple_choice",s.SingleChoice="single_choice",s.Rating="rating",s.Link="link",s})({});(function(s){return s.NextQuestion="next_question",s.End="end",s.ResponseBased="response_based",s.SpecificQuestion="specific_question",s})({});(function(s){return s.Once="once",s.Recurring="recurring",s.Always="always",s})({});var Bc=function(s){return s.SHOWN="survey shown",s.DISMISSED="survey dismissed",s.SENT="survey sent",s.ABANDONED="survey abandoned",s}({}),Bf=function(s){return s.SURVEY_ID="$survey_id",s.SURVEY_NAME="$survey_name",s.SURVEY_RESPONSE="$survey_response",s.SURVEY_ITERATION="$survey_iteration",s.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",s.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",s.SURVEY_SUBMISSION_ID="$survey_submission_id",s.SURVEY_QUESTIONS="$survey_questions",s.SURVEY_COMPLETED="$survey_completed",s.PRODUCT_TOUR_ID="$product_tour_id",s.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",s}({}),Zm=function(s){return s.Popover="popover",s.Inline="inline",s}({}),Pe=ut("[Surveys]"),LS="seenSurvey_",dF=(s,e)=>{var t="$survey_"+e+"/"+s.id;return s.current_iteration&&s.current_iteration>0&&(t="$survey_"+e+"/"+s.id+"/"+s.current_iteration),t},ox=s=>((e,t)=>{var i=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(i=""+e+t.id+"_"+t.current_iteration),i})(LS,s),hF=[Of.Popover,Of.Widget,Of.API],fF={ignoreConditions:!1,ignoreDelay:!1,displayType:Zm.Popover};let hy=class{constructor(){this.Oi={},this.Oi={}}on(e,t){return this.Oi[e]||(this.Oi[e]=[]),this.Oi[e].push(t),()=>{this.Oi[e]=this.Oi[e].filter(i=>i!==t)}}emit(e,t){for(var i of this.Oi[e]||[])i(t);for(var n of this.Oi["*"]||[])n(e,t)}};function Ca(s,e,t){if(Ce(s))return!1;switch(t){case"exact":return s===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(s);case"regex":try{return new RegExp(e).test(s)}catch{return!1}default:return!1}}let pF=class{constructor(e){this.Ai=new hy,this.Di=(t,i)=>this.ji(t,i)&&this.Li(t,i)&&this.Ni(t,i)&&this.Ui(t,i),this.ji=(t,i)=>i==null||!i.event||t?.event===i?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!H((e=this._instance)==null?void 0:e.Bi)){var t;(t=this._instance)==null||t.Bi((i,n)=>{this.on(i,n)})}}register(e){var t,i;if(!H((t=this._instance)==null?void 0:t.Bi)&&(e.forEach(a=>{var o,c;(o=this.Hi)==null||o.add(a),(c=a.steps)==null||c.forEach(l=>{var u;(u=this.zi)==null||u.add(l?.event||"")})}),(i=this._instance)!=null&&i.autocapture)){var n,r=new Set;e.forEach(a=>{var o;(o=a.steps)==null||o.forEach(c=>{c!=null&&c.selector&&r.add(c?.selector)})}),(n=this._instance)==null||n.autocapture.setElementSelectors(r)}}on(e,t){var i;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t?.event))&&this.Hi&&((i=this.Hi)==null?void 0:i.size)>0&&this.Hi.forEach(n=>{this.qi(t,n)&&this.Ai.emit("actionCaptured",n.name)})}Wi(e){this.onAction("actionCaptured",t=>e(t))}qi(e,t){if(t?.steps==null)return!1;for(var i of t.steps)if(this.Di(e,i))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var i,n=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!n||typeof n!="string"||!Ca(n,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Gi(e,t)&&!!this.Vi(e,t)&&!!this.Ji(e,t)}Gi(e,t){var i;if(t==null||!t.href)return!0;var n=this.Ki(e);if(n.length>0)return n.some(o=>Ca(o.href,t.href,t.href_matching||"exact"));var r,a=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!a&&Ca((r=a.match(/(?::|")href="(.*?)"/))?r[1]:"",t.href,t.href_matching||"exact")}Vi(e,t){var i;if(t==null||!t.text)return!0;var n=this.Ki(e);if(n.length>0)return n.some(l=>Ca(l.text,t.text,t.text_matching||"exact")||Ca(l.$el_text,t.text,t.text_matching||"exact"));var r,a,o,c=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!c&&(r=function(l){for(var u,d=[],h=/(?::|")text="(.*?)"/g;!Ce(u=h.exec(l));)d.includes(u[1])||d.push(u[1]);return d}(c),a=t.text,o=t.text_matching||"exact",r.some(l=>Ca(l,a,o)))}Ji(e,t){var i,n;if(t==null||!t.selector)return!0;var r=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(r!=null&&r.includes(t.selector))return!0;var a=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(t.selector_regex&&a)try{return new RegExp(t.selector_regex).test(a)}catch{return!1}return!1}Ki(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e?.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||FS(t.properties.reduce((i,n)=>{var r=Me(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return i[n.key]={values:r,operator:n.operator||"exact"},i},{}),e?.properties)}},mF=class{constructor(e){this._instance=e,this.Yi=new Map,this.Xi=new Map,this.Qi=new Map}Zi(e,t){return!!e&&FS(e.propertyFilters,t?.properties)}te(e,t){var i=new Map;return e.forEach(n=>{var r;(r=n.conditions)==null||(r=r[t])==null||(r=r.values)==null||r.forEach(a=>{if(a!=null&&a.name){var o=i.get(a.name)||[];o.push(n.id),i.set(a.name,o)}})}),i}ie(e,t,i){var n=(i===vc.Activation?this.Yi:this.Xi).get(e),r=[];return this.ee(a=>{r=a.filter(o=>n?.includes(o.id))}),r.filter(a=>{var o,c=(o=a.conditions)==null||(o=o[i])==null||(o=o.values)==null?void 0:o.find(l=>l.name===e);return this.Zi(c,t)})}register(e){var t;H((t=this._instance)==null?void 0:t.Bi)||(this.re(e),this.se(e))}se(e){var t=e.filter(i=>{var n,r;return((n=i.conditions)==null?void 0:n.actions)&&((r=i.conditions)==null||(r=r.actions)==null||(r=r.values)==null?void 0:r.length)>0});t.length!==0&&(this.ne==null&&(this.ne=new pF(this._instance),this.ne.init(),this.ne.Wi(i=>{this.onAction(i)})),t.forEach(i=>{var n,r,a,o,c;i.conditions&&(n=i.conditions)!=null&&n.actions&&(r=i.conditions)!=null&&(r=r.actions)!=null&&r.values&&((a=i.conditions)==null||(a=a.actions)==null||(a=a.values)==null?void 0:a.length)>0&&((o=this.ne)==null||o.register(i.conditions.actions.values),(c=i.conditions)==null||(c=c.actions)==null||(c=c.values)==null||c.forEach(l=>{if(l&&l.name){var u=this.Qi.get(l.name);u&&u.push(i.id),this.Qi.set(l.name,u||[i.id])}}))}))}re(e){var t,i=e.filter(r=>{var a,o;return((a=r.conditions)==null?void 0:a.events)&&((o=r.conditions)==null||(o=o.events)==null||(o=o.values)==null?void 0:o.length)>0}),n=e.filter(r=>{var a,o;return((a=r.conditions)==null?void 0:a.cancelEvents)&&((o=r.conditions)==null||(o=o.cancelEvents)==null||(o=o.values)==null?void 0:o.length)>0});(i.length!==0||n.length!==0)&&((t=this._instance)==null||t.Bi((r,a)=>{this.onEvent(r,a)}),this.Yi=this.te(e,vc.Activation),this.Xi=this.te(e,vc.Cancellation))}onEvent(e,t){var i,n=this.oe(),r=this.ae(),a=this.le(),o=((i=this._instance)==null||(i=i.persistence)==null?void 0:i.props[r])||[];if(a===e&&t&&o.length>0){var c,l;n.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:o});var u=(t==null||(c=t.properties)==null?void 0:c.$survey_id)||(t==null||(l=t.properties)==null?void 0:l.$product_tour_id);if(u){var d=o.indexOf(u);d>=0&&(o.splice(d,1),this.ue(o))}}else{if(this.Xi.has(e)){var h=this.ie(e,t,vc.Cancellation);h.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:h.map(p=>p.id)}),h.forEach(p=>{var m=o.indexOf(p.id);m>=0&&o.splice(m,1),this.he(p.id)}),this.ue(o))}if(this.Yi.has(e)){n.info("event name matched",{event:e,eventPayload:t,items:this.Yi.get(e)});var f=this.ie(e,t,vc.Activation);this.ue(o.concat(f.map(p=>p.id)||[]))}}}onAction(e){var t,i=this.ae(),n=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[i])||[];this.Qi.has(e)&&this.ue(n.concat(this.Qi.get(e)||[]))}ue(e){var t,i=this.oe(),n=this.ae(),r=[...new Set(e)].filter(a=>!this.de(a));i.info("updating activated items",{activatedItems:r}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[n]:r})}getActivatedIds(){var e,t=this.ae(),i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return i||[]}getEventToItemsMap(){return this.Yi}ve(){return this.ne}},gF=class extends mF{constructor(e){super(e)}ae(){return"$surveys_activated"}le(){return Bc.SHOWN}ee(e){var t;(t=this._instance)==null||t.getSurveys(e)}he(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}oe(){return Pe}de(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},yF=class{constructor(e){this.ce=void 0,this._surveyManager=null,this.fe=!1,this.pe=[],this.ge=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(Ce(t))return Pe.warn("Flags not loaded yet. Not loading surveys.");var i=Me(t);this.ce=i?t.length>0:t,Pe.info("flags response received, isSurveysEnabled: "+this.ce),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;tlocalStorage.removeItem(n))}loadIfEnabled(){if(!this._surveyManager)if(this.fe)Pe.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Pe.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Pe.info("Not loading surveys in cookieless mode without consent.");else{var e=ce?.__PosthogExtensions__;if(e){if(!H(this.ce)||this._instance.config.advanced_enable_surveys){var t=this.ce||this._instance.config.advanced_enable_surveys;this.fe=!0;try{var i=e.generateSurveys;if(i)return void this._e(i,t);var n=e.loadExternalDependency;if(!n)return void this.me("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",r=>{r||!e.generateSurveys?this.me("Could not load surveys script",r):this._e(e.generateSurveys,t)})}catch(r){throw this.me("Error initializing surveys",r),r}finally{this.fe=!1}}}else Pe.error("PostHog Extensions not found.")}}_e(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new gF(this._instance),Pe.info("Surveys loaded successfully"),this.ye({isLoaded:!0})}me(e,t){Pe.error(e,t),this.ye({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.pe.push(e),this._surveyManager&&this.ye({isLoaded:!0}),()=>{this.pe=this.pe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return Pe.info("Disabled. Not loading surveys."),e([]);var i,n=this._instance.get_property(zm);if(n&&!t)return e(n,{isLoaded:!0});typeof Promise<"u"&&this.ge?this.ge.then(r=>{var{surveys:a,context:o}=r;return e(a,o)}):(typeof Promise<"u"&&(this.ge=new Promise(r=>{i=r})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:r=>{var a;this.ge=null;var o=r.statusCode;if(o!==200||!r.json){var c="Surveys API could not be loaded, status: "+o;Pe.error(c);var l={isLoaded:!1,error:c};return e([],l),void(i==null||i({surveys:[],context:l}))}var u,d=r.json.surveys||[],h=d.filter(p=>function(m){return!(!m.start_date||m.end_date)}(p)&&(function(m){var g;return!((g=m.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)}(p)||function(m){var g;return!((g=m.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)}(p)));h.length>0&&((u=this._surveyEventReceiver)==null||u.register(h)),(a=this._instance.persistence)==null||a.register({[zm]:d});var f={isLoaded:!0};e(d,f),i?.({surveys:d,context:f})}}))}ye(e){for(var t of this.pe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(i){Pe.error("Error in survey callback",i)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!Ce(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Pe.warn("init was not called")}be(e){var t=null;return this.getSurveys(i=>{var n;t=(n=i.find(r=>r.id===e))!==null&&n!==void 0?n:null}),t}we(e){if(Ce(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ce(this._surveyManager))return Pe.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.we(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return Ce(this._surveyManager)?(Pe.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(i=>{this.getSurveys(n=>{var r,a=(r=n.find(c=>c.id===e))!==null&&r!==void 0?r:null;if(a){var o=this.we(a);i({visible:o.eligible,disabledReason:o.reason})}else i({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,i){var n;if(Ce(this._surveyManager))Pe.warn("init was not called");else{var r=typeof e=="string"?this.be(e):e;if(r!=null&&r.id)if(hF.includes(r.type)){var a=Y?.querySelector(t);if(a)return(n=r.appearance)!=null&&n.surveyPopupDelaySeconds?(Pe.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,c;Pe.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(c=this._surveyManager)==null||c.renderSurvey(r,a,i),Pe.info("Survey "+r.id+" rendered")},1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,a,i);Pe.warn("Survey element not found")}else Pe.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Pe.warn("Survey not found")}}displaySurvey(e,t){var i;if(Ce(this._surveyManager))Pe.warn("init was not called");else{var n=this.be(e);if(n){var r=n;if((i=n.appearance)!=null&&i.surveyPopupDelaySeconds&&t.ignoreDelay&&(r=K({},n,{appearance:K({},n.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Zm.Popover&&t.initialResponses&&Pe.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var a=this.canRenderSurvey(n);if(!a.visible)return void Pe.warn("Survey is not eligible to be displayed: ",a.disabledReason)}t.displayType!==Zm.Inline?this._surveyManager.handlePopoverSurvey(r,t):this.renderSurvey(r,t.selector,t.properties)}else Pe.warn("Survey not found")}}cancelPendingSurvey(e){Ce(this._surveyManager)?Pe.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}};var on=ut("[Conversations]");let vF=class{constructor(e){this.xe=void 0,this._conversationsManager=null,this.Ee=!1,this.$e=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;Ce(t)||(_n(t)?this.xe=t:(this.xe=t.enabled,this.$e=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.xe=void 0,this.$e=null}loadIfEnabled(){if(!this._conversationsManager&&!this.Ee&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=ce?.__PosthogExtensions__;if(e&&!H(this.xe)&&this.xe)if(this.$e&&this.$e.token){this.Ee=!0;try{var t=e.initConversations;if(t)return this.Se(t),void(this.Ee=!1);var i=e.loadExternalDependency;if(!i)return void this.ke("PostHog loadExternalDependency extension not found.");i(this._instance,"conversations",n=>{n||!e.initConversations?this.ke("Could not load conversations script",n):this.Se(e.initConversations),this.Ee=!1})}catch(n){this.ke("Error initializing conversations",n),this.Ee=!1}}else on.error("Conversations enabled but missing token in remote config.")}}Se(e){if(this.$e)try{this._conversationsManager=e(this.$e,this._instance),on.info("Conversations loaded successfully")}catch(t){this.ke("Error completing conversations initialization",t)}else on.error("Cannot complete initialization: remote config is null")}ke(e,t){on.error(e,t),this._conversationsManager=null,this.Ee=!1}show(){this._conversationsManager?this._conversationsManager.show():on.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.xe===!0&&!Is(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,i){var n=this;return $a(function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,t,i):(on.warn("Conversations not available yet."),null)})()}getMessages(e,t){var i=this;return $a(function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(on.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return $a(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(on.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return $a(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(on.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}},bF=class{constructor(e){var t;this.Pe=!1,this.Te=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.Pe=!0)}onRemoteConfig(e){var t,i=(t=e.logs)==null?void 0:t.captureConsoleLogs;!Ce(i)&&i&&(this.Pe=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.Pe&&!this.Te){var e=ut("[logs]"),t=ce?.__PosthogExtensions__;if(t){var i=t.loadExternalDependency;i?i(this._instance,"logs",n=>{var r;n||(r=t.logs)==null||!r.initializeLogs?e.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.Te=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}};var cx=ut("[RateLimiter]");let xF=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var i=t.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach(n=>{cx.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4})}catch(n){return void cx.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,i,n;e===void 0&&(e=!1);var{captureEventsBurstLimit:r,captureEventsPerSecond:a}=this,o=new Date().getTime(),c=(t=(i=this.instance.persistence)==null?void 0:i.get_property(Wm))!==null&&t!==void 0?t:{tokens:r,last:o};c.tokens+=(o-c.last)/1e3*a,c.last=o,c.tokens>r&&(c.tokens=r);var l=c.tokens<1;return l||e||(c.tokens=Math.max(0,c.tokens-1)),!l||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+a+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=l,(n=this.instance.persistence)==null||n.set_property(Wm,c),{isRateLimited:l,remainingTokens:c.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()e(this.remoteConfig)):(Mr.error("PostHog Extensions not found. Cannot load remote config."),e())}Ce(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Mr.info("Using preloaded remote config",this.remoteConfig),void this.bi(this.remoteConfig);if(this._instance.O())return void Mr.warn("Remote config is disabled. Falling back to local config.");this.Ie(e=>{if(!e)return Mr.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ce(t=>{this.bi(t)});this.bi(e)})}catch(e){Mr.error("Error loading remote config",e)}}bi(e){e?this._instance.config.__preview_remote_config?(this._instance.bi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Mr.info("__preview_remote_config is disabled. Logging config instead",e):Mr.error("Failed to fetch remote config from PostHog.")}};var eg=3e3;let _F=class{constructor(e,t){this.Re=!0,this.Fe=[],this.Me=zs(t?.flush_interval_ms||eg,250,5e3,X.createLogger("flush interval"),eg),this.Oe=e}enqueue(e){this.Fe.push(e),this.Ae||this.De()}unload(){this.je();var e=this.Fe.length>0?this.Le():{},t=Object.values(e);[...t.filter(i=>i.url.indexOf("/e")===0),...t.filter(i=>i.url.indexOf("/e")!==0)].map(i=>{this.Oe(K({},i,{transport:"sendBeacon"}))})}enable(){this.Re=!1,this.De()}De(){var e=this;this.Re||(this.Ae=setTimeout(()=>{if(this.je(),this.Fe.length>0){var t=this.Le(),i=function(){var r=t[n],a=new Date().getTime();r.data&&Me(r.data)&&Be(r.data,o=>{o.offset=Math.abs(o.timestamp-a),delete o.timestamp}),e.Oe(r)};for(var n in t)i()}},this.Me))}je(){clearTimeout(this.Ae),this.Ae=void 0}Le(){var e={};return Be(this.Fe,t=>{var i,n=t,r=(n?n.batchKey:null)||n.url;H(e[r])&&(e[r]=K({},n,{data:[]})),(i=e[r].data)==null||i.push(n.data)}),this.Fe=[],e}};var TF=["retriesPerformedSoFar"];let kF=class{constructor(e){this.Ne=!1,this.Ue=3e3,this.Fe=[],this._instance=e,this.Fe=[],this.ze=!0,!H(G)&&"onLine"in G.navigator&&(this.ze=G.navigator.onLine,this.He=()=>{this.ze=!0,this.Lt()},this.Be=()=>{this.ze=!1},_t(G,"online",this.He),_t(G,"offline",this.Be))}get length(){return this.Fe.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,i=IA(e,TF);Fa(t)&&(i.url=Ud(i.url,{retry_count:t})),this._instance._send_request(K({},i,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(t??0)<10?this.qe(K({retriesPerformedSoFar:t},i)):i.callback==null||i.callback(n)}}))}qe(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i=function(a){var o=3e3*Math.pow(2,a),c=o/2,l=Math.min(18e5,o),u=(Math.random()-.5)*(l-c);return Math.ceil(l+u)}(t),n=Date.now()+i;this.Fe.push({retryAt:n,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),X.warn(r),this.Ne||(this.Ne=!0,this.We())}We(){if(this.Ge&&clearTimeout(this.Ge),this.Fe.length===0)return this.Ne=!1,void(this.Ge=void 0);this.Ge=setTimeout(()=>{this.ze&&this.Fe.length>0&&this.Lt(),this.We()},this.Ue)}Lt(){var e=Date.now(),t=[],i=this.Fe.filter(r=>r.retryAt0)for(var{requestOptions:n}of i)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.Ge&&(clearTimeout(this.Ge),this.Ge=void 0),this.Ne=!1,H(G)||(this.He&&(G.removeEventListener("online",this.He),this.He=void 0),this.Be&&(G.removeEventListener("offline",this.Be),this.Be=void 0)),this.Fe))try{this._instance._send_request(K({},e,{transport:"sendBeacon"}))}catch(t){X.error(t)}this.Fe=[]}},AF=class{constructor(e){this.Ve=()=>{var t,i,n,r;this.Je||(this.Je={});var a=this.scrollElement(),o=this.scrollY(),c=a?Math.max(0,a.scrollHeight-a.clientHeight):0,l=o+(a?.clientHeight||0),u=a?.scrollHeight||0;this.Je.lastScrollY=Math.ceil(o),this.Je.maxScrollY=Math.max(o,(t=this.Je.maxScrollY)!==null&&t!==void 0?t:0),this.Je.maxScrollHeight=Math.max(c,(i=this.Je.maxScrollHeight)!==null&&i!==void 0?i:0),this.Je.lastContentY=l,this.Je.maxContentY=Math.max(l,(n=this.Je.maxContentY)!==null&&n!==void 0?n:0),this.Je.maxContentHeight=Math.max(u,(r=this.Je.maxContentHeight)!==null&&r!==void 0?r:0)},this._instance=e}getContext(){return this.Je}resetContext(){var e=this.Je;return setTimeout(this.Ve,0),e}startMeasuringScrollPosition(){_t(G,"scroll",this.Ve,{capture:!0}),_t(G,"scrollend",this.Ve,{capture:!0}),_t(G,"resize",this.Ve)}scrollElement(){if(!this._instance.config.scroll_root_selector)return G?.document.documentElement;var e=Me(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var i=G?.document.querySelector(t);if(i)return i}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return G&&(G.scrollY||G.pageYOffset||G.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return G&&(G.scrollX||G.pageXOffset||G.document.documentElement.scrollLeft)||0}};var SF=s=>AS(s?.config.mask_personal_data_properties,s?.config.custom_personal_data_properties);let lx=class{constructor(e,t,i,n){this.Ke=r=>{var a=this.Ye();if(!a||a.sessionId!==r){var o={sessionId:r,props:this.Xe(this._instance)};this.Qe.register({[Gm]:o})}},this._instance=e,this.Ze=t,this.Qe=i,this.Xe=n||SF,this.Ze.onSessionId(this.Ke)}Ye(){return this.Qe.props[Gm]}getSetOnceProps(){var e,t=(e=this.Ye())==null?void 0:e.props;return t?"r"in t?SS(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return Be(ay(this.getSetOnceProps()),(t,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Dm(i)]=t}),e}};var $f=ut("[SessionId]");let ux=class{on(e,t){return this.tr.on(e,t)}constructor(e,t,i){var n;if(this.ir=[],this.er=void 0,this.tr=new hy,this.rr=(u,d)=>!(!Fa(u)||!Fa(d))&&Math.abs(u-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Qe=e.persistence,this.sr=void 0,this.nr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.ar=t||Qn,this.lr=i||Qn;var r=this.R.persistence_name||this.R.token,a=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*zs(a,60,36e3,$f.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ur(),this.hr="ph_"+r+"_window_id",this.dr="ph_"+r+"_primary_window_exists",this.vr()){var o=zt.W(this.hr),c=zt.W(this.dr);o&&!c?this.sr=o:zt.V(this.hr),zt.G(this.dr,!0)}if((n=this.R.bootstrap)!=null&&n.sessionID)try{var l=(u=>{var d=u.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this.cr(this.R.bootstrap.sessionID,new Date().getTime(),l)}catch(u){$f.error("Invalid sessionID in bootstrap",u)}this.pr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return H(this.ir)&&(this.ir=[]),this.ir.push(e),this.nr&&e(this.nr,this.sr),()=>{this.ir=this.ir.filter(t=>t!==e)}}vr(){return this.R.persistence!=="memory"&&!this.Qe.ki&&zt.H()}gr(e){e!==this.sr&&(this.sr=e,this.vr()&&zt.G(this.hr,e))}_r(){return this.sr?this.sr:this.vr()?zt.W(this.hr):null}cr(e,t,i){e===this.nr&&t===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this.nr=e,this.Qe.register({[Dd]:[t,e,i]}))}mr(){var e=this.Qe.props[Dd];return Me(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.cr(null,null,null)}destroy(){clearTimeout(this.yr),this.yr=void 0,this.er&&G&&(G.removeEventListener("beforeunload",this.er,{capture:!1}),this.er=void 0),this.ir=[]}pr(){this.er=()=>{this.vr()&&zt.V(this.dr)},_t(G,"beforeunload",this.er,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=t||new Date().getTime(),[n,r,a]=this.mr(),o=this._r(),c=Fa(a)&&Math.abs(i-a)>864e5,l=!1,u=!r,d=!u&&!e&&this.rr(i,n);u||d||c?(r=this.ar(),o=this.lr(),$f.info("new session ID generated",{sessionId:r,windowId:o,changeReason:{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:c}}),a=i,l=!0):o||(o=this.lr(),l=!0);var h=Fa(n)&&e&&!c?n:i,f=Fa(a)?a:new Date().getTime();return this.gr(o),this.cr(r,h,f),e||this.ur(),l&&this.ir.forEach(p=>p(r,o,l?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:c}:void 0)),{sessionId:r,windowId:o,sessionStartTimestamp:f,changeReason:l?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:c}:void 0,lastActivityTimestamp:n}}ur(){clearTimeout(this.yr),this.yr=setTimeout(()=>{var[e]=this.mr();if(this.rr(new Date().getTime(),e)){var t=this.nr;this.resetSessionId(),this.tr.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}};var CF=["$set_once","$set"],$n=ut("[SiteApps]");let EF=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}wr(e,t){if(t){var i=this.globalsForEvent(t);this.br.push(i),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=ce._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Bi(this.wr.bind(this));this.Er=()=>{e(),this.br=[],this.Er=void 0}}}globalsForEvent(e){var t,i,n,r,a,o,c;if(!e)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[h,f]of Object.entries(d))l[h]={id:u[h],type:h,properties:f};var{$set_once:p,$set:m}=e;return{event:K({},IA(e,CF),{properties:K({},e.properties,m?{$set:K({},(t=(i=e.properties)==null?void 0:i.$set)!==null&&t!==void 0?t:{},m)}:{},p?{$set_once:K({},(n=(r=e.properties)==null?void 0:r.$set_once)!==null&&n!==void 0?n:{},p)}:{}),elements_chain:(a=(o=e.properties)==null?void 0:o.$elements_chain)!==null&&a!==void 0?a:"",distinct_id:(c=e.properties)==null?void 0:c.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}setupSiteApp(e){var t=this.apps[e.id],i=()=>{var o;!t.errored&&this.br.length&&($n.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach(c=>t.processEvent==null?void 0:t.processEvent(c)),t.processedBuffer=!0),Object.values(this.apps).every(c=>c.processedBuffer||c.errored)&&((o=this.Er)==null||o.call(this))},n=!1,r=o=>{t.errored=!o,t.loaded=!0,$n.info("Site app with id "+e.id+" "+(o?"loaded":"errored")),n&&i()};try{var{processEvent:a}=e.init({posthog:this._instance,callback:o=>{r(o)}});a&&(t.processEvent=a),n=!0}catch(o){$n.error("Error while initializing PostHog app with config id "+e.id,o),r(!1)}if(n&&t.loaded)try{i()}catch(o){$n.error("Error while processing buffered events PostHog app with config id "+e.id,o),t.errored=!0}}$r(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}Sr(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{i.processEvent==null||i.processEvent(t)}catch(n){$n.error("Error while processing event "+e.event+" for site app "+i.id,n)}}}onRemoteConfig(e){var t,i,n,r=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.$r(),void this._instance.on("eventCaptured",l=>this.Sr(l))):void $n.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((i=this.Er)==null||i.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var a=function(l){var u;ce["__$$ph_site_app_"+l]=r._instance,(u=ce.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(r._instance,c,d=>{if(d)return $n.error("Error while initializing PostHog app with config id "+l,d)})};for(var{id:o,url:c}of e.siteApps)a(o)}else $n.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}};var OS=function(s,e){if(!s)return!1;var t=s.userAgent;if(t&&xb(t,e))return!0;try{var i=s?.userAgentData;if(i!=null&&i.brands&&i.brands.some(n=>xb(n?.brand,e)))return!0}catch{}return!!s.webdriver},$c=function(s){return s.US="us",s.EU="eu",s.CUSTOM="custom",s}({}),dx="i.posthog.com";let MF=class{constructor(e){this.kr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+dx,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.kr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.kr[this.apiHost]=$c.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.kr[this.apiHost]=$c.EU:this.kr[this.apiHost]=$c.CUSTOM),this.kr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===$c.CUSTOM)return this.apiHost+t;var i=dx+t;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}};var IF={icontains:(s,e)=>!!G&&e.href.toLowerCase().indexOf(s.toLowerCase())>-1,not_icontains:(s,e)=>!!G&&e.href.toLowerCase().indexOf(s.toLowerCase())===-1,regex:(s,e)=>!!G&&zd(e.href,s),not_regex:(s,e)=>!!G&&!zd(e.href,s),exact:(s,e)=>e.href===s,is_not:(s,e)=>e.href!==s};let PF=class ai{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),t.getWebExperiments(n=>{ai.Pr("retrieved web experiments from the server"),t.Tr=new Map,n.forEach(r=>{if(r.feature_flag_key){var a;t.Tr&&(ai.Pr("setting flag key ",r.feature_flag_key," to web experiment ",r),(a=t.Tr)==null||a.set(r.feature_flag_key,r));var o=t._instance.getFeatureFlag(r.feature_flag_key);It(o)&&r.variants[o]&&t.Ir(r.name,o,r.variants[o].transforms)}else if(r.variants)for(var c in r.variants){var l=r.variants[c];ai.Cr(l)&&t.Ir(r.name,c,l.transforms)}})},i)},this._instance=e,this._instance.onFeatureFlags(i=>{this.onFeatureFlags(i)})}onFeatureFlags(e){if(this._is_bot())ai.Pr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ce(this.Tr))return this.Tr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ai.Pr("applying feature flags",e),e.forEach(t=>{var i;if(this.Tr&&(i=this.Tr)!=null&&i.has(t)){var n,r=this._instance.getFeatureFlag(t),a=(n=this.Tr)==null?void 0:n.get(t);r&&a!=null&&a.variants[r]&&this.Ir(a.name,r,a.variants[r].transforms)}})}}previewWebExperiment(){var e=ai.getWindowLocation();if(e!=null&&e.search){var t=jd(e?.search,"__experiment_id"),i=jd(e?.search,"__experiment_variant");t&&i&&(ai.Pr("previewing web experiments "+t+" && "+i),this.getWebExperiments(n=>{this.Rr(parseInt(t),i,n)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._instance.config.disable_web_experiments&&!i)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!t)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:r=>{if(r.statusCode!==200||!r.json)return e([]);var a=r.json.experiments||[];return e(a)}})}Rr(e,t,i){var n=i.filter(r=>r.id===e);n&&n.length>0&&(ai.Pr("Previewing web experiment ["+n[0].name+"] with variant ["+t+"]"),this.Ir(n[0].name,t,n[0].variants[t].transforms))}static Cr(e){return!Ce(e.conditions)&&ai.Fr(e)&&ai.Mr(e)}static Fr(e){var t;if(Ce(e.conditions)||Ce((t=e.conditions)==null?void 0:t.url))return!0;var i,n,r,a=ai.getWindowLocation();return!!a&&((i=e.conditions)==null||!i.url||IF[(n=(r=e.conditions)==null?void 0:r.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,a))}static getWindowLocation(){return G?.location}static Mr(e){var t;if(Ce(e.conditions)||Ce((t=e.conditions)==null?void 0:t.utm))return!0;var i=wS();if(i.utm_source){var n,r,a,o,c,l,u,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((r=e.conditions)==null||(r=r.utm)==null?void 0:r.utm_campaign)==i.utm_campaign,f=(a=e.conditions)==null||(a=a.utm)==null||!a.utm_source||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_source)==i.utm_source,p=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_medium||((l=e.conditions)==null||(l=l.utm)==null?void 0:l.utm_medium)==i.utm_medium,m=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&m&&f}return!1}static Pr(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{if(n.selector){var r;ai.Pr("applying transform of variant "+t+" for experiment "+e+" ",n);var a=(r=document)==null?void 0:r.querySelectorAll(n.selector);a?.forEach(o=>{var c=o;n.html&&(c.innerHTML=n.html),n.css&&c.setAttribute("style",n.css)})}}):ai.Pr("Control variants leave the page unmodified.")}_is_bot(){return Li&&this._instance?OS(Li,this._instance.config.custom_blocked_useragents):void 0}};var RF=ut("[PostHog ExternalIntegrations]"),DF={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};let FF=class{constructor(e){this._instance=e}it(e,t){var i;(i=ce.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,n=>{if(n)return RF.error("failed to load script",n);t()})}startIfEnabledOrStop(){var e=this,t=function(a){var o,c,l;!n||(o=ce.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[a]||e.it(DF[a],()=>{var u;(u=ce.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[a])==null||u.start(e._instance)}),!n&&(c=ce.__PosthogExtensions__)!=null&&(c=c.integrations)!=null&&c[a]&&((l=ce.__PosthogExtensions__)==null||(l=l.integrations)==null||(l=l[a])==null||l.stop())};for(var[i,n]of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;t(i)}}};var tg="[SessionRecording]",bc=ut(tg);let hx=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Ar&&!this.Dr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ar=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw bc.error("started without valid sessionManager"),new Error(tg+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(tg+' cannot be used with cookieless_mode="always"')}get Dr(){var e,t=!((e=this._instance.get_property(kf))==null||!e.enabled),i=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return G&&t&&i&&!n}startIfEnabledOrStop(e){var t;if(!this.Dr||(t=this.Or)==null||!t.isStarted){var i=!H(Object.assign)&&!H(Array.from);this.Dr&&i?(this.Lr(e),bc.info("starting")):this.stopRecording()}}Lr(e){var t,i,n;this.Dr&&(ce!=null&&(t=ce.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(i=ce.__PosthogExtensions__)!=null&&i.initSessionRecording?this.Nr(e):(n=ce.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.Ur,r=>{if(r)return bc.error("could not load recorder",r);this.Nr(e)}))}stopRecording(){var e,t;(e=this.jr)==null||e.call(this),this.jr=void 0,(t=this.Or)==null||t.stop()}zr(){var e;(e=this._instance.persistence)==null||e.unregister(iS)}Hr(e){if(this._instance.persistence){var t,i,n=this._instance.persistence,r=()=>{var a=e.sessionRecording===!1?void 0:e.sessionRecording,o=a?.sampleRate,c=Ce(o)?null:parseFloat(o);Ce(c)&&this.zr();var l=a?.minimumDurationMilliseconds;n.register({[kf]:K({enabled:!!a},a,{networkPayloadCapture:K({capturePerformance:e.capturePerformance},a?.networkPayloadCapture),canvasRecording:{enabled:a?.recordCanvas,fps:a?.canvasFps,quality:a?.canvasQuality},sampleRate:c,minimumDurationMilliseconds:H(l)?null:l,endpoint:a?.endpoint,triggerMatchType:a?.triggerMatchType,masking:a?.masking,urlTriggers:a?.urlTriggers})})};r(),(t=this.jr)==null||t.call(this),this.jr=(i=this._instance.sessionManager)==null?void 0:i.onSessionId(r)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.Hr(e),this.Ar=!0,this.startIfEnabledOrStop()):this.Ar=!0:bc.info("skipping remote config with no sessionRecording",e)}log(e,t){var i;t===void 0&&(t="log"),(i=this.Or)!=null&&i.log?this.Or.log(e,t):bc.warn("log called before recorder was ready")}get Ur(){var e,t,i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(kf);return(i==null||(t=i.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Nr(e){var t,i;if((t=ce.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(i=ce.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var t;(t=this.Or)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var t,i;this.Or||(i=this._instance.persistence)==null||i.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Or)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var i;return!((i=this.Or)==null||!i.tryAddCustomEvent(e,t))}};var Qc={},ig=()=>{},La="posthog",BS=!nF&&mi?.indexOf("MSIE")===-1&&mi?.indexOf("Mozilla")===-1,fx=s=>{var e;return K({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:cD(Y?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ig,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:s??"unset",__preview_deferred_init_extensions:!1,debug:gi&&It(gi?.search)&&gi.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(G==null||(e=G.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var i="Bad HTTP status: "+t.statusCode+" "+t.text;X.error(i)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:eg},error_tracking:{},_onCapture:ig,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body"}))(s))},px=s=>{var e={};H(s.process_person)||(e.person_profiles=s.process_person),H(s.xhr_headers)||(e.request_headers=s.xhr_headers),H(s.cookie_name)||(e.persistence_name=s.cookie_name),H(s.disable_cookie)||(e.disable_persistence=s.disable_cookie),H(s.store_google)||(e.save_campaign_params=s.store_google),H(s.verbose)||(e.debug=s.verbose);var t=gt({},e,s);return Me(s.property_blacklist)&&(H(s.property_denylist)?t.property_denylist=s.property_blacklist:Me(s.property_denylist)?t.property_denylist=[...s.property_blacklist,...s.property_denylist]:X.error("Invalid value for property_denylist config: "+s.property_denylist)),t};let LF=class{constructor(){this.__forceAllowLocalhost=!1}get Br(){return this.__forceAllowLocalhost}set Br(e){X.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},$S=class jS{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new LF,this.qr=!1,this.version=dn.LIB_VERSION,this.Wr=new hy,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=fx(),this.SentryIntegration=$D,this.sentryIntegration=e=>function(t,i){var n=xS(t,i);return{name:bS,processEvent:r=>n(r)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Gr=!1,this.Vr=null,this.Jr=null,this.Kr=null,this.featureFlags=new cF(this),this.toolbar=new ND(this),this.scrollManager=new AF(this),this.pageViewManager=new Xb(this),this.surveys=new yF(this),this.conversations=new vF(this),this.logs=new bF(this),this.experiments=new PF(this),this.exceptions=new rF(this),this.rateLimiter=new xF(this),this.requestRouter=new MF(this),this.consent=new RD(this),this.externalIntegrations=new FF(this),this.people={set:(e,t,i)=>{var n=It(e)?{[e]:t}:e;this.setPersonProperties(n),i?.({})},set_once:(e,t,i)=>{var n=It(e)?{[e]:t}:e;this.setPersonProperties(void 0,n),i?.({})}},this.on("eventCaptured",e=>X.info('send "'+e?.event+'"',e))}init(e,t,i){if(i&&i!==La){var n,r=(n=Qc[i])!==null&&n!==void 0?n:new jS;return r._init(e,t,i),Qc[i]=r,Qc[La][i]=r,r}return this._init(e,t,i)}_init(e,t,i){var n;if(t===void 0&&(t={}),H(e)||Fm(e))return X.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Yr(t.debug),this.Xr=t,this.Qr=[],t.person_profiles&&(this.Jr=t.person_profiles),this.set_config(gt({},fx(t.defaults),px(t),{name:i,token:e})),this.config.on_xhr_error&&X.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:yn.GZipJS;var r=this.Zr();this.persistence=new Ff(this.config,r),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ff(K({},this.config,{persistence:"sessionStorage"}),r);var a=K({},this.persistence.props),o=K({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.ts=new _F(w=>this.es(w),this.config.request_queue_config),this.rs=new kF(this),this.__request_queue=[];var c=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(c||(this.sessionManager=new ux(this),this.sessionPropsManager=new lx(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(X.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.ss(c)},0)):(X.info("Initializing extensions synchronously"),this.ss(c)),dn.DEBUG=dn.DEBUG||this.config.debug,dn.DEBUG&&X.info("Starting in debug mode",{this:this,config:t,thisC:K({},this.config),p:a,s:o}),((n=t.bootstrap)==null?void 0:n.distinctID)!==void 0){var l,u,d=this.config.get_device_id(Qn()),h=(l=t.bootstrap)!=null&&l.isIdentifiedID?d:t.bootstrap.distinctID;this.persistence.set_property(hn,(u=t.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:h})}if(this.ns()){var f,p,m=Object.keys(((f=t.bootstrap)==null?void 0:f.featureFlags)||{}).filter(w=>{var b;return!((b=t.bootstrap)==null||(b=b.featureFlags)==null||!b[w])}).reduce((w,b)=>{var k;return w[b]=((k=t.bootstrap)==null||(k=k.featureFlags)==null?void 0:k[b])||!1,w},{}),g=Object.keys(((p=t.bootstrap)==null?void 0:p.featureFlagPayloads)||{}).filter(w=>m[w]).reduce((w,b)=>{var k,A;return(k=t.bootstrap)!=null&&(k=k.featureFlagPayloads)!=null&&k[b]&&(w[b]=(A=t.bootstrap)==null||(A=A.featureFlagPayloads)==null?void 0:A[b]),w},{});this.featureFlags.receivedFeatureFlags({featureFlags:m,featureFlagPayloads:g})}if(c)this.register_once({distinct_id:dc,$device_id:null},"");else if(!this.get_distinct_id()){var v=this.config.get_device_id(Qn());this.register_once({distinct_id:v,$device_id:v},""),this.persistence.set_property(hn,"anonymous")}return _t(G,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?BD(this,()=>this.os()):this.os(),ir(this.config._onCapture)&&this.config._onCapture!==ig&&(X.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",w=>this.config._onCapture(w.event,w))),this.config.ip&&X.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}ss(e){var t=performance.now();this.historyAutocapture=new OD(this),this.historyAutocapture.startIfEnabled();var i=[];i.push(()=>{new UD(this).startIfEnabledOrStop()}),i.push(()=>{var n;this.siteApps=new EF(this),(n=this.siteApps)==null||n.init()}),e||i.push(()=>{this.sessionRecording=new hx(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||i.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),i.push(()=>{this.autocapture=new TD(this),this.autocapture.startIfEnabled()}),i.push(()=>{this.surveys.loadIfEnabled()}),i.push(()=>{this.logs.loadIfEnabled()}),i.push(()=>{this.conversations.loadIfEnabled()}),i.push(()=>{this.productTours=new uF(this),this.productTours.loadIfEnabled()}),i.push(()=>{this.heatmaps=new XD(this),this.heatmaps.startIfEnabled()}),i.push(()=>{this.webVitalsAutocapture=new HD(this)}),i.push(()=>{this.exceptionObserver=new LD(this),this.exceptionObserver.startIfEnabledOrStop()}),i.push(()=>{this.deadClicksAutocapture=new vS(this,FD),this.deadClicksAutocapture.startIfEnabled()}),i.push(()=>{if(this.ls){var n=this.ls;this.ls=void 0,this.bi(n)}}),this.us(i,t)}us(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.us(e,t)},0);var i=e.shift();if(i)try{i()}catch(r){X.error("Error initializing extension:",r)}}var n=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:n}),this.config.__preview_deferred_init_extensions&&X.info("PostHog extensions initialized ("+n+"ms)")}bi(e){var t,i,n,r,a,o,c,l,u;if(!Y||!Y.body)return X.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.bi(e)},500);this.config.__preview_deferred_init_extensions&&(this.ls=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=we(e.supportedCompression,yn.GZipJS)?yn.GZipJS:we(e.supportedCompression,yn.Base64)?yn.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Jr?this.Jr:"identified_only"}),(i=this.siteApps)==null||i.onRemoteConfig(e),(n=this.sessionRecording)==null||n.onRemoteConfig(e),(r=this.autocapture)==null||r.onRemoteConfig(e),(a=this.heatmaps)==null||a.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(o=this.productTours)==null||o.onRemoteConfig(e),(c=this.webVitalsAutocapture)==null||c.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}os(){try{this.config.loaded(this)}catch(e){X.critical("`loaded` function failed",e)}this.hs(),this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.ds()},1),new wF(this).load(),this.featureFlags.flags()}hs(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.ts)==null||e.enable())}_dom_loaded(){this.is_capturing()&&sr(this.__request_queue,e=>this.es(e)),this.__request_queue=[],this.hs()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.vs()&&this.capture("$pageleave"),(e=this.ts)==null||e.unload(),(t=this.rs)==null||t.unload()):this.vs()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(BS?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Ud(e.url,{ip:this.config.ip?1:0}),e.headers=K({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var i,n,r,a=K({},t);a.timeout=a.timeout||6e4,a.url=Ud(a.url,{_:new Date().getTime().toString(),ver:dn.LIB_VERSION,compression:a.compression});var o=(i=a.transport)!==null&&i!==void 0?i:"fetch",c=cd.filter(u=>!a.disableTransport||!u.transport||!a.disableTransport.includes(u.transport)),l=(n=(r=ZA(c,u=>u.transport===o))==null?void 0:r.method)!==null&&n!==void 0?n:c[0].method;if(!l)throw new Error("No available transport method");l(a)})(K({},e,{callback:t=>{var i,n;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((i=(n=this.config).on_request_error)==null||i.call(n,t)),e.callback==null||e.callback(t)}}))))}es(e){this.rs?this.rs.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,i=[],n=[],r=[];sr(e,o=>{o&&(t=o[0],Me(t)?r.push(o):ir(o)?o.call(this):Me(o)&&t==="alias"?i.push(o):Me(o)&&t.indexOf("capture")!==-1&&ir(this[t])?r.push(o):n.push(o))});var a=function(o,c){sr(o,function(l){if(Me(l[0])){var u=c;Be(l,function(d){u=u[d[0]].apply(u,d.slice(1))})}else this[l[0]].apply(this,l.slice(1))},c)};a(i,this),a(n,this),a(r,this)}ns(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,i){var n;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.ts){if(this.is_capturing())if(!H(e)&&It(e)){var r=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(r&&!this.config.__preview_capture_bot_pageviews)){var a=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(a==null||!a.isRateLimited){t!=null&&t.$current_url&&!It(t?.$current_url)&&(X.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var o=new Date,c=i?.timestamp||o,l=Qn(),u={uuid:l,event:e,properties:this.calculateEventProperties(e,t||{},c,l)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&r&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),a&&(u.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens),i?.$set&&(u.$set=i?.$set);var d,h=e!=="$groupidentify",f=this.cs(i?.$set_once,h);if(f&&(u.$set_once=f),(u=aD(u,i!=null&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=c,H(i?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=o),e===Bc.DISMISSED||e===Bc.SENT){var p=t?.[Bf.SURVEY_ID],m=t?.[Bf.SURVEY_ITERATION];d={id:p,current_iteration:m},localStorage.getItem(ox(d))||localStorage.setItem(ox(d),"true"),u.$set=K({},u.$set,{[dF({id:p,current_iteration:m},e===Bc.SENT?"responded":"dismissed")]:!0})}else e===Bc.SHOWN&&(u.$set=K({},u.$set,{[Bf.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var g=K({},u.properties.$set,u.$set);if(ja(g)||this.setPersonPropertiesForFlags(g),!Ce(this.config.before_send)){var v=this.fs(u);if(!v)return;u=v}this.Wr.emit("eventCaptured",u);var w={method:"POST",url:(n=i?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:i?._batchKey};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.es(w):this.ts.enqueue(w),u}X.critical("This capture call is ignored due to client rate limiting.")}}else X.error("No event name provided to posthog.capture")}else X.uninitializedWarning("posthog.capture")}Bi(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,i,n,r){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return t;var a=r?void 0:this.persistence.remove_event_timer(e),o=K({},t);if(o.token=this.config.token,o.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(o.$cookieless_mode=!0),e==="$snapshot"){var c=K({},this.persistence.properties(),this.sessionPersistence.properties());return o.distinct_id=c.distinct_id,(!It(o.distinct_id)&&!kn(o.distinct_id)||Fm(o.distinct_id))&&X.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),o}var l,u=qD(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(r,i.getTime());o.$session_id=d,o.$window_id=h}this.sessionPropsManager&>(o,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&>(o,this.sessionRecording.sdkDebugProperties),o.$sdk_debug_retry_queue_size=(f=this.rs)==null?void 0:f.length}catch(v){o.$sdk_debug_error_capturing_properties=String(v)}if(this.requestRouter.region===$c.CUSTOM&&(o.$lib_custom_api_host=this.config.api_host),l=e!=="$pageview"||r?e!=="$pageleave"||r?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,n),o=gt(o,l),e==="$pageview"&&Y&&(o.title=Y.title),!H(a)){var p=i.getTime()-a;o.$duration=parseFloat((p/1e3).toFixed(3))}mi&&this.config.opt_out_useragent_filter&&(o.$browser_type=this._is_bot()?"bot":"browser"),(o=gt({},u,this.persistence.properties(),this.sessionPersistence.properties(),o)).$is_identified=this._isIdentified(),Me(this.config.property_denylist)?Be(this.config.property_denylist,function(v){delete o[v]}):X.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var m=this.config.sanitize_properties;m&&(X.error("sanitize_properties is deprecated. Use before_send instead"),o=m(o,e));var g=this.ps();return o.$process_person_profile=g,g&&!r&&this.gs("_calculate_event_properties"),o}cs(e,t){var i;if(t===void 0&&(t=!0),!this.persistence||!this.ps()||this.qr)return e;var n=this.persistence.get_initial_props(),r=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=gt({},n,r||{},e||{}),o=this.config.sanitize_properties;return o&&(X.error("sanitize_properties is deprecated. Use before_send instead"),a=o(a,"$set_once")),t&&(this.qr=!0),ja(a)?void 0:a}register(e,t){var i;(i=this.persistence)==null||i.register(e,t)}register_once(e,t,i){var n;(n=this.persistence)==null||n.register_once(e,t,i)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}_s(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(t)}catch{return t}}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,i){var n=i!=null&&i.merge?this.featureFlags.getFlagVariants():{},r=i!=null&&i.merge?this.featureFlags.getFlagPayloads():{},a=K({},n,e),o=K({},r,t),c={};for(var[l,u]of Object.entries(a)){var d=typeof u=="string";c[l]={key:l,enabled:!!d||!!u,variant:d?u:void 0,reason:void 0,metadata:H(o?.[l])?void 0:{id:0,version:void 0,description:void 0,payload:o[l]}}}this.featureFlags.receivedFeatureFlags({flags:c})}updateEarlyAccessFeatureEnrollment(e,t,i){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,i)}on(e,t){return this.Wr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,i;return(t=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=fF),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,i){if(!this.__loaded||!this.persistence)return X.uninitializedWarning("posthog.identify");if(kn(e)&&(e=e.toString(),X.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))X.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==dc){if(this.gs("posthog.identify")){var n=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var r=n;this.register_once({$had_persisted_distinct_id:!0,$device_id:r},"")}e!==n&&e!==this.get_property(Rc)&&(this.unregister(Rc),this.register({distinct_id:e}));var a=(this.persistence.get_property(hn)||"anonymous")==="anonymous";e!==n&&a?(this.persistence.set_property(hn,"identified"),this.setPersonPropertiesForFlags(K({},i||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:t||{},$set_once:i||{}}),this.Kr=tx(e,t,i),this.featureFlags.setAnonymousDistinctId(n)):(t||i)&&this.setPersonProperties(t,i),e!==n&&(this.reloadFeatureFlags(),this.unregister(Fd))}}else X.critical('The string "'+dc+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else X.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.gs("posthog.setPersonProperties")){var i=tx(this.get_distinct_id(),e,t);this.Kr!==i?(this.setPersonPropertiesForFlags(K({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Kr=i):X.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,i){if(e&&t){var n=this.getGroups();n[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:K({},n,{[e]:t})}),i&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),n[e]===t||i||this.reloadFeatureFlags()}else X.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.gs("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,i,n,r;if(X.info("reset"),!this.__loaded)return X.uninitializedWarning("posthog.reset");var a=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(i=this.sessionPersistence)==null||i.clear(),this.surveys.reset(),this.featureFlags.reset(),(n=this.persistence)==null||n.set_property(hn,"anonymous"),(r=this.sessionManager)==null||r.resetSessionId(),this.Kr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:dc,$device_id:null},"");else{var o=this.config.get_device_id(Qn());this.register_once({distinct_id:o,$device_id:e?o:a},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&i){var r,a=(r=e.timestampLookBack)!==null&&r!==void 0?r:10;if(!i)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-a,0)}return n}alias(e,t){return e===this.get_property(eS)?(X.critical("Attempting to create alias for existing People user - aborting."),-2):this.gs("posthog.alias")?(H(t)&&(t=this.get_distinct_id()),e!==t?(this._s(Rc,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(X.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=K({},this.config);if(Mt(e)){var i,n,r,a,o,c,l;gt(this.config,px(e));var u=this.Zr();(i=this.persistence)==null||i.update_config(this.config,t,u),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ff(K({},this.config,{persistence:"sessionStorage"}),u);var d=this.Yr(this.config.debug);_n(d)&&(this.config.debug=d),_n(this.config.debug)&&(this.config.debug?(dn.DEBUG=!0,Xe.H()&&Xe.G("ph_debug","true"),X.info("set_config",{config:e,oldConfig:t,newConfig:K({},this.config)})):(dn.DEBUG=!1,Xe.H()&&Xe.V("ph_debug"))),(n=this.exceptionObserver)==null||n.onConfigChange(),(r=this.sessionRecording)==null||r.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),(c=this.exceptionObserver)==null||c.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this.ys(),(l=this.externalIntegrations)==null||l.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,i={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(i).some(Boolean)){var n,r,a,o,c;(n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),i.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),i.linked_flag&&((a=this.sessionRecording)==null||a.overrideLinkedFlag()),i.url_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("url")),i.event_trigger&&((c=this.sessionRecording)==null||c.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var i=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(K({},n,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:La;return t!==La&&(t=La+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(hn))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(hn))==="identified"}ps(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ja(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Rc])&&((t=this.persistence)==null||(t=t.props)==null||!t[Od]))}vs(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.ps()||this.gs("posthog.createPersonProfile")&&this.setPersonProperties({},{})}gs(e){return this.config.person_profiles==="never"?(X.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._s(Od,!0),!0)}Zr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}ys(){var e,t,i,n,r=this.Zr();return((e=this.persistence)==null?void 0:e.ki)!==r&&((i=this.persistence)==null||i.set_disabled(r)),((t=this.sessionPersistence)==null?void 0:t.ki)!==r&&((n=this.sessionPersistence)==null||n.set_disabled(r)),r}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var i,n,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(i=this.sessionManager)==null||i.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new ux(this),this.pageViewManager=new Xb(this),this.persistence&&(this.sessionPropsManager=new lx(this,this.sessionManager,this.persistence)),this.sessionRecording=new hx(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.ys(),this.hs(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(H(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((r=e?.captureEventName)!==null&&r!==void 0?r:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.ds()}else X.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,i;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.ys(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:dc,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(i=this.sessionRecording)==null||i.stopRecording(),this.sessionRecording=void 0,this.ds())):X.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===fn.GRANTED?"granted":e===fn.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.ys()}_is_bot(){return Li?OS(Li,this.config.custom_blocked_useragents):void 0}ds(){Y&&(Y.visibilityState==="visible"?this.Gr||(this.Gr=!0,this.capture("$pageview",{title:Y.title},{send_instantly:!0}),this.Vr&&(Y.removeEventListener("visibilitychange",this.Vr),this.Vr=null)):this.Vr||(this.Vr=this.ds.bind(this),_t(Y,"visibilitychange",this.Vr)))}debug(e){e===!1?(G?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(G?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}O(){var e,t,i,n,r,a,o,c=this.Xr||{};return"advanced_disable_flags"in c?!!c.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(X.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(i="advanced_disable_decide",n=!1,r=X,a=(t="advanced_disable_flags")in(e=c)&&!H(e[t]),o=i in e&&!H(e[i]),a?e[t]:o?(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i]):n)}fs(e){if(Ce(this.config.before_send))return e;var t=Me(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var n of t){if(i=n(i),Ce(i)){var r="Event '"+e.event+"' was rejected in beforeSend function";return TR(e.event)?X.warn(r+". This can cause unexpected behavior."):X.info(r),null}i.properties&&!ja(i.properties)||X.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return i}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}Yr(e){var t=_n(e)&&!e,i=Xe.H()&&Xe.q("ph_debug")==="true";return!t&&(!!i||e)}};(function(s,e){for(var t=0;t-1&&s.splice(t,1)}const An=(s,e,t)=>t>e?e:t{};const Sn={},US=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function zS(s){return typeof s=="object"&&s!==null}const GS=s=>/^0[^.\s]+$/u.test(s);function by(s){let e;return()=>(e===void 0&&(e=s()),e)}const ms=s=>s,VF=(s,e)=>t=>e(s(t)),Jl=(...s)=>s.reduce(VF),wl=(s,e,t)=>{const i=e-s;return i===0?1:(t-s)/i};let xy=class{constructor(){this.subscriptions=[]}add(e){return gy(this.subscriptions,e),()=>yy(this.subscriptions,e)}notify(e,t,i){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](e,t,i);else for(let r=0;rs*1e3,os=s=>s/1e3;function WS(s,e){return e?s*(1e3/e):0}const qS=(s,e,t)=>(((1-3*t+3*e)*s+(3*t-6*e))*s+3*e)*s,UF=1e-7,zF=12;function GF(s,e,t,i,n){let r,a,o=0;do a=e+(t-e)/2,r=qS(a,i,n)-s,r>0?t=a:e=a;while(Math.abs(r)>UF&&++oGF(r,0,1,s,t);return r=>r===0||r===1?r:qS(n(r),e,i)}const HS=s=>e=>e<=.5?s(2*e)/2:(2-s(2*(1-e)))/2,YS=s=>e=>1-s(1-e),XS=Zl(.33,1.53,.69,.99),wy=YS(XS),KS=HS(wy),QS=s=>(s*=2)<1?.5*wy(s):.5*(2-Math.pow(2,-10*(s-1))),_y=s=>1-Math.sin(Math.acos(s)),JS=YS(_y),ZS=HS(_y),WF=Zl(.42,0,1,1),qF=Zl(0,0,.58,1),eC=Zl(.42,0,.58,1),HF=s=>Array.isArray(s)&&typeof s[0]!="number",tC=s=>Array.isArray(s)&&typeof s[0]=="number",YF={linear:ms,easeIn:WF,easeInOut:eC,easeOut:qF,circIn:_y,circInOut:ZS,circOut:JS,backIn:wy,backInOut:KS,backOut:XS,anticipate:QS},XF=s=>typeof s=="string",gx=s=>{if(tC(s)){vy(s.length===4);const[e,t,i,n]=s;return Zl(e,t,i,n)}else if(XF(s))return YF[s];return s},Su=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function KF(s,e){let t=new Set,i=new Set,n=!1,r=!1;const a=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function c(u){a.has(u)&&(l.schedule(u),s()),u(o)}const l={schedule:(u,d=!1,h=!1)=>{const p=h&&n?t:i;return d&&a.add(u),p.has(u)||p.add(u),u},cancel:u=>{i.delete(u),a.delete(u)},process:u=>{if(o=u,n){r=!0;return}n=!0,[t,i]=[i,t],t.forEach(c),t.clear(),n=!1,r&&(r=!1,l.process(u))}};return l}const QF=40;function iC(s,e){let t=!1,i=!0;const n={delta:0,timestamp:0,isProcessing:!1},r=()=>t=!0,a=Su.reduce((b,k)=>(b[k]=KF(r),b),{}),{setup:o,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:h,render:f,postRender:p}=a,m=()=>{const b=Sn.useManualTiming?n.timestamp:performance.now();t=!1,Sn.useManualTiming||(n.delta=i?1e3/60:Math.max(Math.min(b-n.timestamp,QF),1)),n.timestamp=b,n.isProcessing=!0,o.process(n),c.process(n),l.process(n),u.process(n),d.process(n),h.process(n),f.process(n),p.process(n),n.isProcessing=!1,t&&e&&(i=!1,s(m))},g=()=>{t=!0,i=!0,n.isProcessing||s(m)};return{schedule:Su.reduce((b,k)=>{const A=a[k];return b[k]=(M,R=!1,I=!1)=>(t||g(),A.schedule(M,R,I)),b},{}),cancel:b=>{for(let k=0;k(ld===void 0&&bi.set(Vt.isProcessing||Sn.useManualTiming?Vt.timestamp:performance.now()),ld),set:s=>{ld=s,queueMicrotask(JF)}},sC=s=>e=>typeof e=="string"&&e.startsWith(s),Ty=sC("--"),ZF=sC("var(--"),ky=s=>ZF(s)?eL.test(s.split("/*")[0].trim()):!1,eL=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Go={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},_l={...Go,transform:s=>An(0,1,s)},Cu={...Go,default:1},Jc=s=>Math.round(s*1e5)/1e5,Ay=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tL(s){return s==null}const iL=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Sy=(s,e)=>t=>!!(typeof t=="string"&&iL.test(t)&&t.startsWith(s)||e&&!tL(t)&&Object.prototype.hasOwnProperty.call(t,e)),nC=(s,e,t)=>i=>{if(typeof i!="string")return i;const[n,r,a,o]=i.match(Ay);return{[s]:parseFloat(n),[e]:parseFloat(r),[t]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},sL=s=>An(0,255,s),Vf={...Go,transform:s=>Math.round(sL(s))},zr={test:Sy("rgb","red"),parse:nC("red","green","blue"),transform:({red:s,green:e,blue:t,alpha:i=1})=>"rgba("+Vf.transform(s)+", "+Vf.transform(e)+", "+Vf.transform(t)+", "+Jc(_l.transform(i))+")"};function nL(s){let e="",t="",i="",n="";return s.length>5?(e=s.substring(1,3),t=s.substring(3,5),i=s.substring(5,7),n=s.substring(7,9)):(e=s.substring(1,2),t=s.substring(2,3),i=s.substring(3,4),n=s.substring(4,5),e+=e,t+=t,i+=i,n+=n),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:n?parseInt(n,16)/255:1}}const ng={test:Sy("#"),parse:nL,transform:zr.transform},eu=s=>({test:e=>typeof e=="string"&&e.endsWith(s)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${s}`}),qn=eu("deg"),Hs=eu("%"),me=eu("px"),rL=eu("vh"),aL=eu("vw"),yx={...Hs,parse:s=>Hs.parse(s)/100,transform:s=>Hs.transform(s*100)},Va={test:Sy("hsl","hue"),parse:nC("hue","saturation","lightness"),transform:({hue:s,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(s)+", "+Hs.transform(Jc(e))+", "+Hs.transform(Jc(t))+", "+Jc(_l.transform(i))+")"},vt={test:s=>zr.test(s)||ng.test(s)||Va.test(s),parse:s=>zr.test(s)?zr.parse(s):Va.test(s)?Va.parse(s):ng.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?zr.transform(s):Va.transform(s),getAnimatableNone:s=>{const e=vt.parse(s);return e.alpha=0,vt.transform(e)}},oL=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function cL(s){return isNaN(s)&&typeof s=="string"&&(s.match(Ay)?.length||0)+(s.match(oL)?.length||0)>0}const rC="number",aC="color",lL="var",uL="var(",vx="${}",dL=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Tl(s){const e=s.toString(),t=[],i={color:[],number:[],var:[]},n=[];let r=0;const o=e.replace(dL,c=>(vt.test(c)?(i.color.push(r),n.push(aC),t.push(vt.parse(c))):c.startsWith(uL)?(i.var.push(r),n.push(lL),t.push(c)):(i.number.push(r),n.push(rC),t.push(parseFloat(c))),++r,vx)).split(vx);return{values:t,split:o,indexes:i,types:n}}function oC(s){return Tl(s).values}function cC(s){const{split:e,types:t}=Tl(s),i=e.length;return n=>{let r="";for(let a=0;atypeof s=="number"?0:vt.test(s)?vt.getAnimatableNone(s):s;function fL(s){const e=oC(s);return cC(s)(e.map(hL))}const ur={test:cL,parse:oC,createTransformer:cC,getAnimatableNone:fL};function Uf(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*(2/3-t)*6:s}function pL({hue:s,saturation:e,lightness:t,alpha:i}){s/=360,e/=100,t/=100;let n=0,r=0,a=0;if(!e)n=r=a=t;else{const o=t<.5?t*(1+e):t+e-t*e,c=2*t-o;n=Uf(c,o,s+1/3),r=Uf(c,o,s),a=Uf(c,o,s-1/3)}return{red:Math.round(n*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:i}}function Gd(s,e){return t=>t>0?e:s}const Qe=(s,e,t)=>s+(e-s)*t,zf=(s,e,t)=>{const i=s*s,n=t*(e*e-i)+i;return n<0?0:Math.sqrt(n)},mL=[ng,zr,Va],gL=s=>mL.find(e=>e.test(s));function bx(s){const e=gL(s);if(!e)return!1;let t=e.parse(s);return e===Va&&(t=pL(t)),t}const xx=(s,e)=>{const t=bx(s),i=bx(e);if(!t||!i)return Gd(s,e);const n={...t};return r=>(n.red=zf(t.red,i.red,r),n.green=zf(t.green,i.green,r),n.blue=zf(t.blue,i.blue,r),n.alpha=Qe(t.alpha,i.alpha,r),zr.transform(n))},rg=new Set(["none","hidden"]);function yL(s,e){return rg.has(s)?t=>t<=0?s:e:t=>t>=1?e:s}function vL(s,e){return t=>Qe(s,e,t)}function Cy(s){return typeof s=="number"?vL:typeof s=="string"?ky(s)?Gd:vt.test(s)?xx:wL:Array.isArray(s)?lC:typeof s=="object"?vt.test(s)?xx:bL:Gd}function lC(s,e){const t=[...s],i=t.length,n=s.map((r,a)=>Cy(r)(r,e[a]));return r=>{for(let a=0;a{for(const r in i)t[r]=i[r](n);return t}}function xL(s,e){const t=[],i={color:0,var:0,number:0};for(let n=0;n{const t=ur.createTransformer(e),i=Tl(s),n=Tl(e);return i.indexes.var.length===n.indexes.var.length&&i.indexes.color.length===n.indexes.color.length&&i.indexes.number.length>=n.indexes.number.length?rg.has(s)&&!n.values.length||rg.has(e)&&!i.values.length?yL(s,e):Jl(lC(xL(i,n),n.values),t):Gd(s,e)};function uC(s,e,t){return typeof s=="number"&&typeof e=="number"&&typeof t=="number"?Qe(s,e,t):Cy(s)(s,e)}const _L=s=>{const e=({timestamp:t})=>s(t);return{start:(t=!0)=>Ge.update(e,t),stop:()=>lr(e),now:()=>Vt.isProcessing?Vt.timestamp:bi.now()}},dC=(s,e,t=10)=>{let i="";const n=Math.max(Math.round(e/t),2);for(let r=0;r=Wd?1/0:e}function TL(s,e=100,t){const i=t({...s,keyframes:[0,e]}),n=Math.min(Ey(i),Wd);return{type:"keyframes",ease:r=>i.next(n*r).value/e,duration:os(n)}}const kL=5;function hC(s,e,t){const i=Math.max(e-kL,0);return WS(t-s(i),e-i)}const at={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Gf=.001;function AL({duration:s=at.duration,bounce:e=at.bounce,velocity:t=at.velocity,mass:i=at.mass}){let n,r,a=1-e;a=An(at.minDamping,at.maxDamping,a),s=An(at.minDuration,at.maxDuration,os(s)),a<1?(n=l=>{const u=l*a,d=u*s,h=u-t,f=ag(l,a),p=Math.exp(-d);return Gf-h/f*p},r=l=>{const d=l*a*s,h=d*t+t,f=Math.pow(a,2)*Math.pow(l,2)*s,p=Math.exp(-d),m=ag(Math.pow(l,2),a);return(-n(l)+Gf>0?-1:1)*((h-f)*p)/m}):(n=l=>{const u=Math.exp(-l*s),d=(l-t)*s+1;return-Gf+u*d},r=l=>{const u=Math.exp(-l*s),d=(t-l)*(s*s);return u*d});const o=5/s,c=CL(n,r,o);if(s=qs(s),isNaN(c))return{stiffness:at.stiffness,damping:at.damping,duration:s};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:a*2*Math.sqrt(i*l),duration:s}}}const SL=12;function CL(s,e,t){let i=t;for(let n=1;ns[t]!==void 0)}function IL(s){let e={velocity:at.velocity,stiffness:at.stiffness,damping:at.damping,mass:at.mass,isResolvedFromDuration:!1,...s};if(!wx(s,ML)&&wx(s,EL))if(s.visualDuration){const t=s.visualDuration,i=2*Math.PI/(t*1.2),n=i*i,r=2*An(.05,1,1-(s.bounce||0))*Math.sqrt(n);e={...e,mass:at.mass,stiffness:n,damping:r}}else{const t=AL(s);e={...e,...t,mass:at.mass},e.isResolvedFromDuration=!0}return e}function qd(s=at.visualDuration,e=at.bounce){const t=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:e}:s;let{restSpeed:i,restDelta:n}=t;const r=t.keyframes[0],a=t.keyframes[t.keyframes.length-1],o={done:!1,value:r},{stiffness:c,damping:l,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=IL({...t,velocity:-os(t.velocity||0)}),p=h||0,m=l/(2*Math.sqrt(c*u)),g=a-r,v=os(Math.sqrt(c/u)),w=Math.abs(g)<5;i||(i=w?at.restSpeed.granular:at.restSpeed.default),n||(n=w?at.restDelta.granular:at.restDelta.default);let b;if(m<1){const A=ag(v,m);b=M=>{const R=Math.exp(-m*v*M);return a-R*((p+m*v*g)/A*Math.sin(A*M)+g*Math.cos(A*M))}}else if(m===1)b=A=>a-Math.exp(-v*A)*(g+(p+v*g)*A);else{const A=v*Math.sqrt(m*m-1);b=M=>{const R=Math.exp(-m*v*M),I=Math.min(A*M,300);return a-R*((p+m*v*g)*Math.sinh(I)+A*g*Math.cosh(I))/A}}const k={calculatedDuration:f&&d||null,next:A=>{const M=b(A);if(f)o.done=A>=d;else{let R=A===0?p:0;m<1&&(R=A===0?qs(p):hC(b,A,M));const I=Math.abs(R)<=i,D=Math.abs(a-M)<=n;o.done=I&&D}return o.value=o.done?a:M,o},toString:()=>{const A=Math.min(Ey(k),Wd),M=dC(R=>k.next(A*R).value,A,30);return A+"ms "+M},toTransition:()=>{}};return k}qd.applyToOptions=s=>{const e=TL(s,100,qd);return s.ease=e.ease,s.duration=qs(e.duration),s.type="keyframes",s};function og({keyframes:s,velocity:e=0,power:t=.8,timeConstant:i=325,bounceDamping:n=10,bounceStiffness:r=500,modifyTarget:a,min:o,max:c,restDelta:l=.5,restSpeed:u}){const d=s[0],h={done:!1,value:d},f=I=>o!==void 0&&Ic,p=I=>o===void 0?c:c===void 0||Math.abs(o-I)-m*Math.exp(-I/i),b=I=>v+w(I),k=I=>{const D=w(I),B=b(I);h.done=Math.abs(D)<=l,h.value=h.done?v:B};let A,M;const R=I=>{f(h.value)&&(A=I,M=qd({keyframes:[h.value,p(h.value)],velocity:hC(b,I,h.value),damping:n,stiffness:r,restDelta:l,restSpeed:u}))};return R(0),{calculatedDuration:null,next:I=>{let D=!1;return!M&&A===void 0&&(D=!0,k(I),R(I)),A!==void 0&&I>=A?M.next(I-A):(!D&&k(I),h)}}}function PL(s,e,t){const i=[],n=t||Sn.mix||uC,r=s.length-1;for(let a=0;ae[0];if(r===2&&e[0]===e[1])return()=>e[1];const a=s[0]===s[1];s[0]>s[r-1]&&(s=[...s].reverse(),e=[...e].reverse());const o=PL(e,i,n),c=o.length,l=u=>{if(a&&u1)for(;dl(An(s[0],s[r-1],u)):l}function DL(s,e){const t=s[s.length-1];for(let i=1;i<=e;i++){const n=wl(0,e,i);s.push(Qe(t,1,n))}}function FL(s){const e=[0];return DL(e,s.length-1),e}function LL(s,e){return s.map(t=>t*e)}function OL(s,e){return s.map(()=>e||eC).splice(0,s.length-1)}function Zc({duration:s=300,keyframes:e,times:t,ease:i="easeInOut"}){const n=HF(i)?i.map(gx):gx(i),r={done:!1,value:e[0]},a=LL(t&&t.length===e.length?t:FL(e),s),o=RL(a,e,{ease:Array.isArray(n)?n:OL(e,n)});return{calculatedDuration:s,next:c=>(r.value=o(c),r.done=c>=s,r)}}const BL=s=>s!==null;function My(s,{repeat:e,repeatType:t="loop"},i,n=1){const r=s.filter(BL),o=n<0||e&&t!=="loop"&&e%2===1?0:r.length-1;return!o||i===void 0?r[o]:i}const $L={decay:og,inertia:og,tween:Zc,keyframes:Zc,spring:qd};function fC(s){typeof s.type=="string"&&(s.type=$L[s.type])}let Iy=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}};const jL=s=>s/100;let Py=class extends Iy{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==bi.now()&&this.tick(bi.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;fC(e);const{type:t=Zc,repeat:i=0,repeatDelay:n=0,repeatType:r,velocity:a=0}=e;let{keyframes:o}=e;const c=t||Zc;c!==Zc&&typeof o[0]!="number"&&(this.mixKeyframes=Jl(jL,uC(o[0],o[1])),o=[0,100]);const l=c({...e,keyframes:o});r==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...o].reverse(),velocity:-a})),l.calculatedDuration===null&&(l.calculatedDuration=Ey(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+n,this.totalDuration=this.resolvedDuration*(i+1)-n,this.generator=l}updateTime(e){const t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=t}tick(e,t=!1){const{generator:i,totalDuration:n,mixKeyframes:r,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-n/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);const v=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?v<0:v>n;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let b=this.currentTime,k=i;if(d){const I=Math.min(this.currentTime,n)/o;let D=Math.floor(I),B=I%1;!B&&I>=1&&(B=1),B===1&&D--,D=Math.min(D,d+1),!!(D%2)&&(h==="reverse"?(B=1-B,f&&(B-=f/o)):h==="mirror"&&(k=a)),b=An(0,1,B)*o}const A=w?{done:!1,value:u[0]}:k.next(b);r&&(A.value=r(A.value));let{done:M}=A;!w&&c!==null&&(M=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return R&&p!==og&&(A.value=My(u,this.options,g,this.speed)),m&&m(A.value),R&&this.finish(),A}then(e,t){return this.finished.then(e,t)}get duration(){return os(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+os(e)}get time(){return os(this.currentTime)}set time(e){e=qs(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(bi.now());const t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=os(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=_L,startTime:t}=this.options;this.driver||(this.driver=e(n=>this.tick(n))),this.options.onPlay?.();const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=t??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(bi.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}};function NL(s){for(let e=1;es*180/Math.PI,cg=s=>{const e=Gr(Math.atan2(s[1],s[0]));return lg(e)},VL={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:cg,rotateZ:cg,skewX:s=>Gr(Math.atan(s[1])),skewY:s=>Gr(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},lg=s=>(s=s%360,s<0&&(s+=360),s),_x=cg,Tx=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),kx=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),UL={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Tx,scaleY:kx,scale:s=>(Tx(s)+kx(s))/2,rotateX:s=>lg(Gr(Math.atan2(s[6],s[5]))),rotateY:s=>lg(Gr(Math.atan2(-s[2],s[0]))),rotateZ:_x,rotate:_x,skewX:s=>Gr(Math.atan(s[4])),skewY:s=>Gr(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function ug(s){return s.includes("scale")?1:0}function dg(s,e){if(!s||s==="none")return ug(e);const t=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,n;if(t)i=UL,n=t;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=VL,n=o}if(!n)return ug(e);const r=i[e],a=n[1].split(",").map(GL);return typeof r=="function"?r(a):a[r]}const zL=(s,e)=>{const{transform:t="none"}=getComputedStyle(s);return dg(t,e)};function GL(s){return parseFloat(s.trim())}const Wo=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],qo=new Set(Wo),Ax=s=>s===Go||s===me,WL=new Set(["x","y","z"]),qL=Wo.filter(s=>!WL.has(s));function HL(s){const e=[];return qL.forEach(t=>{const i=s.getValue(t);i!==void 0&&(e.push([t,i.get()]),i.set(t.startsWith("scale")?1:0))}),e}const ea={width:({x:s},{paddingLeft:e="0",paddingRight:t="0"})=>s.max-s.min-parseFloat(e)-parseFloat(t),height:({y:s},{paddingTop:e="0",paddingBottom:t="0"})=>s.max-s.min-parseFloat(e)-parseFloat(t),top:(s,{top:e})=>parseFloat(e),left:(s,{left:e})=>parseFloat(e),bottom:({y:s},{top:e})=>parseFloat(e)+(s.max-s.min),right:({x:s},{left:e})=>parseFloat(e)+(s.max-s.min),x:(s,{transform:e})=>dg(e,"x"),y:(s,{transform:e})=>dg(e,"y")};ea.translateX=ea.x;ea.translateY=ea.y;const ta=new Set;let hg=!1,fg=!1,pg=!1;function pC(){if(fg){const s=Array.from(ta).filter(i=>i.needsMeasurement),e=new Set(s.map(i=>i.element)),t=new Map;e.forEach(i=>{const n=HL(i);n.length&&(t.set(i,n),i.render())}),s.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const n=t.get(i);n&&n.forEach(([r,a])=>{i.getValue(r)?.set(a)})}),s.forEach(i=>i.measureEndState()),s.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}fg=!1,hg=!1,ta.forEach(s=>s.complete(pg)),ta.clear()}function mC(){ta.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(fg=!0)})}function YL(){pg=!0,mC(),pC(),pg=!1}let Ry=class{constructor(e,t,i,n,r,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=i,this.motionValue=n,this.element=r,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(ta.add(this),hg||(hg=!0,Ge.read(mC),Ge.resolveKeyframes(pC))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:t,element:i,motionValue:n}=this;if(e[0]===null){const r=n?.get(),a=e[e.length-1];if(r!==void 0)e[0]=r;else if(i&&t){const o=i.readValue(t,a);o!=null&&(e[0]=o)}e[0]===void 0&&(e[0]=a),n&&r===void 0&&n.set(e[0])}NL(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ta.delete(this)}cancel(){this.state==="scheduled"&&(ta.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}};const XL=s=>s.startsWith("--");function KL(s,e,t){XL(e)?s.style.setProperty(e,t):s.style[e]=t}const QL=by(()=>window.ScrollTimeline!==void 0),JL={};function ZL(s,e){const t=by(s);return()=>JL[e]??t()}const gC=ZL(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),jc=([s,e,t,i])=>`cubic-bezier(${s}, ${e}, ${t}, ${i})`,Sx={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:jc([0,.65,.55,1]),circOut:jc([.55,0,1,.45]),backIn:jc([.31,.01,.66,-.59]),backOut:jc([.33,1.53,.69,.99])};function yC(s,e){if(s)return typeof s=="function"?gC()?dC(s,e):"ease-out":tC(s)?jc(s):Array.isArray(s)?s.map(t=>yC(t,e)||Sx.easeOut):Sx[s]}function eO(s,e,t,{delay:i=0,duration:n=300,repeat:r=0,repeatType:a="loop",ease:o="easeOut",times:c}={},l=void 0){const u={[e]:t};c&&(u.offset=c);const d=yC(o,n);Array.isArray(d)&&(u.easing=d);const h={delay:i,duration:n,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:r+1,direction:a==="reverse"?"alternate":"normal"};return l&&(h.pseudoElement=l),s.animate(u,h)}function vC(s){return typeof s=="function"&&"applyToOptions"in s}function tO({type:s,...e}){return vC(s)&&gC()?s.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}let iO=class extends Iy{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:t,name:i,keyframes:n,pseudoElement:r,allowFlatten:a=!1,finalKeyframe:o,onComplete:c}=e;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=e,vy(typeof e.type!="string");const l=tO(e);this.animation=eO(t,i,n,l,r),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=My(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(u):KL(t,i,u),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return os(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+os(e)}get time(){return os(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=qs(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:t}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&QL()?(this.animation.timeline=e,ms):t(this)}};const bC={anticipate:QS,backInOut:KS,circInOut:ZS};function sO(s){return s in bC}function nO(s){typeof s.ease=="string"&&sO(s.ease)&&(s.ease=bC[s.ease])}const Cx=10;let rO=class extends iO{constructor(e){nO(e),fC(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:t,onUpdate:i,onComplete:n,element:r,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}const o=new Py({...a,autoplay:!1}),c=qs(this.finishedTime??this.time);t.setWithVelocity(o.sample(c-Cx).value,o.sample(c).value,Cx),o.stop()}};const Ex=(s,e)=>e==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(ur.test(s)||s==="0")&&!s.startsWith("url("));function aO(s){const e=s[0];if(s.length===1)return!0;for(let t=0;tObject.hasOwnProperty.call(Element.prototype,"animate"));function uO(s){const{motionValue:e,name:t,repeatDelay:i,repeatType:n,damping:r,type:a}=s;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=e.owner.getProps();return lO()&&t&&cO.has(t)&&(t!=="transform"||!l)&&!c&&!i&&n!=="mirror"&&r!==0&&a!=="inertia"}const dO=40;let hO=class extends Iy{constructor({autoplay:e=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:a="loop",keyframes:o,name:c,motionValue:l,element:u,...d}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=bi.now();const h={autoplay:e,delay:t,type:i,repeat:n,repeatDelay:r,repeatType:a,name:c,motionValue:l,element:u,...d},f=u?.KeyframeResolver||Ry;this.keyframeResolver=new f(o,(p,m,g)=>this.onKeyframesResolved(p,m,h,!g),c,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,i,n){this.keyframeResolver=void 0;const{name:r,type:a,velocity:o,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=bi.now(),oO(e,r,a,o)||((Sn.instantAnimations||!c)&&u?.(My(e,i,t)),e[0]=e[e.length-1],mg(i),i.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>dO?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:t,...i,keyframes:e},f=!l&&uO(h)?new rO({...h,element:h.motionValue.owner.current}):new Py(h);f.finished.then(()=>this.notifyFinished()).catch(ms),this.pendingTimeline&&(this.stopTimeline=f.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=f}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),YL()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};const fO=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pO(s){const e=fO.exec(s);if(!e)return[,];const[,t,i,n]=e;return[`--${t??i}`,n]}function xC(s,e,t=1){const[i,n]=pO(s);if(!i)return;const r=window.getComputedStyle(e).getPropertyValue(i);if(r){const a=r.trim();return US(a)?parseFloat(a):a}return ky(n)?xC(n,e,t+1):n}function Dy(s,e){return s?.[e]??s?.default??s}const wC=new Set(["width","height","top","left","right","bottom",...Wo]),mO={test:s=>s==="auto",parse:s=>s},_C=s=>e=>e.test(s),TC=[Go,me,Hs,qn,aL,rL,mO],Mx=s=>TC.find(_C(s));function gO(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||GS(s):!0}const yO=new Set(["brightness","contrast","saturate","opacity"]);function vO(s){const[e,t]=s.slice(0,-1).split("(");if(e==="drop-shadow")return s;const[i]=t.match(Ay)||[];if(!i)return s;const n=t.replace(i,"");let r=yO.has(e)?1:0;return i!==t&&(r*=100),e+"("+r+n+")"}const bO=/\b([a-z-]*)\(.*?\)/gu,gg={...ur,getAnimatableNone:s=>{const e=s.match(bO);return e?e.map(vO).join(" "):s}},Ix={...Go,transform:Math.round},xO={rotate:qn,rotateX:qn,rotateY:qn,rotateZ:qn,scale:Cu,scaleX:Cu,scaleY:Cu,scaleZ:Cu,skew:qn,skewX:qn,skewY:qn,distance:me,translateX:me,translateY:me,translateZ:me,x:me,y:me,z:me,perspective:me,transformPerspective:me,opacity:_l,originX:yx,originY:yx,originZ:me},Fy={borderWidth:me,borderTopWidth:me,borderRightWidth:me,borderBottomWidth:me,borderLeftWidth:me,borderRadius:me,radius:me,borderTopLeftRadius:me,borderTopRightRadius:me,borderBottomRightRadius:me,borderBottomLeftRadius:me,width:me,maxWidth:me,height:me,maxHeight:me,top:me,right:me,bottom:me,left:me,padding:me,paddingTop:me,paddingRight:me,paddingBottom:me,paddingLeft:me,margin:me,marginTop:me,marginRight:me,marginBottom:me,marginLeft:me,backgroundPositionX:me,backgroundPositionY:me,...xO,zIndex:Ix,fillOpacity:_l,strokeOpacity:_l,numOctaves:Ix},wO={...Fy,color:vt,backgroundColor:vt,outlineColor:vt,fill:vt,stroke:vt,borderColor:vt,borderTopColor:vt,borderRightColor:vt,borderBottomColor:vt,borderLeftColor:vt,filter:gg,WebkitFilter:gg},kC=s=>wO[s];function AC(s,e){let t=kC(s);return t!==gg&&(t=ur),t.getAnimatableNone?t.getAnimatableNone(e):void 0}const _O=new Set(["auto","none","0"]);function TO(s,e,t){let i=0,n;for(;i{e.getValue(o).set(c)}),this.resolveNoneKeyframes()}};function AO(s,e,t){if(s instanceof EventTarget)return[s];if(typeof s=="string"){let i=document;const n=t?.[s]??i.querySelectorAll(s);return n?Array.from(n):[]}return Array.from(s)}const SC=(s,e)=>e&&typeof s=="number"?e.transform(s):s;function CC(s){return zS(s)&&"offsetHeight"in s}const Px=30,SO=s=>!isNaN(parseFloat(s));let CO=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{const n=bi.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const r of this.dependents)r.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=bi.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=SO(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new xy);const i=this.events[e].add(t);return e==="change"?()=>{i(),Ge.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,i){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=bi.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Px)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,Px);return WS(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function xo(s,e){return new CO(s,e)}const{schedule:Ly}=iC(queueMicrotask,!1),Ts={x:!1,y:!1};function EC(){return Ts.x||Ts.y}function EO(s){return s==="x"||s==="y"?Ts[s]?null:(Ts[s]=!0,()=>{Ts[s]=!1}):Ts.x||Ts.y?null:(Ts.x=Ts.y=!0,()=>{Ts.x=Ts.y=!1})}function MC(s,e){const t=AO(s),i=new AbortController,n={passive:!0,...e,signal:i.signal};return[t,n,()=>i.abort()]}function Rx(s){return!(s.pointerType==="touch"||EC())}function MO(s,e,t={}){const[i,n,r]=MC(s,t),a=o=>{if(!Rx(o))return;const{target:c}=o,l=e(c,o);if(typeof l!="function"||!c)return;const u=d=>{Rx(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,n)};return i.forEach(o=>{o.addEventListener("pointerenter",a,n)}),r}const IC=(s,e)=>e?s===e?!0:IC(s,e.parentElement):!1,Oy=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,IO=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function PO(s){return IO.has(s.tagName)||s.tabIndex!==-1}const ud=new WeakSet;function Dx(s){return e=>{e.key==="Enter"&&s(e)}}function Wf(s,e){s.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const RO=(s,e)=>{const t=s.currentTarget;if(!t)return;const i=Dx(()=>{if(ud.has(t))return;Wf(t,"down");const n=Dx(()=>{Wf(t,"up")}),r=()=>Wf(t,"cancel");t.addEventListener("keyup",n,e),t.addEventListener("blur",r,e)});t.addEventListener("keydown",i,e),t.addEventListener("blur",()=>t.removeEventListener("keydown",i),e)};function Fx(s){return Oy(s)&&!EC()}function DO(s,e,t={}){const[i,n,r]=MC(s,t),a=o=>{const c=o.currentTarget;if(!Fx(o))return;ud.add(c);const l=e(c,o),u=(f,p)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),ud.has(c)&&ud.delete(c),Fx(f)&&typeof l=="function"&&l(f,{success:p})},d=f=>{u(f,c===window||c===document||t.useGlobalTarget||IC(c,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,n),window.addEventListener("pointercancel",h,n)};return i.forEach(o=>{(t.useGlobalTarget?window:o).addEventListener("pointerdown",a,n),CC(o)&&(o.addEventListener("focus",l=>RO(l,n)),!PO(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),r}function PC(s){return zS(s)&&"ownerSVGElement"in s}function FO(s){return PC(s)&&s.tagName==="svg"}const Jt=s=>!!(s&&s.getVelocity),LO=[...TC,vt,ur],OO=s=>LO.find(_C(s)),By=F.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function Lx(s,e){if(typeof s=="function")return s(e);s!=null&&(s.current=e)}function BO(...s){return e=>{let t=!1;const i=s.map(n=>{const r=Lx(n,e);return!t&&typeof r=="function"&&(t=!0),r});if(t)return()=>{for(let n=0;n{const{width:l,height:u,top:d,left:h,right:f}=a.current;if(e||!r.current||!l||!u)return;const p=t==="left"?`left: ${h}`:`right: ${f}`;r.current.dataset.motionPopId=n;const m=document.createElement("style");o&&(m.nonce=o);const g=i??document.head;return g.appendChild(m),m.sheet&&m.sheet.insertRule(` + [data-motion-pop-id="${n}"] { + position: absolute !important; + width: ${l}px !important; + height: ${u}px !important; + ${p}px !important; + top: ${d}px !important; + } + `),()=>{g.contains(m)&&g.removeChild(m)}},[e]),x.jsx(jO,{isPresent:e,childRef:r,sizeRef:a,children:F.cloneElement(s,{ref:c})})}const VO=({children:s,initial:e,isPresent:t,onExitComplete:i,custom:n,presenceAffectsLayout:r,mode:a,anchorX:o,root:c})=>{const l=py(UO),u=F.useId();let d=!0,h=F.useMemo(()=>(d=!1,{id:u,initial:e,isPresent:t,custom:n,onExitComplete:f=>{l.set(f,!0);for(const p of l.values())if(!p)return;i&&i()},register:f=>(l.set(f,!1),()=>l.delete(f))}),[t,l,i]);return r&&d&&(h={...h}),F.useMemo(()=>{l.forEach((f,p)=>l.set(p,!1))},[t]),F.useEffect(()=>{!t&&!l.size&&i&&i()},[t]),a==="popLayout"&&(s=x.jsx(NO,{isPresent:t,anchorX:o,root:c,children:s})),x.jsx(Rh.Provider,{value:h,children:s})};function UO(){return new Map}function RC(s=!0){const e=F.useContext(Rh);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:i,register:n}=e,r=F.useId();F.useEffect(()=>{if(s)return n(r)},[s]);const a=F.useCallback(()=>s&&i&&i(r),[r,i,s]);return!t&&i?[!1,a]:[!0]}const Eu=s=>s.key||"";function Ox(s){const e=[];return F.Children.forEach(s,t=>{F.isValidElement(t)&&e.push(t)}),e}const zO=({children:s,custom:e,initial:t=!0,onExitComplete:i,presenceAffectsLayout:n=!0,mode:r="sync",propagate:a=!1,anchorX:o="left",root:c})=>{const[l,u]=RC(a),d=F.useMemo(()=>Ox(s),[s]),h=a&&!l?[]:d.map(Eu),f=F.useRef(!0),p=F.useRef(d),m=py(()=>new Map),[g,v]=F.useState(d),[w,b]=F.useState(d);VS(()=>{f.current=!1,p.current=d;for(let M=0;M{const R=Eu(M),I=a&&!l?!1:d===w||h.includes(R),D=()=>{if(m.has(R))m.set(R,!0);else return;let B=!0;m.forEach($=>{$||(B=!1)}),B&&(A?.(),b(p.current),a&&u?.(),i&&i())};return x.jsx(VO,{isPresent:I,initial:!f.current||t?void 0:!1,custom:e,presenceAffectsLayout:n,mode:r,root:c,onExitComplete:I?void 0:D,anchorX:o,children:M},R)})})},DC=F.createContext({strict:!1}),Bx={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},wo={};for(const s in Bx)wo[s]={isEnabled:e=>Bx[s].some(t=>!!e[t])};function GO(s){for(const e in s)wo[e]={...wo[e],...s[e]}}const WO=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Hd(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||WO.has(s)}let FC=s=>!Hd(s);function qO(s){typeof s=="function"&&(FC=e=>e.startsWith("on")?!Hd(e):s(e))}try{qO(require("@emotion/is-prop-valid").default)}catch{}function HO(s,e,t){const i={};for(const n in s)n==="values"&&typeof s.values=="object"||(FC(n)||t===!0&&Hd(n)||!e&&!Hd(n)||s.draggable&&n.startsWith("onDrag"))&&(i[n]=s[n]);return i}const Dh=F.createContext({});function Fh(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function kl(s){return typeof s=="string"||Array.isArray(s)}const $y=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],jy=["initial",...$y];function Lh(s){return Fh(s.animate)||jy.some(e=>kl(s[e]))}function LC(s){return!!(Lh(s)||s.variants)}function YO(s,e){if(Lh(s)){const{initial:t,animate:i}=s;return{initial:t===!1||kl(t)?t:void 0,animate:kl(i)?i:void 0}}return s.inherit!==!1?e:{}}function XO(s){const{initial:e,animate:t}=YO(s,F.useContext(Dh));return F.useMemo(()=>({initial:e,animate:t}),[$x(e),$x(t)])}function $x(s){return Array.isArray(s)?s.join(" "):s}const Al={};function KO(s){for(const e in s)Al[e]=s[e],Ty(e)&&(Al[e].isCSSVariable=!0)}function OC(s,{layout:e,layoutId:t}){return qo.has(s)||s.startsWith("origin")||(e||t!==void 0)&&(!!Al[s]||s==="opacity")}const QO={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},JO=Wo.length;function ZO(s,e,t){let i="",n=!0;for(let r=0;r({style:{},transform:{},transformOrigin:{},vars:{}});function BC(s,e,t){for(const i in e)!Jt(e[i])&&!OC(i,t)&&(s[i]=e[i])}function e6({transformTemplate:s},e){return F.useMemo(()=>{const t=Vy();return Ny(t,e,s),Object.assign({},t.vars,t.style)},[e])}function t6(s,e){const t=s.style||{},i={};return BC(i,t,s),Object.assign(i,e6(s,e)),i}function i6(s,e){const t={},i=t6(s,e);return s.drag&&s.dragListener!==!1&&(t.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(t.tabIndex=0),t.style=i,t}const s6={offset:"stroke-dashoffset",array:"stroke-dasharray"},n6={offset:"strokeDashoffset",array:"strokeDasharray"};function r6(s,e,t=1,i=0,n=!0){s.pathLength=1;const r=n?s6:n6;s[r.offset]=me.transform(-i);const a=me.transform(e),o=me.transform(t);s[r.array]=`${a} ${o}`}function $C(s,{attrX:e,attrY:t,attrScale:i,pathLength:n,pathSpacing:r=1,pathOffset:a=0,...o},c,l,u){if(Ny(s,o,l),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:d,style:h}=s;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=u?.transformBox??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),t!==void 0&&(d.y=t),i!==void 0&&(d.scale=i),n!==void 0&&r6(d,n,r,a,!1)}const jC=()=>({...Vy(),attrs:{}}),NC=s=>typeof s=="string"&&s.toLowerCase()==="svg";function a6(s,e,t,i){const n=F.useMemo(()=>{const r=jC();return $C(r,e,NC(i),s.transformTemplate,s.style),{...r.attrs,style:{...r.style}}},[e]);if(s.style){const r={};BC(r,s.style,s),n.style={...r,...n.style}}return n}const o6=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Uy(s){return typeof s!="string"||s.includes("-")?!1:!!(o6.indexOf(s)>-1||/[A-Z]/u.test(s))}function c6(s,e,t,{latestValues:i},n,r=!1){const o=(Uy(s)?a6:i6)(e,i,n,s),c=HO(e,typeof s=="string",r),l=s!==F.Fragment?{...c,...o,ref:t}:{},{children:u}=e,d=F.useMemo(()=>Jt(u)?u.get():u,[u]);return F.createElement(s,{...l,children:d})}function jx(s){const e=[{},{}];return s?.values.forEach((t,i)=>{e[0][i]=t.get(),e[1][i]=t.getVelocity()}),e}function zy(s,e,t,i){if(typeof e=="function"){const[n,r]=jx(i);e=e(t!==void 0?t:s.custom,n,r)}if(typeof e=="string"&&(e=s.variants&&s.variants[e]),typeof e=="function"){const[n,r]=jx(i);e=e(t!==void 0?t:s.custom,n,r)}return e}function dd(s){return Jt(s)?s.get():s}function l6({scrapeMotionValuesFromProps:s,createRenderState:e},t,i,n){return{latestValues:u6(t,i,n,s),renderState:e()}}function u6(s,e,t,i){const n={},r=i(s,{});for(const h in r)n[h]=dd(r[h]);let{initial:a,animate:o}=s;const c=Lh(s),l=LC(s);e&&l&&!c&&s.inherit!==!1&&(a===void 0&&(a=e.initial),o===void 0&&(o=e.animate));let u=t?t.initial===!1:!1;u=u||a===!1;const d=u?o:a;if(d&&typeof d!="boolean"&&!Fh(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f(e,t)=>{const i=F.useContext(Dh),n=F.useContext(Rh),r=()=>l6(s,e,i,n);return t?r():py(r)};function Gy(s,e,t){const{style:i}=s,n={};for(const r in i)(Jt(i[r])||e.style&&Jt(e.style[r])||OC(r,s)||t?.getValue(r)?.liveStyle!==void 0)&&(n[r]=i[r]);return n}const d6=VC({scrapeMotionValuesFromProps:Gy,createRenderState:Vy});function UC(s,e,t){const i=Gy(s,e,t);for(const n in s)if(Jt(s[n])||Jt(e[n])){const r=Wo.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;i[r]=s[n]}return i}const h6=VC({scrapeMotionValuesFromProps:UC,createRenderState:jC}),f6=Symbol.for("motionComponentSymbol");function Ua(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function p6(s,e,t){return F.useCallback(i=>{i&&s.onMount&&s.onMount(i),e&&(i?e.mount(i):e.unmount()),t&&(typeof t=="function"?t(i):Ua(t)&&(t.current=i))},[e])}const Wy=s=>s.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),m6="framerAppearId",zC="data-"+Wy(m6),GC=F.createContext({});function g6(s,e,t,i,n){const{visualElement:r}=F.useContext(Dh),a=F.useContext(DC),o=F.useContext(Rh),c=F.useContext(By).reducedMotion,l=F.useRef(null);i=i||a.renderer,!l.current&&i&&(l.current=i(s,{visualState:e,parent:r,props:t,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=F.useContext(GC);u&&!u.projection&&n&&(u.type==="html"||u.type==="svg")&&y6(l.current,t,n,d);const h=F.useRef(!1);F.useInsertionEffect(()=>{u&&h.current&&u.update(t,o)});const f=t[zC],p=F.useRef(!!f&&!window.MotionHandoffIsComplete?.(f)&&window.MotionHasOptimisedAnimation?.(f));return VS(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),p.current&&u.animationState&&u.animationState.animateChanges())}),F.useEffect(()=>{u&&(!p.current&&u.animationState&&u.animationState.animateChanges(),p.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(f)}),p.current=!1),u.enteringChildren=void 0)}),u}function y6(s,e,t,i){const{layoutId:n,layout:r,drag:a,dragConstraints:o,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=e;s.projection=new t(s.latestValues,e["data-framer-portal-id"]?void 0:WC(s.parent)),s.projection.setOptions({layoutId:n,layout:r,alwaysMeasureLayout:!!a||o&&Ua(o),visualElement:s,animationType:typeof r=="string"?r:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function WC(s){if(s)return s.options.allowProjection!==!1?s.projection:WC(s.parent)}function qf(s,{forwardMotionProps:e=!1}={},t,i){t&&GO(t);const n=Uy(s)?h6:d6;function r(o,c){let l;const u={...F.useContext(By),...o,layoutId:v6(o)},{isStatic:d}=u,h=XO(o),f=n(o,d);if(!d&&my){b6();const p=x6(u);l=p.MeasureLayout,h.visualElement=g6(s,f,u,i,p.ProjectionNode)}return x.jsxs(Dh.Provider,{value:h,children:[l&&h.visualElement?x.jsx(l,{visualElement:h.visualElement,...u}):null,c6(s,o,p6(f,h.visualElement,c),f,d,e)]})}r.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const a=F.forwardRef(r);return a[f6]=s,a}function v6({layoutId:s}){const e=F.useContext(fy).id;return e&&s!==void 0?e+"-"+s:s}function b6(s,e){F.useContext(DC).strict}function x6(s){const{drag:e,layout:t}=wo;if(!e&&!t)return{};const i={...e,...t};return{MeasureLayout:e?.isEnabled(s)||t?.isEnabled(s)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function w6(s,e){if(typeof Proxy>"u")return qf;const t=new Map,i=(r,a)=>qf(r,a,s,e),n=(r,a)=>i(r,a);return new Proxy(n,{get:(r,a)=>a==="create"?i:(t.has(a)||t.set(a,qf(a,void 0,s,e)),t.get(a))})}function qC({top:s,left:e,right:t,bottom:i}){return{x:{min:e,max:t},y:{min:s,max:i}}}function _6({x:s,y:e}){return{top:e.min,right:s.max,bottom:e.max,left:s.min}}function T6(s,e){if(!e)return s;const t=e({x:s.left,y:s.top}),i=e({x:s.right,y:s.bottom});return{top:t.y,left:t.x,bottom:i.y,right:i.x}}function Hf(s){return s===void 0||s===1}function yg({scale:s,scaleX:e,scaleY:t}){return!Hf(s)||!Hf(e)||!Hf(t)}function jr(s){return yg(s)||HC(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function HC(s){return Nx(s.x)||Nx(s.y)}function Nx(s){return s&&s!=="0%"}function Yd(s,e,t){const i=s-t,n=e*i;return t+n}function Vx(s,e,t,i,n){return n!==void 0&&(s=Yd(s,n,i)),Yd(s,t,i)+e}function vg(s,e=0,t=1,i,n){s.min=Vx(s.min,e,t,i,n),s.max=Vx(s.max,e,t,i,n)}function YC(s,{x:e,y:t}){vg(s.x,e.translate,e.scale,e.originPoint),vg(s.y,t.translate,t.scale,t.originPoint)}const Ux=.999999999999,zx=1.0000000000001;function k6(s,e,t,i=!1){const n=t.length;if(!n)return;e.x=e.y=1;let r,a;for(let o=0;oUx&&(e.x=1),e.yUx&&(e.y=1)}function za(s,e){s.min=s.min+e,s.max=s.max+e}function Gx(s,e,t,i,n=.5){const r=Qe(s.min,s.max,n);vg(s,e,t,r,i)}function Ga(s,e){Gx(s.x,e.x,e.scaleX,e.scale,e.originX),Gx(s.y,e.y,e.scaleY,e.scale,e.originY)}function XC(s,e){return qC(T6(s.getBoundingClientRect(),e))}function A6(s,e,t){const i=XC(s,t),{scroll:n}=e;return n&&(za(i.x,n.offset.x),za(i.y,n.offset.y)),i}const Wx=()=>({translate:0,scale:1,origin:0,originPoint:0}),Wa=()=>({x:Wx(),y:Wx()}),qx=()=>({min:0,max:0}),ft=()=>({x:qx(),y:qx()}),bg={current:null},KC={current:!1};function S6(){if(KC.current=!0,!!my)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),e=()=>bg.current=s.matches;s.addEventListener("change",e),e()}else bg.current=!1}const C6=new WeakMap;function E6(s,e,t){for(const i in e){const n=e[i],r=t[i];if(Jt(n))s.addValue(i,n);else if(Jt(r))s.addValue(i,xo(n,{owner:s}));else if(r!==n)if(s.hasValue(i)){const a=s.getValue(i);a.liveStyle===!0?a.jump(n):a.hasAnimated||a.set(n)}else{const a=s.getStaticValue(i);s.addValue(i,xo(a!==void 0?a:n,{owner:s}))}}for(const i in t)e[i]===void 0&&s.removeValue(i);return e}const Hx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let M6=class{scrapeMotionValuesFromProps(e,t,i){return{}}constructor({parent:e,props:t,presenceContext:i,reducedMotionConfig:n,blockInitialAnimation:r,visualState:a},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ry,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=bi.now();this.renderScheduledAtthis.bindToMotionValue(i,t)),KC.current||S6(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:bg.current,this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),lr(this.notifyUpdate),lr(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=qo.has(e);i&&this.onBindTransform&&this.onBindTransform();const n=t.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&Ge.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{n(),r&&r(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in wo){const t=wo[e];if(!t)continue;const{isEnabled:i,Feature:n}=t;if(!this.features[e]&&n&&i(this.props)&&(this.features[e]=new n(this)),this.features[e]){const r=this.features[e];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ft()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let i=0;it.variantChildren.delete(e)}addValue(e,t){const i=this.values.get(e);t!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);const t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&t!==void 0&&(i=xo(t===null?void 0:t,{owner:this}),this.addValue(e,i)),i}readValue(e,t){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(US(i)||GS(i))?i=parseFloat(i):!OO(i)&&ur.test(t)&&(i=AC(e,t)),this.setBaseTarget(e,Jt(i)?i.get():i)),Jt(i)?i.get():i}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){const{initial:t}=this.props;let i;if(typeof t=="string"||typeof t=="object"){const r=zy(this.props,t,this.presenceContext?.custom);r&&(i=r[e])}if(t&&i!==void 0)return i;const n=this.getBaseTargetFromProps(this.props,e);return n!==void 0&&!Jt(n)?n:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new xy),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Ly.render(this.render)}},QC=class extends M6{constructor(){super(...arguments),this.KeyframeResolver=kO}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){return e.style?e.style[t]:void 0}removeValueFromRenderState(e,{vars:t,style:i}){delete t[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Jt(e)&&(this.childSubscription=e.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}};function JC(s,{style:e,vars:t},i,n){const r=s.style;let a;for(a in e)r[a]=e[a];n?.applyProjectionStyles(r,i);for(a in t)r.setProperty(a,t[a])}function I6(s){return window.getComputedStyle(s)}let P6=class extends QC{constructor(){super(...arguments),this.type="html",this.renderInstance=JC}readValueFromInstance(e,t){if(qo.has(t))return this.projection?.isProjecting?ug(t):zL(e,t);{const i=I6(e),n=(Ty(t)?i.getPropertyValue(t):i[t])||0;return typeof n=="string"?n.trim():n}}measureInstanceViewportBox(e,{transformPagePoint:t}){return XC(e,t)}build(e,t,i){Ny(e,t,i.transformTemplate)}scrapeMotionValuesFromProps(e,t,i){return Gy(e,t,i)}};const ZC=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function R6(s,e,t,i){JC(s,e,void 0,i);for(const n in e.attrs)s.setAttribute(ZC.has(n)?n:Wy(n),e.attrs[n])}let D6=class extends QC{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ft}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(qo.has(t)){const i=kC(t);return i&&i.default||0}return t=ZC.has(t)?t:Wy(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,i){return UC(e,t,i)}build(e,t,i){$C(e,t,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,t,i,n){R6(e,t,i,n)}mount(e){this.isSVGTag=NC(e.tagName),super.mount(e)}};const F6=(s,e)=>Uy(s)?new D6(e):new P6(e,{allowProjection:s!==F.Fragment});function so(s,e,t){const i=s.getProps();return zy(i,e,t!==void 0?t:i.custom,s)}const xg=s=>Array.isArray(s);function L6(s,e,t){s.hasValue(e)?s.getValue(e).set(t):s.addValue(e,xo(t))}function O6(s){return xg(s)?s[s.length-1]||0:s}function B6(s,e){const t=so(s,e);let{transitionEnd:i={},transition:n={},...r}=t||{};r={...r,...i};for(const a in r){const o=O6(r[a]);L6(s,a,o)}}function $6(s){return!!(Jt(s)&&s.add)}function wg(s,e){const t=s.getValue("willChange");if($6(t))return t.add(e);if(!t&&Sn.WillChange){const i=new Sn.WillChange("auto");s.addValue("willChange",i),i.add(e)}}function e3(s){return s.props[zC]}const j6=s=>s!==null;function N6(s,{repeat:e,repeatType:t="loop"},i){const n=s.filter(j6),r=e&&t!=="loop"&&e%2===1?0:n.length-1;return n[r]}const V6={type:"spring",stiffness:500,damping:25,restSpeed:10},U6=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),z6={type:"keyframes",duration:.8},G6={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},W6=(s,{keyframes:e})=>e.length>2?z6:qo.has(s)?s.startsWith("scale")?U6(e[1]):V6:G6;function q6({when:s,delay:e,delayChildren:t,staggerChildren:i,staggerDirection:n,repeat:r,repeatType:a,repeatDelay:o,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const qy=(s,e,t,i={},n,r)=>a=>{const o=Dy(i,s)||{},c=o.delay||i.delay||0;let{elapsed:l=0}=i;l=l-qs(c);const u={keyframes:Array.isArray(t)?t:[null,t],ease:"easeOut",velocity:e.getVelocity(),...o,delay:-l,onUpdate:h=>{e.set(h),o.onUpdate&&o.onUpdate(h)},onComplete:()=>{a(),o.onComplete&&o.onComplete()},name:s,motionValue:e,element:r?void 0:n};q6(o)||Object.assign(u,W6(s,u)),u.duration&&(u.duration=qs(u.duration)),u.repeatDelay&&(u.repeatDelay=qs(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(mg(u),u.delay===0&&(d=!0)),(Sn.instantAnimations||Sn.skipAnimations)&&(d=!0,mg(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,d&&!r&&e.get()!==void 0){const h=N6(u.keyframes,o);if(h!==void 0){Ge.update(()=>{u.onUpdate(h),u.onComplete()});return}}return o.isSync?new Py(u):new hO(u)};function H6({protectedKeys:s,needsAnimating:e},t){const i=s.hasOwnProperty(t)&&e[t]!==!0;return e[t]=!1,i}function t3(s,e,{delay:t=0,transitionOverride:i,type:n}={}){let{transition:r=s.getDefaultTransition(),transitionEnd:a,...o}=e;i&&(r=i);const c=[],l=n&&s.animationState&&s.animationState.getState()[n];for(const u in o){const d=s.getValue(u,s.latestValues[u]??null),h=o[u];if(h===void 0||l&&H6(l,u))continue;const f={delay:t,...Dy(r||{},u)},p=d.get();if(p!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===p&&!f.velocity)continue;let m=!1;if(window.MotionHandoffAnimation){const v=e3(s);if(v){const w=window.MotionHandoffAnimation(v,u,Ge);w!==null&&(f.startTime=w,m=!0)}}wg(s,u),d.start(qy(u,d,h,s.shouldReduceMotion&&wC.has(u)?{type:!1}:f,s,m));const g=d.animation;g&&c.push(g)}return a&&Promise.all(c).then(()=>{Ge.update(()=>{a&&B6(s,a)})}),c}function i3(s,e,t,i=0,n=1){const r=Array.from(s).sort((l,u)=>l.sortNodePosition(u)).indexOf(e),a=s.size,o=(a-1)*i;return typeof t=="function"?t(r,a):n===1?r*i:o-r*i}function _g(s,e,t={}){const i=so(s,e,t.type==="exit"?s.presenceContext?.custom:void 0);let{transition:n=s.getDefaultTransition()||{}}=i||{};t.transitionOverride&&(n=t.transitionOverride);const r=i?()=>Promise.all(t3(s,i,t)):()=>Promise.resolve(),a=s.variantChildren&&s.variantChildren.size?(c=0)=>{const{delayChildren:l=0,staggerChildren:u,staggerDirection:d}=n;return Y6(s,e,c,l,u,d,t)}:()=>Promise.resolve(),{when:o}=n;if(o){const[c,l]=o==="beforeChildren"?[r,a]:[a,r];return c().then(()=>l())}else return Promise.all([r(),a(t.delay)])}function Y6(s,e,t=0,i=0,n=0,r=1,a){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",e),o.push(_g(c,e,{...a,delay:t+(typeof i=="function"?0:i)+i3(s.variantChildren,c,i,n,r)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(o)}function X6(s,e,t={}){s.notify("AnimationStart",e);let i;if(Array.isArray(e)){const n=e.map(r=>_g(s,r,t));i=Promise.all(n)}else if(typeof e=="string")i=_g(s,e,t);else{const n=typeof e=="function"?so(s,e,t.custom):e;i=Promise.all(t3(s,n,t))}return i.then(()=>{s.notify("AnimationComplete",e)})}function s3(s,e){if(!Array.isArray(e))return!1;const t=e.length;if(t!==s.length)return!1;for(let i=0;iPromise.all(e.map(({animation:t,options:i})=>X6(s,t,i)))}function eB(s){let e=Z6(s),t=Yx(),i=!0;const n=c=>(l,u)=>{const d=so(s,u,c==="exit"?s.presenceContext?.custom:void 0);if(d){const{transition:h,transitionEnd:f,...p}=d;l={...l,...p,...f}}return l};function r(c){e=c(s)}function a(c){const{props:l}=s,u=n3(s.parent)||{},d=[],h=new Set;let f={},p=1/0;for(let g=0;gp&&k,D=!1;const B=Array.isArray(b)?b:[b];let $=B.reduce(n(v),{});A===!1&&($={});const{prevResolvedValues:V={}}=w,y={...V,...$},_=C=>{I=!0,h.has(C)&&(D=!0,h.delete(C)),w.needsAnimating[C]=!0;const E=s.getValue(C);E&&(E.liveStyle=!1)};for(const C in y){const E=$[C],P=V[C];if(f.hasOwnProperty(C))continue;let L=!1;xg(E)&&xg(P)?L=!s3(E,P):L=E!==P,L?E!=null?_(C):h.add(C):E!==void 0&&h.has(C)?_(C):w.protectedKeys[C]=!0}w.prevProp=b,w.prevResolvedValues=$,w.isActive&&(f={...f,...$}),i&&s.blockInitialAnimation&&(I=!1);const T=M&&R;I&&(!T||D)&&d.push(...B.map(C=>{const E={type:v};if(typeof C=="string"&&i&&!T&&s.manuallyAnimateOnMount&&s.parent){const{parent:P}=s,L=so(P,C);if(P.enteringChildren&&L){const{delayChildren:O}=L.transition||{};E.delay=i3(P.enteringChildren,s,O)}}return{animation:C,options:E}}))}if(h.size){const g={};if(typeof l.initial!="boolean"){const v=so(s,Array.isArray(l.initial)?l.initial[0]:l.initial);v&&v.transition&&(g.transition=v.transition)}h.forEach(v=>{const w=s.getBaseTarget(v),b=s.getValue(v);b&&(b.liveStyle=!0),g[v]=w??null}),d.push({animation:g})}let m=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!s.manuallyAnimateOnMount&&(m=!1),i=!1,m?e(d):Promise.resolve()}function o(c,l){if(t[c].isActive===l)return Promise.resolve();s.variantChildren?.forEach(d=>d.animationState?.setActive(c,l)),t[c].isActive=l;const u=a(c);for(const d in t)t[d].protectedKeys={};return u}return{animateChanges:a,setActive:o,setAnimateFunction:r,getState:()=>t,reset:()=>{t=Yx()}}}function tB(s,e){return typeof e=="string"?e!==s:Array.isArray(e)?!s3(e,s):!1}function Ir(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Yx(){return{animate:Ir(!0),whileInView:Ir(),whileHover:Ir(),whileTap:Ir(),whileDrag:Ir(),whileFocus:Ir(),exit:Ir()}}let br=class{constructor(e){this.isMounted=!1,this.node=e}update(){}},iB=class extends br{constructor(e){super(e),e.animationState||(e.animationState=eB(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Fh(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},sB=0,nB=class extends br{constructor(){super(...arguments),this.id=sB++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const n=this.node.animationState.setActive("exit",!e);t&&!e&&n.then(()=>{t(this.id)})}mount(){const{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}};const rB={animation:{Feature:iB},exit:{Feature:nB}};function Sl(s,e,t,i={passive:!0}){return s.addEventListener(e,t,i),()=>s.removeEventListener(e,t)}function tu(s){return{point:{x:s.pageX,y:s.pageY}}}const aB=s=>e=>Oy(e)&&s(e,tu(e));function el(s,e,t,i){return Sl(s,e,aB(t),i)}const r3=1e-4,oB=1-r3,cB=1+r3,a3=.01,lB=0-a3,uB=0+a3;function li(s){return s.max-s.min}function dB(s,e,t){return Math.abs(s-e)<=t}function Xx(s,e,t,i=.5){s.origin=i,s.originPoint=Qe(e.min,e.max,s.origin),s.scale=li(t)/li(e),s.translate=Qe(t.min,t.max,s.origin)-s.originPoint,(s.scale>=oB&&s.scale<=cB||isNaN(s.scale))&&(s.scale=1),(s.translate>=lB&&s.translate<=uB||isNaN(s.translate))&&(s.translate=0)}function tl(s,e,t,i){Xx(s.x,e.x,t.x,i?i.originX:void 0),Xx(s.y,e.y,t.y,i?i.originY:void 0)}function Kx(s,e,t){s.min=t.min+e.min,s.max=s.min+li(e)}function hB(s,e,t){Kx(s.x,e.x,t.x),Kx(s.y,e.y,t.y)}function Qx(s,e,t){s.min=e.min-t.min,s.max=s.min+li(e)}function il(s,e,t){Qx(s.x,e.x,t.x),Qx(s.y,e.y,t.y)}function is(s){return[s("x"),s("y")]}const o3=({current:s})=>s?s.ownerDocument.defaultView:null,Jx=(s,e)=>Math.abs(s-e);function fB(s,e){const t=Jx(s.x,e.x),i=Jx(s.y,e.y);return Math.sqrt(t**2+i**2)}let c3=class{constructor(e,t,{transformPagePoint:i,contextWindow:n=window,dragSnapToOrigin:r=!1,distanceThreshold:a=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=Xf(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,p=fB(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!p)return;const{point:m}=h,{timestamp:g}=Vt;this.history.push({...m,timestamp:g});const{onStart:v,onMove:w}=this.handlers;f||(v&&v(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,h)},this.handlePointerMove=(h,f)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Yf(f,this.transformPagePoint),Ge.update(this.updatePoint,!0)},this.handlePointerUp=(h,f)=>{this.end();const{onEnd:p,onSessionEnd:m,resumeAnimation:g}=this.handlers;if(this.dragSnapToOrigin&&g&&g(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=Xf(h.type==="pointercancel"?this.lastMoveEventInfo:Yf(f,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,v),m&&m(h,v)},!Oy(e))return;this.dragSnapToOrigin=r,this.handlers=t,this.transformPagePoint=i,this.distanceThreshold=a,this.contextWindow=n||window;const o=tu(e),c=Yf(o,this.transformPagePoint),{point:l}=c,{timestamp:u}=Vt;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=t;d&&d(e,Xf(c,this.history)),this.removeListeners=Jl(el(this.contextWindow,"pointermove",this.handlePointerMove),el(this.contextWindow,"pointerup",this.handlePointerUp),el(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),lr(this.updatePoint)}};function Yf(s,e){return e?{point:e(s.point)}:s}function Zx(s,e){return{x:s.x-e.x,y:s.y-e.y}}function Xf({point:s},e){return{point:s,delta:Zx(s,l3(e)),offset:Zx(s,pB(e)),velocity:mB(e,.1)}}function pB(s){return s[0]}function l3(s){return s[s.length-1]}function mB(s,e){if(s.length<2)return{x:0,y:0};let t=s.length-1,i=null;const n=l3(s);for(;t>=0&&(i=s[t],!(n.timestamp-i.timestamp>qs(e)));)t--;if(!i)return{x:0,y:0};const r=os(n.timestamp-i.timestamp);if(r===0)return{x:0,y:0};const a={x:(n.x-i.x)/r,y:(n.y-i.y)/r};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function gB(s,{min:e,max:t},i){return e!==void 0&&st&&(s=i?Qe(t,s,i.max):Math.min(s,t)),s}function ew(s,e,t){return{min:e!==void 0?s.min+e:void 0,max:t!==void 0?s.max+t-(s.max-s.min):void 0}}function yB(s,{top:e,left:t,bottom:i,right:n}){return{x:ew(s.x,t,n),y:ew(s.y,e,i)}}function tw(s,e){let t=e.min-s.min,i=e.max-s.max;return e.max-e.mini?t=wl(e.min,e.max-i,s.min):i>n&&(t=wl(s.min,s.max-n,e.min)),An(0,1,t)}function xB(s,e){const t={};return e.min!==void 0&&(t.min=e.min-s.min),e.max!==void 0&&(t.max=e.max-s.min),t}const Tg=.35;function wB(s=Tg){return s===!1?s=0:s===!0&&(s=Tg),{x:iw(s,"left","right"),y:iw(s,"top","bottom")}}function iw(s,e,t){return{min:sw(s,e),max:sw(s,t)}}function sw(s,e){return typeof s=="number"?s:s[e]||0}const _B=new WeakMap;let TB=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ft(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:i}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const r=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(tu(d).point)},a=(d,h)=>{const{drag:f,dragPropagation:p,onDragStart:m}=this.getProps();if(f&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=EO(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),is(v=>{let w=this.getAxisMotionValue(v).get()||0;if(Hs.test(w)){const{projection:b}=this.visualElement;if(b&&b.layout){const k=b.layout.layoutBox[v];k&&(w=li(k)*(parseFloat(w)/100))}}this.originPoint[v]=w}),m&&Ge.postRender(()=>m(d,h)),wg(this.visualElement,"transform");const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:p,onDirectionLock:m,onDrag:g}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:v}=h;if(p&&this.currentDirection===null){this.currentDirection=kB(v),this.currentDirection!==null&&m&&m(this.currentDirection);return}this.updateAxis("x",h.point,v),this.updateAxis("y",h.point,v),this.visualElement.render(),g&&g(d,h)},c=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>is(d=>this.getAnimationState(d)==="paused"&&this.getAxisMotionValue(d).animation?.play()),{dragSnapToOrigin:u}=this.getProps();this.panSession=new c3(e,{onSessionStart:r,onStart:a,onMove:o,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:o3(this.visualElement)})}stop(e,t){const i=e||this.latestPointerEvent,n=t||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!n||!i)return;const{velocity:a}=n;this.startAnimation(a);const{onDragEnd:o}=this.getProps();o&&Ge.postRender(()=>o(i,n))}cancel(){this.isDragging=!1;const{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(e,t,i){const{drag:n}=this.getProps();if(!i||!Mu(e,n,this.currentDirection))return;const r=this.getAxisMotionValue(e);let a=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(a=gB(a,this.constraints[e],this.elastic[e])),r.set(a)}resolveConstraints(){const{dragConstraints:e,dragElastic:t}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,n=this.constraints;e&&Ua(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=yB(i.layoutBox,e):this.constraints=!1,this.elastic=wB(t),n!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&is(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=xB(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Ua(e))return!1;const i=e.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const r=A6(i,n.root,this.visualElement.getTransformPagePoint());let a=vB(n.layout.layoutBox,r);if(t){const o=t(_6(a));this.hasMutatedConstraints=!!o,o&&(a=qC(o))}return a}startAnimation(e){const{drag:t,dragMomentum:i,dragElastic:n,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},l=is(u=>{if(!Mu(u,t,this.currentDirection))return;let d=c&&c[u]||{};a&&(d={min:0,max:0});const h=n?200:1e6,f=n?40:1e7,p={type:"inertia",velocity:i?e[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...r,...d};return this.startAxisValueAnimation(u,p)});return Promise.all(l).then(o)}startAxisValueAnimation(e,t){const i=this.getAxisMotionValue(e);return wg(this.visualElement,e),i.start(qy(e,i,0,t,this.visualElement,!1))}stopAnimation(){is(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){is(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const t=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),n=i[t];return n||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){is(t=>{const{drag:i}=this.getProps();if(!Mu(t,i,this.currentDirection))return;const{projection:n}=this.visualElement,r=this.getAxisMotionValue(t);if(n&&n.layout){const{min:a,max:o}=n.layout.layoutBox[t];r.set(e[t]-Qe(a,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:t}=this.getProps(),{projection:i}=this.visualElement;if(!Ua(t)||!i||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};is(a=>{const o=this.getAxisMotionValue(a);if(o&&this.constraints!==!1){const c=o.get();n[a]=bB({min:c,max:c},this.constraints[a])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),is(a=>{if(!Mu(a,e,null))return;const o=this.getAxisMotionValue(a),{min:c,max:l}=this.constraints[a];o.set(Qe(c,l,n[a]))})}addListeners(){if(!this.visualElement.current)return;_B.set(this.visualElement,this);const e=this.visualElement.current,t=el(e,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps();l&&u&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();Ua(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,r=n.addEventListener("measure",i);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Ge.read(i);const a=Sl(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(is(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].translate))}),this.visualElement.render())});return()=>{a(),t(),r(),o&&o()}}getProps(){const e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:i=!1,dragPropagation:n=!1,dragConstraints:r=!1,dragElastic:a=Tg,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:r,dragElastic:a,dragMomentum:o}}};function Mu(s,e,t){return(e===!0||e===s)&&(t===null||t===s)}function kB(s,e=10){let t=null;return Math.abs(s.y)>e?t="y":Math.abs(s.x)>e&&(t="x"),t}let AB=class extends br{constructor(e){super(e),this.removeGroupControls=ms,this.removeListeners=ms,this.controls=new TB(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ms}unmount(){this.removeGroupControls(),this.removeListeners()}};const nw=s=>(e,t)=>{s&&Ge.postRender(()=>s(e,t))};let SB=class extends br{constructor(){super(...arguments),this.removePointerDownListener=ms}onPointerDown(e){this.session=new c3(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:o3(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:nw(e),onStart:nw(t),onMove:i,onEnd:(r,a)=>{delete this.session,n&&Ge.postRender(()=>n(r,a))}}}mount(){this.removePointerDownListener=el(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}};const hd={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function rw(s,e){return e.max===e.min?0:s/(e.max-e.min)*100}const xc={correct:(s,e)=>{if(!e.target)return s;if(typeof s=="string")if(me.test(s))s=parseFloat(s);else return s;const t=rw(s,e.target.x),i=rw(s,e.target.y);return`${t}% ${i}%`}},CB={correct:(s,{treeScale:e,projectionDelta:t})=>{const i=s,n=ur.parse(s);if(n.length>5)return i;const r=ur.createTransformer(s),a=typeof n[0]!="number"?1:0,o=t.x.scale*e.x,c=t.y.scale*e.y;n[0+a]/=o,n[1+a]/=c;const l=Qe(o,c,.5);return typeof n[2+a]=="number"&&(n[2+a]/=l),typeof n[3+a]=="number"&&(n[3+a]/=l),r(n)}};let Kf=!1,EB=class extends F.Component{componentDidMount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:r}=e;KO(MB),r&&(t.group&&t.group.add(r),i&&i.register&&n&&i.register(r),Kf&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),hd.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:t,visualElement:i,drag:n,isPresent:r}=this.props,{projection:a}=i;return a&&(a.isPresent=r,Kf=!0,n||e.layoutDependency!==t||t===void 0||e.isPresent!==r?a.willUpdate():this.safeToRemove(),e.isPresent!==r&&(r?a.promote():a.relegate()||Ge.postRender(()=>{const o=a.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Ly.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=e;Kf=!0,n&&(n.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(n),i&&i.deregister&&i.deregister(n))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}};function u3(s){const[e,t]=RC(),i=F.useContext(fy);return x.jsx(EB,{...s,layoutGroup:i,switchLayoutGroup:F.useContext(GC),isPresent:e,safeToRemove:t})}const MB={borderRadius:{...xc,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:xc,borderTopRightRadius:xc,borderBottomLeftRadius:xc,borderBottomRightRadius:xc,boxShadow:CB};function IB(s,e,t){const i=Jt(s)?s:xo(s);return i.start(qy("",i,e,t)),i.animation}const PB=(s,e)=>s.depth-e.depth;let RB=class{constructor(){this.children=[],this.isDirty=!1}add(e){gy(this.children,e),this.isDirty=!0}remove(e){yy(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(PB),this.isDirty=!1,this.children.forEach(e)}};function DB(s,e){const t=bi.now(),i=({timestamp:n})=>{const r=n-t;r>=e&&(lr(i),s(r-e))};return Ge.setup(i,!0),()=>lr(i)}const d3=["TopLeft","TopRight","BottomLeft","BottomRight"],FB=d3.length,aw=s=>typeof s=="string"?parseFloat(s):s,ow=s=>typeof s=="number"||me.test(s);function LB(s,e,t,i,n,r){n?(s.opacity=Qe(0,t.opacity??1,OB(i)),s.opacityExit=Qe(e.opacity??1,0,BB(i))):r&&(s.opacity=Qe(e.opacity??1,t.opacity??1,i));for(let a=0;aie?1:t(wl(s,e,i))}function lw(s,e){s.min=e.min,s.max=e.max}function Xi(s,e){lw(s.x,e.x),lw(s.y,e.y)}function uw(s,e){s.translate=e.translate,s.scale=e.scale,s.originPoint=e.originPoint,s.origin=e.origin}function dw(s,e,t,i,n){return s-=e,s=Yd(s,1/t,i),n!==void 0&&(s=Yd(s,1/n,i)),s}function $B(s,e=0,t=1,i=.5,n,r=s,a=s){if(Hs.test(e)&&(e=parseFloat(e),e=Qe(a.min,a.max,e/100)-a.min),typeof e!="number")return;let o=Qe(r.min,r.max,i);s===r&&(o-=e),s.min=dw(s.min,e,t,o,n),s.max=dw(s.max,e,t,o,n)}function hw(s,e,[t,i,n],r,a){$B(s,e[t],e[i],e[n],e.scale,r,a)}const jB=["x","scaleX","originX"],NB=["y","scaleY","originY"];function fw(s,e,t,i){hw(s.x,e,jB,t?t.x:void 0,i?i.x:void 0),hw(s.y,e,NB,t?t.y:void 0,i?i.y:void 0)}function pw(s){return s.translate===0&&s.scale===1}function f3(s){return pw(s.x)&&pw(s.y)}function mw(s,e){return s.min===e.min&&s.max===e.max}function VB(s,e){return mw(s.x,e.x)&&mw(s.y,e.y)}function gw(s,e){return Math.round(s.min)===Math.round(e.min)&&Math.round(s.max)===Math.round(e.max)}function p3(s,e){return gw(s.x,e.x)&&gw(s.y,e.y)}function yw(s){return li(s.x)/li(s.y)}function vw(s,e){return s.translate===e.translate&&s.scale===e.scale&&s.originPoint===e.originPoint}let UB=class{constructor(){this.members=[]}add(e){gy(this.members,e),e.scheduleRender()}remove(e){if(yy(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(e){const t=this.members.findIndex(n=>e===n);if(t===0)return!1;let i;for(let n=t;n>=0;n--){const r=this.members[n];if(r.isPresent!==!1){i=r;break}}return i?(this.promote(i),!0):!1}promote(e,t){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,t&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:n}=e.options;n===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:t,resumingFrom:i}=e;t.onExitComplete&&t.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}};function zB(s,e,t){let i="";const n=s.x.translate/e.x,r=s.y.translate/e.y,a=t?.z||0;if((n||r||a)&&(i=`translate3d(${n}px, ${r}px, ${a}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),t){const{transformPerspective:l,rotate:u,rotateX:d,rotateY:h,skewX:f,skewY:p}=t;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),h&&(i+=`rotateY(${h}deg) `),f&&(i+=`skewX(${f}deg) `),p&&(i+=`skewY(${p}deg) `)}const o=s.x.scale*e.x,c=s.y.scale*e.y;return(o!==1||c!==1)&&(i+=`scale(${o}, ${c})`),i||"none"}const Qf=["","X","Y","Z"],GB=1e3;let WB=0;function Jf(s,e,t,i){const{latestValues:n}=e;n[s]&&(t[s]=n[s],e.setStaticValue(s,0),i&&(i[s]=0))}function m3(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:e}=s.options;if(!e)return;const t=e3(e);if(window.MotionHasOptimisedAnimation(t,"transform")){const{layout:n,layoutId:r}=s.options;window.MotionCancelOptimisedAnimation(t,"transform",Ge,!(n||r))}const{parent:i}=s;i&&!i.hasCheckedOptimisedAppear&&m3(i)}function g3({attachResizeListener:s,defaultParent:e,measureScroll:t,checkIsScrollRoot:i,resetTransform:n}){return class{constructor(a={},o=e?.()){this.id=WB++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(YB),this.nodes.forEach(JB),this.nodes.forEach(ZB),this.nodes.forEach(XB)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=a,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Ge.read(()=>{d=window.innerWidth}),s(a,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=DB(h,250),hd.hasAnimatedSinceResize&&(hd.hasAnimatedSinceResize=!1,this.nodes.forEach(ww)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&l&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||l.getDefaultTransition()||n$,{onLayoutAnimationStart:m,onLayoutAnimationComplete:g}=l.getProps(),v=!this.targetLayout||!p3(this.targetLayout,f),w=!d&&h;if(this.options.layoutRoot||this.resumeFrom||w||d&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const b={...Dy(p,"layout"),onPlay:m,onComplete:g};(l.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b),this.setAnimationOrigin(u,w)}else d||ww(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const a=this.getStack();a&&a.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),lr(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(e$),this.animationId++)}getTransformTemplate(){const{visualElement:a}=this.options;return a&&a.getProps().transformTemplate}willUpdate(a=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&m3(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!li(this.snapshot.measuredBox.x)&&!li(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const A=k/1e3;_w(d.x,a.x,A),_w(d.y,a.y,A),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(il(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),i$(this.relativeTarget,this.relativeTargetOrigin,h,A),b&&VB(this.relativeTarget,b)&&(this.isProjectionDirty=!1),b||(b=ft()),Xi(b,this.relativeTarget)),m&&(this.animationValues=u,LB(u,l,this.latestValues,A,w,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(lr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ge.update(()=>{hd.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xo(0)),this.currentAnimation=IB(this.motionValue,[0,1e3],{...a,velocity:0,isSync:!0,onUpdate:o=>{this.mixTargetDelta(o),a.onUpdate&&a.onUpdate(o)},onStop:()=>{},onComplete:()=>{a.onComplete&&a.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const a=this.getStack();a&&a.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(GB),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const a=this.getLead();let{targetWithTransforms:o,target:c,layout:l,latestValues:u}=a;if(!(!o||!c||!l)){if(this!==a&&this.layout&&l&&y3(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||ft();const d=li(this.layout.layoutBox.x);c.x.min=a.target.x.min,c.x.max=c.x.min+d;const h=li(this.layout.layoutBox.y);c.y.min=a.target.y.min,c.y.max=c.y.min+h}Xi(o,c),Ga(o,u),tl(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(a,o){this.sharedNodes.has(a)||this.sharedNodes.set(a,new UB),this.sharedNodes.get(a).add(o);const l=o.options.initialPromotionConfig;o.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.shouldPreserveFollowOpacity(o):void 0})}isLead(){const a=this.getStack();return a?a.lead===this:!0}getLead(){const{layoutId:a}=this.options;return a?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:a}=this.options;return a?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:a}=this.options;if(a)return this.root.sharedNodes.get(a)}promote({needsReset:a,transition:o,preserveFollowOpacity:c}={}){const l=this.getStack();l&&l.promote(this,c),a&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const a=this.getStack();return a?a.relegate(this):!1}resetSkewAndRotation(){const{visualElement:a}=this.options;if(!a)return;let o=!1;const{latestValues:c}=a;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const l={};c.z&&Jf("z",a,l,this.animationValues);for(let u=0;ua.currentAnimation?.stop()),this.root.nodes.forEach(bw),this.root.sharedNodes.clear()}}}function qB(s){s.updateLayout()}function HB(s){const e=s.resumeFrom?.snapshot||s.snapshot;if(s.isLead()&&s.layout&&e&&s.hasListeners("didUpdate")){const{layoutBox:t,measuredBox:i}=s.layout,{animationType:n}=s.options,r=e.source!==s.layout.source;n==="size"?is(u=>{const d=r?e.measuredBox[u]:e.layoutBox[u],h=li(d);d.min=t[u].min,d.max=d.min+h}):y3(n,e.layoutBox,t)&&is(u=>{const d=r?e.measuredBox[u]:e.layoutBox[u],h=li(t[u]);d.max=d.min+h,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[u].max=s.relativeTarget[u].min+h)});const a=Wa();tl(a,t,e.layoutBox);const o=Wa();r?tl(o,s.applyTransform(i,!0),e.measuredBox):tl(o,t,e.layoutBox);const c=!f3(a);let l=!1;if(!s.resumeFrom){const u=s.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:d,layout:h}=u;if(d&&h){const f=ft();il(f,e.layoutBox,d.layoutBox);const p=ft();il(p,t,h.layoutBox),p3(f,p)||(l=!0),u.options.layoutRoot&&(s.relativeTarget=p,s.relativeTargetOrigin=f,s.relativeParent=u)}}}s.notifyListeners("didUpdate",{layout:t,snapshot:e,delta:o,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(s.isLead()){const{onExitComplete:t}=s.options;t&&t()}s.options.transition=void 0}function YB(s){s.parent&&(s.isProjecting()||(s.isProjectionDirty=s.parent.isProjectionDirty),s.isSharedProjectionDirty||(s.isSharedProjectionDirty=!!(s.isProjectionDirty||s.parent.isProjectionDirty||s.parent.isSharedProjectionDirty)),s.isTransformDirty||(s.isTransformDirty=s.parent.isTransformDirty))}function XB(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function KB(s){s.clearSnapshot()}function bw(s){s.clearMeasurements()}function xw(s){s.isLayoutDirty=!1}function QB(s){const{visualElement:e}=s.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),s.resetTransform()}function ww(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function JB(s){s.resolveTargetDelta()}function ZB(s){s.calcProjection()}function e$(s){s.resetSkewAndRotation()}function t$(s){s.removeLeadSnapshot()}function _w(s,e,t){s.translate=Qe(e.translate,0,t),s.scale=Qe(e.scale,1,t),s.origin=e.origin,s.originPoint=e.originPoint}function Tw(s,e,t,i){s.min=Qe(e.min,t.min,i),s.max=Qe(e.max,t.max,i)}function i$(s,e,t,i){Tw(s.x,e.x,t.x,i),Tw(s.y,e.y,t.y,i)}function s$(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const n$={duration:.45,ease:[.4,0,.1,1]},kw=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),Aw=kw("applewebkit/")&&!kw("chrome/")?Math.round:ms;function Sw(s){s.min=Aw(s.min),s.max=Aw(s.max)}function r$(s){Sw(s.x),Sw(s.y)}function y3(s,e,t){return s==="position"||s==="preserve-aspect"&&!dB(yw(e),yw(t),.2)}function a$(s){return s!==s.root&&s.scroll?.wasRoot}const o$=g3({attachResizeListener:(s,e)=>Sl(s,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Zf={current:void 0},v3=g3({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!Zf.current){const s=new o$({});s.mount(window),s.setOptions({layoutScroll:!0}),Zf.current=s}return Zf.current},resetTransform:(s,e)=>{s.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),c$={pan:{Feature:SB},drag:{Feature:AB,ProjectionNode:v3,MeasureLayout:u3}};function Cw(s,e,t){const{props:i}=s;s.animationState&&i.whileHover&&s.animationState.setActive("whileHover",t==="Start");const n="onHover"+t,r=i[n];r&&Ge.postRender(()=>r(e,tu(e)))}let l$=class extends br{mount(){const{current:e}=this.node;e&&(this.unmount=MO(e,(t,i)=>(Cw(this.node,i,"Start"),n=>Cw(this.node,n,"End"))))}unmount(){}},u$=class extends br{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Jl(Sl(this.node.current,"focus",()=>this.onFocus()),Sl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}};function Ew(s,e,t){const{props:i}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&i.whileTap&&s.animationState.setActive("whileTap",t==="Start");const n="onTap"+(t==="End"?"":t),r=i[n];r&&Ge.postRender(()=>r(e,tu(e)))}let d$=class extends br{mount(){const{current:e}=this.node;e&&(this.unmount=DO(e,(t,i)=>(Ew(this.node,i,"Start"),(n,{success:r})=>Ew(this.node,n,r?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}};const kg=new WeakMap,ep=new WeakMap,h$=s=>{const e=kg.get(s.target);e&&e(s)},f$=s=>{s.forEach(h$)};function p$({root:s,...e}){const t=s||document;ep.has(t)||ep.set(t,{});const i=ep.get(t),n=JSON.stringify(e);return i[n]||(i[n]=new IntersectionObserver(f$,{root:s,...e})),i[n]}function m$(s,e,t){const i=p$(e);return kg.set(s,t),i.observe(s),()=>{kg.delete(s),i.unobserve(s)}}const g$={some:0,all:1};let y$=class extends br{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:t,margin:i,amount:n="some",once:r}=e,a={root:t?t.current:void 0,rootMargin:i,threshold:typeof n=="number"?n:g$[n]},o=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,r&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=l?u:d;h&&h(c)};return m$(this.node.current,a,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:t}=this.node;["amount","margin","root"].some(v$(e,t))&&this.startObserver()}unmount(){}};function v$({viewport:s={}},{viewport:e={}}={}){return t=>s[t]!==e[t]}const b$={inView:{Feature:y$},tap:{Feature:d$},focus:{Feature:u$},hover:{Feature:l$}},x$={layout:{ProjectionNode:v3,MeasureLayout:u3}},w$={...rB,...b$,...c$,...x$},Ea=w6(w$,F6);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _$=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),T$=s=>s.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase()),Mw=s=>{const e=T$(s);return e.charAt(0).toUpperCase()+e.slice(1)},b3=(...s)=>s.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim(),k$=s=>{for(const e in s)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var A$={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const S$=F.forwardRef(({color:s="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:n="",children:r,iconNode:a,...o},c)=>F.createElement("svg",{ref:c,...A$,width:e,height:e,stroke:s,strokeWidth:i?Number(t)*24/Number(e):t,className:b3("lucide",n),...!r&&!k$(o)&&{"aria-hidden":"true"},...o},[...a.map(([l,u])=>F.createElement(l,u)),...Array.isArray(r)?r:[r]]));/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const he=(s,e)=>{const t=F.forwardRef(({className:i,...n},r)=>F.createElement(S$,{ref:r,iconNode:e,className:b3(`lucide-${_$(Mw(s))}`,`lucide-${s}`,i),...n}));return t.displayName=Mw(s),t};/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const C$=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],tp=he("arrow-right",C$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const E$=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]],M$=he("at-sign",E$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const I$=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],P$=he("bookmark",I$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const R$=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],D$=he("briefcase",R$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const F$=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],iu=he("check",F$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L$=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Hy=he("chevron-down",L$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const O$=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Xd=he("chevron-right",O$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const B$=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],$$=he("chevron-up",B$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Ag=he("circle-alert",j$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const N$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Sg=he("circle-check",N$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const V$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],U$=he("circle-x",V$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const z$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],x3=he("circle",z$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const G$=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Cn=he("clock",G$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const W$=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],q$=he("copy",W$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const H$=[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]],Y$=he("crown",H$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const X$=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],w3=he("download",X$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K$=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Iw=he("external-link",K$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Q$=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],J$=he("eye",Q$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Z$=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],ip=he("file-code",Z$);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ej=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M15.033 13.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56v-4.704a.645.645 0 0 1 .967-.56z",key:"1tzo1f"}]],tj=he("file-play",ej);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ij=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]],sj=he("film",ij);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nj=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]],rj=he("focus",nj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const aj=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],oj=he("folder-open",aj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cj=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],lj=he("hash",cj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uj=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],dj=he("image",uj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hj=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],fj=he("info",hj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pj=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],En=he("layers",pj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mj=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],_3=he("layout-grid",mj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gj=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],T3=he("loader-circle",gj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yj=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],Wr=he("monitor",yj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vj=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],sp=he("move",vj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bj=[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]],Cg=he("music-2",bj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xj=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],wj=he("music",xj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _j=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],Eg=he("palette",_j);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Tj=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],dr=he("play",Tj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kj=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Aj=he("rotate-ccw",kj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Sj=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Mg=he("search",Sj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Cj=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ej=he("settings",Cj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Mj=[["path",{d:"M22 2 2 22",key:"y4kqgn"}]],Ij=he("slash",Mj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Pj=[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],fd=he("sliders-vertical",Pj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Rj=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Ns=he("smartphone",Rj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Dj=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Ys=he("square",Dj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fj=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],Yy=he("star",Fj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Lj=[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],Oj=he("toggle-left",Lj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bj=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],k3=he("trash-2",Bj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $j=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],A3=he("triangle-alert",$j);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jj=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],rr=he("type",jj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nj=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Pw=he("upload",Nj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vj=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Uj=he("users",Vj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zj=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Gj=he("video",zj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wj=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],qj=he("wand-sparkles",Wj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Xy=he("x",Hj);/** + * @license lucide-react v0.555.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yj=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],pd=he("zap",Yj);let Xj=0;const Nc=Yl((s,e)=>({notifications:[],addNotification:t=>{const i=`notification-${++Xj}`,n={id:i,duration:4e3,dismissible:!0,...t};return s(r=>({notifications:[...r.notifications,n]})),n.duration&&n.duration>0&&setTimeout(()=>{e().removeNotification(i)},n.duration),i},removeNotification:t=>{s(i=>({notifications:i.notifications.filter(n=>n.id!==t)}))},clearAll:()=>{s({notifications:[]})}})),Kj={success:(s,e)=>Nc.getState().addNotification({type:"success",title:s,message:e}),error:(s,e)=>Nc.getState().addNotification({type:"error",title:s,message:e,duration:6e3}),warning:(s,e)=>Nc.getState().addNotification({type:"warning",title:s,message:e}),info:(s,e)=>Nc.getState().addNotification({type:"info",title:s,message:e})},Qj={success:x.jsx(Sg,{size:20}),error:x.jsx(U$,{size:20}),warning:x.jsx(A3,{size:20}),info:x.jsx(fj,{size:20})},Jj={success:{light:{bg:"bg-white",border:"border-emerald-200",icon:"text-emerald-600",progress:"bg-emerald-500"},dark:{bg:"bg-zinc-900/95",border:"border-emerald-500/30",icon:"text-emerald-400",progress:"bg-emerald-500"}},error:{light:{bg:"bg-white",border:"border-red-200",icon:"text-red-600",progress:"bg-red-500"},dark:{bg:"bg-zinc-900/95",border:"border-red-500/30",icon:"text-red-400",progress:"bg-red-500"}},warning:{light:{bg:"bg-white",border:"border-amber-200",icon:"text-amber-600",progress:"bg-amber-500"},dark:{bg:"bg-zinc-900/95",border:"border-amber-500/30",icon:"text-amber-400",progress:"bg-amber-500"}},info:{light:{bg:"bg-white",border:"border-blue-200",icon:"text-blue-600",progress:"bg-blue-500"},dark:{bg:"bg-zinc-900/95",border:"border-blue-500/30",icon:"text-blue-400",progress:"bg-blue-500"}}},S3=Xn.forwardRef(({notification:s,onRemove:e},t)=>{const[i,n]=F.useState(100),r=typeof document<"u"&&document.documentElement.classList.contains("dark"),a=r?"dark":"light",o=Jj[s.type][a],c=s.duration||4e3;return F.useEffect(()=>{if(c<=0)return;const l=Date.now(),u=setInterval(()=>{const d=Date.now()-l,h=Math.max(0,100-d/c*100);n(h),h<=0&&clearInterval(u)},50);return()=>clearInterval(u)},[c]),x.jsxs(Ea.div,{ref:t,layout:!0,initial:{opacity:0,x:100,scale:.9},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:100,scale:.9},transition:{type:"spring",stiffness:500,damping:30,opacity:{duration:.2}},className:` + relative overflow-hidden + min-w-[320px] max-w-[420px] + rounded-xl border shadow-lg + ${o.bg} ${o.border} + backdrop-blur-xl + `,children:[x.jsxs("div",{className:"flex items-start gap-3 p-4",children:[x.jsx(Ea.div,{initial:{scale:0,rotate:-180},animate:{scale:1,rotate:0},transition:{type:"spring",stiffness:500,damping:25,delay:.1},className:`flex-shrink-0 mt-0.5 ${o.icon}`,children:Qj[s.type]}),x.jsxs("div",{className:"flex-1 min-w-0 pr-2",children:[x.jsx(Ea.p,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{delay:.05},className:`text-sm font-semibold ${r?"text-zinc-100":"text-zinc-900"}`,children:s.title}),s.message&&x.jsx(Ea.p,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{delay:.1},className:`text-xs mt-1 leading-relaxed ${r?"text-zinc-400":"text-zinc-600"}`,children:s.message})]}),s.dismissible&&x.jsx(Ea.button,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},whileHover:{scale:1.1},whileTap:{scale:.9},onClick:()=>e(s.id),className:` + flex-shrink-0 p-1.5 rounded-lg + transition-colors duration-150 + ${r?"hover:bg-white/10 text-zinc-500 hover:text-zinc-300":"hover:bg-black/5 text-zinc-400 hover:text-zinc-600"} + `,"aria-label":"Dismiss notification",children:x.jsx(Xy,{size:16})})]}),c>0&&x.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-1 bg-black/5 dark:bg-white/5",children:x.jsx(Ea.div,{initial:{width:"100%"},animate:{width:`${i}%`},transition:{duration:.05,ease:"linear"},className:`h-full ${o.progress}`})})]})});S3.displayName="ToastItem";const Zj=()=>{const{notifications:s,removeNotification:e}=Nc();return x.jsx("div",{className:"fixed top-4 right-4 z-[9999] flex flex-col gap-3",role:"region","aria-label":"Notifications",children:x.jsx(zO,{mode:"popLayout",children:s.map(t=>x.jsx(S3,{notification:t,onRemove:e},t.id))})})};function C3(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;e{const t=new Array(s.length+e.length);for(let i=0;i({classGroupId:s,validator:e}),M3=(s=new Map,e=null,t)=>({nextPart:s,validators:e,classGroupId:t}),Kd="-",Rw=[],i8="arbitrary..",s8=s=>{const e=r8(s),{conflictingClassGroups:t,conflictingClassGroupModifiers:i}=s;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return n8(a);const o=a.split(Kd),c=o[0]===""&&o.length>1?1:0;return I3(o,c,e)},getConflictingClassGroupIds:(a,o)=>{if(o){const c=i[a],l=t[a];return c?l?e8(l,c):c:l||Rw}return t[a]||Rw}}},I3=(s,e,t)=>{if(s.length-e===0)return t.classGroupId;const n=s[e],r=t.nextPart.get(n);if(r){const l=I3(s,e+1,r);if(l)return l}const a=t.validators;if(a===null)return;const o=e===0?s.join(Kd):s.slice(e).join(Kd),c=a.length;for(let l=0;ls.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=s.slice(1,-1),t=e.indexOf(":"),i=e.slice(0,t);return i?i8+i:void 0})(),r8=s=>{const{theme:e,classGroups:t}=s;return a8(t,e)},a8=(s,e)=>{const t=M3();for(const i in s){const n=s[i];Ky(n,t,i,e)}return t},Ky=(s,e,t,i)=>{const n=s.length;for(let r=0;r{if(typeof s=="string"){c8(s,e,t);return}if(typeof s=="function"){l8(s,e,t,i);return}u8(s,e,t,i)},c8=(s,e,t)=>{const i=s===""?e:P3(e,s);i.classGroupId=t},l8=(s,e,t,i)=>{if(d8(s)){Ky(s(i),e,t,i);return}e.validators===null&&(e.validators=[]),e.validators.push(t8(t,s))},u8=(s,e,t,i)=>{const n=Object.entries(s),r=n.length;for(let a=0;a{let t=s;const i=e.split(Kd),n=i.length;for(let r=0;r"isThemeGetter"in s&&s.isThemeGetter===!0,h8=s=>{if(s<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),i=Object.create(null);const n=(r,a)=>{t[r]=a,e++,e>s&&(e=0,i=t,t=Object.create(null))};return{get(r){let a=t[r];if(a!==void 0)return a;if((a=i[r])!==void 0)return n(r,a),a},set(r,a){r in t?t[r]=a:n(r,a)}}},Ig="!",Dw=":",f8=[],Fw=(s,e,t,i,n)=>({modifiers:s,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:i,isExternal:n}),p8=s=>{const{prefix:e,experimentalParseClassName:t}=s;let i=n=>{const r=[];let a=0,o=0,c=0,l;const u=n.length;for(let m=0;mc?l-c:void 0;return Fw(r,f,h,p)};if(e){const n=e+Dw,r=i;i=a=>a.startsWith(n)?r(a.slice(n.length)):Fw(f8,!1,a,void 0,!0)}if(t){const n=i;i=r=>t({className:r,parseClassName:n})}return i},m8=s=>{const e=new Map;return s.orderSensitiveModifiers.forEach((t,i)=>{e.set(t,1e6+i)}),t=>{const i=[];let n=[];for(let r=0;r0&&(n.sort(),i.push(...n),n=[]),i.push(a)):n.push(a)}return n.length>0&&(n.sort(),i.push(...n)),i}},g8=s=>({cache:h8(s.cacheSize),parseClassName:p8(s),sortModifiers:m8(s),...s8(s)}),y8=/\s+/,v8=(s,e)=>{const{parseClassName:t,getClassGroupId:i,getConflictingClassGroupIds:n,sortModifiers:r}=e,a=[],o=s.trim().split(y8);let c="";for(let l=o.length-1;l>=0;l-=1){const u=o[l],{isExternal:d,modifiers:h,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=t(u);if(d){c=u+(c.length>0?" "+c:c);continue}let g=!!m,v=i(g?p.substring(0,m):p);if(!v){if(!g){c=u+(c.length>0?" "+c:c);continue}if(v=i(p),!v){c=u+(c.length>0?" "+c:c);continue}g=!1}const w=h.length===0?"":h.length===1?h[0]:r(h).join(":"),b=f?w+Ig:w,k=b+v;if(a.indexOf(k)>-1)continue;a.push(k);const A=n(v,g);for(let M=0;M0?" "+c:c)}return c},b8=(...s)=>{let e=0,t,i,n="";for(;e{if(typeof s=="string")return s;let e,t="";for(let i=0;i{let t,i,n,r;const a=c=>{const l=e.reduce((u,d)=>d(u),s());return t=g8(l),i=t.cache.get,n=t.cache.set,r=o,o(c)},o=c=>{const l=i(c);if(l)return l;const u=v8(c,t);return n(c,u),u};return r=a,(...c)=>r(b8(...c))},w8=[],At=s=>{const e=t=>t[s]||w8;return e.isThemeGetter=!0,e},D3=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,F3=/^\((?:(\w[\w-]*):)?(.+)\)$/i,_8=/^\d+\/\d+$/,T8=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,k8=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,A8=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,S8=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,C8=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ma=s=>_8.test(s),xe=s=>!!s&&!Number.isNaN(Number(s)),jn=s=>!!s&&Number.isInteger(Number(s)),np=s=>s.endsWith("%")&&xe(s.slice(0,-1)),cn=s=>T8.test(s),E8=()=>!0,M8=s=>k8.test(s)&&!A8.test(s),L3=()=>!1,I8=s=>S8.test(s),P8=s=>C8.test(s),R8=s=>!J(s)&&!Z(s),D8=s=>Ho(s,$3,L3),J=s=>D3.test(s),Pr=s=>Ho(s,j3,M8),rp=s=>Ho(s,$8,xe),Lw=s=>Ho(s,O3,L3),F8=s=>Ho(s,B3,P8),Iu=s=>Ho(s,N3,I8),Z=s=>F3.test(s),wc=s=>Yo(s,j3),L8=s=>Yo(s,j8),Ow=s=>Yo(s,O3),O8=s=>Yo(s,$3),B8=s=>Yo(s,B3),Pu=s=>Yo(s,N3,!0),Ho=(s,e,t)=>{const i=D3.exec(s);return i?i[1]?e(i[1]):t(i[2]):!1},Yo=(s,e,t=!1)=>{const i=F3.exec(s);return i?i[1]?e(i[1]):t:!1},O3=s=>s==="position"||s==="percentage",B3=s=>s==="image"||s==="url",$3=s=>s==="length"||s==="size"||s==="bg-size",j3=s=>s==="length",$8=s=>s==="number",j8=s=>s==="family-name",N3=s=>s==="shadow",N8=()=>{const s=At("color"),e=At("font"),t=At("text"),i=At("font-weight"),n=At("tracking"),r=At("leading"),a=At("breakpoint"),o=At("container"),c=At("spacing"),l=At("radius"),u=At("shadow"),d=At("inset-shadow"),h=At("text-shadow"),f=At("drop-shadow"),p=At("blur"),m=At("perspective"),g=At("aspect"),v=At("ease"),w=At("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...k(),Z,J],M=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto","contain","none"],I=()=>[Z,J,c],D=()=>[Ma,"full","auto",...I()],B=()=>[jn,"none","subgrid",Z,J],$=()=>["auto",{span:["full",jn,Z,J]},jn,Z,J],V=()=>[jn,"auto",Z,J],y=()=>["auto","min","max","fr",Z,J],_=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],T=()=>["start","end","center","stretch","center-safe","end-safe"],S=()=>["auto",...I()],C=()=>[Ma,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...I()],E=()=>[s,Z,J],P=()=>[...k(),Ow,Lw,{position:[Z,J]}],L=()=>["no-repeat",{repeat:["","x","y","space","round"]}],O=()=>["auto","cover","contain",O8,D8,{size:[Z,J]}],U=()=>[np,wc,Pr],j=()=>["","none","full",l,Z,J],N=()=>["",xe,wc,Pr],z=()=>["solid","dashed","dotted","double"],W=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>[xe,np,Ow,Lw],fe=()=>["","none",p,Z,J],ye=()=>["none",xe,Z,J],le=()=>["none",xe,Z,J],Le=()=>[xe,Z,J],Oe=()=>[Ma,"full",...I()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[cn],breakpoint:[cn],color:[E8],container:[cn],"drop-shadow":[cn],ease:["in","out","in-out"],font:[R8],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[cn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[cn],shadow:[cn],spacing:["px",xe],text:[cn],"text-shadow":[cn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ma,J,Z,g]}],container:["container"],columns:[{columns:[xe,J,Z,o]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:D()}],"inset-x":[{"inset-x":D()}],"inset-y":[{"inset-y":D()}],start:[{start:D()}],end:[{end:D()}],top:[{top:D()}],right:[{right:D()}],bottom:[{bottom:D()}],left:[{left:D()}],visibility:["visible","invisible","collapse"],z:[{z:[jn,"auto",Z,J]}],basis:[{basis:[Ma,"full","auto",o,...I()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[xe,Ma,"auto","initial","none",J]}],grow:[{grow:["",xe,Z,J]}],shrink:[{shrink:["",xe,Z,J]}],order:[{order:[jn,"first","last","none",Z,J]}],"grid-cols":[{"grid-cols":B()}],"col-start-end":[{col:$()}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":B()}],"row-start-end":[{row:$()}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":y()}],"auto-rows":[{"auto-rows":y()}],gap:[{gap:I()}],"gap-x":[{"gap-x":I()}],"gap-y":[{"gap-y":I()}],"justify-content":[{justify:[..._(),"normal"]}],"justify-items":[{"justify-items":[...T(),"normal"]}],"justify-self":[{"justify-self":["auto",...T()]}],"align-content":[{content:["normal",..._()]}],"align-items":[{items:[...T(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...T(),{baseline:["","last"]}]}],"place-content":[{"place-content":_()}],"place-items":[{"place-items":[...T(),"baseline"]}],"place-self":[{"place-self":["auto",...T()]}],p:[{p:I()}],px:[{px:I()}],py:[{py:I()}],ps:[{ps:I()}],pe:[{pe:I()}],pt:[{pt:I()}],pr:[{pr:I()}],pb:[{pb:I()}],pl:[{pl:I()}],m:[{m:S()}],mx:[{mx:S()}],my:[{my:S()}],ms:[{ms:S()}],me:[{me:S()}],mt:[{mt:S()}],mr:[{mr:S()}],mb:[{mb:S()}],ml:[{ml:S()}],"space-x":[{"space-x":I()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":I()}],"space-y-reverse":["space-y-reverse"],size:[{size:C()}],w:[{w:[o,"screen",...C()]}],"min-w":[{"min-w":[o,"screen","none",...C()]}],"max-w":[{"max-w":[o,"screen","none","prose",{screen:[a]},...C()]}],h:[{h:["screen","lh",...C()]}],"min-h":[{"min-h":["screen","lh","none",...C()]}],"max-h":[{"max-h":["screen","lh",...C()]}],"font-size":[{text:["base",t,wc,Pr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,Z,rp]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",np,J]}],"font-family":[{font:[L8,J,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[n,Z,J]}],"line-clamp":[{"line-clamp":[xe,"none",Z,rp]}],leading:[{leading:[r,...I()]}],"list-image":[{"list-image":["none",Z,J]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Z,J]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:E()}],"text-color":[{text:E()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...z(),"wavy"]}],"text-decoration-thickness":[{decoration:[xe,"from-font","auto",Z,Pr]}],"text-decoration-color":[{decoration:E()}],"underline-offset":[{"underline-offset":[xe,"auto",Z,J]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z,J]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Z,J]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:P()}],"bg-repeat":[{bg:L()}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},jn,Z,J],radial:["",Z,J],conic:[jn,Z,J]},B8,F8]}],"bg-color":[{bg:E()}],"gradient-from-pos":[{from:U()}],"gradient-via-pos":[{via:U()}],"gradient-to-pos":[{to:U()}],"gradient-from":[{from:E()}],"gradient-via":[{via:E()}],"gradient-to":[{to:E()}],rounded:[{rounded:j()}],"rounded-s":[{"rounded-s":j()}],"rounded-e":[{"rounded-e":j()}],"rounded-t":[{"rounded-t":j()}],"rounded-r":[{"rounded-r":j()}],"rounded-b":[{"rounded-b":j()}],"rounded-l":[{"rounded-l":j()}],"rounded-ss":[{"rounded-ss":j()}],"rounded-se":[{"rounded-se":j()}],"rounded-ee":[{"rounded-ee":j()}],"rounded-es":[{"rounded-es":j()}],"rounded-tl":[{"rounded-tl":j()}],"rounded-tr":[{"rounded-tr":j()}],"rounded-br":[{"rounded-br":j()}],"rounded-bl":[{"rounded-bl":j()}],"border-w":[{border:N()}],"border-w-x":[{"border-x":N()}],"border-w-y":[{"border-y":N()}],"border-w-s":[{"border-s":N()}],"border-w-e":[{"border-e":N()}],"border-w-t":[{"border-t":N()}],"border-w-r":[{"border-r":N()}],"border-w-b":[{"border-b":N()}],"border-w-l":[{"border-l":N()}],"divide-x":[{"divide-x":N()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":N()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...z(),"hidden","none"]}],"divide-style":[{divide:[...z(),"hidden","none"]}],"border-color":[{border:E()}],"border-color-x":[{"border-x":E()}],"border-color-y":[{"border-y":E()}],"border-color-s":[{"border-s":E()}],"border-color-e":[{"border-e":E()}],"border-color-t":[{"border-t":E()}],"border-color-r":[{"border-r":E()}],"border-color-b":[{"border-b":E()}],"border-color-l":[{"border-l":E()}],"divide-color":[{divide:E()}],"outline-style":[{outline:[...z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[xe,Z,J]}],"outline-w":[{outline:["",xe,wc,Pr]}],"outline-color":[{outline:E()}],shadow:[{shadow:["","none",u,Pu,Iu]}],"shadow-color":[{shadow:E()}],"inset-shadow":[{"inset-shadow":["none",d,Pu,Iu]}],"inset-shadow-color":[{"inset-shadow":E()}],"ring-w":[{ring:N()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:E()}],"ring-offset-w":[{"ring-offset":[xe,Pr]}],"ring-offset-color":[{"ring-offset":E()}],"inset-ring-w":[{"inset-ring":N()}],"inset-ring-color":[{"inset-ring":E()}],"text-shadow":[{"text-shadow":["none",h,Pu,Iu]}],"text-shadow-color":[{"text-shadow":E()}],opacity:[{opacity:[xe,Z,J]}],"mix-blend":[{"mix-blend":[...W(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":W()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Q()}],"mask-image-linear-to-pos":[{"mask-linear-to":Q()}],"mask-image-linear-from-color":[{"mask-linear-from":E()}],"mask-image-linear-to-color":[{"mask-linear-to":E()}],"mask-image-t-from-pos":[{"mask-t-from":Q()}],"mask-image-t-to-pos":[{"mask-t-to":Q()}],"mask-image-t-from-color":[{"mask-t-from":E()}],"mask-image-t-to-color":[{"mask-t-to":E()}],"mask-image-r-from-pos":[{"mask-r-from":Q()}],"mask-image-r-to-pos":[{"mask-r-to":Q()}],"mask-image-r-from-color":[{"mask-r-from":E()}],"mask-image-r-to-color":[{"mask-r-to":E()}],"mask-image-b-from-pos":[{"mask-b-from":Q()}],"mask-image-b-to-pos":[{"mask-b-to":Q()}],"mask-image-b-from-color":[{"mask-b-from":E()}],"mask-image-b-to-color":[{"mask-b-to":E()}],"mask-image-l-from-pos":[{"mask-l-from":Q()}],"mask-image-l-to-pos":[{"mask-l-to":Q()}],"mask-image-l-from-color":[{"mask-l-from":E()}],"mask-image-l-to-color":[{"mask-l-to":E()}],"mask-image-x-from-pos":[{"mask-x-from":Q()}],"mask-image-x-to-pos":[{"mask-x-to":Q()}],"mask-image-x-from-color":[{"mask-x-from":E()}],"mask-image-x-to-color":[{"mask-x-to":E()}],"mask-image-y-from-pos":[{"mask-y-from":Q()}],"mask-image-y-to-pos":[{"mask-y-to":Q()}],"mask-image-y-from-color":[{"mask-y-from":E()}],"mask-image-y-to-color":[{"mask-y-to":E()}],"mask-image-radial":[{"mask-radial":[Z,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":Q()}],"mask-image-radial-to-pos":[{"mask-radial-to":Q()}],"mask-image-radial-from-color":[{"mask-radial-from":E()}],"mask-image-radial-to-color":[{"mask-radial-to":E()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Q()}],"mask-image-conic-to-pos":[{"mask-conic-to":Q()}],"mask-image-conic-from-color":[{"mask-conic-from":E()}],"mask-image-conic-to-color":[{"mask-conic-to":E()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:P()}],"mask-repeat":[{mask:L()}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Z,J]}],filter:[{filter:["","none",Z,J]}],blur:[{blur:fe()}],brightness:[{brightness:[xe,Z,J]}],contrast:[{contrast:[xe,Z,J]}],"drop-shadow":[{"drop-shadow":["","none",f,Pu,Iu]}],"drop-shadow-color":[{"drop-shadow":E()}],grayscale:[{grayscale:["",xe,Z,J]}],"hue-rotate":[{"hue-rotate":[xe,Z,J]}],invert:[{invert:["",xe,Z,J]}],saturate:[{saturate:[xe,Z,J]}],sepia:[{sepia:["",xe,Z,J]}],"backdrop-filter":[{"backdrop-filter":["","none",Z,J]}],"backdrop-blur":[{"backdrop-blur":fe()}],"backdrop-brightness":[{"backdrop-brightness":[xe,Z,J]}],"backdrop-contrast":[{"backdrop-contrast":[xe,Z,J]}],"backdrop-grayscale":[{"backdrop-grayscale":["",xe,Z,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[xe,Z,J]}],"backdrop-invert":[{"backdrop-invert":["",xe,Z,J]}],"backdrop-opacity":[{"backdrop-opacity":[xe,Z,J]}],"backdrop-saturate":[{"backdrop-saturate":[xe,Z,J]}],"backdrop-sepia":[{"backdrop-sepia":["",xe,Z,J]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":I()}],"border-spacing-x":[{"border-spacing-x":I()}],"border-spacing-y":[{"border-spacing-y":I()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Z,J]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[xe,"initial",Z,J]}],ease:[{ease:["linear","initial",v,Z,J]}],delay:[{delay:[xe,Z,J]}],animate:[{animate:["none",w,Z,J]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,Z,J]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:ye()}],"rotate-x":[{"rotate-x":ye()}],"rotate-y":[{"rotate-y":ye()}],"rotate-z":[{"rotate-z":ye()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:Le()}],"skew-x":[{"skew-x":Le()}],"skew-y":[{"skew-y":Le()}],transform:[{transform:[Z,J,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"translate-none":["translate-none"],accent:[{accent:E()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:E()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Z,J]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Z,J]}],fill:[{fill:["none",...E()]}],"stroke-w":[{stroke:[xe,wc,Pr,rp]}],stroke:[{stroke:["none",...E()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},V8=x8(N8);function ie(...s){return V8(E3(s))}const Bw=s=>typeof s=="boolean"?`${s}`:s===0?"0":s,$w=E3,Oh=(s,e)=>t=>{var i;if(e?.variants==null)return $w(s,t?.class,t?.className);const{variants:n,defaultVariants:r}=e,a=Object.keys(n).map(l=>{const u=t?.[l],d=r?.[l];if(u===null)return null;const h=Bw(u)||Bw(d);return n[l][h]}),o=t&&Object.entries(t).reduce((l,u)=>{let[d,h]=u;return h===void 0||(l[d]=h),l},{}),c=e==null||(i=e.compoundVariants)===null||i===void 0?void 0:i.reduce((l,u)=>{let{class:d,className:h,...f}=u;return Object.entries(f).every(p=>{let[m,g]=p;return Array.isArray(g)?g.includes({...r,...o}[m]):{...r,...o}[m]===g})?[...l,d,h]:l},[]);return $w(s,a,c,t?.class,t?.className)},U8=Oh("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),z8=F.forwardRef(({className:s,variant:e,...t},i)=>x.jsx("div",{ref:i,role:"alert",className:ie(U8({variant:e}),s),...t}));z8.displayName="Alert";const G8=F.forwardRef(({className:s,...e},t)=>x.jsx("h5",{ref:t,className:ie("mb-1 font-medium leading-none tracking-tight",s),...e}));G8.displayName="AlertTitle";const W8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("text-sm [&_p]:leading-relaxed",s),...e}));W8.displayName="AlertDescription";const q8=Oh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-white hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 [&_svg]:size-4","icon-xs":"h-6 w-6 [&_svg]:size-3.5"}},defaultVariants:{variant:"default",size:"default"}}),Kt=F.forwardRef(({className:s,variant:e,size:t,asChild:i=!1,...n},r)=>{const a=i?L5:"button";return x.jsx(a,{className:ie(q8({variant:e,size:t,className:s})),ref:r,...n})});Kt.displayName="Button";const H8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));H8.displayName="Card";const Y8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("flex flex-col space-y-1.5 p-6",s),...e}));Y8.displayName="CardHeader";const X8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("text-2xl font-semibold leading-none tracking-tight",s),...e}));X8.displayName="CardTitle";const K8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("text-sm text-muted-foreground",s),...e}));K8.displayName="CardDescription";const Q8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("p-6 pt-0",s),...e}));Q8.displayName="CardContent";const J8=F.forwardRef(({className:s,...e},t)=>x.jsx("div",{ref:t,className:ie("flex items-center p-6 pt-0",s),...e}));J8.displayName="CardFooter";const Z8=F.forwardRef(({className:s,...e},t)=>x.jsx(jk,{ref:t,className:ie("grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",s),...e,children:x.jsx(O5,{className:ie("grid place-content-center text-current"),children:x.jsx(iu,{className:"h-4 w-4"})})}));Z8.displayName=jk.displayName;const eN=$5,tN=j5,V3=F.forwardRef(({className:s,align:e="center",sideOffset:t=4,...i},n)=>x.jsx(B5,{children:x.jsx(Nk,{ref:n,align:e,sideOffset:t,className:ie("z-[9999] w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...i})}));V3.displayName=Nk.displayName;const su=F.forwardRef(({className:s,...e},t)=>x.jsxs(Vk,{ref:t,className:ie("relative flex w-full touch-none select-none items-center",s),...e,children:[x.jsx(N5,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-background-tertiary",children:x.jsx(V5,{className:"absolute h-full bg-text-secondary"})}),x.jsx(U5,{className:"block h-2.5 w-2.5 rounded-full bg-white shadow-sm ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));su.displayName=Vk.displayName;const jw="#000000",qa="transparent",iN="linear-gradient(45deg, rgba(148, 163, 184, 0.35) 25%, transparent 25%, transparent 75%, rgba(148, 163, 184, 0.35) 75%), linear-gradient(45deg, rgba(148, 163, 184, 0.35) 25%, transparent 25%, transparent 75%, rgba(148, 163, 184, 0.35) 75%)",Nw={backgroundImage:iN,backgroundPosition:"0 0, 4px 4px",backgroundSize:"8px 8px"};function Cl(s,e,t){return Math.min(t,Math.max(e,s))}function ap(s){return Cl(Math.round(s),0,255).toString(16).padStart(2,"0")}function U3(s){const e=s.trim();if(!e.startsWith("#"))return null;const t=e.slice(1);return/^[0-9a-fA-F]{3}$/.test(t)?`#${t.split("").map(i=>`${i}${i}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{4}$/.test(t)?`#${t.slice(0,3).split("").map(i=>`${i}${i}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{6}$/.test(t)?`#${t.toLowerCase()}`:/^[0-9a-fA-F]{8}$/.test(t)?`#${t.slice(0,6).toLowerCase()}`:null}function op(s){const e=s.trim();if(e.endsWith("%")){const i=Number.parseFloat(e.slice(0,-1));return Number.isNaN(i)?null:Cl(i/100*255,0,255)}const t=Number.parseFloat(e);return Number.isNaN(t)?null:Cl(t,0,255)}function sN(s){const e=s.trim();if(e.endsWith("%")){const i=Number.parseFloat(e.slice(0,-1));return Number.isNaN(i)?null:Cl(i/100,0,1)}const t=Number.parseFloat(e);return Number.isNaN(t)?null:Cl(t,0,1)}function Vw(s){const e=s.trim().toLowerCase();if(!e||e===qa)return{hex:jw,alpha:0,isTransparent:!0};const t=U3(e);if(t){const n=e.slice(1),r=n.length===4?parseInt(`${n[3]}${n[3]}`,16)/255:n.length===8?parseInt(n.slice(6,8),16)/255:1;return{hex:t,alpha:r,isTransparent:!1}}const i=e.match(/^rgba?\(\s*([^\s,]+)\s*,\s*([^\s,]+)\s*,\s*([^\s,\/\)]+)(?:\s*[,\/]\s*([^\s\)]+))?\s*\)$/);if(i){const n=op(i[1]),r=op(i[2]),a=op(i[3]),o=i[4]?sN(i[4]):1;if(n!==null&&r!==null&&a!==null&&o!==null)return{hex:`#${ap(n)}${ap(r)}${ap(a)}`,alpha:o,isTransparent:!1}}return{hex:jw,alpha:1,isTransparent:!1}}function nN(s){return s<=0?"0":s>=1?"1":s.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function cp(s,e,t){if(t&&e<=0)return qa;if(!t||e>=1)return s;const i=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),r=parseInt(s.slice(5,7),16);return`rgba(${i}, ${n}, ${r}, ${nN(e)})`}const rN=F.forwardRef(({value:s,onChange:e,showAlpha:t=!1,allowTransparent:i=!1,disabled:n=!1,className:r},a)=>{const o=F.useMemo(()=>Vw(s),[s]),[c,l]=F.useState(!1),[u,d]=F.useState(s||"");F.useEffect(()=>{d(s||"")},[s]);const h=F.useMemo(()=>cp(o.hex,o.alpha,t),[o.alpha,o.hex,t]),f=F.useCallback((v,w,b=!1)=>{if(i&&b){e(qa);return}e(cp(v,w,t))},[i,e,t]),p=F.useCallback(v=>{f(v.target.value,t?o.isTransparent?1:Math.max(o.alpha,0):1)},[f,o.alpha,o.isTransparent,t]),m=F.useCallback(([v])=>{f(o.hex,v)},[f,o.hex]),g=F.useCallback(v=>{const w=v.target.value;if(d(w),i&&w.trim().toLowerCase()===qa){e(qa);return}const b=Vw(w),k=U3(w),A=/^rgba?\(/i.test(w.trim());(k||A)&&e(cp(b.hex,b.alpha,t))},[i,e,t]);return x.jsxs(eN,{open:c,onOpenChange:l,children:[x.jsx(tN,{asChild:!0,children:x.jsxs("button",{ref:a,type:"button",disabled:n,className:ie("flex h-8 w-full items-center gap-2 rounded-md border border-border bg-background-tertiary px-2 text-left text-[10px] text-text-primary transition-colors hover:border-primary/60 disabled:cursor-not-allowed disabled:opacity-50",r),children:[x.jsxs("span",{className:"relative h-4 w-4 shrink-0 overflow-hidden rounded border border-border",style:Nw,children:[!o.isTransparent&&x.jsx("span",{className:"absolute inset-0",style:{backgroundColor:o.hex,opacity:t?o.alpha:1}}),o.isTransparent&&x.jsx(Ij,{className:"absolute inset-0 m-auto h-3 w-3 text-text-muted"})]}),x.jsx("span",{className:"min-w-0 flex-1 truncate font-mono uppercase text-text-muted",children:o.isTransparent?qa:h})]})}),x.jsxs(V3,{align:"end",className:"w-64 space-y-3",children:[x.jsxs("div",{className:"space-y-2",children:[x.jsxs("div",{className:"flex items-center justify-between",children:[x.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-text-secondary",children:"Color"}),i&&x.jsx("button",{type:"button",onClick:()=>f(o.hex,0,!0),className:"text-[10px] text-text-muted transition-colors hover:text-text-primary",children:"Clear"})]}),x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx("span",{className:"relative h-10 w-10 overflow-hidden rounded-md border border-border",style:Nw,children:!o.isTransparent&&x.jsx("span",{className:"absolute inset-0",style:{backgroundColor:o.hex,opacity:t?o.alpha:1}})}),x.jsx("input",{type:"color",value:o.hex,onChange:p,className:"h-10 w-full cursor-pointer rounded-md border border-border bg-background"})]})]}),t&&x.jsxs("div",{className:"space-y-2",children:[x.jsxs("div",{className:"flex items-center justify-between text-[10px] text-text-secondary",children:[x.jsx("span",{className:"font-medium uppercase tracking-wide",children:"Opacity"}),x.jsxs("span",{className:"font-mono text-text-muted",children:[Math.round(o.alpha*100),"%"]})]}),x.jsx(su,{value:[o.alpha],onValueChange:m,min:0,max:1,step:.01})]}),x.jsxs("div",{className:"space-y-2",children:[x.jsx("label",{className:"block text-[10px] font-medium uppercase tracking-wide text-text-secondary",children:"Value"}),x.jsx("input",{type:"text",value:u,onChange:g,placeholder:i?"#000000 or transparent":"#000000",className:"w-full rounded-md border border-border bg-background px-2 py-1.5 text-[11px] font-mono text-text-primary outline-none transition-colors focus:border-primary"})]}),i&&o.isTransparent&&x.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-text-muted",children:[x.jsx(iu,{className:"h-3 w-3"}),"Transparent background is active"]})]})]})});rN.displayName="ColorPicker";const aN=F.forwardRef(({icon:s,iconSize:e=14,className:t,variant:i="ghost",size:n="icon-xs",...r},a)=>x.jsx(Kt,{ref:a,variant:i,size:n,className:ie("text-text-secondary hover:text-text-primary hover:bg-background-elevated",t),...r,children:x.jsx(s,{size:e})}));aN.displayName="IconButton";const El=F.createContext({});function Qy(s){const e=F.useRef(null);return e.current===null&&(e.current=s()),e.current}const z3=typeof window<"u",Jy=z3?F.useLayoutEffect:F.useEffect,Bh=F.createContext(null);function Zy(s,e){s.indexOf(e)===-1&&s.push(e)}function e1(s,e){const t=s.indexOf(e);t>-1&&s.splice(t,1)}const Qs=(s,e,t)=>t>e?e:t{};const Mn={},G3=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function W3(s){return typeof s=="object"&&s!==null}const q3=s=>/^0[^.\s]+$/u.test(s);function i1(s){let e;return()=>(e===void 0&&(e=s()),e)}const gs=s=>s,oN=(s,e)=>t=>e(s(t)),nu=(...s)=>s.reduce(oN),Ml=(s,e,t)=>{const i=e-s;return i===0?1:(t-s)/i};class s1{constructor(){this.subscriptions=[]}add(e){return Zy(this.subscriptions,e),()=>e1(this.subscriptions,e)}notify(e,t,i){const n=this.subscriptions.length;if(n)if(n===1)this.subscriptions[0](e,t,i);else for(let r=0;rs*1e3,cs=s=>s/1e3;function H3(s,e){return e?s*(1e3/e):0}const Y3=(s,e,t)=>(((1-3*t+3*e)*s+(3*t-6*e))*s+3*e)*s,cN=1e-7,lN=12;function uN(s,e,t,i,n){let r,a,o=0;do a=e+(t-e)/2,r=Y3(a,i,n)-s,r>0?t=a:e=a;while(Math.abs(r)>cN&&++ouN(r,0,1,s,t);return r=>r===0||r===1?r:Y3(n(r),e,i)}const X3=s=>e=>e<=.5?s(2*e)/2:(2-s(2*(1-e)))/2,K3=s=>e=>1-s(1-e),Q3=ru(.33,1.53,.69,.99),n1=K3(Q3),J3=X3(n1),Z3=s=>(s*=2)<1?.5*n1(s):.5*(2-Math.pow(2,-10*(s-1))),r1=s=>1-Math.sin(Math.acos(s)),eE=K3(r1),tE=X3(r1),dN=ru(.42,0,1,1),hN=ru(0,0,.58,1),iE=ru(.42,0,.58,1),fN=s=>Array.isArray(s)&&typeof s[0]!="number",sE=s=>Array.isArray(s)&&typeof s[0]=="number",pN={linear:gs,easeIn:dN,easeInOut:iE,easeOut:hN,circIn:r1,circInOut:tE,circOut:eE,backIn:n1,backInOut:J3,backOut:Q3,anticipate:Z3},mN=s=>typeof s=="string",Uw=s=>{if(sE(s)){t1(s.length===4);const[e,t,i,n]=s;return ru(e,t,i,n)}else if(mN(s))return pN[s];return s},Ru=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function gN(s,e){let t=new Set,i=new Set,n=!1,r=!1;const a=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function c(u){a.has(u)&&(l.schedule(u),s()),u(o)}const l={schedule:(u,d=!1,h=!1)=>{const p=h&&n?t:i;return d&&a.add(u),p.has(u)||p.add(u),u},cancel:u=>{i.delete(u),a.delete(u)},process:u=>{if(o=u,n){r=!0;return}n=!0,[t,i]=[i,t],t.forEach(c),t.clear(),n=!1,r&&(r=!1,l.process(u))}};return l}const yN=40;function nE(s,e){let t=!1,i=!0;const n={delta:0,timestamp:0,isProcessing:!1},r=()=>t=!0,a=Ru.reduce((b,k)=>(b[k]=gN(r),b),{}),{setup:o,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:h,render:f,postRender:p}=a,m=()=>{const b=Mn.useManualTiming?n.timestamp:performance.now();t=!1,Mn.useManualTiming||(n.delta=i?1e3/60:Math.max(Math.min(b-n.timestamp,yN),1)),n.timestamp=b,n.isProcessing=!0,o.process(n),c.process(n),l.process(n),u.process(n),d.process(n),h.process(n),f.process(n),p.process(n),n.isProcessing=!1,t&&e&&(i=!1,s(m))},g=()=>{t=!0,i=!0,n.isProcessing||s(m)};return{schedule:Ru.reduce((b,k)=>{const A=a[k];return b[k]=(M,R=!1,I=!1)=>(t||g(),A.schedule(M,R,I)),b},{}),cancel:b=>{for(let k=0;k(md===void 0&&ui.set(Ut.isProcessing||Mn.useManualTiming?Ut.timestamp:performance.now()),md),set:s=>{md=s,queueMicrotask(vN)}},rE=s=>e=>typeof e=="string"&&e.startsWith(s),aE=rE("--"),bN=rE("var(--"),a1=s=>bN(s)?xN.test(s.split("/*")[0].trim()):!1,xN=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function zw(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const Xo={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},Il={...Xo,transform:s=>Qs(0,1,s)},Du={...Xo,default:1},sl=s=>Math.round(s*1e5)/1e5,o1=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function wN(s){return s==null}const _N=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,c1=(s,e)=>t=>!!(typeof t=="string"&&_N.test(t)&&t.startsWith(s)||e&&!wN(t)&&Object.prototype.hasOwnProperty.call(t,e)),oE=(s,e,t)=>i=>{if(typeof i!="string")return i;const[n,r,a,o]=i.match(o1);return{[s]:parseFloat(n),[e]:parseFloat(r),[t]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},TN=s=>Qs(0,255,s),up={...Xo,transform:s=>Math.round(TN(s))},qr={test:c1("rgb","red"),parse:oE("red","green","blue"),transform:({red:s,green:e,blue:t,alpha:i=1})=>"rgba("+up.transform(s)+", "+up.transform(e)+", "+up.transform(t)+", "+sl(Il.transform(i))+")"};function kN(s){let e="",t="",i="",n="";return s.length>5?(e=s.substring(1,3),t=s.substring(3,5),i=s.substring(5,7),n=s.substring(7,9)):(e=s.substring(1,2),t=s.substring(2,3),i=s.substring(3,4),n=s.substring(4,5),e+=e,t+=t,i+=i,n+=n),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:n?parseInt(n,16)/255:1}}const Pg={test:c1("#"),parse:kN,transform:qr.transform},au=s=>({test:e=>typeof e=="string"&&e.endsWith(s)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${s}`}),Hn=au("deg"),Xs=au("%"),ee=au("px"),AN=au("vh"),SN=au("vw"),Gw={...Xs,parse:s=>Xs.parse(s)/100,transform:s=>Xs.transform(s*100)},Ha={test:c1("hsl","hue"),parse:oE("hue","saturation","lightness"),transform:({hue:s,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(s)+", "+Xs.transform(sl(e))+", "+Xs.transform(sl(t))+", "+sl(Il.transform(i))+")"},bt={test:s=>qr.test(s)||Pg.test(s)||Ha.test(s),parse:s=>qr.test(s)?qr.parse(s):Ha.test(s)?Ha.parse(s):Pg.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?qr.transform(s):Ha.transform(s),getAnimatableNone:s=>{const e=bt.parse(s);return e.alpha=0,bt.transform(e)}},CN=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function EN(s){return isNaN(s)&&typeof s=="string"&&(s.match(o1)?.length||0)+(s.match(CN)?.length||0)>0}const cE="number",lE="color",MN="var",IN="var(",Ww="${}",PN=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Pl(s){const e=s.toString(),t=[],i={color:[],number:[],var:[]},n=[];let r=0;const o=e.replace(PN,c=>(bt.test(c)?(i.color.push(r),n.push(lE),t.push(bt.parse(c))):c.startsWith(IN)?(i.var.push(r),n.push(MN),t.push(c)):(i.number.push(r),n.push(cE),t.push(parseFloat(c))),++r,Ww)).split(Ww);return{values:t,split:o,indexes:i,types:n}}function uE(s){return Pl(s).values}function dE(s){const{split:e,types:t}=Pl(s),i=e.length;return n=>{let r="";for(let a=0;atypeof s=="number"?0:bt.test(s)?bt.getAnimatableNone(s):s;function DN(s){const e=uE(s);return dE(s)(e.map(RN))}const fr={test:EN,parse:uE,createTransformer:dE,getAnimatableNone:DN};function dp(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*(2/3-t)*6:s}function FN({hue:s,saturation:e,lightness:t,alpha:i}){s/=360,e/=100,t/=100;let n=0,r=0,a=0;if(!e)n=r=a=t;else{const o=t<.5?t*(1+e):t+e-t*e,c=2*t-o;n=dp(c,o,s+1/3),r=dp(c,o,s),a=dp(c,o,s-1/3)}return{red:Math.round(n*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:i}}function Qd(s,e){return t=>t>0?e:s}const Je=(s,e,t)=>s+(e-s)*t,hp=(s,e,t)=>{const i=s*s,n=t*(e*e-i)+i;return n<0?0:Math.sqrt(n)},LN=[Pg,qr,Ha],ON=s=>LN.find(e=>e.test(s));function qw(s){const e=ON(s);if(!e)return!1;let t=e.parse(s);return e===Ha&&(t=FN(t)),t}const Hw=(s,e)=>{const t=qw(s),i=qw(e);if(!t||!i)return Qd(s,e);const n={...t};return r=>(n.red=hp(t.red,i.red,r),n.green=hp(t.green,i.green,r),n.blue=hp(t.blue,i.blue,r),n.alpha=Je(t.alpha,i.alpha,r),qr.transform(n))},Rg=new Set(["none","hidden"]);function BN(s,e){return Rg.has(s)?t=>t<=0?s:e:t=>t>=1?e:s}function $N(s,e){return t=>Je(s,e,t)}function l1(s){return typeof s=="number"?$N:typeof s=="string"?a1(s)?Qd:bt.test(s)?Hw:VN:Array.isArray(s)?hE:typeof s=="object"?bt.test(s)?Hw:jN:Qd}function hE(s,e){const t=[...s],i=t.length,n=s.map((r,a)=>l1(r)(r,e[a]));return r=>{for(let a=0;a{for(const r in i)t[r]=i[r](n);return t}}function NN(s,e){const t=[],i={color:0,var:0,number:0};for(let n=0;n{const t=fr.createTransformer(e),i=Pl(s),n=Pl(e);return i.indexes.var.length===n.indexes.var.length&&i.indexes.color.length===n.indexes.color.length&&i.indexes.number.length>=n.indexes.number.length?Rg.has(s)&&!n.values.length||Rg.has(e)&&!i.values.length?BN(s,e):nu(hE(NN(i,n),n.values),t):Qd(s,e)};function fE(s,e,t){return typeof s=="number"&&typeof e=="number"&&typeof t=="number"?Je(s,e,t):l1(s)(s,e)}const UN=s=>{const e=({timestamp:t})=>s(t);return{start:(t=!0)=>$e.update(e,t),stop:()=>hr(e),now:()=>Ut.isProcessing?Ut.timestamp:ui.now()}},pE=(s,e,t=10)=>{let i="";const n=Math.max(Math.round(e/t),2);for(let r=0;r=Jd?1/0:e}function zN(s,e=100,t){const i=t({...s,keyframes:[0,e]}),n=Math.min(u1(i),Jd);return{type:"keyframes",ease:r=>i.next(n*r).value/e,duration:cs(n)}}const GN=5;function mE(s,e,t){const i=Math.max(e-GN,0);return H3(t-s(i),e-i)}const ot={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},fp=.001;function WN({duration:s=ot.duration,bounce:e=ot.bounce,velocity:t=ot.velocity,mass:i=ot.mass}){let n,r,a=1-e;a=Qs(ot.minDamping,ot.maxDamping,a),s=Qs(ot.minDuration,ot.maxDuration,cs(s)),a<1?(n=l=>{const u=l*a,d=u*s,h=u-t,f=Dg(l,a),p=Math.exp(-d);return fp-h/f*p},r=l=>{const d=l*a*s,h=d*t+t,f=Math.pow(a,2)*Math.pow(l,2)*s,p=Math.exp(-d),m=Dg(Math.pow(l,2),a);return(-n(l)+fp>0?-1:1)*((h-f)*p)/m}):(n=l=>{const u=Math.exp(-l*s),d=(l-t)*s+1;return-fp+u*d},r=l=>{const u=Math.exp(-l*s),d=(t-l)*(s*s);return u*d});const o=5/s,c=HN(n,r,o);if(s=Tn(s),isNaN(c))return{stiffness:ot.stiffness,damping:ot.damping,duration:s};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:a*2*Math.sqrt(i*l),duration:s}}}const qN=12;function HN(s,e,t){let i=t;for(let n=1;ns[t]!==void 0)}function KN(s){let e={velocity:ot.velocity,stiffness:ot.stiffness,damping:ot.damping,mass:ot.mass,isResolvedFromDuration:!1,...s};if(!Yw(s,XN)&&Yw(s,YN))if(s.visualDuration){const t=s.visualDuration,i=2*Math.PI/(t*1.2),n=i*i,r=2*Qs(.05,1,1-(s.bounce||0))*Math.sqrt(n);e={...e,mass:ot.mass,stiffness:n,damping:r}}else{const t=WN(s);e={...e,...t,mass:ot.mass},e.isResolvedFromDuration=!0}return e}function Zd(s=ot.visualDuration,e=ot.bounce){const t=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:e}:s;let{restSpeed:i,restDelta:n}=t;const r=t.keyframes[0],a=t.keyframes[t.keyframes.length-1],o={done:!1,value:r},{stiffness:c,damping:l,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=KN({...t,velocity:-cs(t.velocity||0)}),p=h||0,m=l/(2*Math.sqrt(c*u)),g=a-r,v=cs(Math.sqrt(c/u)),w=Math.abs(g)<5;i||(i=w?ot.restSpeed.granular:ot.restSpeed.default),n||(n=w?ot.restDelta.granular:ot.restDelta.default);let b;if(m<1){const A=Dg(v,m);b=M=>{const R=Math.exp(-m*v*M);return a-R*((p+m*v*g)/A*Math.sin(A*M)+g*Math.cos(A*M))}}else if(m===1)b=A=>a-Math.exp(-v*A)*(g+(p+v*g)*A);else{const A=v*Math.sqrt(m*m-1);b=M=>{const R=Math.exp(-m*v*M),I=Math.min(A*M,300);return a-R*((p+m*v*g)*Math.sinh(I)+A*g*Math.cosh(I))/A}}const k={calculatedDuration:f&&d||null,next:A=>{const M=b(A);if(f)o.done=A>=d;else{let R=A===0?p:0;m<1&&(R=A===0?Tn(p):mE(b,A,M));const I=Math.abs(R)<=i,D=Math.abs(a-M)<=n;o.done=I&&D}return o.value=o.done?a:M,o},toString:()=>{const A=Math.min(u1(k),Jd),M=pE(R=>k.next(A*R).value,A,30);return A+"ms "+M},toTransition:()=>{}};return k}Zd.applyToOptions=s=>{const e=zN(s,100,Zd);return s.ease=e.ease,s.duration=Tn(e.duration),s.type="keyframes",s};function Fg({keyframes:s,velocity:e=0,power:t=.8,timeConstant:i=325,bounceDamping:n=10,bounceStiffness:r=500,modifyTarget:a,min:o,max:c,restDelta:l=.5,restSpeed:u}){const d=s[0],h={done:!1,value:d},f=I=>o!==void 0&&Ic,p=I=>o===void 0?c:c===void 0||Math.abs(o-I)-m*Math.exp(-I/i),b=I=>v+w(I),k=I=>{const D=w(I),B=b(I);h.done=Math.abs(D)<=l,h.value=h.done?v:B};let A,M;const R=I=>{f(h.value)&&(A=I,M=Zd({keyframes:[h.value,p(h.value)],velocity:mE(b,I,h.value),damping:n,stiffness:r,restDelta:l,restSpeed:u}))};return R(0),{calculatedDuration:null,next:I=>{let D=!1;return!M&&A===void 0&&(D=!0,k(I),R(I)),A!==void 0&&I>=A?M.next(I-A):(!D&&k(I),h)}}}function QN(s,e,t){const i=[],n=t||Mn.mix||fE,r=s.length-1;for(let a=0;ae[0];if(r===2&&e[0]===e[1])return()=>e[1];const a=s[0]===s[1];s[0]>s[r-1]&&(s=[...s].reverse(),e=[...e].reverse());const o=QN(e,i,n),c=o.length,l=u=>{if(a&&u1)for(;dl(Qs(s[0],s[r-1],u)):l}function ZN(s,e){const t=s[s.length-1];for(let i=1;i<=e;i++){const n=Ml(0,e,i);s.push(Je(t,1,n))}}function eV(s){const e=[0];return ZN(e,s.length-1),e}function tV(s,e){return s.map(t=>t*e)}function iV(s,e){return s.map(()=>e||iE).splice(0,s.length-1)}function nl({duration:s=300,keyframes:e,times:t,ease:i="easeInOut"}){const n=fN(i)?i.map(Uw):Uw(i),r={done:!1,value:e[0]},a=tV(t&&t.length===e.length?t:eV(e),s),o=JN(a,e,{ease:Array.isArray(n)?n:iV(e,n)});return{calculatedDuration:s,next:c=>(r.value=o(c),r.done=c>=s,r)}}const sV=s=>s!==null;function d1(s,{repeat:e,repeatType:t="loop"},i,n=1){const r=s.filter(sV),o=n<0||e&&t!=="loop"&&e%2===1?0:r.length-1;return!o||i===void 0?r[o]:i}const nV={decay:Fg,inertia:Fg,tween:nl,keyframes:nl,spring:Zd};function gE(s){typeof s.type=="string"&&(s.type=nV[s.type])}class h1{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}}const rV=s=>s/100;class f1 extends h1{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==ui.now()&&this.tick(ui.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;gE(e);const{type:t=nl,repeat:i=0,repeatDelay:n=0,repeatType:r,velocity:a=0}=e;let{keyframes:o}=e;const c=t||nl;c!==nl&&typeof o[0]!="number"&&(this.mixKeyframes=nu(rV,fE(o[0],o[1])),o=[0,100]);const l=c({...e,keyframes:o});r==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...o].reverse(),velocity:-a})),l.calculatedDuration===null&&(l.calculatedDuration=u1(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+n,this.totalDuration=this.resolvedDuration*(i+1)-n,this.generator=l}updateTime(e){const t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=t}tick(e,t=!1){const{generator:i,totalDuration:n,mixKeyframes:r,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-n/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);const v=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?v<0:v>n;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let b=this.currentTime,k=i;if(d){const I=Math.min(this.currentTime,n)/o;let D=Math.floor(I),B=I%1;!B&&I>=1&&(B=1),B===1&&D--,D=Math.min(D,d+1),!!(D%2)&&(h==="reverse"?(B=1-B,f&&(B-=f/o)):h==="mirror"&&(k=a)),b=Qs(0,1,B)*o}const A=w?{done:!1,value:u[0]}:k.next(b);r&&(A.value=r(A.value));let{done:M}=A;!w&&c!==null&&(M=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return R&&p!==Fg&&(A.value=d1(u,this.options,g,this.speed)),m&&m(A.value),R&&this.finish(),A}then(e,t){return this.finished.then(e,t)}get duration(){return cs(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+cs(e)}get time(){return cs(this.currentTime)}set time(e){e=Tn(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(ui.now());const t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=cs(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=UN,startTime:t}=this.options;this.driver||(this.driver=e(n=>this.tick(n))),this.options.onPlay?.();const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=t??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ui.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}}function aV(s){for(let e=1;es*180/Math.PI,Lg=s=>{const e=Hr(Math.atan2(s[1],s[0]));return Og(e)},oV={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:Lg,rotateZ:Lg,skewX:s=>Hr(Math.atan(s[1])),skewY:s=>Hr(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},Og=s=>(s=s%360,s<0&&(s+=360),s),Xw=Lg,Kw=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),Qw=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),cV={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Kw,scaleY:Qw,scale:s=>(Kw(s)+Qw(s))/2,rotateX:s=>Og(Hr(Math.atan2(s[6],s[5]))),rotateY:s=>Og(Hr(Math.atan2(-s[2],s[0]))),rotateZ:Xw,rotate:Xw,skewX:s=>Hr(Math.atan(s[4])),skewY:s=>Hr(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function Bg(s){return s.includes("scale")?1:0}function $g(s,e){if(!s||s==="none")return Bg(e);const t=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,n;if(t)i=cV,n=t;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=oV,n=o}if(!n)return Bg(e);const r=i[e],a=n[1].split(",").map(uV);return typeof r=="function"?r(a):a[r]}const lV=(s,e)=>{const{transform:t="none"}=getComputedStyle(s);return $g(t,e)};function uV(s){return parseFloat(s.trim())}const Ko=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Qo=new Set(Ko),Jw=s=>s===Xo||s===ee,dV=new Set(["x","y","z"]),hV=Ko.filter(s=>!dV.has(s));function fV(s){const e=[];return hV.forEach(t=>{const i=s.getValue(t);i!==void 0&&(e.push([t,i.get()]),i.set(t.startsWith("scale")?1:0))}),e}const Jn={width:({x:s},{paddingLeft:e="0",paddingRight:t="0"})=>s.max-s.min-parseFloat(e)-parseFloat(t),height:({y:s},{paddingTop:e="0",paddingBottom:t="0"})=>s.max-s.min-parseFloat(e)-parseFloat(t),top:(s,{top:e})=>parseFloat(e),left:(s,{left:e})=>parseFloat(e),bottom:({y:s},{top:e})=>parseFloat(e)+(s.max-s.min),right:({x:s},{left:e})=>parseFloat(e)+(s.max-s.min),x:(s,{transform:e})=>$g(e,"x"),y:(s,{transform:e})=>$g(e,"y")};Jn.translateX=Jn.x;Jn.translateY=Jn.y;const ia=new Set;let jg=!1,Ng=!1,Vg=!1;function yE(){if(Ng){const s=Array.from(ia).filter(i=>i.needsMeasurement),e=new Set(s.map(i=>i.element)),t=new Map;e.forEach(i=>{const n=fV(i);n.length&&(t.set(i,n),i.render())}),s.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const n=t.get(i);n&&n.forEach(([r,a])=>{i.getValue(r)?.set(a)})}),s.forEach(i=>i.measureEndState()),s.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}Ng=!1,jg=!1,ia.forEach(s=>s.complete(Vg)),ia.clear()}function vE(){ia.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(Ng=!0)})}function pV(){Vg=!0,vE(),yE(),Vg=!1}class p1{constructor(e,t,i,n,r,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=i,this.motionValue=n,this.element=r,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(ia.add(this),jg||(jg=!0,$e.read(vE),$e.resolveKeyframes(yE))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:t,element:i,motionValue:n}=this;if(e[0]===null){const r=n?.get(),a=e[e.length-1];if(r!==void 0)e[0]=r;else if(i&&t){const o=i.readValue(t,a);o!=null&&(e[0]=o)}e[0]===void 0&&(e[0]=a),n&&r===void 0&&n.set(e[0])}aV(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ia.delete(this)}cancel(){this.state==="scheduled"&&(ia.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const mV=s=>s.startsWith("--");function gV(s,e,t){mV(e)?s.style.setProperty(e,t):s.style[e]=t}const yV=i1(()=>window.ScrollTimeline!==void 0),vV={};function bV(s,e){const t=i1(s);return()=>vV[e]??t()}const bE=bV(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Vc=([s,e,t,i])=>`cubic-bezier(${s}, ${e}, ${t}, ${i})`,Zw={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Vc([0,.65,.55,1]),circOut:Vc([.55,0,1,.45]),backIn:Vc([.31,.01,.66,-.59]),backOut:Vc([.33,1.53,.69,.99])};function xE(s,e){if(s)return typeof s=="function"?bE()?pE(s,e):"ease-out":sE(s)?Vc(s):Array.isArray(s)?s.map(t=>xE(t,e)||Zw.easeOut):Zw[s]}function xV(s,e,t,{delay:i=0,duration:n=300,repeat:r=0,repeatType:a="loop",ease:o="easeOut",times:c}={},l=void 0){const u={[e]:t};c&&(u.offset=c);const d=xE(o,n);Array.isArray(d)&&(u.easing=d);const h={delay:i,duration:n,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:r+1,direction:a==="reverse"?"alternate":"normal"};return l&&(h.pseudoElement=l),s.animate(u,h)}function wE(s){return typeof s=="function"&&"applyToOptions"in s}function wV({type:s,...e}){return wE(s)&&bE()?s.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class _V extends h1{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:t,name:i,keyframes:n,pseudoElement:r,allowFlatten:a=!1,finalKeyframe:o,onComplete:c}=e;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=e,t1(typeof e.type!="string");const l=wV(e);this.animation=xV(t,i,n,l,r),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=d1(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(u):gV(t,i,u),this.animation.cancel()}c?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return cs(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+cs(e)}get time(){return cs(Number(this.animation.currentTime)||0)}set time(e){this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Tn(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,observe:t}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&yV()?(this.animation.timeline=e,gs):t(this)}}const _E={anticipate:Z3,backInOut:J3,circInOut:tE};function TV(s){return s in _E}function kV(s){typeof s.ease=="string"&&TV(s.ease)&&(s.ease=_E[s.ease])}const pp=10;class AV extends _V{constructor(e){kV(e),gE(e),super(e),e.startTime!==void 0&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:t,onUpdate:i,onComplete:n,element:r,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}const o=new f1({...a,autoplay:!1}),c=Math.max(pp,ui.now()-this.startTime),l=Qs(0,pp,c-pp);t.setWithVelocity(o.sample(Math.max(0,c-l)).value,o.sample(c).value,l),o.stop()}}const e2=(s,e)=>e==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(fr.test(s)||s==="0")&&!s.startsWith("url("));function SV(s){const e=s[0];if(s.length===1)return!0;for(let t=0;tObject.hasOwnProperty.call(Element.prototype,"animate"));function IV(s){const{motionValue:e,name:t,repeatDelay:i,repeatType:n,damping:r,type:a}=s;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=e.owner.getProps();return MV()&&t&&EV.has(t)&&(t!=="transform"||!l)&&!c&&!i&&n!=="mirror"&&r!==0&&a!=="inertia"}const PV=40;class RV extends h1{constructor({autoplay:e=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:a="loop",keyframes:o,name:c,motionValue:l,element:u,...d}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ui.now();const h={autoplay:e,delay:t,type:i,repeat:n,repeatDelay:r,repeatType:a,name:c,motionValue:l,element:u,...d},f=u?.KeyframeResolver||p1;this.keyframeResolver=new f(o,(p,m,g)=>this.onKeyframesResolved(p,m,h,!g),c,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,i,n){this.keyframeResolver=void 0;const{name:r,type:a,velocity:o,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=ui.now(),CV(e,r,a,o)||((Mn.instantAnimations||!c)&&u?.(d1(e,i,t)),e[0]=e[e.length-1],Ug(i),i.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>PV?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:t,...i,keyframes:e},f=!l&&IV(h),p=h.motionValue?.owner?.current,m=f?new AV({...h,element:p}):new f1(h);m.finished.then(()=>{this.notifyFinished()}).catch(gs),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),pV()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}function TE(s,e,t,i=0,n=1){const r=Array.from(s).sort((l,u)=>l.sortNodePosition(u)).indexOf(e),a=s.size,o=(a-1)*i;return typeof t=="function"?t(r,a):n===1?r*i:o-r*i}const DV=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function FV(s){const e=DV.exec(s);if(!e)return[,];const[,t,i,n]=e;return[`--${t??i}`,n]}function kE(s,e,t=1){const[i,n]=FV(s);if(!i)return;const r=window.getComputedStyle(e).getPropertyValue(i);if(r){const a=r.trim();return G3(a)?parseFloat(a):a}return a1(n)?kE(n,e,t+1):n}const LV={type:"spring",stiffness:500,damping:25,restSpeed:10},OV=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),BV={type:"keyframes",duration:.8},$V={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},jV=(s,{keyframes:e})=>e.length>2?BV:Qo.has(s)?s.startsWith("scale")?OV(e[1]):LV:$V,NV=s=>s!==null;function VV(s,{repeat:e,repeatType:t="loop"},i){const n=s.filter(NV),r=e&&t!=="loop"&&e%2===1?0:n.length-1;return n[r]}function m1(s,e){return s?.[e]??s?.default??s}function UV({when:s,delay:e,delayChildren:t,staggerChildren:i,staggerDirection:n,repeat:r,repeatType:a,repeatDelay:o,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const g1=(s,e,t,i={},n,r)=>a=>{const o=m1(i,s)||{},c=o.delay||i.delay||0;let{elapsed:l=0}=i;l=l-Tn(c);const u={keyframes:Array.isArray(t)?t:[null,t],ease:"easeOut",velocity:e.getVelocity(),...o,delay:-l,onUpdate:h=>{e.set(h),o.onUpdate&&o.onUpdate(h)},onComplete:()=>{a(),o.onComplete&&o.onComplete()},name:s,motionValue:e,element:r?void 0:n};UV(o)||Object.assign(u,jV(s,u)),u.duration&&(u.duration=Tn(u.duration)),u.repeatDelay&&(u.repeatDelay=Tn(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Ug(u),u.delay===0&&(d=!0)),(Mn.instantAnimations||Mn.skipAnimations)&&(d=!0,Ug(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,d&&!r&&e.get()!==void 0){const h=VV(u.keyframes,o);if(h!==void 0){$e.update(()=>{u.onUpdate(h),u.onComplete()});return}}return o.isSync?new f1(u):new RV(u)};function t2(s){const e=[{},{}];return s?.values.forEach((t,i)=>{e[0][i]=t.get(),e[1][i]=t.getVelocity()}),e}function y1(s,e,t,i){if(typeof e=="function"){const[n,r]=t2(i);e=e(t!==void 0?t:s.custom,n,r)}if(typeof e=="string"&&(e=s.variants&&s.variants[e]),typeof e=="function"){const[n,r]=t2(i);e=e(t!==void 0?t:s.custom,n,r)}return e}function no(s,e,t){const i=s.getProps();return y1(i,e,t!==void 0?t:i.custom,s)}const AE=new Set(["width","height","top","left","right","bottom",...Ko]),i2=30,zV=s=>!isNaN(parseFloat(s));class GV{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{const n=ui.now();if(this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const r of this.dependents)r.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=ui.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=zV(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new s1);const i=this.events[e].add(t);return e==="change"?()=>{i(),$e.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,i){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=ui.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>i2)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,i2);return H3(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function _o(s,e){return new GV(s,e)}const zg=s=>Array.isArray(s);function WV(s,e,t){s.hasValue(e)?s.getValue(e).set(t):s.addValue(e,_o(t))}function qV(s){return zg(s)?s[s.length-1]||0:s}function HV(s,e){const t=no(s,e);let{transitionEnd:i={},transition:n={},...r}=t||{};r={...r,...i};for(const a in r){const o=qV(r[a]);WV(s,a,o)}}const Zt=s=>!!(s&&s.getVelocity);function YV(s){return!!(Zt(s)&&s.add)}function Gg(s,e){const t=s.getValue("willChange");if(YV(t))return t.add(e);if(!t&&Mn.WillChange){const i=new Mn.WillChange("auto");s.addValue("willChange",i),i.add(e)}}function v1(s){return s.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const XV="framerAppearId",SE="data-"+v1(XV);function CE(s){return s.props[SE]}function KV({protectedKeys:s,needsAnimating:e},t){const i=s.hasOwnProperty(t)&&e[t]!==!0;return e[t]=!1,i}function EE(s,e,{delay:t=0,transitionOverride:i,type:n}={}){let{transition:r=s.getDefaultTransition(),transitionEnd:a,...o}=e;i&&(r=i);const c=[],l=n&&s.animationState&&s.animationState.getState()[n];for(const u in o){const d=s.getValue(u,s.latestValues[u]??null),h=o[u];if(h===void 0||l&&KV(l,u))continue;const f={delay:t,...m1(r||{},u)},p=d.get();if(p!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===p&&!f.velocity)continue;let m=!1;if(window.MotionHandoffAnimation){const v=CE(s);if(v){const w=window.MotionHandoffAnimation(v,u,$e);w!==null&&(f.startTime=w,m=!0)}}Gg(s,u),d.start(g1(u,d,h,s.shouldReduceMotion&&AE.has(u)?{type:!1}:f,s,m));const g=d.animation;g&&c.push(g)}return a&&Promise.all(c).then(()=>{$e.update(()=>{a&&HV(s,a)})}),c}function Wg(s,e,t={}){const i=no(s,e,t.type==="exit"?s.presenceContext?.custom:void 0);let{transition:n=s.getDefaultTransition()||{}}=i||{};t.transitionOverride&&(n=t.transitionOverride);const r=i?()=>Promise.all(EE(s,i,t)):()=>Promise.resolve(),a=s.variantChildren&&s.variantChildren.size?(c=0)=>{const{delayChildren:l=0,staggerChildren:u,staggerDirection:d}=n;return QV(s,e,c,l,u,d,t)}:()=>Promise.resolve(),{when:o}=n;if(o){const[c,l]=o==="beforeChildren"?[r,a]:[a,r];return c().then(()=>l())}else return Promise.all([r(),a(t.delay)])}function QV(s,e,t=0,i=0,n=0,r=1,a){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",e),o.push(Wg(c,e,{...a,delay:t+(typeof i=="function"?0:i)+TE(s.variantChildren,c,i,n,r)}).then(()=>c.notify("AnimationComplete",e)));return Promise.all(o)}function JV(s,e,t={}){s.notify("AnimationStart",e);let i;if(Array.isArray(e)){const n=e.map(r=>Wg(s,r,t));i=Promise.all(n)}else if(typeof e=="string")i=Wg(s,e,t);else{const n=typeof e=="function"?no(s,e,t.custom):e;i=Promise.all(EE(s,n,t))}return i.then(()=>{s.notify("AnimationComplete",e)})}const ZV={test:s=>s==="auto",parse:s=>s},ME=s=>e=>e.test(s),IE=[Xo,ee,Xs,Hn,SN,AN,ZV],s2=s=>IE.find(ME(s));function e9(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||q3(s):!0}const t9=new Set(["brightness","contrast","saturate","opacity"]);function i9(s){const[e,t]=s.slice(0,-1).split("(");if(e==="drop-shadow")return s;const[i]=t.match(o1)||[];if(!i)return s;const n=t.replace(i,"");let r=t9.has(e)?1:0;return i!==t&&(r*=100),e+"("+r+n+")"}const s9=/\b([a-z-]*)\(.*?\)/gu,qg={...fr,getAnimatableNone:s=>{const e=s.match(s9);return e?e.map(i9).join(" "):s}},n2={...Xo,transform:Math.round},n9={rotate:Hn,rotateX:Hn,rotateY:Hn,rotateZ:Hn,scale:Du,scaleX:Du,scaleY:Du,scaleZ:Du,skew:Hn,skewX:Hn,skewY:Hn,distance:ee,translateX:ee,translateY:ee,translateZ:ee,x:ee,y:ee,z:ee,perspective:ee,transformPerspective:ee,opacity:Il,originX:Gw,originY:Gw,originZ:ee},b1={borderWidth:ee,borderTopWidth:ee,borderRightWidth:ee,borderBottomWidth:ee,borderLeftWidth:ee,borderRadius:ee,borderTopLeftRadius:ee,borderTopRightRadius:ee,borderBottomRightRadius:ee,borderBottomLeftRadius:ee,width:ee,maxWidth:ee,height:ee,maxHeight:ee,top:ee,right:ee,bottom:ee,left:ee,inset:ee,insetBlock:ee,insetBlockStart:ee,insetBlockEnd:ee,insetInline:ee,insetInlineStart:ee,insetInlineEnd:ee,padding:ee,paddingTop:ee,paddingRight:ee,paddingBottom:ee,paddingLeft:ee,paddingBlock:ee,paddingBlockStart:ee,paddingBlockEnd:ee,paddingInline:ee,paddingInlineStart:ee,paddingInlineEnd:ee,margin:ee,marginTop:ee,marginRight:ee,marginBottom:ee,marginLeft:ee,marginBlock:ee,marginBlockStart:ee,marginBlockEnd:ee,marginInline:ee,marginInlineStart:ee,marginInlineEnd:ee,fontSize:ee,backgroundPositionX:ee,backgroundPositionY:ee,...n9,zIndex:n2,fillOpacity:Il,strokeOpacity:Il,numOctaves:n2},r9={...b1,color:bt,backgroundColor:bt,outlineColor:bt,fill:bt,stroke:bt,borderColor:bt,borderTopColor:bt,borderRightColor:bt,borderBottomColor:bt,borderLeftColor:bt,filter:qg,WebkitFilter:qg},PE=s=>r9[s];function RE(s,e){let t=PE(s);return t!==qg&&(t=fr),t.getAnimatableNone?t.getAnimatableNone(e):void 0}const a9=new Set(["auto","none","0"]);function o9(s,e,t){let i=0,n;for(;i{e.getValue(o).set(c)}),this.resolveNoneKeyframes()}}function l9(s,e,t){if(s==null)return[];if(s instanceof EventTarget)return[s];if(typeof s=="string"){let i=document;const n=t?.[s]??i.querySelectorAll(s);return n?Array.from(n):[]}return Array.from(s).filter(i=>i!=null)}const DE=(s,e)=>e&&typeof s=="number"?e.transform(s):s;function Hg(s){return W3(s)&&"offsetHeight"in s}const{schedule:x1}=nE(queueMicrotask,!1),ks={x:!1,y:!1};function FE(){return ks.x||ks.y}function u9(s){return s==="x"||s==="y"?ks[s]?null:(ks[s]=!0,()=>{ks[s]=!1}):ks.x||ks.y?null:(ks.x=ks.y=!0,()=>{ks.x=ks.y=!1})}function LE(s,e){const t=l9(s),i=new AbortController,n={passive:!0,...e,signal:i.signal};return[t,n,()=>i.abort()]}function r2(s){return!(s.pointerType==="touch"||FE())}function d9(s,e,t={}){const[i,n,r]=LE(s,t),a=o=>{if(!r2(o))return;const{target:c}=o,l=e(c,o);if(typeof l!="function"||!c)return;const u=d=>{r2(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,n)};return i.forEach(o=>{o.addEventListener("pointerenter",a,n)}),r}const OE=(s,e)=>e?s===e?!0:OE(s,e.parentElement):!1,w1=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,h9=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function BE(s){return h9.has(s.tagName)||s.isContentEditable===!0}const gd=new WeakSet;function a2(s){return e=>{e.key==="Enter"&&s(e)}}function mp(s,e){s.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const f9=(s,e)=>{const t=s.currentTarget;if(!t)return;const i=a2(()=>{if(gd.has(t))return;mp(t,"down");const n=a2(()=>{mp(t,"up")}),r=()=>mp(t,"cancel");t.addEventListener("keyup",n,e),t.addEventListener("blur",r,e)});t.addEventListener("keydown",i,e),t.addEventListener("blur",()=>t.removeEventListener("keydown",i),e)};function o2(s){return w1(s)&&!FE()}function p9(s,e,t={}){const[i,n,r]=LE(s,t),a=o=>{const c=o.currentTarget;if(!o2(o))return;gd.add(c);const l=e(c,o),u=(f,p)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),gd.has(c)&&gd.delete(c),o2(f)&&typeof l=="function"&&l(f,{success:p})},d=f=>{u(f,c===window||c===document||t.useGlobalTarget||OE(c,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,n),window.addEventListener("pointercancel",h,n)};return i.forEach(o=>{(t.useGlobalTarget?window:o).addEventListener("pointerdown",a,n),Hg(o)&&(o.addEventListener("focus",l=>f9(l,n)),!BE(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),r}function $E(s){return W3(s)&&"ownerSVGElement"in s}function m9(s){return $E(s)&&s.tagName==="svg"}const g9=[...IE,bt,fr],y9=s=>g9.find(ME(s)),c2=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ya=()=>({x:c2(),y:c2()}),l2=()=>({min:0,max:0}),St=()=>({x:l2(),y:l2()}),Yg={current:null},jE={current:!1},v9=typeof window<"u";function b9(){if(jE.current=!0,!!v9)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),e=()=>Yg.current=s.matches;s.addEventListener("change",e),e()}else Yg.current=!1}const x9=new WeakMap;function $h(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function Rl(s){return typeof s=="string"||Array.isArray(s)}const _1=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],T1=["initial",..._1];function jh(s){return $h(s.animate)||T1.some(e=>Rl(s[e]))}function NE(s){return!!(jh(s)||s.variants)}function w9(s,e,t){for(const i in e){const n=e[i],r=t[i];if(Zt(n))s.addValue(i,n);else if(Zt(r))s.addValue(i,_o(n,{owner:s}));else if(r!==n)if(s.hasValue(i)){const a=s.getValue(i);a.liveStyle===!0?a.jump(n):a.hasAnimated||a.set(n)}else{const a=s.getStaticValue(i);s.addValue(i,_o(a!==void 0?a:n,{owner:s}))}}for(const i in t)e[i]===void 0&&s.removeValue(i);return e}const u2=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let eh={};function VE(s){eh=s}function _9(){return eh}class T9{scrapeMotionValuesFromProps(e,t,i){return{}}constructor({parent:e,props:t,presenceContext:i,reducedMotionConfig:n,blockInitialAnimation:r,visualState:a},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=p1,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=ui.now();this.renderScheduledAtthis.bindToMotionValue(i,t)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(jE.current||b9(),this.shouldReduceMotion=Yg.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),hr(this.notifyUpdate),hr(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=Qo.has(e);i&&this.onBindTransform&&this.onBindTransform();const n=t.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&$e.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let r;typeof window<"u"&&window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{n(),r&&r(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in eh){const t=eh[e];if(!t)continue;const{isEnabled:i,Feature:n}=t;if(!this.features[e]&&n&&i(this.props)&&(this.features[e]=new n(this)),this.features[e]){const r=this.features[e];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):St()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let i=0;it.variantChildren.delete(e)}addValue(e,t){const i=this.values.get(e);t!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);const t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&t!==void 0&&(i=_o(t===null?void 0:t,{owner:this}),this.addValue(e,i)),i}readValue(e,t){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(G3(i)||q3(i))?i=parseFloat(i):!y9(i)&&fr.test(t)&&(i=RE(e,t)),this.setBaseTarget(e,Zt(i)?i.get():i)),Zt(i)?i.get():i}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){const{initial:t}=this.props;let i;if(typeof t=="string"||typeof t=="object"){const r=y1(this.props,t,this.presenceContext?.custom);r&&(i=r[e])}if(t&&i!==void 0)return i;const n=this.getBaseTargetFromProps(this.props,e);return n!==void 0&&!Zt(n)?n:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new s1),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){x1.render(this.render)}}class UE extends T9{constructor(){super(...arguments),this.KeyframeResolver=c9}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){const i=e.style;return i?i[t]:void 0}removeValueFromRenderState(e,{vars:t,style:i}){delete t[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Zt(e)&&(this.childSubscription=e.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}class xr{constructor(e){this.isMounted=!1,this.node=e}update(){}}function zE({top:s,left:e,right:t,bottom:i}){return{x:{min:e,max:t},y:{min:s,max:i}}}function k9({x:s,y:e}){return{top:e.min,right:s.max,bottom:e.max,left:s.min}}function A9(s,e){if(!e)return s;const t=e({x:s.left,y:s.top}),i=e({x:s.right,y:s.bottom});return{top:t.y,left:t.x,bottom:i.y,right:i.x}}function gp(s){return s===void 0||s===1}function Xg({scale:s,scaleX:e,scaleY:t}){return!gp(s)||!gp(e)||!gp(t)}function Nr(s){return Xg(s)||GE(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function GE(s){return d2(s.x)||d2(s.y)}function d2(s){return s&&s!=="0%"}function th(s,e,t){const i=s-t,n=e*i;return t+n}function h2(s,e,t,i,n){return n!==void 0&&(s=th(s,n,i)),th(s,t,i)+e}function Kg(s,e=0,t=1,i,n){s.min=h2(s.min,e,t,i,n),s.max=h2(s.max,e,t,i,n)}function WE(s,{x:e,y:t}){Kg(s.x,e.translate,e.scale,e.originPoint),Kg(s.y,t.translate,t.scale,t.originPoint)}const f2=.999999999999,p2=1.0000000000001;function S9(s,e,t,i=!1){const n=t.length;if(!n)return;e.x=e.y=1;let r,a;for(let o=0;of2&&(e.x=1),e.yf2&&(e.y=1)}function Xa(s,e){s.min=s.min+e,s.max=s.max+e}function m2(s,e,t,i,n=.5){const r=Je(s.min,s.max,n);Kg(s,e,t,r,i)}function Ka(s,e){m2(s.x,e.x,e.scaleX,e.scale,e.originX),m2(s.y,e.y,e.scaleY,e.scale,e.originY)}function qE(s,e){return zE(A9(s.getBoundingClientRect(),e))}function C9(s,e,t){const i=qE(s,t),{scroll:n}=e;return n&&(Xa(i.x,n.offset.x),Xa(i.y,n.offset.y)),i}const E9={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},M9=Ko.length;function I9(s,e,t){let i="",n=!0;for(let r=0;r{if(!e.target)return s;if(typeof s=="string")if(ee.test(s))s=parseFloat(s);else return s;const t=g2(s,e.target.x),i=g2(s,e.target.y);return`${t}% ${i}%`}},P9={correct:(s,{treeScale:e,projectionDelta:t})=>{const i=s,n=fr.parse(s);if(n.length>5)return i;const r=fr.createTransformer(s),a=typeof n[0]!="number"?1:0,o=t.x.scale*e.x,c=t.y.scale*e.y;n[0+a]/=o,n[1+a]/=c;const l=Je(o,c,.5);return typeof n[2+a]=="number"&&(n[2+a]/=l),typeof n[3+a]=="number"&&(n[3+a]/=l),r(n)}},Qg={borderRadius:{..._c,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:_c,borderTopRightRadius:_c,borderBottomLeftRadius:_c,borderBottomRightRadius:_c,boxShadow:P9};function YE(s,{layout:e,layoutId:t}){return Qo.has(s)||s.startsWith("origin")||(e||t!==void 0)&&(!!Qg[s]||s==="opacity")}function A1(s,e,t){const i=s.style,n=e?.style,r={};if(!i)return r;for(const a in i)(Zt(i[a])||n&&Zt(n[a])||YE(a,s)||t?.getValue(a)?.liveStyle!==void 0)&&(r[a]=i[a]);return r}function R9(s){return window.getComputedStyle(s)}class D9 extends UE{constructor(){super(...arguments),this.type="html",this.renderInstance=HE}readValueFromInstance(e,t){if(Qo.has(t))return this.projection?.isProjecting?Bg(t):lV(e,t);{const i=R9(e),n=(aE(t)?i.getPropertyValue(t):i[t])||0;return typeof n=="string"?n.trim():n}}measureInstanceViewportBox(e,{transformPagePoint:t}){return qE(e,t)}build(e,t,i){k1(e,t,i.transformTemplate)}scrapeMotionValuesFromProps(e,t,i){return A1(e,t,i)}}const F9={offset:"stroke-dashoffset",array:"stroke-dasharray"},L9={offset:"strokeDashoffset",array:"strokeDasharray"};function O9(s,e,t=1,i=0,n=!0){s.pathLength=1;const r=n?F9:L9;s[r.offset]=`${-i}`,s[r.array]=`${e} ${t}`}const B9=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function XE(s,{attrX:e,attrY:t,attrScale:i,pathLength:n,pathSpacing:r=1,pathOffset:a=0,...o},c,l,u){if(k1(s,o,l),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:d,style:h}=s;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=u?.transformBox??"fill-box",delete d.transformBox);for(const f of B9)d[f]!==void 0&&(h[f]=d[f],delete d[f]);e!==void 0&&(d.x=e),t!==void 0&&(d.y=t),i!==void 0&&(d.scale=i),n!==void 0&&O9(d,n,r,a,!1)}const KE=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),QE=s=>typeof s=="string"&&s.toLowerCase()==="svg";function $9(s,e,t,i){HE(s,e,void 0,i);for(const n in e.attrs)s.setAttribute(KE.has(n)?n:v1(n),e.attrs[n])}function JE(s,e,t){const i=A1(s,e,t);for(const n in s)if(Zt(s[n])||Zt(e[n])){const r=Ko.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;i[r]=s[n]}return i}class j9 extends UE{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=St}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Qo.has(t)){const i=PE(t);return i&&i.default||0}return t=KE.has(t)?t:v1(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,i){return JE(e,t,i)}build(e,t,i){XE(e,t,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,t,i,n){$9(e,t,i,n)}mount(e){this.isSVGTag=QE(e.tagName),super.mount(e)}}const N9=T1.length;function ZE(s){if(!s)return;if(!s.isControllingVariants){const t=s.parent?ZE(s.parent)||{}:{};return s.props.initial!==void 0&&(t.initial=s.props.initial),t}const e={};for(let t=0;tPromise.all(e.map(({animation:t,options:i})=>JV(s,t,i)))}function G9(s){let e=z9(s),t=y2(),i=!0;const n=c=>(l,u)=>{const d=no(s,u,c==="exit"?s.presenceContext?.custom:void 0);if(d){const{transition:h,transitionEnd:f,...p}=d;l={...l,...p,...f}}return l};function r(c){e=c(s)}function a(c){const{props:l}=s,u=ZE(s.parent)||{},d=[],h=new Set;let f={},p=1/0;for(let g=0;gp&&k,D=!1;const B=Array.isArray(b)?b:[b];let $=B.reduce(n(v),{});A===!1&&($={});const{prevResolvedValues:V={}}=w,y={...V,...$},_=C=>{I=!0,h.has(C)&&(D=!0,h.delete(C)),w.needsAnimating[C]=!0;const E=s.getValue(C);E&&(E.liveStyle=!1)};for(const C in y){const E=$[C],P=V[C];if(f.hasOwnProperty(C))continue;let L=!1;zg(E)&&zg(P)?L=!eM(E,P):L=E!==P,L?E!=null?_(C):h.add(C):E!==void 0&&h.has(C)?_(C):w.protectedKeys[C]=!0}w.prevProp=b,w.prevResolvedValues=$,w.isActive&&(f={...f,...$}),i&&s.blockInitialAnimation&&(I=!1);const T=M&&R;I&&(!T||D)&&d.push(...B.map(C=>{const E={type:v};if(typeof C=="string"&&i&&!T&&s.manuallyAnimateOnMount&&s.parent){const{parent:P}=s,L=no(P,C);if(P.enteringChildren&&L){const{delayChildren:O}=L.transition||{};E.delay=TE(P.enteringChildren,s,O)}}return{animation:C,options:E}}))}if(h.size){const g={};if(typeof l.initial!="boolean"){const v=no(s,Array.isArray(l.initial)?l.initial[0]:l.initial);v&&v.transition&&(g.transition=v.transition)}h.forEach(v=>{const w=s.getBaseTarget(v),b=s.getValue(v);b&&(b.liveStyle=!0),g[v]=w??null}),d.push({animation:g})}let m=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!s.manuallyAnimateOnMount&&(m=!1),i=!1,m?e(d):Promise.resolve()}function o(c,l){if(t[c].isActive===l)return Promise.resolve();s.variantChildren?.forEach(d=>d.animationState?.setActive(c,l)),t[c].isActive=l;const u=a(c);for(const d in t)t[d].protectedKeys={};return u}return{animateChanges:a,setActive:o,setAnimateFunction:r,getState:()=>t,reset:()=>{t=y2()}}}function W9(s,e){return typeof e=="string"?e!==s:Array.isArray(e)?!eM(e,s):!1}function Rr(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function y2(){return{animate:Rr(!0),whileInView:Rr(),whileHover:Rr(),whileTap:Rr(),whileDrag:Rr(),whileFocus:Rr(),exit:Rr()}}function v2(s,e){s.min=e.min,s.max=e.max}function _s(s,e){v2(s.x,e.x),v2(s.y,e.y)}function b2(s,e){s.translate=e.translate,s.scale=e.scale,s.originPoint=e.originPoint,s.origin=e.origin}const tM=1e-4,q9=1-tM,H9=1+tM,iM=.01,Y9=0-iM,X9=0+iM;function di(s){return s.max-s.min}function K9(s,e,t){return Math.abs(s-e)<=t}function x2(s,e,t,i=.5){s.origin=i,s.originPoint=Je(e.min,e.max,s.origin),s.scale=di(t)/di(e),s.translate=Je(t.min,t.max,s.origin)-s.originPoint,(s.scale>=q9&&s.scale<=H9||isNaN(s.scale))&&(s.scale=1),(s.translate>=Y9&&s.translate<=X9||isNaN(s.translate))&&(s.translate=0)}function rl(s,e,t,i){x2(s.x,e.x,t.x,i?i.originX:void 0),x2(s.y,e.y,t.y,i?i.originY:void 0)}function w2(s,e,t){s.min=t.min+e.min,s.max=s.min+di(e)}function Q9(s,e,t){w2(s.x,e.x,t.x),w2(s.y,e.y,t.y)}function _2(s,e,t){s.min=e.min-t.min,s.max=s.min+di(e)}function ih(s,e,t){_2(s.x,e.x,t.x),_2(s.y,e.y,t.y)}function T2(s,e,t,i,n){return s-=e,s=th(s,1/t,i),n!==void 0&&(s=th(s,1/n,i)),s}function J9(s,e=0,t=1,i=.5,n,r=s,a=s){if(Xs.test(e)&&(e=parseFloat(e),e=Je(a.min,a.max,e/100)-a.min),typeof e!="number")return;let o=Je(r.min,r.max,i);s===r&&(o-=e),s.min=T2(s.min,e,t,o,n),s.max=T2(s.max,e,t,o,n)}function k2(s,e,[t,i,n],r,a){J9(s,e[t],e[i],e[n],e.scale,r,a)}const Z9=["x","scaleX","originX"],eU=["y","scaleY","originY"];function A2(s,e,t,i){k2(s.x,e,Z9,t?t.x:void 0,i?i.x:void 0),k2(s.y,e,eU,t?t.y:void 0,i?i.y:void 0)}function S2(s){return s.translate===0&&s.scale===1}function sM(s){return S2(s.x)&&S2(s.y)}function C2(s,e){return s.min===e.min&&s.max===e.max}function tU(s,e){return C2(s.x,e.x)&&C2(s.y,e.y)}function E2(s,e){return Math.round(s.min)===Math.round(e.min)&&Math.round(s.max)===Math.round(e.max)}function nM(s,e){return E2(s.x,e.x)&&E2(s.y,e.y)}function M2(s){return di(s.x)/di(s.y)}function I2(s,e){return s.translate===e.translate&&s.scale===e.scale&&s.originPoint===e.originPoint}function ss(s){return[s("x"),s("y")]}function iU(s,e,t){let i="";const n=s.x.translate/e.x,r=s.y.translate/e.y,a=t?.z||0;if((n||r||a)&&(i=`translate3d(${n}px, ${r}px, ${a}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),t){const{transformPerspective:l,rotate:u,rotateX:d,rotateY:h,skewX:f,skewY:p}=t;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),h&&(i+=`rotateY(${h}deg) `),f&&(i+=`skewX(${f}deg) `),p&&(i+=`skewY(${p}deg) `)}const o=s.x.scale*e.x,c=s.y.scale*e.y;return(o!==1||c!==1)&&(i+=`scale(${o}, ${c})`),i||"none"}const rM=["TopLeft","TopRight","BottomLeft","BottomRight"],sU=rM.length,P2=s=>typeof s=="string"?parseFloat(s):s,R2=s=>typeof s=="number"||ee.test(s);function nU(s,e,t,i,n,r){n?(s.opacity=Je(0,t.opacity??1,rU(i)),s.opacityExit=Je(e.opacity??1,0,aU(i))):r&&(s.opacity=Je(e.opacity??1,t.opacity??1,i));for(let a=0;aie?1:t(Ml(s,e,i))}function oU(s,e,t){const i=Zt(s)?s:_o(s);return i.start(g1("",i,e,t)),i.animation}function Dl(s,e,t,i={passive:!0}){return s.addEventListener(e,t,i),()=>s.removeEventListener(e,t)}const cU=(s,e)=>s.depth-e.depth;class lU{constructor(){this.children=[],this.isDirty=!1}add(e){Zy(this.children,e),this.isDirty=!0}remove(e){e1(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(cU),this.isDirty=!1,this.children.forEach(e)}}function uU(s,e){const t=ui.now(),i=({timestamp:n})=>{const r=n-t;r>=e&&(hr(i),s(r-e))};return $e.setup(i,!0),()=>hr(i)}function yd(s){return Zt(s)?s.get():s}class dU{constructor(){this.members=[]}add(e){Zy(this.members,e),e.scheduleRender()}remove(e){if(e1(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(e){const t=this.members.findIndex(n=>e===n);if(t===0)return!1;let i;for(let n=t;n>=0;n--){const r=this.members[n];if(r.isPresent!==!1){i=r;break}}return i?(this.promote(i),!0):!1}promote(e,t){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender();const n=i.options.layoutDependency,r=e.options.layoutDependency;n!==void 0&&r!==void 0&&n===r||(e.resumeFrom=i,t&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0));const{crossfade:o}=e.options;o===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:t,resumingFrom:i}=e;t.onExitComplete&&t.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const vd={hasAnimatedSinceResize:!0,hasEverUpdated:!1},yp=["","X","Y","Z"],hU=1e3;let fU=0;function vp(s,e,t,i){const{latestValues:n}=e;n[s]&&(t[s]=n[s],e.setStaticValue(s,0),i&&(i[s]=0))}function oM(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:e}=s.options;if(!e)return;const t=CE(e);if(window.MotionHasOptimisedAnimation(t,"transform")){const{layout:n,layoutId:r}=s.options;window.MotionCancelOptimisedAnimation(t,"transform",$e,!(n||r))}const{parent:i}=s;i&&!i.hasCheckedOptimisedAppear&&oM(i)}function cM({attachResizeListener:s,defaultParent:e,measureScroll:t,checkIsScrollRoot:i,resetTransform:n}){return class{constructor(a={},o=e?.()){this.id=fU++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(gU),this.nodes.forEach(xU),this.nodes.forEach(wU),this.nodes.forEach(yU)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=a,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;$e.read(()=>{d=window.innerWidth}),s(a,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=uU(h,250),vd.hasAnimatedSinceResize&&(vd.hasAnimatedSinceResize=!1,this.nodes.forEach(O2)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&l&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||l.getDefaultTransition()||SU,{onLayoutAnimationStart:m,onLayoutAnimationComplete:g}=l.getProps(),v=!this.targetLayout||!nM(this.targetLayout,f),w=!d&&h;if(this.options.layoutRoot||this.resumeFrom||w||d&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const b={...m1(p,"layout"),onPlay:m,onComplete:g};(l.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b),this.setAnimationOrigin(u,w)}else d||O2(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const a=this.getStack();a&&a.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),hr(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(_U),this.animationId++)}getTransformTemplate(){const{visualElement:a}=this.options;return a&&a.getProps().transformTemplate}willUpdate(a=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&oM(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!di(this.snapshot.measuredBox.x)&&!di(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const A=k/1e3;B2(d.x,a.x,A),B2(d.y,a.y,A),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ih(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),kU(this.relativeTarget,this.relativeTargetOrigin,h,A),b&&tU(this.relativeTarget,b)&&(this.isProjectionDirty=!1),b||(b=St()),_s(b,this.relativeTarget)),m&&(this.animationValues=u,nU(u,l,this.latestValues,A,w,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(hr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=$e.update(()=>{vd.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=_o(0)),this.currentAnimation=oU(this.motionValue,[0,1e3],{...a,velocity:0,isSync:!0,onUpdate:o=>{this.mixTargetDelta(o),a.onUpdate&&a.onUpdate(o)},onStop:()=>{},onComplete:()=>{a.onComplete&&a.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const a=this.getStack();a&&a.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(hU),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const a=this.getLead();let{targetWithTransforms:o,target:c,layout:l,latestValues:u}=a;if(!(!o||!c||!l)){if(this!==a&&this.layout&&l&&lM(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||St();const d=di(this.layout.layoutBox.x);c.x.min=a.target.x.min,c.x.max=c.x.min+d;const h=di(this.layout.layoutBox.y);c.y.min=a.target.y.min,c.y.max=c.y.min+h}_s(o,c),Ka(o,u),rl(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(a,o){this.sharedNodes.has(a)||this.sharedNodes.set(a,new dU),this.sharedNodes.get(a).add(o);const l=o.options.initialPromotionConfig;o.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.shouldPreserveFollowOpacity(o):void 0})}isLead(){const a=this.getStack();return a?a.lead===this:!0}getLead(){const{layoutId:a}=this.options;return a?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:a}=this.options;return a?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:a}=this.options;if(a)return this.root.sharedNodes.get(a)}promote({needsReset:a,transition:o,preserveFollowOpacity:c}={}){const l=this.getStack();l&&l.promote(this,c),a&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const a=this.getStack();return a?a.relegate(this):!1}resetSkewAndRotation(){const{visualElement:a}=this.options;if(!a)return;let o=!1;const{latestValues:c}=a;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const l={};c.z&&vp("z",a,l,this.animationValues);for(let u=0;ua.currentAnimation?.stop()),this.root.nodes.forEach(F2),this.root.sharedNodes.clear()}}}function pU(s){s.updateLayout()}function mU(s){const e=s.resumeFrom?.snapshot||s.snapshot;if(s.isLead()&&s.layout&&e&&s.hasListeners("didUpdate")){const{layoutBox:t,measuredBox:i}=s.layout,{animationType:n}=s.options,r=e.source!==s.layout.source;n==="size"?ss(u=>{const d=r?e.measuredBox[u]:e.layoutBox[u],h=di(d);d.min=t[u].min,d.max=d.min+h}):lM(n,e.layoutBox,t)&&ss(u=>{const d=r?e.measuredBox[u]:e.layoutBox[u],h=di(t[u]);d.max=d.min+h,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[u].max=s.relativeTarget[u].min+h)});const a=Ya();rl(a,t,e.layoutBox);const o=Ya();r?rl(o,s.applyTransform(i,!0),e.measuredBox):rl(o,t,e.layoutBox);const c=!sM(a);let l=!1;if(!s.resumeFrom){const u=s.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:d,layout:h}=u;if(d&&h){const f=St();ih(f,e.layoutBox,d.layoutBox);const p=St();ih(p,t,h.layoutBox),nM(f,p)||(l=!0),u.options.layoutRoot&&(s.relativeTarget=p,s.relativeTargetOrigin=f,s.relativeParent=u)}}}s.notifyListeners("didUpdate",{layout:t,snapshot:e,delta:o,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(s.isLead()){const{onExitComplete:t}=s.options;t&&t()}s.options.transition=void 0}function gU(s){s.parent&&(s.isProjecting()||(s.isProjectionDirty=s.parent.isProjectionDirty),s.isSharedProjectionDirty||(s.isSharedProjectionDirty=!!(s.isProjectionDirty||s.parent.isProjectionDirty||s.parent.isSharedProjectionDirty)),s.isTransformDirty||(s.isTransformDirty=s.parent.isTransformDirty))}function yU(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function vU(s){s.clearSnapshot()}function F2(s){s.clearMeasurements()}function L2(s){s.isLayoutDirty=!1}function bU(s){const{visualElement:e}=s.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),s.resetTransform()}function O2(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function xU(s){s.resolveTargetDelta()}function wU(s){s.calcProjection()}function _U(s){s.resetSkewAndRotation()}function TU(s){s.removeLeadSnapshot()}function B2(s,e,t){s.translate=Je(e.translate,0,t),s.scale=Je(e.scale,1,t),s.origin=e.origin,s.originPoint=e.originPoint}function $2(s,e,t,i){s.min=Je(e.min,t.min,i),s.max=Je(e.max,t.max,i)}function kU(s,e,t,i){$2(s.x,e.x,t.x,i),$2(s.y,e.y,t.y,i)}function AU(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const SU={duration:.45,ease:[.4,0,.1,1]},j2=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),N2=j2("applewebkit/")&&!j2("chrome/")?Math.round:gs;function V2(s){s.min=N2(s.min),s.max=N2(s.max)}function CU(s){V2(s.x),V2(s.y)}function lM(s,e,t){return s==="position"||s==="preserve-aspect"&&!K9(M2(e),M2(t),.2)}function EU(s){return s!==s.root&&s.scroll?.wasRoot}const MU=cM({attachResizeListener:(s,e)=>Dl(s,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),IU=s=>!s.isLayoutDirty&&s.willUpdate(!1);function U2(){const s=new Set,e=new WeakMap,t=()=>s.forEach(IU);return{add:i=>{s.add(i),e.set(i,i.addEventListener("willUpdate",t))},remove:i=>{s.delete(i);const n=e.get(i);n&&(n(),e.delete(i)),t()},dirty:t}}const bp={current:void 0},uM=cM({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!bp.current){const s=new MU({});s.mount(window),s.setOptions({layoutScroll:!0}),bp.current=s}return bp.current},resetTransform:(s,e)=>{s.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),S1=F.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function z2(s,e){if(typeof s=="function")return s(e);s!=null&&(s.current=e)}function PU(...s){return e=>{let t=!1;const i=s.map(n=>{const r=z2(n,e);return!t&&typeof r=="function"&&(t=!0),r});if(t)return()=>{for(let n=0;n{const{width:d,height:h,top:f,left:p,right:m,bottom:g}=o.current;if(e||!a.current||!d||!h)return;const v=t==="left"?`left: ${p}`:`right: ${m}`,w=i==="bottom"?`bottom: ${g}`:`top: ${f}`;a.current.dataset.motionPopId=r;const b=document.createElement("style");c&&(b.nonce=c);const k=n??document.head;return k.appendChild(b),b.sheet&&b.sheet.insertRule(` + [data-motion-pop-id="${r}"] { + position: absolute !important; + width: ${d}px !important; + height: ${h}px !important; + ${v}px !important; + ${w}px !important; + } + `),()=>{k.contains(b)&&k.removeChild(b)}},[e]),x.jsx(DU,{isPresent:e,childRef:a,sizeRef:o,children:F.cloneElement(s,{ref:u})})}const LU=({children:s,initial:e,isPresent:t,onExitComplete:i,custom:n,presenceAffectsLayout:r,mode:a,anchorX:o,anchorY:c,root:l})=>{const u=Qy(OU),d=F.useId();let h=!0,f=F.useMemo(()=>(h=!1,{id:d,initial:e,isPresent:t,custom:n,onExitComplete:p=>{u.set(p,!0);for(const m of u.values())if(!m)return;i&&i()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[t,u,i]);return r&&h&&(f={...f}),F.useMemo(()=>{u.forEach((p,m)=>u.set(m,!1))},[t]),F.useEffect(()=>{!t&&!u.size&&i&&i()},[t]),a==="popLayout"&&(s=x.jsx(FU,{isPresent:t,anchorX:o,anchorY:c,root:l,children:s})),x.jsx(Bh.Provider,{value:f,children:s})};function OU(){return new Map}function dM(s=!0){const e=F.useContext(Bh);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:i,register:n}=e,r=F.useId();F.useEffect(()=>{if(s)return n(r)},[s]);const a=F.useCallback(()=>s&&i&&i(r),[r,i,s]);return!t&&i?[!1,a]:[!0]}const Fu=s=>s.key||"";function G2(s){const e=[];return F.Children.forEach(s,t=>{F.isValidElement(t)&&e.push(t)}),e}const hM=({children:s,custom:e,initial:t=!0,onExitComplete:i,presenceAffectsLayout:n=!0,mode:r="sync",propagate:a=!1,anchorX:o="left",anchorY:c="top",root:l})=>{const[u,d]=dM(a),h=F.useMemo(()=>G2(s),[s]),f=a&&!u?[]:h.map(Fu),p=F.useRef(!0),m=F.useRef(h),g=Qy(()=>new Map),v=F.useRef(new Set),[w,b]=F.useState(h),[k,A]=F.useState(h);Jy(()=>{p.current=!1,m.current=h;for(let I=0;I{const D=Fu(I),B=a&&!u?!1:h===k||f.includes(D),$=()=>{if(v.current.has(D))return;if(v.current.add(D),g.has(D))g.set(D,!0);else return;let V=!0;g.forEach(y=>{y||(V=!1)}),V&&(R?.(),A(m.current),a&&d?.(),i&&i())};return x.jsx(LU,{isPresent:B,initial:!p.current||t?void 0:!1,custom:e,presenceAffectsLayout:n,mode:r,root:l,onExitComplete:B?void 0:$,anchorX:o,anchorY:c,children:I},D)})})},BU=F.createContext(null);function $U(){const s=F.useRef(!1);return Jy(()=>(s.current=!0,()=>{s.current=!1}),[]),s}function jU(){const s=$U(),[e,t]=F.useState(0),i=F.useCallback(()=>{s.current&&t(e+1)},[e]);return[F.useCallback(()=>$e.postRender(i),[i]),e]}const fM=s=>s===!0,NU=s=>fM(s===!0)||s==="id",VU=({children:s,id:e,inherit:t=!0})=>{const i=F.useContext(El),n=F.useContext(BU),[r,a]=jU(),o=F.useRef(null),c=i.id||n;o.current===null&&(NU(t)&&c&&(e=e?c+"-"+e:c),o.current={id:e,group:fM(t)&&i.group||U2()});const l=F.useMemo(()=>({...o.current,forceRender:r}),[a]);return x.jsx(El.Provider,{value:l,children:s})},pM=F.createContext({strict:!1}),W2={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let q2=!1;function UU(){if(q2)return;const s={};for(const e in W2)s[e]={isEnabled:t=>W2[e].some(i=>!!t[i])};VE(s),q2=!0}function mM(){return UU(),_9()}function zU(s){const e=mM();for(const t in s)e[t]={...e[t],...s[t]};VE(e)}const GU=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function sh(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||GU.has(s)}let gM=s=>!sh(s);function WU(s){typeof s=="function"&&(gM=e=>e.startsWith("on")?!sh(e):s(e))}try{WU(require("@emotion/is-prop-valid").default)}catch{}function qU(s,e,t){const i={};for(const n in s)n==="values"&&typeof s.values=="object"||(gM(n)||t===!0&&sh(n)||!e&&!sh(n)||s.draggable&&n.startsWith("onDrag"))&&(i[n]=s[n]);return i}const Nh=F.createContext({});function HU(s,e){if(jh(s)){const{initial:t,animate:i}=s;return{initial:t===!1||Rl(t)?t:void 0,animate:Rl(i)?i:void 0}}return s.inherit!==!1?e:{}}function YU(s){const{initial:e,animate:t}=HU(s,F.useContext(Nh));return F.useMemo(()=>({initial:e,animate:t}),[H2(e),H2(t)])}function H2(s){return Array.isArray(s)?s.join(" "):s}const C1=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function yM(s,e,t){for(const i in e)!Zt(e[i])&&!YE(i,t)&&(s[i]=e[i])}function XU({transformTemplate:s},e){return F.useMemo(()=>{const t=C1();return k1(t,e,s),Object.assign({},t.vars,t.style)},[e])}function KU(s,e){const t=s.style||{},i={};return yM(i,t,s),Object.assign(i,XU(s,e)),i}function QU(s,e){const t={},i=KU(s,e);return s.drag&&s.dragListener!==!1&&(t.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(t.tabIndex=0),t.style=i,t}const vM=()=>({...C1(),attrs:{}});function JU(s,e,t,i){const n=F.useMemo(()=>{const r=vM();return XE(r,e,QE(i),s.transformTemplate,s.style),{...r.attrs,style:{...r.style}}},[e]);if(s.style){const r={};yM(r,s.style,s),n.style={...r,...n.style}}return n}const ZU=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function E1(s){return typeof s!="string"||s.includes("-")?!1:!!(ZU.indexOf(s)>-1||/[A-Z]/u.test(s))}function ez(s,e,t,{latestValues:i},n,r=!1,a){const c=(a??E1(s)?JU:QU)(e,i,n,s),l=qU(e,typeof s=="string",r),u=s!==F.Fragment?{...l,...c,ref:t}:{},{children:d}=e,h=F.useMemo(()=>Zt(d)?d.get():d,[d]);return F.createElement(s,{...u,children:h})}function tz({scrapeMotionValuesFromProps:s,createRenderState:e},t,i,n){return{latestValues:iz(t,i,n,s),renderState:e()}}function iz(s,e,t,i){const n={},r=i(s,{});for(const h in r)n[h]=yd(r[h]);let{initial:a,animate:o}=s;const c=jh(s),l=NE(s);e&&l&&!c&&s.inherit!==!1&&(a===void 0&&(a=e.initial),o===void 0&&(o=e.animate));let u=t?t.initial===!1:!1;u=u||a===!1;const d=u?o:a;if(d&&typeof d!="boolean"&&!$h(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f(e,t)=>{const i=F.useContext(Nh),n=F.useContext(Bh),r=()=>tz(s,e,i,n);return t?r():Qy(r)},sz=bM({scrapeMotionValuesFromProps:A1,createRenderState:C1}),nz=bM({scrapeMotionValuesFromProps:JE,createRenderState:vM}),rz=Symbol.for("motionComponentSymbol");function az(s,e,t){const i=F.useRef(t);F.useInsertionEffect(()=>{i.current=t});const n=F.useRef(null);return F.useCallback(r=>{r&&s.onMount?.(r),e&&(r?e.mount(r):e.unmount());const a=i.current;if(typeof a=="function")if(r){const o=a(r);typeof o=="function"&&(n.current=o)}else n.current?(n.current(),n.current=null):a(r);else a&&(a.current=r)},[e])}const xM=F.createContext({});function Uc(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function oz(s,e,t,i,n,r){const{visualElement:a}=F.useContext(Nh),o=F.useContext(pM),c=F.useContext(Bh),l=F.useContext(S1).reducedMotion,u=F.useRef(null),d=F.useRef(!1);i=i||o.renderer,!u.current&&i&&(u.current=i(s,{visualState:e,parent:a,props:t,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:l,isSVG:r}),d.current&&u.current&&(u.current.manuallyAnimateOnMount=!0));const h=u.current,f=F.useContext(xM);h&&!h.projection&&n&&(h.type==="html"||h.type==="svg")&&cz(u.current,t,n,f);const p=F.useRef(!1);F.useInsertionEffect(()=>{h&&p.current&&h.update(t,c)});const m=t[SE],g=F.useRef(!!m&&!window.MotionHandoffIsComplete?.(m)&&window.MotionHasOptimisedAnimation?.(m));return Jy(()=>{d.current=!0,h&&(p.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),g.current&&h.animationState&&h.animationState.animateChanges())}),F.useEffect(()=>{h&&(!g.current&&h.animationState&&h.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(m)}),g.current=!1),h.enteringChildren=void 0)}),h}function cz(s,e,t,i){const{layoutId:n,layout:r,drag:a,dragConstraints:o,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=e;s.projection=new t(s.latestValues,e["data-framer-portal-id"]?void 0:wM(s.parent)),s.projection.setOptions({layoutId:n,layout:r,alwaysMeasureLayout:!!a||o&&Uc(o),visualElement:s,animationType:typeof r=="string"?r:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function wM(s){if(s)return s.options.allowProjection!==!1?s.projection:wM(s.parent)}function xp(s,{forwardMotionProps:e=!1,type:t}={},i,n){i&&zU(i);const r=t?t==="svg":E1(s),a=r?nz:sz;function o(l,u){let d;const h={...F.useContext(S1),...l,layoutId:lz(l)},{isStatic:f}=h,p=YU(l),m=a(l,f);if(!f&&z3){uz();const g=dz(h);d=g.MeasureLayout,p.visualElement=oz(s,m,h,n,g.ProjectionNode,r)}return x.jsxs(Nh.Provider,{value:p,children:[d&&p.visualElement?x.jsx(d,{visualElement:p.visualElement,...h}):null,ez(s,l,az(m,p.visualElement,u),m,f,e,r)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=F.forwardRef(o);return c[rz]=s,c}function lz({layoutId:s}){const e=F.useContext(El).id;return e&&s!==void 0?e+"-"+s:s}function uz(s,e){F.useContext(pM).strict}function dz(s){const e=mM(),{drag:t,layout:i}=e;if(!t&&!i)return{};const n={...t,...i};return{MeasureLayout:t?.isEnabled(s)||i?.isEnabled(s)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}function hz(s,e){if(typeof Proxy>"u")return xp;const t=new Map,i=(r,a)=>xp(r,a,s,e),n=(r,a)=>i(r,a);return new Proxy(n,{get:(r,a)=>a==="create"?i:(t.has(a)||t.set(a,xp(a,void 0,s,e)),t.get(a))})}const fz=(s,e)=>e.isSVG??E1(s)?new j9(e):new D9(e,{allowProjection:s!==F.Fragment});class pz extends xr{constructor(e){super(e),e.animationState||(e.animationState=G9(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();$h(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let mz=0;class gz extends xr{constructor(){super(...arguments),this.id=mz++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const n=this.node.animationState.setActive("exit",!e);t&&!e&&n.then(()=>{t(this.id)})}mount(){const{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const yz={animation:{Feature:pz},exit:{Feature:gz}};function ou(s){return{point:{x:s.pageX,y:s.pageY}}}const vz=s=>e=>w1(e)&&s(e,ou(e));function al(s,e,t,i){return Dl(s,e,vz(t),i)}const _M=({current:s})=>s?s.ownerDocument.defaultView:null,Y2=(s,e)=>Math.abs(s-e);function bz(s,e){const t=Y2(s.x,e.x),i=Y2(s.y,e.y);return Math.sqrt(t**2+i**2)}const X2=new Set(["auto","scroll"]);class TM{constructor(e,t,{transformPagePoint:i,contextWindow:n=window,dragSnapToOrigin:r=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=_p(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,m=bz(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!m)return;const{point:g}=f,{timestamp:v}=Ut;this.history.push({...g,timestamp:v});const{onStart:w,onMove:b}=this.handlers;p||(w&&w(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),b&&b(this.lastMoveEvent,f)},this.handlePointerMove=(f,p)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=wp(p,this.transformPagePoint),$e.update(this.updatePoint,!0)},this.handlePointerUp=(f,p)=>{this.end();const{onEnd:m,onSessionEnd:g,resumeAnimation:v}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=_p(f.type==="pointercancel"?this.lastMoveEventInfo:wp(p,this.transformPagePoint),this.history);this.startEvent&&m&&m(f,w),g&&g(f,w)},!w1(e))return;this.dragSnapToOrigin=r,this.handlers=t,this.transformPagePoint=i,this.distanceThreshold=a,this.contextWindow=n||window;const c=ou(e),l=wp(c,this.transformPagePoint),{point:u}=l,{timestamp:d}=Ut;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=t;h&&h(e,_p(l,this.history)),this.removeListeners=nu(al(this.contextWindow,"pointermove",this.handlePointerMove),al(this.contextWindow,"pointerup",this.handlePointerUp),al(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){const i=getComputedStyle(t);(X2.has(i.overflowX)||X2.has(i.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener("scroll",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const t=this.scrollPositions.get(e);if(!t)return;const i=e===window,n=i?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},r={x:n.x-t.x,y:n.y-t.y};r.x===0&&r.y===0||(i?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=r.x,this.lastMoveEventInfo.point.y+=r.y):this.history.length>0&&(this.history[0].x-=r.x,this.history[0].y-=r.y),this.scrollPositions.set(e,n),$e.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),hr(this.updatePoint)}}function wp(s,e){return e?{point:e(s.point)}:s}function K2(s,e){return{x:s.x-e.x,y:s.y-e.y}}function _p({point:s},e){return{point:s,delta:K2(s,kM(e)),offset:K2(s,xz(e)),velocity:wz(e,.1)}}function xz(s){return s[0]}function kM(s){return s[s.length-1]}function wz(s,e){if(s.length<2)return{x:0,y:0};let t=s.length-1,i=null;const n=kM(s);for(;t>=0&&(i=s[t],!(n.timestamp-i.timestamp>Tn(e)));)t--;if(!i)return{x:0,y:0};const r=cs(n.timestamp-i.timestamp);if(r===0)return{x:0,y:0};const a={x:(n.x-i.x)/r,y:(n.y-i.y)/r};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function _z(s,{min:e,max:t},i){return e!==void 0&&st&&(s=i?Je(t,s,i.max):Math.min(s,t)),s}function Q2(s,e,t){return{min:e!==void 0?s.min+e:void 0,max:t!==void 0?s.max+t-(s.max-s.min):void 0}}function Tz(s,{top:e,left:t,bottom:i,right:n}){return{x:Q2(s.x,t,n),y:Q2(s.y,e,i)}}function J2(s,e){let t=e.min-s.min,i=e.max-s.max;return e.max-e.mini?t=Ml(e.min,e.max-i,s.min):i>n&&(t=Ml(s.min,s.max-n,e.min)),Qs(0,1,t)}function Sz(s,e){const t={};return e.min!==void 0&&(t.min=e.min-s.min),e.max!==void 0&&(t.max=e.max-s.min),t}const Jg=.35;function Cz(s=Jg){return s===!1?s=0:s===!0&&(s=Jg),{x:Z2(s,"left","right"),y:Z2(s,"top","bottom")}}function Z2(s,e,t){return{min:e_(s,e),max:e_(s,t)}}function e_(s,e){return typeof s=="number"?s:s[e]||0}const Ez=new WeakMap;class Mz{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=St(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:i}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const r=d=>{t?(this.stopAnimation(),this.snapToCursor(ou(d).point)):this.pauseAnimation()},a=(d,h)=>{this.stopAnimation();const{drag:f,dragPropagation:p,onDragStart:m}=this.getProps();if(f&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=u9(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ss(v=>{let w=this.getAxisMotionValue(v).get()||0;if(Xs.test(w)){const{projection:b}=this.visualElement;if(b&&b.layout){const k=b.layout.layoutBox[v];k&&(w=di(k)*(parseFloat(w)/100))}}this.originPoint[v]=w}),m&&$e.postRender(()=>m(d,h)),Gg(this.visualElement,"transform");const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:p,onDirectionLock:m,onDrag:g}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:v}=h;if(p&&this.currentDirection===null){this.currentDirection=Iz(v),this.currentDirection!==null&&m&&m(this.currentDirection);return}this.updateAxis("x",h.point,v),this.updateAxis("y",h.point,v),this.visualElement.render(),g&&g(d,h)},c=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>ss(d=>this.getAnimationState(d)==="paused"&&this.getAxisMotionValue(d).animation?.play()),{dragSnapToOrigin:u}=this.getProps();this.panSession=new TM(e,{onSessionStart:r,onStart:a,onMove:o,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:_M(this.visualElement),element:this.visualElement.current})}stop(e,t){const i=e||this.latestPointerEvent,n=t||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!n||!i)return;const{velocity:a}=n;this.startAnimation(a);const{onDragEnd:o}=this.getProps();o&&$e.postRender(()=>o(i,n))}cancel(){this.isDragging=!1;const{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,i){const{drag:n}=this.getProps();if(!i||!Lu(e,n,this.currentDirection))return;const r=this.getAxisMotionValue(e);let a=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(a=_z(a,this.constraints[e],this.elastic[e])),r.set(a)}resolveConstraints(){const{dragConstraints:e,dragElastic:t}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,n=this.constraints;e&&Uc(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Tz(i.layoutBox,e):this.constraints=!1,this.elastic=Cz(t),n!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ss(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Sz(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Uc(e))return!1;const i=e.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const r=C9(i,n.root,this.visualElement.getTransformPagePoint());let a=kz(n.layout.layoutBox,r);if(t){const o=t(k9(a));this.hasMutatedConstraints=!!o,o&&(a=zE(o))}return a}startAnimation(e){const{drag:t,dragMomentum:i,dragElastic:n,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},l=ss(u=>{if(!Lu(u,t,this.currentDirection))return;let d=c&&c[u]||{};a&&(d={min:0,max:0});const h=n?200:1e6,f=n?40:1e7,p={type:"inertia",velocity:i?e[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...r,...d};return this.startAxisValueAnimation(u,p)});return Promise.all(l).then(o)}startAxisValueAnimation(e,t){const i=this.getAxisMotionValue(e);return Gg(this.visualElement,e),i.start(g1(e,i,0,t,this.visualElement,!1))}stopAnimation(){ss(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ss(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const t=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),n=i[t];return n||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){ss(t=>{const{drag:i}=this.getProps();if(!Lu(t,i,this.currentDirection))return;const{projection:n}=this.visualElement,r=this.getAxisMotionValue(t);if(n&&n.layout){const{min:a,max:o}=n.layout.layoutBox[t],c=r.get()||0;r.set(e[t]-Je(a,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:t}=this.getProps(),{projection:i}=this.visualElement;if(!Uc(t)||!i||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ss(a=>{const o=this.getAxisMotionValue(a);if(o&&this.constraints!==!1){const c=o.get();n[a]=Az({min:c,max:c},this.constraints[a])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),ss(a=>{if(!Lu(a,e,null))return;const o=this.getAxisMotionValue(a),{min:c,max:l}=this.constraints[a];o.set(Je(c,l,n[a]))})}addListeners(){if(!this.visualElement.current)return;Ez.set(this.visualElement,this);const e=this.visualElement.current,t=al(e,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps(),d=c.target,h=d!==e&&BE(d);l&&u&&!h&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();Uc(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,r=n.addEventListener("measure",i);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),$e.read(i);const a=Dl(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(ss(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].translate))}),this.visualElement.render())});return()=>{a(),t(),r(),o&&o()}}getProps(){const e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:i=!1,dragPropagation:n=!1,dragConstraints:r=!1,dragElastic:a=Jg,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:r,dragElastic:a,dragMomentum:o}}}function Lu(s,e,t){return(e===!0||e===s)&&(t===null||t===s)}function Iz(s,e=10){let t=null;return Math.abs(s.y)>e?t="y":Math.abs(s.x)>e&&(t="x"),t}class Pz extends xr{constructor(e){super(e),this.removeGroupControls=gs,this.removeListeners=gs,this.controls=new Mz(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||gs}update(){const{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const t_=s=>(e,t)=>{s&&$e.postRender(()=>s(e,t))};class Rz extends xr{constructor(){super(...arguments),this.removePointerDownListener=gs}onPointerDown(e){this.session=new TM(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:_M(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:t_(e),onStart:t_(t),onMove:i,onEnd:(r,a)=>{delete this.session,n&&$e.postRender(()=>n(r,a))}}}mount(){this.removePointerDownListener=al(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let Tp=!1;class Dz extends F.Component{componentDidMount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:r}=e;r&&(t.group&&t.group.add(r),i&&i.register&&n&&i.register(r),Tp&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),vd.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:t,visualElement:i,drag:n,isPresent:r}=this.props,{projection:a}=i;return a&&(a.isPresent=r,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),Tp=!0,n||e.layoutDependency!==t||t===void 0||e.isPresent!==r?a.willUpdate():this.safeToRemove(),e.isPresent!==r&&(r?a.promote():a.relegate()||$e.postRender(()=>{const o=a.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),x1.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=e;Tp=!0,n&&(n.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(n),i&&i.deregister&&i.deregister(n))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function AM(s){const[e,t]=dM(),i=F.useContext(El);return x.jsx(Dz,{...s,layoutGroup:i,switchLayoutGroup:F.useContext(xM),isPresent:e,safeToRemove:t})}const Fz={pan:{Feature:Rz},drag:{Feature:Pz,ProjectionNode:uM,MeasureLayout:AM}};function i_(s,e,t){const{props:i}=s;s.animationState&&i.whileHover&&s.animationState.setActive("whileHover",t==="Start");const n="onHover"+t,r=i[n];r&&$e.postRender(()=>r(e,ou(e)))}class Lz extends xr{mount(){const{current:e}=this.node;e&&(this.unmount=d9(e,(t,i)=>(i_(this.node,i,"Start"),n=>i_(this.node,n,"End"))))}unmount(){}}class Oz extends xr{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=nu(Dl(this.node.current,"focus",()=>this.onFocus()),Dl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function s_(s,e,t){const{props:i}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&i.whileTap&&s.animationState.setActive("whileTap",t==="Start");const n="onTap"+(t==="End"?"":t),r=i[n];r&&$e.postRender(()=>r(e,ou(e)))}class Bz extends xr{mount(){const{current:e}=this.node;e&&(this.unmount=p9(e,(t,i)=>(s_(this.node,i,"Start"),(n,{success:r})=>s_(this.node,n,r?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Zg=new WeakMap,kp=new WeakMap,$z=s=>{const e=Zg.get(s.target);e&&e(s)},jz=s=>{s.forEach($z)};function Nz({root:s,...e}){const t=s||document;kp.has(t)||kp.set(t,{});const i=kp.get(t),n=JSON.stringify(e);return i[n]||(i[n]=new IntersectionObserver(jz,{root:s,...e})),i[n]}function Vz(s,e,t){const i=Nz(e);return Zg.set(s,t),i.observe(s),()=>{Zg.delete(s),i.unobserve(s)}}const Uz={some:0,all:1};class zz extends xr{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:t,margin:i,amount:n="some",once:r}=e,a={root:t?t.current:void 0,rootMargin:i,threshold:typeof n=="number"?n:Uz[n]},o=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,r&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=l?u:d;h&&h(c)};return Vz(this.node.current,a,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:t}=this.node;["amount","margin","root"].some(Gz(e,t))&&this.startObserver()}unmount(){}}function Gz({viewport:s={}},{viewport:e={}}={}){return t=>s[t]!==e[t]}const Wz={inView:{Feature:zz},tap:{Feature:Bz},focus:{Feature:Oz},hover:{Feature:Lz}},qz={layout:{ProjectionNode:uM,MeasureLayout:AM}},Hz={...yz,...Wz,...Fz,...qz},wa=hz(Hz,fz),SM=F.createContext({open:!1}),M1=F.forwardRef(({open:s,onOpenChange:e,defaultOpen:t=!1,children:i,...n},r)=>{const[a,o]=F.useState(t),c=s??a,l=F.useCallback(u=>{o(u),e?.(u)},[e]);return x.jsx(SM.Provider,{value:{open:c},children:x.jsx(z5,{ref:r,open:c,onOpenChange:l,...n,children:i})})});M1.displayName="Collapsible";const CM=W5,I1=F.forwardRef(({className:s,children:e,...t},i)=>{const{open:n}=F.useContext(SM);return x.jsx(hM,{initial:!1,children:n&&x.jsx(G5,{forceMount:!0,asChild:!0,...t,children:x.jsx(wa.div,{ref:i,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{height:{type:"spring",stiffness:500,damping:40},opacity:{duration:.15}},className:ie("overflow-hidden",s),children:e})})})});I1.displayName="CollapsibleContent";const hee=H5,fee=Y5,pee=X5,Yz=F.forwardRef(({className:s,inset:e,children:t,...i},n)=>x.jsxs(Uk,{ref:n,className:ie("flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",e&&"pl-8",s),...i,children:[t,x.jsx(Xd,{className:"ml-auto h-4 w-4"})]}));Yz.displayName=Uk.displayName;const Xz=F.forwardRef(({className:s,...e},t)=>x.jsx(zk,{ref:t,className:ie("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 slide-in-from-left-1 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",s),...e}));Xz.displayName=zk.displayName;const Kz=F.forwardRef(({className:s,...e},t)=>x.jsx(q5,{children:x.jsx(Gk,{ref:t,className:ie("z-50 max-h-[--radix-context-menu-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",s),...e})}));Kz.displayName=Gk.displayName;const Qz=F.forwardRef(({className:s,inset:e,...t},i)=>x.jsx(Wk,{ref:i,className:ie("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed",e&&"pl-8",s),...t}));Qz.displayName=Wk.displayName;const Jz=F.forwardRef(({className:s,children:e,checked:t,...i},n)=>x.jsxs(qk,{ref:n,className:ie("relative flex cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed",s),checked:t,...i,children:[x.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:x.jsx(hM,{children:t&&x.jsx(Hk,{forceMount:!0,asChild:!0,children:x.jsx(wa.span,{initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},transition:{type:"spring",stiffness:500,damping:30},children:x.jsx(iu,{className:"h-4 w-4"})})})})}),e]}));Jz.displayName=qk.displayName;const Zz=F.forwardRef(({className:s,children:e,...t},i)=>x.jsxs(Yk,{ref:i,className:ie("relative flex cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed",s),...t,children:[x.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:x.jsx(Hk,{asChild:!0,children:x.jsx(wa.span,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:30},children:x.jsx(x3,{className:"h-2 w-2 fill-current"})})})}),e]}));Zz.displayName=Yk.displayName;const e7=F.forwardRef(({className:s,inset:e,...t},i)=>x.jsx(Xk,{ref:i,className:ie("px-2 py-1.5 text-sm font-semibold text-foreground",e&&"pl-8",s),...t}));e7.displayName=Xk.displayName;const t7=F.forwardRef(({className:s,...e},t)=>x.jsx(Kk,{ref:t,className:ie("-mx-1 my-1 h-px bg-border",s),...e}));t7.displayName=Kk.displayName;const i7=({className:s,...e})=>x.jsx("span",{className:ie("ml-auto text-xs tracking-widest text-muted-foreground",s),...e});i7.displayName="ContextMenuShortcut";const Vh=J5,s7=K5,EM=F.forwardRef(({className:s,...e},t)=>x.jsx(Qk,{ref:t,className:ie("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e}));EM.displayName=Qk.displayName;const cu=F.forwardRef(({className:s,children:e,hideCloseButton:t=!1,...i},n)=>x.jsxs(s7,{children:[x.jsx(EM,{}),x.jsxs(Jk,{ref:n,className:ie("fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg",s),...i,children:[e,!t&&x.jsxs(Q5,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[x.jsx(Xy,{className:"h-4 w-4"}),x.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));cu.displayName=Jk.displayName;const Uh=({className:s,...e})=>x.jsx("div",{className:ie("flex flex-col space-y-1.5 text-center sm:text-left",s),...e});Uh.displayName="DialogHeader";const n7=({className:s,...e})=>x.jsx("div",{className:ie("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...e});n7.displayName="DialogFooter";const zh=F.forwardRef(({className:s,...e},t)=>x.jsx(Zk,{ref:t,className:ie("text-lg font-semibold leading-none tracking-tight",s),...e}));zh.displayName=Zk.displayName;const Gh=F.forwardRef(({className:s,...e},t)=>x.jsx(eA,{ref:t,className:ie("text-sm text-muted-foreground",s),...e}));Gh.displayName=eA.displayName;const mee=eR,gee=tR,r7=F.forwardRef(({className:s,inset:e,children:t,...i},n)=>x.jsxs(tA,{ref:n,className:ie("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",e&&"pl-8",s),...i,children:[t,x.jsx(Xd,{className:"ml-auto"})]}));r7.displayName=tA.displayName;const a7=F.forwardRef(({className:s,...e},t)=>x.jsx(iA,{ref:t,className:ie("z-[9999] min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...e}));a7.displayName=iA.displayName;const o7=F.forwardRef(({className:s,sideOffset:e=4,...t},i)=>x.jsx(Z5,{children:x.jsx(sA,{ref:i,sideOffset:e,className:ie("z-[9999] max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...t})}));o7.displayName=sA.displayName;const c7=F.forwardRef(({className:s,inset:e,...t},i)=>x.jsx(nA,{ref:i,className:ie("relative flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",e&&"pl-8",s),...t}));c7.displayName=nA.displayName;const l7=F.forwardRef(({className:s,children:e,checked:t,...i},n)=>x.jsxs(rA,{ref:n,className:ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),checked:t,...i,children:[x.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:x.jsx(aA,{children:x.jsx(iu,{className:"h-4 w-4"})})}),e]}));l7.displayName=rA.displayName;const u7=F.forwardRef(({className:s,children:e,...t},i)=>x.jsxs(oA,{ref:i,className:ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...t,children:[x.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:x.jsx(aA,{children:x.jsx(x3,{className:"h-2 w-2 fill-current"})})}),e]}));u7.displayName=oA.displayName;const d7=F.forwardRef(({className:s,inset:e,...t},i)=>x.jsx(cA,{ref:i,className:ie("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",s),...t}));d7.displayName=cA.displayName;const h7=F.forwardRef(({className:s,...e},t)=>x.jsx(lA,{ref:t,className:ie("-mx-1 my-1 h-px bg-muted",s),...e}));h7.displayName=lA.displayName;const ro=F.forwardRef(({className:s,type:e,...t},i)=>x.jsx("input",{type:e,className:ie("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:i,...t}));ro.displayName="Input";const f7=Oh("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),P1=F.forwardRef(({className:s,...e},t)=>x.jsx(uA,{ref:t,className:ie(f7(),s),...e}));P1.displayName=uA.displayName;const p7=F.forwardRef(({className:s,value:e,...t},i)=>x.jsx(dA,{ref:i,className:ie("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...t,children:x.jsx(iR,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));p7.displayName=dA.displayName;const yee=cR,vee=uR,bee=lR,m7=F.forwardRef(({className:s,children:e,...t},i)=>x.jsxs(hA,{ref:i,className:ie("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...t,children:[e,x.jsx(sR,{asChild:!0,children:x.jsx(Hy,{className:"h-4 w-4 opacity-50"})})]}));m7.displayName=hA.displayName;const MM=F.forwardRef(({className:s,...e},t)=>x.jsx(fA,{ref:t,className:ie("flex cursor-default items-center justify-center py-1",s),...e,children:x.jsx($$,{className:"h-4 w-4"})}));MM.displayName=fA.displayName;const IM=F.forwardRef(({className:s,...e},t)=>x.jsx(pA,{ref:t,className:ie("flex cursor-default items-center justify-center py-1",s),...e,children:x.jsx(Hy,{className:"h-4 w-4"})}));IM.displayName=pA.displayName;const g7=F.forwardRef(({className:s,children:e,position:t="popper",...i},n)=>x.jsx(nR,{children:x.jsx(mA,{ref:n,position:t,asChild:!0,...i,children:x.jsxs(wa.div,{initial:{opacity:0,scale:.96,y:-4},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.96,y:-4},transition:{type:"spring",stiffness:500,damping:30},className:ie("relative z-[9999] max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md origin-[--radix-select-content-transform-origin]",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),children:[x.jsx(MM,{}),x.jsx(rR,{className:ie("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),x.jsx(IM,{})]})})}));g7.displayName=mA.displayName;const y7=F.forwardRef(({className:s,...e},t)=>x.jsx(gA,{ref:t,className:ie("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));y7.displayName=gA.displayName;const v7=F.forwardRef(({className:s,children:e,...t},i)=>x.jsxs(yA,{ref:i,className:ie("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...t,children:[x.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:x.jsx(aR,{asChild:!0,children:x.jsx(wa.span,{initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:500,damping:30},children:x.jsx(iu,{className:"h-4 w-4"})})})}),x.jsx(oR,{children:e})]}));v7.displayName=yA.displayName;const b7=F.forwardRef(({className:s,...e},t)=>x.jsx(vA,{ref:t,className:ie("-mx-1 my-1 h-px bg-muted",s),...e}));b7.displayName=vA.displayName;const x7=F.forwardRef(({className:s,children:e,...t},i)=>x.jsxs(bA,{ref:i,className:ie("relative overflow-hidden",s),...t,children:[x.jsx(dR,{className:"h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!min-w-0",children:e}),x.jsx(PM,{}),x.jsx(hR,{})]}));x7.displayName=bA.displayName;const PM=F.forwardRef(({className:s,orientation:e="vertical",...t},i)=>x.jsx(xA,{ref:i,orientation:e,className:ie("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...t,children:x.jsx(fR,{className:"relative flex-1 rounded-full bg-border"})}));PM.displayName=xA.displayName;const w7=F.forwardRef(({label:s,value:e,onChange:t,min:i=0,max:n=100,step:r=1,unit:a="",defaultValue:o,className:c},l)=>{const u=r<1?e.toFixed(1):Math.round(e),[d,h]=F.useState(!1),[f,p]=F.useState(""),m=F.useRef(null),g=()=>{p(String(e)),h(!0)},v=b=>Math.min(n,Math.max(i,b)),w=()=>{const b=parseFloat(f);Number.isNaN(b)||t(v(b)),h(!1)};return x.jsxs("div",{ref:l,className:ie("space-y-1",c),children:[x.jsxs("div",{className:"flex items-center justify-between",children:[x.jsx("span",{className:"text-[10px] text-text-secondary",children:s}),d?x.jsx("input",{autoFocus:!0,type:"number",value:f,onChange:b=>p(b.target.value),onBlur:w,onKeyDown:b=>{b.key==="Enter"&&w(),b.key==="Escape"&&h(!1)},className:"w-14 text-[10px] font-mono text-text-primary bg-background-tertiary px-1 py-0.5 rounded border border-border text-right"}):x.jsxs("span",{role:"button",tabIndex:0,title:o!==void 0?"Click to edit, double-click to reset":"Click to edit",onClick:()=>{if(o===void 0){g();return}m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{g(),m.current=null},200)},onDoubleClick:()=>{o!==void 0&&(m.current&&(clearTimeout(m.current),m.current=null),t(o))},className:"text-[10px] font-mono text-text-primary bg-background-tertiary px-1.5 py-0.5 rounded border border-border cursor-text select-none",children:[u,a]})]}),x.jsx(su,{value:[e],onValueChange:b=>t(b[0]),min:i,max:n,step:r,className:"h-1.5"})]})});w7.displayName="LabeledSlider";const _7=F.forwardRef(({value:s,onChange:e,min:t=0,max:i=100,step:n=1,className:r},a)=>x.jsxs("div",{ref:a,className:ie("flex items-center gap-3",r),children:[x.jsx(su,{value:[s],onValueChange:o=>e(o[0]),min:t,max:i,step:n,className:"flex-1 h-1.5"}),x.jsx("span",{className:"text-[10px] font-mono text-text-primary w-8 text-right bg-background-tertiary px-1 py-0.5 rounded border border-border",children:Math.round(s)})]}));_7.displayName="InspectorSlider";const R1=F.forwardRef(({className:s,...e},t)=>x.jsx(wA,{className:ie("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...e,ref:t,children:x.jsx(pR,{className:ie("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));R1.displayName=wA.displayName;const RM=F.createContext({activeValue:void 0}),T7=F.forwardRef(({value:s,defaultValue:e,onValueChange:t,children:i,...n},r)=>{const[a,o]=F.useState(e),c=s??a,l=F.useCallback(u=>{o(u),t?.(u)},[t]);return x.jsx(RM.Provider,{value:{activeValue:c},children:x.jsx(mR,{ref:r,value:c,onValueChange:l,...n,children:i})})});T7.displayName="Tabs";const k7=F.forwardRef(({className:s,layoutId:e="tabs-indicator",children:t,...i},n)=>x.jsx(_A,{ref:n,className:ie("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground relative",s),...i,children:x.jsx(VU,{id:e,children:t})}));k7.displayName=_A.displayName;const A7=F.forwardRef(({className:s,value:e,children:t,...i},n)=>{const{activeValue:r}=F.useContext(RM),a=r===e;return x.jsxs(TA,{ref:n,value:e,className:ie("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 relative z-10 data-[state=active]:text-foreground",s),...i,children:[a&&x.jsx(wa.span,{layoutId:"active-tab",className:"absolute inset-0 bg-background rounded-sm shadow-sm -z-10",transition:{type:"spring",stiffness:500,damping:30}}),t]})});A7.displayName=TA.displayName;const S7=F.forwardRef(({className:s,...e},t)=>x.jsx(kA,{ref:t,asChild:!0,...e,children:x.jsx(wa.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.15},className:ie("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s)})}));S7.displayName=kA.displayName;const DM=Oh("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3 min-w-10",sm:"h-9 px-2.5 min-w-9",lg:"h-11 px-5 min-w-11"}},defaultVariants:{variant:"default",size:"default"}}),C7=F.forwardRef(({className:s,variant:e,size:t,...i},n)=>x.jsx(AA,{ref:n,className:ie(DM({variant:e,size:t,className:s})),...i}));C7.displayName=AA.displayName;const FM=F.createContext({size:"default",variant:"default"}),E7=F.forwardRef(({className:s,variant:e,size:t,children:i,...n},r)=>x.jsx(SA,{ref:r,className:ie("flex items-center justify-center gap-1",s),...n,children:x.jsx(FM.Provider,{value:{variant:e,size:t},children:i})}));E7.displayName=SA.displayName;const M7=F.forwardRef(({className:s,children:e,variant:t,size:i,...n},r)=>{const a=F.useContext(FM);return x.jsx(CA,{ref:r,className:ie(DM({variant:a.variant||t,size:a.size||i}),s),...n,children:e})});M7.displayName=CA.displayName;const I7=vR,xee=gR,wee=yR,P7=F.forwardRef(({className:s,sideOffset:e=4,...t},i)=>x.jsx(EA,{ref:i,sideOffset:e,className:ie("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",s),...t}));P7.displayName=EA.displayName;const nh={tiktok:{width:1080,height:1920,frameRate:30,maxDuration:180,recommendedDuration:15,safeZone:{top:150,bottom:300,left:40,right:40}},"instagram-reels":{width:1080,height:1920,frameRate:30,maxDuration:90,recommendedDuration:30,safeZone:{top:200,bottom:280,left:40,right:40}},"instagram-stories":{width:1080,height:1920,frameRate:30,maxDuration:15,recommendedDuration:10,safeZone:{top:200,bottom:200,left:40,right:40}},"instagram-post":{width:1080,height:1080,frameRate:30,maxDuration:60,recommendedDuration:30},"youtube-shorts":{width:1080,height:1920,frameRate:30,maxDuration:60,recommendedDuration:30,safeZone:{top:100,bottom:200,left:40,right:40}},"youtube-video":{width:1920,height:1080,frameRate:30},facebook:{width:1080,height:1080,frameRate:30,maxDuration:240,recommendedDuration:60},twitter:{width:1280,height:720,frameRate:30,maxDuration:140,recommendedDuration:45},linkedin:{width:1920,height:1080,frameRate:30,maxDuration:600,recommendedDuration:90},pinterest:{width:1e3,height:1500,frameRate:30,maxDuration:60,recommendedDuration:15},intro:{width:1920,height:1080,frameRate:30,recommendedDuration:5},outro:{width:1920,height:1080,frameRate:30,recommendedDuration:10},promo:{width:1920,height:1080,frameRate:30,recommendedDuration:30},"lower-third":{width:1920,height:1080,frameRate:30,recommendedDuration:5},slideshow:{width:1920,height:1080,frameRate:30},custom:{width:1920,height:1080,frameRate:30}},LM=[{id:"tiktok",name:"TikTok",icon:"smartphone",platform:"TikTok"},{id:"instagram-reels",name:"Reels",icon:"film",platform:"Instagram"},{id:"instagram-stories",name:"Stories",icon:"clock",platform:"Instagram"},{id:"instagram-post",name:"Post",icon:"square",platform:"Instagram"},{id:"youtube-shorts",name:"Shorts",icon:"smartphone",platform:"YouTube"},{id:"youtube-video",name:"Video",icon:"monitor",platform:"YouTube"},{id:"facebook",name:"Facebook",icon:"users",platform:"Facebook"},{id:"twitter",name:"Twitter/X",icon:"at-sign",platform:"Twitter"},{id:"linkedin",name:"LinkedIn",icon:"briefcase",platform:"LinkedIn"},{id:"pinterest",name:"Pinterest",icon:"bookmark",platform:"Pinterest"},{id:"intro",name:"Intro",icon:"play",platform:"General"},{id:"outro",name:"Outro",icon:"square",platform:"General"},{id:"promo",name:"Promo",icon:"megaphone",platform:"General"},{id:"lower-third",name:"Lower Third",icon:"type",platform:"General"},{id:"slideshow",name:"Slideshow",icon:"images",platform:"General"},{id:"custom",name:"Custom",icon:"settings",platform:"Custom"}];function R7(s){return JSON.stringify(s,null,2)}function D7(s){return JSON.parse(s)}function Ap(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}class F7{validate(e,t){const i=[];if(!e.type||typeof e.type!="string")return i.push({code:"INVALID_TYPE",message:"Action type is required and must be a string"}),{valid:!1,errors:i};if(!e.params||typeof e.params!="object")return i.push({code:"INVALID_PARAMS",message:"Action params are required and must be an object"}),{valid:!1,errors:i};const n=this.validateActionType(e,t);return i.push(...n),{valid:i.length===0,errors:i}}validateActionType(e,t){const i=e.type;return i.startsWith("project/")?this.validateProjectAction(e,t):i.startsWith("media/")?this.validateMediaAction(e,t):i.startsWith("track/")?this.validateTrackAction(e,t):i.startsWith("clip/")?this.validateClipAction(e,t):i.startsWith("effect/")?this.validateEffectAction(e,t):i.startsWith("transform/")?this.validateTransformAction(e,t):i.startsWith("keyframe/")?this.validateKeyframeAction(e,t):i.startsWith("transition/")?this.validateTransitionAction(e,t):i.startsWith("audio/")?this.validateAudioAction(e,t):i.startsWith("subtitle/")?this.validateSubtitleAction(e,t):[{code:"UNKNOWN_ACTION_TYPE",message:`Unknown action type: ${i}`}]}validateProjectAction(e,t){const i=[];switch(e.type){case"project/create":(!e.params.name||typeof e.params.name!="string")&&i.push({code:"INVALID_PARAMS",message:"Project name is required and must be a string",path:"params.name"}),e.params.settings||i.push({code:"INVALID_PARAMS",message:"Project settings are required",path:"params.settings"});break;case"project/rename":(!e.params.name||typeof e.params.name!="string")&&i.push({code:"INVALID_PARAMS",message:"Project name is required and must be a string",path:"params.name"});break;case"project/updateSettings":(!e.params||typeof e.params!="object"||Array.isArray(e.params))&&i.push({code:"INVALID_PARAMS",message:"Settings must be an object",path:"params"});break}return i}validateMediaAction(e,t){const i=[];switch(e.type){case"media/import":e.params.file||i.push({code:"INVALID_PARAMS",message:"File is required for media import",path:"params.file"});break;case"media/delete":case"media/rename":!e.params.mediaId||typeof e.params.mediaId!="string"?i.push({code:"INVALID_PARAMS",message:"Media ID is required and must be a string",path:"params.mediaId"}):t.mediaLibrary.items.some(r=>r.id===e.params.mediaId)||i.push({code:"MEDIA_NOT_FOUND",message:`Media with ID ${e.params.mediaId} not found`,path:"params.mediaId"}),e.type==="media/rename"&&(!e.params.name||typeof e.params.name!="string")&&i.push({code:"INVALID_PARAMS",message:"Media name is required and must be a string",path:"params.name"});break}return i}validateTrackAction(e,t){const i=[],n=t.timeline;switch(e.type){case"track/add":["video","audio","image","text","graphics"].includes(e.params.trackType)||i.push({code:"INVALID_PARAMS",message:"Track type must be 'video', 'audio', 'image', 'text', or 'graphics'",path:"params.trackType"}),e.params.position!==void 0&&(typeof e.params.position!="number"||e.params.position<0)&&i.push({code:"INVALID_PARAMS",message:"Track position must be a non-negative number",path:"params.position"});break;case"track/remove":case"track/lock":case"track/hide":case"track/mute":case"track/solo":!e.params.trackId||typeof e.params.trackId!="string"?i.push({code:"INVALID_PARAMS",message:"Track ID is required and must be a string",path:"params.trackId"}):this.findTrack(n,e.params.trackId)||i.push({code:"TRACK_NOT_FOUND",message:`Track with ID ${e.params.trackId} not found`,path:"params.trackId"}),e.type==="track/lock"&&typeof e.params.locked!="boolean"&&i.push({code:"INVALID_PARAMS",message:"Locked parameter must be a boolean",path:"params.locked"}),e.type==="track/hide"&&typeof e.params.hidden!="boolean"&&i.push({code:"INVALID_PARAMS",message:"Hidden parameter must be a boolean",path:"params.hidden"}),e.type==="track/mute"&&typeof e.params.muted!="boolean"&&i.push({code:"INVALID_PARAMS",message:"Muted parameter must be a boolean",path:"params.muted"}),e.type==="track/solo"&&typeof e.params.solo!="boolean"&&i.push({code:"INVALID_PARAMS",message:"Solo parameter must be a boolean",path:"params.solo"});break;case"track/reorder":!e.params.trackId||typeof e.params.trackId!="string"?i.push({code:"INVALID_PARAMS",message:"Track ID is required and must be a string",path:"params.trackId"}):this.findTrack(n,e.params.trackId)||i.push({code:"TRACK_NOT_FOUND",message:`Track with ID ${e.params.trackId} not found`,path:"params.trackId"}),(typeof e.params.newPosition!="number"||e.params.newPosition<0||e.params.newPosition>=n.tracks.length)&&i.push({code:"INVALID_PARAMS",message:`New position must be between 0 and ${n.tracks.length-1}`,path:"params.newPosition"});break}return i}validateClipAction(e,t){const i=[],n=t.timeline;switch(e.type){case"clip/add":if(!e.params.trackId||typeof e.params.trackId!="string")i.push({code:"INVALID_PARAMS",message:"Track ID is required and must be a string",path:"params.trackId"});else{const r=this.findTrack(n,e.params.trackId);r?r.locked&&i.push({code:"TRACK_LOCKED",message:`Track ${e.params.trackId} is locked`,path:"params.trackId"}):i.push({code:"TRACK_NOT_FOUND",message:`Track with ID ${e.params.trackId} not found`,path:"params.trackId"})}!e.params.mediaId||typeof e.params.mediaId!="string"?i.push({code:"INVALID_PARAMS",message:"Media ID is required and must be a string",path:"params.mediaId"}):t.mediaLibrary.items.some(a=>a.id===e.params.mediaId)||i.push({code:"MEDIA_NOT_FOUND",message:`Media with ID ${e.params.mediaId} not found`,path:"params.mediaId"}),(typeof e.params.startTime!="number"||e.params.startTime<0)&&i.push({code:"INVALID_PARAMS",message:"Start time must be a non-negative number",path:"params.startTime"});break;case"clip/remove":case"clip/rippleDelete":if(!e.params.clipId||typeof e.params.clipId!="string")i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"});else{const r=this.findClip(n,e.params.clipId);r?this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}):i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"})}break;case"clip/move":if(!e.params.clipId||typeof e.params.clipId!="string")i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"});else{const r=this.findClip(n,e.params.clipId);r?this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}):i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"})}if((typeof e.params.startTime!="number"||e.params.startTime<0)&&i.push({code:"INVALID_PARAMS",message:"Start time must be a non-negative number",path:"params.startTime"}),e.params.trackId!==void 0)if(typeof e.params.trackId!="string")i.push({code:"INVALID_PARAMS",message:"Track ID must be a string",path:"params.trackId"});else{const r=this.findTrack(n,e.params.trackId);r?r.locked&&i.push({code:"TRACK_LOCKED",message:`Target track ${e.params.trackId} is locked`,path:"params.trackId"}):i.push({code:"TRACK_NOT_FOUND",message:`Target track with ID ${e.params.trackId} not found`,path:"params.trackId"})}break;case"clip/trim":if(!e.params.clipId||typeof e.params.clipId!="string")i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"});else{const r=this.findClip(n,e.params.clipId);r?this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}):i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"})}e.params.inPoint!==void 0&&(typeof e.params.inPoint!="number"||e.params.inPoint<0)&&i.push({code:"INVALID_PARAMS",message:"In-point must be a non-negative number",path:"params.inPoint"}),e.params.outPoint!==void 0&&(typeof e.params.outPoint!="number"||e.params.outPoint<0)&&i.push({code:"INVALID_PARAMS",message:"Out-point must be a non-negative number",path:"params.outPoint"}),e.params.inPoint!==void 0&&e.params.outPoint!==void 0&&e.params.outPoint<=e.params.inPoint&&i.push({code:"INVALID_TIME_RANGE",message:"Out-point must be greater than in-point",path:"params"});break;case"clip/split":if(!e.params.clipId||typeof e.params.clipId!="string")i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"});else{const r=this.findClip(n,e.params.clipId);r?(this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}),typeof e.params.time=="number"?(e.params.time<=r.startTime||e.params.time>=r.startTime+r.duration)&&i.push({code:"OUT_OF_BOUNDS",message:`Split time must be within clip bounds (${r.startTime} to ${r.startTime+r.duration})`,path:"params.time"}):i.push({code:"INVALID_PARAMS",message:"Split time is required and must be a number",path:"params.time"})):i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"})}break}return i}validateEffectAction(e,t){const i=[],n=t.timeline;if(!e.params.clipId||typeof e.params.clipId!="string")return i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"}),i;const r=this.findClip(n,e.params.clipId);if(!r)return i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"}),i;switch(this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}),e.type){case"effect/add":(!e.params.effectType||typeof e.params.effectType!="string")&&i.push({code:"INVALID_PARAMS",message:"Effect type is required and must be a string",path:"params.effectType"});break;case"effect/remove":case"effect/update":case"effect/reorder":!e.params.effectId||typeof e.params.effectId!="string"?i.push({code:"INVALID_PARAMS",message:"Effect ID is required and must be a string",path:"params.effectId"}):r.effects.some(c=>c.id===e.params.effectId)||i.push({code:"EFFECT_NOT_FOUND",message:`Effect with ID ${e.params.effectId} not found on clip`,path:"params.effectId"}),e.type==="effect/reorder"&&(typeof e.params.newIndex!="number"||e.params.newIndex<0||e.params.newIndex>=r.effects.length)&&i.push({code:"INVALID_PARAMS",message:`New index must be between 0 and ${r.effects.length-1}`,path:"params.newIndex"});break}return i}validateTransformAction(e,t){const i=[],n=t.timeline;if(!e.params.clipId||typeof e.params.clipId!="string")return i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"}),i;const r=this.findClip(n,e.params.clipId);return r?(this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}),(!e.params.transform||typeof e.params.transform!="object")&&i.push({code:"INVALID_PARAMS",message:"Transform is required and must be an object",path:"params.transform"}),i):(i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"}),i)}validateKeyframeAction(e,t){const i=[],n=t.timeline;if(!e.params.clipId||typeof e.params.clipId!="string")return i.push({code:"INVALID_PARAMS",message:"Clip ID is required and must be a string",path:"params.clipId"}),i;const r=this.findClip(n,e.params.clipId);return r?(this.findTrack(n,r.trackId)?.locked&&i.push({code:"TRACK_LOCKED",message:`Track containing clip ${e.params.clipId} is locked`,path:"params.clipId"}),(!e.params.property||typeof e.params.property!="string")&&i.push({code:"INVALID_PARAMS",message:"Property is required and must be a string",path:"params.property"}),(typeof e.params.time!="number"||e.params.time<0)&&i.push({code:"INVALID_PARAMS",message:"Time is required and must be a non-negative number",path:"params.time"}),i):(i.push({code:"CLIP_NOT_FOUND",message:`Clip with ID ${e.params.clipId} not found`,path:"params.clipId"}),i)}validateTransitionAction(e,t){const i=[],n=t.timeline;switch(e.type){case"transition/add":if((!e.params.clipAId||typeof e.params.clipAId!="string")&&i.push({code:"INVALID_PARAMS",message:"Clip A ID is required and must be a string",path:"params.clipAId"}),(!e.params.clipBId||typeof e.params.clipBId!="string")&&i.push({code:"INVALID_PARAMS",message:"Clip B ID is required and must be a string",path:"params.clipBId"}),(typeof e.params.duration!="number"||e.params.duration<=0)&&i.push({code:"INVALID_PARAMS",message:"Duration must be a positive number",path:"params.duration"}),e.params.clipAId&&e.params.clipBId){const r=this.findClip(n,e.params.clipAId),a=this.findClip(n,e.params.clipBId);if(r||i.push({code:"CLIP_NOT_FOUND",message:`Clip A with ID ${e.params.clipAId} not found`,path:"params.clipAId"}),a||i.push({code:"CLIP_NOT_FOUND",message:`Clip B with ID ${e.params.clipBId} not found`,path:"params.clipBId"}),r&&a){r.trackId!==a.trackId&&i.push({code:"INVALID_PARAMS",message:"Clips must be on the same track for transition",path:"params"});const o=r.startTime+r.duration,c=a.startTime+a.duration,l=.001,u=Math.abs(o-a.startTime)4)&&i.push({code:"INVALID_PARAMS",message:"Volume must be a number between 0 and 4",path:"params.volume"});break;case"audio/setFade":e.params.fadeIn!==void 0&&(typeof e.params.fadeIn!="number"||e.params.fadeIn<0)&&i.push({code:"INVALID_PARAMS",message:"Fade-in must be a non-negative number",path:"params.fadeIn"}),e.params.fadeOut!==void 0&&(typeof e.params.fadeOut!="number"||e.params.fadeOut<0)&&i.push({code:"INVALID_PARAMS",message:"Fade-out must be a non-negative number",path:"params.fadeOut"});break;case"audio/addAutomation":Array.isArray(e.params.points)||i.push({code:"INVALID_PARAMS",message:"Automation points must be an array",path:"params.points"});break}return i}validateSubtitleAction(e,t){const i=[];switch(e.type){case"subtitle/import":(!e.params.srtContent||typeof e.params.srtContent!="string")&&i.push({code:"INVALID_PARAMS",message:"SRT content is required and must be a string",path:"params.srtContent"});break;case"subtitle/add":(!e.params.text||typeof e.params.text!="string")&&i.push({code:"INVALID_PARAMS",message:"Subtitle text is required and must be a string",path:"params.text"}),(typeof e.params.startTime!="number"||e.params.startTime<0)&&i.push({code:"INVALID_PARAMS",message:"Start time must be a non-negative number",path:"params.startTime"}),(typeof e.params.endTime!="number"||e.params.endTime<0)&&i.push({code:"INVALID_PARAMS",message:"End time must be a non-negative number",path:"params.endTime"}),typeof e.params.startTime=="number"&&typeof e.params.endTime=="number"&&e.params.endTime<=e.params.startTime&&i.push({code:"INVALID_TIME_RANGE",message:"End time must be greater than start time",path:"params"});break;case"subtitle/update":(!e.params.subtitleId||typeof e.params.subtitleId!="string")&&i.push({code:"INVALID_PARAMS",message:"Subtitle ID is required and must be a string",path:"params.subtitleId"}),e.params.startTime!==void 0&&(typeof e.params.startTime!="number"||e.params.startTime<0)&&i.push({code:"INVALID_PARAMS",message:"Start time must be a non-negative number",path:"params.startTime"}),e.params.endTime!==void 0&&(typeof e.params.endTime!="number"||e.params.endTime<0)&&i.push({code:"INVALID_PARAMS",message:"End time must be a non-negative number",path:"params.endTime"});break;case"subtitle/remove":(!e.params.subtitleId||typeof e.params.subtitleId!="string")&&i.push({code:"INVALID_PARAMS",message:"Subtitle ID is required and must be a string",path:"params.subtitleId"});break;case"subtitle/setStyle":(!e.params.style||typeof e.params.style!="object")&&i.push({code:"INVALID_PARAMS",message:"Style is required and must be an object",path:"params.style"});break}return i}findTrack(e,t){return e.tracks.find(i=>i.id===t)||null}findClip(e,t){for(const i of e.tracks){const n=i.clips.find(r=>r.id===t);if(n)return n}return null}}const L7={"clip/add":()=>"Add clip","clip/remove":()=>"Delete clip","clip/move":()=>"Move clip","clip/trim":()=>"Trim clip","clip/split":()=>"Split clip","clip/rippleDelete":()=>"Ripple delete","clip/duplicate":()=>"Duplicate clip","track/add":s=>`Add ${s.trackType} track`,"track/remove":()=>"Remove track","effect/add":s=>`Add ${s.effectType} effect`,"effect/remove":()=>"Remove effect","effect/update":()=>"Update effect","transform/update":()=>"Transform clip","keyframe/add":s=>`Add ${s.property} keyframe`,"keyframe/remove":()=>"Remove keyframe","transition/add":s=>`Add ${s.transitionType} transition`,"transition/remove":()=>"Remove transition","audio/setVolume":()=>"Adjust volume","audio/setFade":()=>"Adjust fade","subtitle/add":()=>"Add subtitle","subtitle/remove":()=>"Remove subtitle","project/rename":()=>"Rename project","project/updateSettings":()=>"Update settings","media/import":()=>"Import media","media/delete":()=>"Delete media","clip/closeGapBefore":()=>"Close gap","track/consolidate":()=>"Remove gaps","track/restorePositions":()=>"Restore positions"};function O7(s){const e=L7[s.type];if(e)return e(s.params);const t=s.type.split("/");return`${t[0]}: ${t[1]||"action"}`}const B7=new Set(["transform/update","effect/update","audio/setVolume","audio/setFade","clip/move","clip/trim","clip/slip","clip/slide","clip/roll","keyframe/move","keyframe/update","project/updateSettings"]),$7=["clipId","effectId","trackId","keyframeId","transitionId","subtitleId"];function n_(s){const e=s.params;for(const t of $7){const i=e[t];if(typeof i=="string"&&i.length>0)return i}return null}class zc{undoStack=[];redoStack=[];maxHistorySize;currentGroupId=null;snapshots=[];listeners=new Set;lastActionTime=0;autoGroupWindow=100;constructor(e=1e3){this.maxHistorySize=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){this.listeners.forEach(e=>e())}push(e,t=null){const i=Date.now(),n=i-this.lastActionTime;this.lastActionTime=i;const r=this.undoStack.length>0?this.undoStack[this.undoStack.length-1]:null;let a=this.currentGroupId;if(!a&&r&&nc.stackIndex<=this.undoStack.length),this.undoStack.length>this.maxHistorySize&&(this.undoStack.shift(),this.snapshots=this.snapshots.map(c=>({...c,stackIndex:c.stackIndex-1})).filter(c=>c.stackIndex>=0)),this.notify()}beginGroup(e){return this.currentGroupId=`group-${Date.now()}`,this.currentGroupId}endGroup(){this.currentGroupId=null,this.notify()}setAutoGroupWindow(e){this.autoGroupWindow=e}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(e),this.notify(),e.inverseAction):null}undoGroup(){if(this.undoStack.length===0)return[];const t=this.undoStack[this.undoStack.length-1].groupId;if(!t){const n=this.undo();return n?[n]:[]}const i=[];for(;this.undoStack.length>0&&this.undoStack[this.undoStack.length-1].groupId===t;){const n=this.undo();n&&i.push(n)}return i}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(e),this.notify(),e.action):null}redoGroup(){if(this.redoStack.length===0)return[];const t=this.redoStack[this.redoStack.length-1].groupId;if(!t){const n=this.redo();return n?[n]:[]}const i=[];for(;this.redoStack.length>0&&this.redoStack[this.redoStack.length-1].groupId===t;){const n=this.redo();n&&i.push(n)}return i}createSnapshot(e){const t={id:`snapshot-${Date.now()}`,name:e,timestamp:Date.now(),stackIndex:this.undoStack.length};return this.snapshots.push(t),this.notify(),t}getSnapshots(){return[...this.snapshots]}deleteSnapshot(e){const t=this.snapshots.findIndex(i=>i.id===e);return t!==-1?(this.snapshots.splice(t,1),this.notify(),!0):!1}getDisplayHistory(){const e=[],t=new Set;for(let i=this.undoStack.length-1;i>=0;i--){const n=this.undoStack[i];n.groupId?t.has(n.groupId)||(t.add(n.groupId),e.push({entry:n,isCurrent:i===this.undoStack.length-1})):e.push({entry:n,isCurrent:i===this.undoStack.length-1})}return e.reverse()}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}getHistory(){return this.undoStack.map(e=>e.action)}getHistoryEntries(){return[...this.undoStack]}getRedoEntries(){return[...this.redoStack]}clear(){this.undoStack=[],this.redoStack=[],this.snapshots=[],this.currentGroupId=null,this.notify()}getUndoStackSize(){return this.undoStack.length}getRedoStackSize(){return this.redoStack.length}peekUndo(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1]:null}peekRedo(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1]:null}getMaxHistorySize(){return this.maxHistorySize}setMaxHistorySize(e){for(this.maxHistorySize=e;this.undoStack.length>this.maxHistorySize;)this.undoStack.shift()}}class j7{generate(e,t){const i=e.type;return i.startsWith("project/")?this.generateProjectInverse(e,t):i.startsWith("media/")?this.generateMediaInverse(e,t):i.startsWith("track/")?this.generateTrackInverse(e,t):i.startsWith("clip/")?this.generateClipInverse(e,t):i.startsWith("effect/")?this.generateEffectInverse(e,t):i.startsWith("transform/")?this.generateTransformInverse(e,t):i.startsWith("keyframe/")?this.generateKeyframeInverse(e,t):i.startsWith("transition/")?this.generateTransitionInverse(e,t):i.startsWith("audio/")?this.generateAudioInverse(e,t):i.startsWith("subtitle/")?this.generateSubtitleInverse(e,t):null}createInverseAction(e,t,i){return{type:t,id:`inverse-${e.id}`,timestamp:Date.now(),params:i}}generateProjectInverse(e,t){switch(e.type){case"project/rename":return this.createInverseAction(e,"project/rename",{name:t.name});case"project/updateSettings":return this.createInverseAction(e,"project/updateSettings",{...t.settings});case"project/create":return null}}generateMediaInverse(e,t){switch(e.type){case"media/import":return this.createInverseAction(e,"media/delete",{mediaId:"__LAST_IMPORTED__"});case"media/delete":{const i=t.mediaLibrary.items.find(n=>n.id===e.params.mediaId);return i?this.createInverseAction(e,"media/restore",{mediaItem:this.cloneMediaItem(i)}):null}case"media/rename":{const i=t.mediaLibrary.items.find(n=>n.id===e.params.mediaId);return i?this.createInverseAction(e,"media/rename",{mediaId:e.params.mediaId,name:i.name}):null}}}generateTrackInverse(e,t){const i=t.timeline;switch(e.type){case"track/add":return this.createInverseAction(e,"track/remove",{trackId:"__LAST_ADDED__"});case"track/remove":{const n=i.tracks.find(a=>a.id===e.params.trackId);if(!n)return null;const r=i.tracks.findIndex(a=>a.id===e.params.trackId);return this.createInverseAction(e,"track/restore",{track:this.cloneTrack(n),position:r})}case"track/reorder":{const n=i.tracks.findIndex(r=>r.id===e.params.trackId);return n===-1?null:this.createInverseAction(e,"track/reorder",{trackId:e.params.trackId,newPosition:n})}case"track/lock":{const n=i.tracks.find(r=>r.id===e.params.trackId);return n?this.createInverseAction(e,"track/lock",{trackId:e.params.trackId,locked:n.locked}):null}case"track/hide":{const n=i.tracks.find(r=>r.id===e.params.trackId);return n?this.createInverseAction(e,"track/hide",{trackId:e.params.trackId,hidden:n.hidden}):null}case"track/mute":{const n=i.tracks.find(r=>r.id===e.params.trackId);return n?this.createInverseAction(e,"track/mute",{trackId:e.params.trackId,muted:n.muted}):null}case"track/solo":{const n=i.tracks.find(r=>r.id===e.params.trackId);return n?this.createInverseAction(e,"track/solo",{trackId:e.params.trackId,solo:n.solo}):null}case"track/consolidate":{const n=e.params.trackId,r=i.tracks.find(o=>o.id===n);if(!r)return null;const a=r.clips.map(o=>({clipId:o.id,startTime:o.startTime}));return this.createInverseAction(e,"track/restorePositions",{trackId:n,positions:a})}}return null}generateClipInverse(e,t){const i=t.timeline;switch(e.type){case"clip/add":return this.createInverseAction(e,"clip/remove",{clipId:"__LAST_ADDED__"});case"clip/remove":{const n=this.findClip(i,e.params.clipId);return n?this.createInverseAction(e,"clip/restore",{clip:this.cloneClip(n)}):null}case"clip/move":{const n=this.findClip(i,e.params.clipId);return n?this.createInverseAction(e,"clip/move",{clipId:e.params.clipId,startTime:n.startTime,trackId:n.trackId}):null}case"clip/trim":{const n=this.findClip(i,e.params.clipId);return n?this.createInverseAction(e,"clip/trim",{clipId:e.params.clipId,inPoint:n.inPoint,outPoint:n.outPoint}):null}case"clip/split":{const n=this.findClip(i,e.params.clipId);return n?this.createInverseAction(e,"clip/merge",{clipId:e.params.clipId,originalClip:this.cloneClip(n)}):null}case"clip/rippleDelete":{const n=this.findClip(i,e.params.clipId);if(!n)return null;const a=i.tracks.find(o=>o.id===n.trackId)?.clips.filter(o=>o.startTime>n.startTime).map(o=>({id:o.id,originalStartTime:o.startTime}))||[];return this.createInverseAction(e,"clip/rippleRestore",{clip:this.cloneClip(n),affectedClips:a})}case"clip/closeGapBefore":{const n=e.params,r=this.findClip(i,n.clipId);if(!r)return null;const a=i.tracks.find(c=>c.id===r.trackId);if(!a)return null;const o=a.clips.filter(c=>c.startTime>=r.startTime).map(c=>({clipId:c.id,startTime:c.startTime}));return this.createInverseAction(e,"track/restorePositions",{trackId:a.id,positions:o})}}return null}generateEffectInverse(e,t){const i=t.timeline,n=this.findClip(i,e.params.clipId);if(!n)return null;switch(e.type){case"effect/add":return this.createInverseAction(e,"effect/remove",{clipId:e.params.clipId,effectId:"__LAST_ADDED__"});case"effect/remove":{const r=n.effects.find(o=>o.id===e.params.effectId);if(!r)return null;const a=n.effects.findIndex(o=>o.id===e.params.effectId);return this.createInverseAction(e,"effect/restore",{clipId:e.params.clipId,effect:{...r},index:a})}case"effect/update":{const r=n.effects.find(a=>a.id===e.params.effectId);return r?this.createInverseAction(e,"effect/update",{clipId:e.params.clipId,effectId:e.params.effectId,params:{...r.params}}):null}case"effect/reorder":{const r=n.effects.findIndex(a=>a.id===e.params.effectId);return r===-1?null:this.createInverseAction(e,"effect/reorder",{clipId:e.params.clipId,effectId:e.params.effectId,newIndex:r})}}}generateTransformInverse(e,t){const i=this.findClip(t.timeline,e.params.clipId);return i?this.createInverseAction(e,"transform/update",{clipId:e.params.clipId,transform:{...i.transform}}):null}generateKeyframeInverse(e,t){const i=this.findClip(t.timeline,e.params.clipId);if(!i)return null;switch(e.type){case"keyframe/add":return this.createInverseAction(e,"keyframe/remove",{clipId:e.params.clipId,property:e.params.property,time:e.params.time});case"keyframe/remove":{const n=i.keyframes.find(r=>r.property===e.params.property&&r.time===e.params.time);return n?this.createInverseAction(e,"keyframe/add",{clipId:e.params.clipId,property:n.property,time:n.time,value:n.value}):null}case"keyframe/update":{const n=i.keyframes.find(r=>r.property===e.params.property&&r.time===e.params.time);return n?this.createInverseAction(e,"keyframe/update",{clipId:e.params.clipId,property:n.property,time:n.time,value:n.value,easing:n.easing}):null}}}generateTransitionInverse(e,t){const i=t.timeline;switch(e.type){case"transition/add":return this.createInverseAction(e,"transition/remove",{transitionId:"__LAST_ADDED__"});case"transition/remove":{const n=this.findTransition(i,e.params.transitionId);return n?this.createInverseAction(e,"transition/restore",{transition:{...n}}):null}case"transition/update":{const n=this.findTransition(i,e.params.transitionId);return n?this.createInverseAction(e,"transition/update",{transitionId:e.params.transitionId,duration:n.duration,params:{...n.params}}):null}}}generateAudioInverse(e,t){const i=this.findClip(t.timeline,e.params.clipId);if(!i)return null;switch(e.type){case"audio/setVolume":return this.createInverseAction(e,"audio/setVolume",{clipId:e.params.clipId,volume:i.volume});case"audio/setFade":return this.createInverseAction(e,"audio/setFade",{clipId:e.params.clipId,fadeIn:i.fade?.fadeIn??0,fadeOut:i.fade?.fadeOut??0});case"audio/addAutomation":return this.createInverseAction(e,"audio/addAutomation",{clipId:e.params.clipId,points:i.automation?.volume??[]})}}generateSubtitleInverse(e,t){const i=t.timeline;switch(e.type){case"subtitle/import":return this.createInverseAction(e,"subtitle/restoreAll",{subtitles:i.subtitles.map(n=>({...n}))});case"subtitle/add":return this.createInverseAction(e,"subtitle/remove",{subtitleId:"__LAST_ADDED__"});case"subtitle/remove":{const n=i.subtitles.find(r=>r.id===e.params.subtitleId);return n?this.createInverseAction(e,"subtitle/restore",{subtitle:{...n}}):null}case"subtitle/update":{const n=i.subtitles.find(r=>r.id===e.params.subtitleId);return n?this.createInverseAction(e,"subtitle/update",{subtitleId:e.params.subtitleId,text:n.text,startTime:n.startTime,endTime:n.endTime}):null}case"subtitle/setStyle":{const n=i.subtitles[0];return this.createInverseAction(e,"subtitle/setStyle",{style:n?.style??null})}}}findClip(e,t){for(const i of e.tracks){const n=i.clips.find(r=>r.id===t);if(n)return n}return null}findTransition(e,t){for(const i of e.tracks){const n=i.transitions?.find(r=>r.id===t);if(n)return n}return null}cloneMediaItem(e){return{id:e.id,name:e.name,type:e.type,fileHandle:e.fileHandle,blob:e.blob,metadata:{...e.metadata},thumbnailUrl:e.thumbnailUrl,waveformData:e.waveformData?new Float32Array(e.waveformData):null}}cloneTrack(e){return{id:e.id,type:e.type,name:e.name,clips:e.clips.map(t=>this.cloneClip(t)),transitions:e.transitions?.map(t=>({...t}))??[],locked:e.locked,hidden:e.hidden,muted:e.muted,solo:e.solo}}cloneClip(e){return{id:e.id,mediaId:e.mediaId,trackId:e.trackId,startTime:e.startTime,duration:e.duration,inPoint:e.inPoint,outPoint:e.outPoint,effects:e.effects.map(t=>({...t,params:{...t.params}})),transform:{...e.transform},volume:e.volume,fade:e.fade?{...e.fade}:void 0,automation:e.automation?{volume:e.automation.volume?.map(t=>({...t})),pan:e.automation.pan?.map(t=>({...t}))}:void 0,keyframes:e.keyframes.map(t=>({...t}))}}}class Ou{validator;history;inverseGenerator;lastAddedIds=new Map;constructor(e){this.validator=new F7,this.history=e||new zc,this.inverseGenerator=new j7}async execute(e,t){const i=this.validator.validate(e,t);if(!i.valid)return{success:!1,error:{code:"INVALID_PARAMS",message:i.errors.map(a=>a.message).join("; "),details:{errors:i.errors}}};const n=JSON.parse(JSON.stringify(t)),r=this.inverseGenerator.generate(e,n);try{return await this.applyAction(e,t),this.history.push(e,r),{success:!0,actionId:e.id}}catch(a){return{success:!1,error:{code:"INVALID_PARAMS",message:a instanceof Error?a.message:"Unknown error occurred"}}}}async executeMany(e,t){const i=[];for(const n of e){const r=await this.execute(n,t);if(i.push(r),!r.success)break}return i}async undo(e){if(!this.history.canUndo())return{success:!1,error:{code:"INVALID_PARAMS",message:"Nothing to undo"}};const t=this.history.undoGroup();if(t.length===0)return{success:!1,error:{code:"INVALID_PARAMS",message:"No inverse action available"}};try{for(const i of t){const n=this.resolveSpecialMarkers(i);await this.applyAction(n,e)}return{success:!0,actionId:t[0].id}}catch(i){return{success:!1,error:{code:"INVALID_PARAMS",message:i instanceof Error?i.message:"Undo failed"}}}}async redo(e){if(!this.history.canRedo())return{success:!1,error:{code:"INVALID_PARAMS",message:"Nothing to redo"}};const t=this.history.redoGroup();if(t.length===0)return{success:!1,error:{code:"INVALID_PARAMS",message:"No action to redo"}};try{for(const i of t)await this.applyAction(i,e);return{success:!0,actionId:t[0].id}}catch(i){return{success:!1,error:{code:"INVALID_PARAMS",message:i instanceof Error?i.message:"Redo failed"}}}}getHistory(){return this.history}resolveSpecialMarkers(e){const t={...e.params};for(const[i,n]of Object.entries(t))if(n==="__LAST_ADDED__"){const r=this.lastAddedIds.get(e.type.split("/")[0]);r&&(t[i]=r)}return{...e,params:t}}async applyAction(e,t){const i=e.type;i.startsWith("project/")?this.applyProjectAction(e,t):i.startsWith("media/")?await this.applyMediaAction(e,t):i.startsWith("track/")?this.applyTrackAction(e,t):i.startsWith("clip/")?this.applyClipAction(e,t):i.startsWith("effect/")?this.applyEffectAction(e,t):i.startsWith("transform/")?this.applyTransformAction(e,t):i.startsWith("keyframe/")?this.applyKeyframeAction(e,t):i.startsWith("transition/")?this.applyTransitionAction(e,t):i.startsWith("audio/")?this.applyAudioAction(e,t):i.startsWith("subtitle/")&&this.applySubtitleAction(e,t),this.recalculateTimelineDuration(t)}recalculateTimelineDuration(e){let t=0;for(const i of e.timeline.tracks)for(const n of i.clips){const r=n.startTime+n.duration;r>t&&(t=r)}e.timeline.duration=t}applyProjectAction(e,t){switch(e.type){case"project/rename":t.name=e.params.name,t.modifiedAt=Date.now();break;case"project/updateSettings":t.settings={...t.settings,...e.params},t.modifiedAt=Date.now();break;case"project/create":t.name=e.params.name,t.settings=e.params.settings,t.modifiedAt=Date.now();break}}async applyMediaAction(e,t){const i=t.mediaLibrary;switch(e.type){case"media/import":{const n=e.params,r={id:`media-${Date.now()}`,name:n.file.name,type:this.inferMediaType(n.file),fileHandle:null,blob:n.file,metadata:{duration:0,width:0,height:0,frameRate:0,codec:"",sampleRate:0,channels:0,fileSize:n.file.size},thumbnailUrl:null,waveformData:null};i.items=[...i.items,r],this.lastAddedIds.set("media",r.id);break}case"media/delete":{const n=e.params;i.items=i.items.filter(r=>r.id!==n.mediaId);break}case"media/rename":{const n=e.params;i.items=i.items.map(r=>r.id===n.mediaId?{...r,name:n.name}:r);break}case"media/restore":{const n=e.params;i.items=[...i.items,n.mediaItem];break}}}inferMediaType(e){return e.type.startsWith("video/")?"video":e.type.startsWith("audio/")?"audio":e.type.startsWith("image/")?"image":"video"}applyTrackAction(e,t){const i=t.timeline;switch(e.type){case"track/add":{const n=e.params,r={video:"Video",audio:"Audio",image:"Image",text:"Text",graphics:"Graphics"},a=i.tracks.filter(l=>l.type===n.trackType).length+1,o={id:n.trackId??`track-${Date.now()}`,type:n.trackType,name:`${r[n.trackType]||n.trackType} ${a}`,clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},c=n.position!==void 0?n.position:i.tracks.length;i.tracks=[...i.tracks.slice(0,c),o,...i.tracks.slice(c)],this.lastAddedIds.set("track",o.id);break}case"track/remove":{const n=e.params;i.tracks=i.tracks.filter(r=>r.id!==n.trackId);break}case"track/restore":{const n=e.params;i.tracks=[...i.tracks.slice(0,n.position),n.track,...i.tracks.slice(n.position)];break}case"track/reorder":{const n=e.params,r=i.tracks.findIndex(a=>a.id===n.trackId);if(r!==-1){const[a]=i.tracks.splice(r,1);i.tracks.splice(n.newPosition,0,a)}break}case"track/lock":{const n=e.params;i.tracks=i.tracks.map(r=>r.id===n.trackId?{...r,locked:n.locked}:r);break}case"track/hide":{const n=e.params;i.tracks=i.tracks.map(r=>r.id===n.trackId?{...r,hidden:n.hidden}:r);break}case"track/mute":{const n=e.params;i.tracks=i.tracks.map(r=>r.id===n.trackId?{...r,muted:n.muted}:r);break}case"track/solo":{const n=e.params;i.tracks=i.tracks.map(r=>r.id===n.trackId?{...r,solo:n.solo}:r);break}}}applyClipAction(e,t){const i=t.timeline;switch(e.type){case"clip/add":{const n=e.params,r=i.tracks.find(a=>a.id===n.trackId);if(r){const a=t.mediaLibrary.items.find(u=>u.id===n.mediaId),o=n.duration??(a?.metadata.duration&&a.metadata.duration>0?a.metadata.duration:5),c={position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1,fitMode:"contain"},l={id:crypto.randomUUID(),mediaId:n.mediaId,trackId:n.trackId,startTime:n.startTime,duration:o,inPoint:n.inPoint??0,outPoint:n.outPoint??o,effects:n.effects??[],audioEffects:n.audioEffects??[],transform:n.transform?{...c,...n.transform}:c,volume:n.volume??1,keyframes:n.keyframes??[],...n.fade?{fade:n.fade}:{},...n.speed!==void 0?{speed:n.speed}:{},...n.reversed!==void 0?{reversed:n.reversed}:{},...n.audioTrackIndex!==void 0?{audioTrackIndex:n.audioTrackIndex}:{}};r.clips=[...r.clips,l],this.lastAddedIds.set("clip",l.id)}break}case"clip/remove":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.filter(a=>a.id!==n.clipId)}));break}case"clip/restore":{const n=e.params;i.tracks=i.tracks.map(r=>r.id===n.clip.trackId?{...r,clips:[...r.clips,n.clip]}:r);break}case"clip/move":{const n=e.params,r=this.findClip(i,n.clipId);if(r){i.tracks=i.tracks.map(o=>({...o,clips:o.clips.filter(c=>c.id!==n.clipId)}));const a=n.trackId||r.trackId;i.tracks=i.tracks.map(o=>o.id===a?{...o,clips:[...o.clips,{...r,startTime:n.startTime,trackId:a}]}:o)}break}case"clip/trim":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>{if(a.id===n.clipId){const o={};return n.inPoint!==void 0&&(o.inPoint=n.inPoint,o.duration=a.outPoint-n.inPoint),n.outPoint!==void 0&&(o.outPoint=n.outPoint,o.duration=n.outPoint-a.inPoint),{...a,...o}}return a})}));break}case"clip/split":{const n=e.params,r=this.findClip(i,n.clipId);if(r){const a=n.time,o=a-r.startTime,c={...r,duration:o,outPoint:r.inPoint+o},l={...r,id:crypto.randomUUID(),startTime:a,duration:r.duration-o,inPoint:r.inPoint+o};i.tracks=i.tracks.map(u=>({...u,clips:u.clips.flatMap(d=>d.id===n.clipId?[c,l]:[d])})),this.lastAddedIds.set("clip",l.id)}break}case"clip/merge":{const n=e.params,r=n.originalClip.startTime,a=r+n.originalClip.duration,o=n.originalClip.mediaId;i.tracks=i.tracks.map(c=>{if(c.id===n.originalClip.trackId){const l=c.clips.filter(u=>{if(u.id===n.clipId)return!1;if(u.mediaId===o){const d=u.startTime+u.duration;if(u.startTime>=r&&d<=a)return!1}return!0});return{...c,clips:[...l,n.originalClip]}}return c});break}case"clip/rippleDelete":{const n=e.params,r=this.findClip(i,n.clipId);if(r){const a=r.duration,o=r.startTime;i.tracks=i.tracks.map(c=>c.id===r.trackId?{...c,clips:c.clips.filter(l=>l.id!==n.clipId).map(l=>l.startTime>o?{...l,startTime:l.startTime-a}:l)}:c)}break}case"clip/rippleRestore":{const n=e.params;i.tracks=i.tracks.map(r=>{if(r.id===n.clip.trackId){const a=r.clips.map(o=>{const c=n.affectedClips.find(l=>l.id===o.id);return c?{...o,startTime:c.originalStartTime}:o});return{...r,clips:[...a,n.clip]}}return r});break}case"clip/slip":{const n=e.params,r=this.findClip(i,n.clipId);if(r){const a=Math.max(0,r.inPoint+n.delta),o=a+r.duration;i.tracks=i.tracks.map(c=>({...c,clips:c.clips.map(l=>l.id===n.clipId?{...l,inPoint:a,outPoint:o}:l)}))}break}case"clip/slide":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,startTime:Math.max(0,a.startTime+n.delta)}:a.id===n.prevClipId&&n.delta>0?{...a,duration:a.duration+n.delta}:a.id===n.nextClipId&&n.delta<0?{...a,startTime:a.startTime+n.delta,inPoint:a.inPoint-n.delta,duration:a.duration-n.delta}:a)}));break}case"clip/roll":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.leftClipId?{...a,duration:a.duration+n.delta,outPoint:a.outPoint+n.delta}:a.id===n.rightClipId?{...a,startTime:a.startTime+n.delta,inPoint:a.inPoint+n.delta,duration:a.duration-n.delta}:a)}));break}case"clip/trimToPlayhead":{const n=e.params;this.findClip(i,n.clipId)&&(i.tracks=i.tracks.map(a=>({...a,clips:a.clips.map(o=>{if(o.id!==n.clipId)return o;if(n.trimStart){const c=n.playheadTime-o.startTime;return{...o,startTime:n.playheadTime,inPoint:o.inPoint+c,duration:o.duration-c}}else return{...o,duration:n.playheadTime-o.startTime,outPoint:o.inPoint+(n.playheadTime-o.startTime)}})})));break}case"clip/closeGapBefore":{const n=e.params,r=this.findClip(i,n.clipId);if(r){const a=i.tracks.find(o=>o.id===r.trackId);if(a){const o=[...a.clips].sort((l,u)=>l.startTime-u.startTime),c=o.findIndex(l=>l.id===r.id);if(c>=0){const l=c>0?o[c-1]:null,u=l?l.startTime+l.duration:0,d=r.startTime-u;if(d>0){const h=new Set(o.slice(c).map(f=>f.id));i.tracks=i.tracks.map(f=>f.id!==a.id?f:{...f,clips:f.clips.map(p=>h.has(p.id)?{...p,startTime:p.startTime-d}:p)})}}}}break}case"track/consolidate":{const n=e.params;i.tracks=i.tracks.map(r=>{if(r.id!==n.trackId)return r;const a=[...r.clips].sort((l,u)=>l.startTime-u.startTime);let o=0;const c=new Map;for(const l of a){const u=Math.max(0,o);c.set(l.id,u),o=u+l.duration}return{...r,clips:r.clips.map(l=>{const u=c.get(l.id);return u!==void 0&&u!==l.startTime?{...l,startTime:u}:l})}});break}case"track/restorePositions":{const n=e.params,r=new Map(n.positions.map(a=>[a.clipId,a.startTime]));i.tracks=i.tracks.map(a=>a.id!==n.trackId?a:{...a,clips:a.clips.map(o=>{const c=r.get(o.id);return c!==void 0&&c!==o.startTime?{...o,startTime:c}:o})});break}}}applyEffectAction(e,t){const i=t.timeline;switch(e.type){case"effect/add":{const n=e.params,r={id:`effect-${Date.now()}`,type:n.effectType,params:n.params||{},enabled:!0};i.tracks=i.tracks.map(a=>({...a,clips:a.clips.map(o=>o.id===n.clipId?{...o,effects:[...o.effects,r]}:o)})),this.lastAddedIds.set("effect",r.id);break}case"effect/remove":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,effects:a.effects.filter(o=>o.id!==n.effectId)}:a)}));break}case"effect/restore":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>{if(a.id===n.clipId){const o=[...a.effects];return o.splice(n.index,0,n.effect),{...a,effects:o}}return a})}));break}case"effect/update":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,effects:a.effects.map(o=>o.id===n.effectId?{...o,params:{...o.params,...n.params}}:o)}:a)}));break}case"effect/reorder":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>{if(a.id===n.clipId){const o=[...a.effects],c=o.findIndex(l=>l.id===n.effectId);if(c!==-1){const[l]=o.splice(c,1);o.splice(n.newIndex,0,l)}return{...a,effects:o}}return a})}));break}}}applyTransformAction(e,t){const i=t.timeline;i.tracks=i.tracks.map(n=>({...n,clips:n.clips.map(r=>r.id===e.params.clipId?{...r,transform:{...r.transform,...e.params.transform}}:r)}))}applyKeyframeAction(e,t){const i=t.timeline;switch(e.type){case"keyframe/add":{const n=e.params,r={id:`keyframe-${Date.now()}`,time:n.time,property:n.property,value:n.value,easing:"linear"};i.tracks=i.tracks.map(a=>({...a,clips:a.clips.map(o=>o.id===n.clipId?{...o,keyframes:[...o.keyframes,r]}:o)})),this.lastAddedIds.set("keyframe",r.id);break}case"keyframe/remove":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,keyframes:a.keyframes.filter(o=>!(o.property===n.property&&o.time===n.time))}:a)}));break}case"keyframe/update":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,keyframes:a.keyframes.map(o=>o.property===n.property&&o.time===n.time?{...o,...n.value!==void 0&&{value:n.value},...n.easing!==void 0&&{easing:n.easing}}:o)}:a)}));break}}}applyTransitionAction(e,t){const i=t.timeline;switch(e.type){case"transition/add":{const n=e.params,r=this.findClip(i,n.clipAId);if(r){const a=i.tracks.find(o=>o.id===r.trackId);if(a){const o={id:`transition-${Date.now()}`,clipAId:n.clipAId,clipBId:n.clipBId,type:n.transitionType,duration:n.duration,params:{}};a.transitions=[...a.transitions||[],o],this.lastAddedIds.set("transition",o.id)}}break}case"transition/remove":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,transitions:(r.transitions||[]).filter(a=>a.id!==n.transitionId)}));break}case"transition/restore":{const n=e.params,r=this.findClip(i,n.transition.clipAId);r&&(i.tracks=i.tracks.map(a=>a.id===r.trackId?{...a,transitions:[...a.transitions||[],n.transition]}:a));break}case"transition/update":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,transitions:(r.transitions||[]).map(a=>a.id===n.transitionId?{...a,...n.duration!==void 0&&{duration:n.duration},...n.params!==void 0&&{params:{...a.params,...n.params}}}:a)}));break}}}applyAudioAction(e,t){const i=t.timeline;switch(e.type){case"audio/setVolume":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,volume:n.volume}:a)}));break}case"audio/setFade":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,fade:{fadeIn:n.fadeIn!==void 0?n.fadeIn:a.fade?.fadeIn||0,fadeOut:n.fadeOut!==void 0?n.fadeOut:a.fade?.fadeOut||0}}:a)}));break}case"audio/addAutomation":{const n=e.params;i.tracks=i.tracks.map(r=>({...r,clips:r.clips.map(a=>a.id===n.clipId?{...a,automation:{...a.automation,volume:n.points}}:a)}));break}}}applySubtitleAction(e,t){const i=t.timeline;switch(e.type){case"subtitle/add":{const n=e.params,r={id:`subtitle-${Date.now()}`,text:n.text,startTime:n.startTime,endTime:n.endTime};i.subtitles=[...i.subtitles||[],r],this.lastAddedIds.set("subtitle",r.id);break}case"subtitle/remove":{const n=e.params;i.subtitles=(i.subtitles||[]).filter(r=>r.id!==n.subtitleId);break}case"subtitle/restore":{const n=e.params;i.subtitles=[...i.subtitles||[],n.subtitle];break}case"subtitle/restoreAll":{const n=e.params;i.subtitles=n.subtitles;break}case"subtitle/update":{const n=e.params;i.subtitles=(i.subtitles||[]).map(r=>r.id===n.subtitleId?{...r,...n.text!==void 0&&{text:n.text},...n.startTime!==void 0&&{startTime:n.startTime},...n.endTime!==void 0&&{endTime:n.endTime}}:r);break}case"subtitle/setStyle":{const n=e.params;i.subtitles=(i.subtitles||[]).map(r=>({...r,style:n.style}));break}case"subtitle/import":{const n=e.params,r=/(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n([\s\S]*?)(?=\n\n|\n*$)/g;let a;const o=[];for(;(a=r.exec(n.srtContent))!==null;){const c=this.parseSrtTime(a[2]),l=this.parseSrtTime(a[3]),u=a[4].trim();o.push({id:`subtitle-${Date.now()}-${a[1]}`,text:u,startTime:c,endTime:l})}o.length>0&&(i.subtitles=[...i.subtitles||[],...o]);break}}}parseSrtTime(e){const[t,i]=e.split(","),[n,r,a]=t.split(":").map(Number);return n*3600+r*60+a+Number(i)/1e3}findClip(e,t){for(const i of e.tracks){const n=i.clips.find(r=>r.id===t);if(n)return n}return null}}const N7=3,V7="openreel-db",ne={PROJECTS:"projects",MEDIA:"media",CACHE:"cache",WAVEFORMS:"waveforms",FILE_HANDLES:"fileHandles",DIR_HANDLES:"dirHandles"};function ln(s,e,t){return{code:s,message:e,quotaInfo:t}}class OM{db=null;dbPromise=null;async getDb(){return this.db?this.db:this.dbPromise?this.dbPromise:(this.dbPromise=this.openDatabase(),this.db=await this.dbPromise,this.db)}openDatabase(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(ln("BROWSER_NOT_SUPPORTED","IndexedDB is not supported in this environment"));return}const i=indexedDB.open(V7,N7);i.onerror=()=>{t(ln("DATABASE_ERROR",`Failed to open database: ${i.error?.message}`))},i.onsuccess=()=>{e(i.result)},i.onupgradeneeded=n=>{const r=n.target.result;this.createStores(r)}})}createStores(e){if(!e.objectStoreNames.contains(ne.PROJECTS)){const t=e.createObjectStore(ne.PROJECTS,{keyPath:"id"});t.createIndex("modifiedAt","modifiedAt",{unique:!1}),t.createIndex("name","name",{unique:!1})}e.objectStoreNames.contains(ne.MEDIA)||e.createObjectStore(ne.MEDIA,{keyPath:"id"}).createIndex("projectId","projectId",{unique:!1}),e.objectStoreNames.contains(ne.CACHE)||e.createObjectStore(ne.CACHE,{keyPath:"key"}).createIndex("timestamp","timestamp",{unique:!1}),e.objectStoreNames.contains(ne.WAVEFORMS)||e.createObjectStore(ne.WAVEFORMS,{keyPath:"mediaId"}),e.objectStoreNames.contains(ne.FILE_HANDLES)||e.createObjectStore(ne.FILE_HANDLES,{keyPath:"key"}),e.objectStoreNames.contains(ne.DIR_HANDLES)||e.createObjectStore(ne.DIR_HANDLES,{keyPath:"key"})}async transaction(e,t,i){const n=await this.getDb();return new Promise((r,a)=>{const o=n.transaction(e,t),c={},l=Array.isArray(e)?e:[e];for(const d of l)c[d]=o.objectStore(d);const u=i(c);u.onsuccess=()=>r(u.result),u.onerror=()=>a(ln("DATABASE_ERROR",`Transaction failed: ${u.error?.message}`))})}async transactionGetAll(e,t,i){const n=await this.getDb();return new Promise((r,a)=>{const c=n.transaction(e,"readonly").objectStore(e),l=t?c.index(t):c,u=i?l.getAll(i):l.getAll();u.onsuccess=()=>r(u.result),u.onerror=()=>a(ln("DATABASE_ERROR",`Failed to get all: ${u.error?.message}`))})}async saveProject(e){try{const t=R7(e),i={id:e.id,name:e.name,createdAt:e.createdAt,modifiedAt:e.modifiedAt,data:t};await this.transaction(ne.PROJECTS,"readwrite",n=>n[ne.PROJECTS].put(i))}catch(t){throw t.code?t:ln("SERIALIZATION_FAILED",`Failed to serialize project: ${t.message}`)}}async loadProject(e){try{const t=await this.transaction(ne.PROJECTS,"readonly",i=>i[ne.PROJECTS].get(e));return t?D7(t.data):null}catch(t){throw t.code?t:ln("DESERIALIZATION_FAILED",`Failed to deserialize project: ${t.message}`)}}async listProjects(){return(await this.transactionGetAll(ne.PROJECTS)).map(t=>({id:t.id,name:t.name,createdAt:t.createdAt,modifiedAt:t.modifiedAt})).sort((t,i)=>i.modifiedAt-t.modifiedAt)}async deleteProject(e){const t=await this.getDb(),i=await this.getMediaByProject(e);for(const n of i)await this.deleteMedia(n.id);return new Promise((n,r)=>{const c=t.transaction(ne.PROJECTS,"readwrite").objectStore(ne.PROJECTS).delete(e);c.onsuccess=()=>n(),c.onerror=()=>r(ln("DATABASE_ERROR",`Failed to delete project: ${c.error?.message}`))})}async saveMedia(e){await this.transaction(ne.MEDIA,"readwrite",t=>t[ne.MEDIA].put(e))}async loadMedia(e){return await this.transaction(ne.MEDIA,"readonly",i=>i[ne.MEDIA].get(e))||null}async deleteMedia(e){await this.deleteWaveform(e),await this.transaction(ne.MEDIA,"readwrite",t=>t[ne.MEDIA].delete(e))}async getMediaByProject(e){return this.transactionGetAll(ne.MEDIA,"projectId",e)}async saveCache(e){await this.transaction(ne.CACHE,"readwrite",t=>t[ne.CACHE].put(e))}async loadCache(e){const t=await this.transaction(ne.CACHE,"readonly",i=>i[ne.CACHE].get(e));if(t){const i={...t,timestamp:Date.now()};return await this.saveCache(i),i}return null}async deleteCache(e){await this.transaction(ne.CACHE,"readwrite",t=>t[ne.CACHE].delete(e))}async clearCache(){const e=await this.getDb();return new Promise((t,i)=>{const a=e.transaction(ne.CACHE,"readwrite").objectStore(ne.CACHE).clear();a.onsuccess=()=>t(),a.onerror=()=>i(ln("DATABASE_ERROR",`Failed to clear cache: ${a.error?.message}`))})}async saveWaveform(e){await this.transaction(ne.WAVEFORMS,"readwrite",t=>t[ne.WAVEFORMS].put(e))}async loadWaveform(e){return await this.transaction(ne.WAVEFORMS,"readonly",i=>i[ne.WAVEFORMS].get(e))||null}async deleteWaveform(e){await this.transaction(ne.WAVEFORMS,"readwrite",t=>t[ne.WAVEFORMS].delete(e))}async getStorageUsage(){const e=await this.getDb(),t=await new Promise((a,o)=>{const u=e.transaction(ne.PROJECTS,"readonly").objectStore(ne.PROJECTS).count();u.onsuccess=()=>a(u.result),u.onerror=()=>o(u.error)}),i=await new Promise((a,o)=>{const u=e.transaction(ne.MEDIA,"readonly").objectStore(ne.MEDIA).count();u.onsuccess=()=>a(u.result),u.onerror=()=>o(u.error)});let n=0,r=0;if(navigator.storage&&navigator.storage.estimate)try{const a=await navigator.storage.estimate();n=a.usage||0,r=a.quota||0}catch{}return{used:n,quota:r,projects:t,mediaItems:i}}async saveFileHandle(e,t,i){const n=await this.getDb();return new Promise((r,a)=>{const l=n.transaction(ne.FILE_HANDLES,"readwrite").objectStore(ne.FILE_HANDLES).put({key:`${e}:${t}`,handle:i});l.onsuccess=()=>r(),l.onerror=()=>a(l.error)})}async loadFileHandle(e,t){const i=await this.getDb();return new Promise((n,r)=>{const c=i.transaction(ne.FILE_HANDLES,"readonly").objectStore(ne.FILE_HANDLES).get(`${e}:${t}`);c.onsuccess=()=>n(c.result?.handle??null),c.onerror=()=>r(c.error)})}async saveDirectoryHandle(e,t){const i=await this.getDb();return new Promise((n,r)=>{const c=i.transaction(ne.DIR_HANDLES,"readwrite").objectStore(ne.DIR_HANDLES).put({key:e,handle:t,folderName:t.name});c.onsuccess=()=>n(),c.onerror=()=>r(c.error)})}async loadDirectoryHandle(e){const t=await this.getDb();return new Promise((i,n)=>{const o=t.transaction(ne.DIR_HANDLES,"readonly").objectStore(ne.DIR_HANDLES).get(e);o.onsuccess=()=>{const c=o.result;i(c?{handle:c.handle,folderName:c.folderName}:null)},o.onerror=()=>n(o.error)})}async clearAllData(){const e=await this.getDb(),t=[ne.PROJECTS,ne.MEDIA,ne.CACHE,ne.WAVEFORMS,ne.FILE_HANDLES,ne.DIR_HANDLES];return new Promise((i,n)=>{const r=e.transaction(t,"readwrite");for(const a of t)r.objectStore(a).clear();r.oncomplete=()=>i(),r.onerror=()=>n(ln("DATABASE_ERROR",`Failed to clear all data: ${r.error?.message}`))})}close(){this.db&&(this.db.close(),this.db=null,this.dbPromise=null)}}function U7(){return new OM}const Tc="1.0.0";class z7{storage;constructor(e){this.storage=e}async saveProject(e){await this.saveMediaBlobs(e);const t={...e,modifiedAt:Date.now()};await this.storage.saveProject(t)}async loadProject(e){const t=await this.storage.loadProject(e);return t?await this.restoreMediaBlobs(t):null}exportToJson(e){const t={version:Tc,project:this.stripMediaBlobs(e)};return JSON.stringify(t,null,2)}importFromJson(e){const t=JSON.parse(e);if(t.version!==Tc)return this.migrateProject(t);const i=t.project,n=i.mediaLibrary.items.map(r=>r.blob?r:{...r,isPlaceholder:!0,originalUrl:r.thumbnailUrl||void 0});return{...i,mediaLibrary:{items:n}}}exportToJsonWithMetadata(e,t){const i={version:Tc,project:this.stripMediaBlobs(e),metadata:{exportedAt:Date.now(),description:t}};return JSON.stringify(i,null,2)}validateProjectJson(e){const t={valid:!0,errors:[],warnings:[],missingAssets:[]};try{const i=JSON.parse(e);if(i.version?i.version!==Tc&&t.warnings.push(`Version mismatch: expected ${Tc}, got ${i.version}`):(t.errors.push("Missing version field"),t.valid=!1),!i.project)return t.errors.push("Missing project field"),t.valid=!1,t;const n=i.project;if(n.id||(t.errors.push("Missing project.id"),t.valid=!1),n.name||(t.errors.push("Missing project.name"),t.valid=!1),n.settings||(t.errors.push("Missing project.settings"),t.valid=!1),n.timeline||(t.errors.push("Missing project.timeline"),t.valid=!1),n.mediaLibrary||(t.errors.push("Missing project.mediaLibrary"),t.valid=!1),!t.valid)return t;const r=new Set(n.mediaLibrary.items.map(a=>a.id));for(const a of n.mediaLibrary.items)!a.blob&&!a.thumbnailUrl&&t.missingAssets.push(a.id);if(n.timeline.tracks){for(const a of n.timeline.tracks)if(a.clips)for(const o of a.clips){const c=o.mediaId&&(o.mediaId.startsWith("text-")||o.mediaId.startsWith("shape-")||o.mediaId.startsWith("svg-")||o.mediaId.startsWith("sticker-"));o.mediaId&&!c&&!r.has(o.mediaId)&&(t.errors.push(`Clip ${o.id} references non-existent mediaId: ${o.mediaId}`),t.valid=!1)}}t.missingAssets&&t.missingAssets.length>0&&t.warnings.push(`${t.missingAssets.length} asset(s) need replacement`)}catch(i){t.errors.push(`Invalid JSON: ${i instanceof Error?i.message:"Parse error"}`),t.valid=!1}return t}importFromJsonWithValidation(e){const t=this.validateProjectJson(e);return t.valid?{project:this.importFromJson(e),validation:t}:{project:null,validation:t}}async saveMediaBlobs(e){for(const t of e.mediaLibrary.items)if(t.blob){const i={id:t.id,projectId:e.id,blob:t.blob,metadata:t.metadata};await this.storage.saveMedia(i)}}async restoreMediaBlobs(e){const t=[];for(const i of e.mediaLibrary.items){const n=await this.storage.loadMedia(i.id);n?t.push({...i,blob:n.blob,metadata:n.metadata}):t.push(i)}return{...e,mediaLibrary:{items:t}}}stripMediaBlobs(e){const t=e.mediaLibrary.items.map(i=>({...i,blob:null,fileHandle:null,waveformData:null}));return{...e,mediaLibrary:{items:t}}}migrateProject(e){return e.project}async deleteProject(e){await this.storage.deleteProject(e)}async listProjects(){return this.storage.listProjects()}}function G7(s){return new z7(s)}const r_=["#8b5cf6","#ec4899","#f97316","#22c55e","#06b6d4","#3b82f6","#eab308","#ef4444"];function a_(){return`compound_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}class W7{compoundClips=new Map;instances=new Map;instancesByCompound=new Map;colorIndex=0;createCompoundClip(e,t,i={}){if(e.length===0)throw new Error("Cannot create compound clip from empty selection");const n=Math.min(...e.map(d=>d.startTime)),a=Math.max(...e.map(d=>d.startTime+d.duration))-n,o=e.map(d=>({...d,startTime:d.startTime-n})),c=new Set(e.map(d=>d.trackId)),l=t.filter(d=>c.has(d.id)),u={id:a_(),name:i.name||`Compound Clip ${this.compoundClips.size+1}`,content:{clips:o,tracks:l,duration:a},createdAt:Date.now(),modifiedAt:Date.now(),color:i.color||r_[this.colorIndex++%r_.length]};return this.compoundClips.set(u.id,u),this.instancesByCompound.set(u.id,new Set),u}getCompoundClip(e){return this.compoundClips.get(e)}getAllCompoundClips(){return Array.from(this.compoundClips.values())}updateCompoundClip(e,t){const i=this.compoundClips.get(e);return i?(this.compoundClips.set(e,{...i,content:t,modifiedAt:Date.now()}),!0):!1}renameCompoundClip(e,t){const i=this.compoundClips.get(e);return i?(this.compoundClips.set(e,{...i,name:t,modifiedAt:Date.now()}),!0):!1}deleteCompoundClip(e){const t=this.instancesByCompound.get(e);return t&&t.size>0?!1:(this.instancesByCompound.delete(e),this.compoundClips.delete(e))}createInstance(e,t,i){const n=this.compoundClips.get(e);if(!n)return null;const r={id:`instance_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,compoundClipId:e,trackId:t,startTime:i,duration:n.content.duration,inPoint:0,outPoint:n.content.duration,transform:{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},volume:1};return this.instances.set(r.id,r),this.instancesByCompound.get(e)?.add(r.id),r}getInstance(e){return this.instances.get(e)}getInstancesForCompound(e){const t=this.instancesByCompound.get(e);return t?Array.from(t).map(i=>this.instances.get(i)).filter(i=>i!==void 0):[]}getAllInstances(){return Array.from(this.instances.values())}updateInstance(e,t){const i=this.instances.get(e);return i?(this.instances.set(e,{...i,...t,id:i.id,compoundClipId:i.compoundClipId}),!0):!1}deleteInstance(e){const t=this.instances.get(e);return t?(this.instancesByCompound.get(t.compoundClipId)?.delete(e),this.instances.delete(e)):!1}flattenInstance(e){const t=this.instances.get(e);if(!t)return null;const i=this.compoundClips.get(t.compoundClipId);if(!i)return null;const n=i.content.clips.map(r=>({...r,id:`flat_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,startTime:t.startTime+r.startTime,trackId:t.trackId}));return this.deleteInstance(e),{clips:n,trackId:t.trackId,startTime:t.startTime}}duplicateCompoundClip(e,t){const i=this.compoundClips.get(e);if(!i)return null;const n={...i,id:a_(),name:t||`${i.name} (Copy)`,createdAt:Date.now(),modifiedAt:Date.now()};return this.compoundClips.set(n.id,n),this.instancesByCompound.set(n.id,new Set),n}getCompoundClipForInstance(e){const t=this.instances.get(e);if(t)return this.compoundClips.get(t.compoundClipId)}getInstanceCount(e){return this.instancesByCompound.get(e)?.size||0}clearAll(){this.compoundClips.clear(),this.instances.clear(),this.instancesByCompound.clear(),this.colorIndex=0}}const D1=["video/mp4","video/webm","video/quicktime","video/x-matroska"],F1=["audio/mpeg","audio/mp3","audio/wav","audio/ogg","audio/aac","audio/flac","audio/webm"],L1=["image/jpeg","image/png","image/webp","image/gif"];function O1(s){const e=s.split(";")[0].trim();return D1.includes(e)||F1.includes(e)||L1.includes(e)}function e0(s){const e=s.split(";")[0].trim();return D1.includes(e)?"video":F1.includes(e)?"audio":L1.includes(e)?"image":null}class q7{input=null;sink=null;mediabunny;file;width;initialized=!1;reusableCanvas=null;reusableCtx=null;constructor(e,t,i){this.mediabunny=e,this.file=t,this.width=i}async initialize(){if(this.initialized)return!0;const{Input:e,ALL_FORMATS:t,BlobSource:i,CanvasSink:n}=this.mediabunny;this.input=new e({source:new i(this.file),formats:t});const r=await this.input.getPrimaryVideoTrack();if(!r)return this.dispose(),!1;if(!await r.canDecode())return this.dispose(),!1;const o={poolSize:2};if(this.width){const c=r.displayHeight/r.displayWidth;o.width=this.width,o.height=Math.round(this.width*c),o.fit="contain"}return this.sink=new n(r,o),this.initialized=!0,!0}async getFrame(e){if(!this.sink)return null;const t=await this.sink.getCanvas(e);if(!t)return null;const i=t.canvas.width,n=t.canvas.height;return(!this.reusableCanvas||this.reusableCanvas.width!==i||this.reusableCanvas.height!==n)&&(this.reusableCanvas=new OffscreenCanvas(i,n),this.reusableCtx=this.reusableCanvas.getContext("2d")),this.reusableCtx.clearRect(0,0,i,n),this.reusableCtx.drawImage(t.canvas,0,0),this.reusableCanvas}dispose(){this.input&&(this.input[Symbol.dispose]?.(),this.input=null),this.sink=null,this.reusableCanvas=null,this.reusableCtx=null,this.initialized=!1}}class BM{initialized=!1;mediabunny=null;frameCache=new Map;MAX_CACHE_SIZE=5;exportDecoders=new Map;async initialize(){if(!this.initialized)try{this.mediabunny=await ii(()=>import("./index-DjtrfS0G.js"),[]),this.initialized=!0}catch{throw console.warn("MediaBunny not available, will use fallback"),new Error("MediaBunny initialization failed")}}isAvailable(){return this.initialized&&this.mediabunny!==null}clearFrameCache(){for(const e of this.frameCache.values())e.image instanceof OffscreenCanvas&&(e.image.width=0,e.image.height=0);this.frameCache.clear()}getFrameCacheSize(){return this.frameCache.size}async createExportDecoder(e,t,i){this.ensureInitialized();const n=this.exportDecoders.get(e);if(n)return n;const r=new q7(this.mediabunny,t,i);return await r.initialize()?(this.exportDecoders.set(e,r),r):null}getExportDecoder(e){return this.exportDecoders.get(e)||null}disposeExportDecoder(e){const t=this.exportDecoders.get(e);t&&(t.dispose(),this.exportDecoders.delete(e))}disposeAllExportDecoders(){for(const e of this.exportDecoders.values())e.dispose();this.exportDecoders.clear()}ensureInitialized(){if(!this.mediabunny)throw new Error("MediaBunny not initialized. Call initialize() first.")}async createInput(e){this.ensureInitialized();const{Input:t,ALL_FORMATS:i,BlobSource:n}=this.mediabunny;return new t({source:new n(e),formats:i})}async validateFormat(e){const t=e.type;if(!O1(t))return{supported:!1,format:null,error:`Unsupported format: ${t||"unknown"}. Supported formats: MP4, WebM, MOV, MP3, WAV, AAC, JPG, PNG, WebP`};if(t.startsWith("image/"))return{supported:!0,format:t};try{const i=await this.createInput(e),n=await i.getFormat();return i[Symbol.dispose]?.(),n?{supported:!0,format:t}:{supported:!1,format:null,error:"Could not determine file format. The file may be corrupted."}}catch(i){return{supported:!1,format:null,error:`Failed to parse file: ${i instanceof Error?i.message:"Unknown error"}`}}}async extractImageMetadata(e,t){const i=new Image,n=URL.createObjectURL(e);try{return await new Promise((r,a)=>{i.onload=()=>r(),i.onerror=()=>a(new Error("Failed to load image")),i.src=n}),{duration:0,width:i.naturalWidth,height:i.naturalHeight,frameRate:0,codec:"",sampleRate:0,channels:0,fileSize:e.size,mimeType:t,hasVideo:!1,hasAudio:!1,rotation:0,canDecode:!0,videoBitrate:0}}finally{URL.revokeObjectURL(n)}}async extractMetadata(e){const t=e instanceof File?e.type:"";if(t.startsWith("image/"))return await this.extractImageMetadata(e,t);const i=await this.createInput(e);try{const n=await i.computeDuration(),r=await i.getMimeType(),a=await i.getPrimaryVideoTrack(),o=await i.getPrimaryAudioTrack();let c=0,l=0,u=0,d="",h=0,f=!1,p=0;if(a){c=a.displayWidth,l=a.displayHeight,h=a.rotation||0,d=a.codec||"",f=await a.canDecode();try{const k=await a.computePacketStats(100);u=k.averagePacketRate||30,p=k.averageBitrate||0}catch{u=30}}let m=0,g=0,v="",w=!1,b=0;o&&(m=o.sampleRate,g=o.numberOfChannels,v=o.codec||"",w=await o.canDecode());try{b=(await i.getAudioTracks()).length}catch{b=o?1:0}return{duration:n,width:c,height:l,frameRate:u,codec:d||v,sampleRate:m,channels:g,fileSize:e.size,mimeType:r,hasVideo:!!a,hasAudio:!!o,rotation:h,canDecode:f||w,videoBitrate:p,audioTrackCount:b}}finally{i[Symbol.dispose]?.()}}async generateThumbnails(e,t=5,i=320){this.ensureInitialized();const{CanvasSink:n}=this.mediabunny,r=await this.createInput(e);try{const a=await r.getPrimaryVideoTrack();if(!a)return[];if(!await a.canDecode())throw new Error("Cannot decode video track");const c=a.displayHeight/a.displayWidth,l=Math.round(i*c),u=new n(a,{width:i,height:l,fit:"contain",poolSize:Math.min(t,10)}),d=await a.getFirstTimestamp(),f=await a.computeDuration()-d,p=t===1?[d]:Array.from({length:t},(g,v)=>d+v/(t-1)*f),m=[];for await(const g of u.canvasesAtTimestamps(p))if(g){const v=new OffscreenCanvas(g.canvas.width,g.canvas.height),w=v.getContext("2d");w&&w.drawImage(g.canvas,0,0);let b;try{const k=await v.convertToBlob({type:"image/jpeg",quality:.7});b=URL.createObjectURL(k)}catch{}m.push({timestamp:g.timestamp,canvas:v,dataUrl:b})}return m}finally{r[Symbol.dispose]?.()}}async generateFilmstripThumbnails(e,t,i=80,n=1){this.ensureInitialized();const{CanvasSink:r}=this.mediabunny,a=await this.createInput(e);try{const o=await a.getPrimaryVideoTrack();if(!o)return[];if(!await o.canDecode())throw new Error("Cannot decode video track");const l=o.displayHeight/o.displayWidth,u=Math.round(i*l),d=Math.max(1,Math.ceil(t/n)),h=new r(o,{width:i,height:u,fit:"cover",poolSize:Math.min(d,20)}),f=await o.getFirstTimestamp(),p=Array.from({length:d},(g,v)=>f+v*n),m=[];for await(const g of h.canvasesAtTimestamps(p))if(g){const v=new OffscreenCanvas(g.canvas.width,g.canvas.height),w=v.getContext("2d");w&&w.drawImage(g.canvas,0,0);let b;try{const k=await v.convertToBlob({type:"image/jpeg",quality:.6});b=URL.createObjectURL(k)}catch{}m.push({timestamp:g.timestamp,canvas:v,dataUrl:b})}return m}finally{a[Symbol.dispose]?.()}}async getFrameAtTime(e,t,i){this.ensureInitialized();const{CanvasSink:n}=this.mediabunny,a=`${"name"in e?e.name:"blob"}-${e.size}-${t}-${i||"auto"}`,o=this.frameCache.get(a);if(o)return o.lastAccessed=Date.now(),{timestamp:o.timestamp,duration:0,canvas:o.image,width:o.width,height:o.height};const c=await this.createInput(e);try{const l=await c.getPrimaryVideoTrack();if(!l)return null;if(!await l.canDecode())throw new Error("Cannot decode video track");const d={poolSize:1};if(i){const g=l.displayHeight/l.displayWidth;d.width=i,d.height=Math.round(i*g),d.fit="contain"}const f=await new n(l,d).getCanvas(t);if(!f)return null;const p=new OffscreenCanvas(f.canvas.width,f.canvas.height),m=p.getContext("2d");if(m&&m.drawImage(f.canvas,0,0),this.frameCache.size>=this.MAX_CACHE_SIZE){let g="",v=1/0;for(const[w,b]of this.frameCache.entries())b.lastAccessedp/t);for await(const f of o.samplesAtTimestamps(h)){if(!f){u.push(0),d.push(0);continue}const p=f.allocationSize({format:"f32",planeIndex:0}),m=new Float32Array(p/4);f.copyTo(m,{format:"f32",planeIndex:0});let g=0,v=0;for(let w=0;wD.reason).join(", ");throw new Error(`Conversion invalid: ${I}`)}if(A.discardedTracks.length>0&&console.warn("Some tracks were discarded during conversion:",A.discardedTracks),i){let I=0;A.onProgress=D=>{D>I&&(I=D,i({phase:D<1?"encoding":"complete",progress:D,currentFrame:0,totalFrames:0,estimatedTimeRemaining:0}))}}n&&n.addEventListener("abort",()=>{A.cancel()});try{await A.execute()}catch(I){throw n?.aborted?new DOMException("Aborted","AbortError"):I}const M=b.target.buffer;if(!M)throw new Error("Output buffer is empty");const R=this.getMimeTypeForFormat(t.format);return new Blob([M],{type:R})}async extractAudio(e,t="mp3",i,n){return this.convertMedia(e,{format:t,audioBitrate:128e3,sampleRate:48e3,channels:2},i,n)}async trimMedia(e,t,i,n,r,a){this.ensureInitialized();const{Input:o,Output:c,Conversion:l,ALL_FORMATS:u,BlobSource:d,BufferTarget:h,Mp4OutputFormat:f}=this.mediabunny;if(a?.aborted)throw new DOMException("Aborted","AbortError");const p=new o({source:new d(e),formats:u}),m=new c({format:new f({fastStart:"in-memory"}),target:new h}),g=await l.init({input:p,output:m,trim:{start:t,end:i},...n?.videoBitrate&&{video:{bitrate:n.videoBitrate}},...n?.audioBitrate&&{audio:{bitrate:n.audioBitrate}}});if(!g.isValid){const v=g.discardedTracks.map(w=>w.reason).join(", ");throw new Error(`Trim conversion invalid: ${v}`)}r&&(g.onProgress=v=>{r({phase:v<1?"encoding":"complete",progress:v,currentFrame:0,totalFrames:0,estimatedTimeRemaining:0})}),a&&a.addEventListener("abort",()=>{g.cancel()});try{await g.execute()}catch(v){throw a?.aborted?new DOMException("Aborted","AbortError"):v}if(!m.target.buffer)throw new Error("Output buffer is empty");return new Blob([m.target.buffer],{type:"video/mp4"})}getMimeTypeForFormat(e){switch(e){case"mp4":return"video/mp4";case"webm":return"video/webm";case"mov":return"video/quicktime";case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"aac":return"audio/aac";default:return"video/mp4"}}async checkCodecSupport(){this.ensureInitialized();const{getEncodableVideoCodecs:e,getEncodableAudioCodecs:t}=this.mediabunny,[i,n]=await Promise.all([e(),t()]);return{video:i,audio:n}}async getBestVideoCodec(e,t){this.ensureInitialized();const{getFirstEncodableVideoCodec:i,Mp4OutputFormat:n}=this.mediabunny,a=new n().getSupportedVideoCodecs();try{return await i(a,{width:e,height:t})||null}catch{return null}}async exportFrame(e,t,i="image/jpeg",n=.8){const r=await this.getFrameAtTime(e,t);if(!r)throw new Error("Could not extract frame");const{canvas:a}=r;let o=null;if(a instanceof OffscreenCanvas)o=await a.convertToBlob({type:i,quality:n});else if(a instanceof HTMLCanvasElement)o=await new Promise(c=>a.toBlob(c,i,n));else if(a instanceof ImageBitmap){const c=new OffscreenCanvas(a.width,a.height),l=c.getContext("2d");l&&(l.drawImage(a,0,0),o=await c.convertToBlob({type:i,quality:n}))}if(!o)throw new Error("Failed to create image blob");return o}async generateProxy(e,t,i){const n={format:"mp4",height:540,videoBitrate:1e6,audioBitrate:96e3};return this.convertMedia(e,n,t,i)}async exportImageSequence(e,t,i,n,r="image/jpeg",a=.8,o,c){this.ensureInitialized();const{CanvasSink:l}=this.mediabunny,u=await this.createInput(e);try{const d=await u.getPrimaryVideoTrack();if(!d)throw new Error("No video track found");if(!await d.canDecode())throw new Error("Cannot decode video track");const f=i-t,p=Math.ceil(f*n),m=Array.from({length:p},(b,k)=>t+k/n),g=new l(d,{fit:"contain",poolSize:5}),v=[];let w=0;for await(const b of g.canvasesAtTimestamps(m)){if(c?.aborted)throw new DOMException("Aborted","AbortError");if(b){const{canvas:k}=b;let A=null;k instanceof OffscreenCanvas&&(A=await k.convertToBlob({type:r,quality:a})),A&&v.push(A)}w++,o?.(w/p)}return v}finally{u[Symbol.dispose]?.()}}async getBestAudioCodec(){this.ensureInitialized();const{getFirstEncodableAudioCodec:e,Mp4OutputFormat:t}=this.mediabunny,n=new t().getSupportedAudioCodecs();try{return await e(n)||null}catch{return null}}}let Sp=null;function sa(){return Sp||(Sp=new BM),Sp}const rh={low:{scale:.25,preset:"ultrafast",crf:32,audioBitrate:96,maxWidth:960,maxHeight:540},medium:{scale:.5,preset:"fast",crf:28,audioBitrate:128,maxWidth:1280,maxHeight:720},high:{scale:.75,preset:"medium",crf:23,audioBitrate:192,maxWidth:1920,maxHeight:1080}},ao={minPixelCount:3840*2160,minDuration:600,minFileSize:500*1024*1024},H7={format:"webm",videoCodec:"libvpx-vp9",audioCodec:"libopus",videoBitrate:"2M",audioBitrate:"128k",enableRowMt:!0};class B1{ffmpeg=null;loaded=!1;loading=null;progressCallback=null;calculateBufsize(e){const t=e.match(/^(\d+(?:\.\d+)?)\s*([KkMmGg]?)$/);if(!t)return e;const i=parseFloat(t[1]),n=t[2]||"";return`${Math.round(i*2)}${n}`}async load(){if(!this.loaded){if(this.loading)return this.loading;this.loading=this.doLoad(),await this.loading}}async doLoad(){try{const{FFmpeg:e}=await ii(async()=>{const{FFmpeg:r}=await import("./index-DfgTfcu_.js");return{FFmpeg:r}},[]),{toBlobURL:t}=await ii(async()=>{const{toBlobURL:r}=await import("./index-CiM7N5zy.js");return{toBlobURL:r}},[]);this.ffmpeg=new e;const i=typeof crossOriginIsolated<"u"&&crossOriginIsolated,n=i?"https://unpkg.com/@ffmpeg/core-mt@0.12.6/dist/esm":"https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm";if(i){const[r,a,o]=await Promise.all([t(`${n}/ffmpeg-core.js`,"text/javascript"),t(`${n}/ffmpeg-core.wasm`,"application/wasm"),t(`${n}/ffmpeg-core.worker.js`,"text/javascript")]);await this.ffmpeg.load({coreURL:r,wasmURL:a,workerURL:o})}else{const[r,a]=await Promise.all([t(`${n}/ffmpeg-core.js`,"text/javascript"),t(`${n}/ffmpeg-core.wasm`,"application/wasm")]);await this.ffmpeg.load({coreURL:r,wasmURL:a})}this.loaded=!0}catch(e){throw this.loading=null,console.error("[FFmpeg] Load error:",e),new Error(`Failed to load FFmpeg.wasm: ${e instanceof Error?e.message:"Unknown error"}`)}}isLoaded(){return this.loaded&&this.ffmpeg!==null}ensureLoaded(){if(!this.ffmpeg||!this.loaded)throw new Error("FFmpeg not loaded. Call load() first.")}async fileToUint8Array(e){const t=await e.arrayBuffer();return new Uint8Array(t)}async cleanupFiles(e){if(this.ffmpeg)for(const t of e)try{await this.ffmpeg.deleteFile(t)}catch{}}setupProgressTracking(e,t){!this.ffmpeg||!e||(this.progressCallback&&this.ffmpeg.off("progress",this.progressCallback),this.progressCallback=({progress:i,time:n})=>{const r=i??0;let a=0;if(t&&n&&r>0){const c=n/1e6/r;a=(1-r)*c}e({phase:r<1?"encoding":"complete",progress:Math.min(r,1),currentFrame:0,totalFrames:0,estimatedTimeRemaining:a,bytesWritten:0,currentBitrate:0})},this.ffmpeg.on("progress",this.progressCallback))}removeProgressTracking(){!this.ffmpeg||!this.progressCallback||(this.ffmpeg.off("progress",this.progressCallback),this.progressCallback=null)}async transcodeToCompatible(e,t,i={}){await this.load(),this.ensureLoaded();const n={...H7,...i},r="input",a=`output.${n.format}`;try{const o=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(r,o),this.setupProgressTracking(t);const c=["-i",r];c.push("-c:v",n.videoCodec),c.push("-b:v",n.videoBitrate),n.videoCodec==="libvpx-vp9"&&n.enableRowMt&&c.push("-row-mt","1"),c.push("-c:a",n.audioCodec),c.push("-b:a",n.audioBitrate),c.push(a),await this.ffmpeg.exec(c);const l=await this.ffmpeg.readFile(a),u=n.format==="webm"?"video/webm":"video/mp4";return new Blob([l.buffer],{type:u})}finally{this.removeProgressTracking(),await this.cleanupFiles([r,a])}}async transcodeToMp4(e,t){return this.transcodeToCompatible(e,t,{format:"mp4",videoCodec:"libx264",audioCodec:"aac",videoBitrate:"5M",audioBitrate:"192k"})}async extractAudioAsWav(e,t,i={}){await this.load(),this.ensureLoaded();const n="input",r="output.wav";try{const a=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(n,a),this.setupProgressTracking(i.onProgress);const o=["-i",n];t!==void 0?o.push("-map",`0:a:${t}`):o.push("-vn"),o.push("-acodec","pcm_f32le","-ar","48000","-ac","2",r),await this.ffmpeg.exec(o);const c=await this.ffmpeg.readFile(r);return new Blob([c.buffer],{type:"audio/wav"})}finally{this.removeProgressTracking(),await this.cleanupFiles([n,r])}}async generateProxy(e,t={},i){await this.load(),this.ensureLoaded();const n={...rh.medium,...t},r="input",a="proxy.mp4";try{const o=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(r,o),this.setupProgressTracking(i);let c;n.maxWidth&&n.maxHeight?c=`scale='min(${n.maxWidth},iw*${n.scale})':'min(${n.maxHeight},ih*${n.scale})':force_original_aspect_ratio=decrease`:c=`scale=iw*${n.scale}:ih*${n.scale}`,c+=",pad=ceil(iw/2)*2:ceil(ih/2)*2",await this.ffmpeg.exec(["-i",r,"-vf",c,"-c:v","libx264","-preset",n.preset,"-crf",n.crf.toString(),"-c:a","aac","-b:a",`${n.audioBitrate}k`,"-movflags","+faststart",a]);const l=await this.ffmpeg.readFile(a);return new Blob([l.buffer],{type:"video/mp4"})}finally{this.removeProgressTracking(),await this.cleanupFiles([r,a])}}async generateProxyWithPreset(e,t,i){return this.generateProxy(e,rh[t],i)}async extractRange(e,t,i,n){await this.load(),this.ensureLoaded();const r="input",a="output.mp4",o=i-t;try{const c=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(r,c),this.setupProgressTracking(n,o),await this.ffmpeg.exec(["-ss",t.toString(),"-i",r,"-t",o.toString(),"-c:v","libx264","-preset","fast","-c:a","aac","-movflags","+faststart",a]);const l=await this.ffmpeg.readFile(a);return new Blob([l.buffer],{type:"video/mp4"})}finally{this.removeProgressTracking(),await this.cleanupFiles([r,a])}}async getMetadata(e){await this.load(),this.ensureLoaded();const t="input";try{const i=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(t,i);try{await this.ffmpeg.exec(["-i",t,"-f","null","-"])}catch{}return{duration:0,width:0,height:0,hasVideo:!0,hasAudio:!0}}finally{await this.cleanupFiles([t])}}async probeAudioStreams(e){await this.load(),this.ensureLoaded();const t=`probe_${Date.now()}`,i=[],n=r=>{r.message&&i.push(r.message)};try{const r=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(t,r),this.ffmpeg.on("log",n);try{await this.ffmpeg.exec(["-i",t,"-hide_banner"])}catch{}this.ffmpeg.off("log",n);const a=[],o=/Stream #\d+:(\d+).*?: Audio: (\w+)/,c=/(\d+) Hz/,l=/(mono|stereo|5\.1|7\.1|(\d+) channels)/;for(const u of i){const d=u.match(o);if(!d)continue;const h=parseInt(d[1],10),f=d[2],p=u.match(c),m=p?parseInt(p[1],10):0,g=u.match(l);let v=2,w="stereo";g&&(w=g[1],w==="mono"?v=1:w==="stereo"?v=2:w==="5.1"?v=6:w==="7.1"?v=8:g[2]&&(v=parseInt(g[2],10))),a.push({index:h,codec:f,sampleRate:m,channels:v,channelLayout:w})}return{audioStreamCount:a.length,streams:a}}finally{this.ffmpeg.off("log",n),await this.cleanupFiles([t])}}shouldUseProxy(e){return e.width*e.height>=ao.minPixelCount||e.duration>=ao.minDuration||e.fileSize!==void 0&&e.fileSize>=ao.minFileSize}getRecommendedProxyPreset(e){const t=e.width*e.height;return t>=7680*4320?"low":t>=3840*2160?"medium":"high"}async convertAudio(e,t,i={}){await this.load(),this.ensureLoaded();const n="input",r=`output.${t}`;try{const a=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(n,a);const o=["-i",n,"-vn"];switch(t){case"mp3":o.push("-c:a","libmp3lame");break;case"wav":o.push("-c:a","pcm_s16le");break;case"aac":o.push("-c:a","aac");break;case"ogg":o.push("-c:a","libvorbis");break}i.bitrate&&o.push("-b:a",i.bitrate),i.sampleRate&&o.push("-ar",i.sampleRate.toString()),i.channels&&o.push("-ac",i.channels.toString()),o.push(r),await this.ffmpeg.exec(o);const c=await this.ffmpeg.readFile(r),l={mp3:"audio/mpeg",wav:"audio/wav",aac:"audio/aac",ogg:"audio/ogg"};return new Blob([c.buffer],{type:l[t]})}finally{await this.cleanupFiles([n,r])}}async extractFrame(e,t,i="jpg"){await this.load(),this.ensureLoaded();const n="input",r=`frame.${i}`;try{const a=await this.fileToUint8Array(e);await this.ffmpeg.writeFile(n,a),await this.ffmpeg.exec(["-ss",t.toString(),"-i",n,"-vframes","1","-q:v","2",r]);const o=await this.ffmpeg.readFile(r),c=i==="png"?"image/png":"image/jpeg";return new Blob([o.buffer],{type:c})}finally{await this.cleanupFiles([n,r])}}async encodeFrameSequence(e,t,i){await this.load(),this.ensureLoaded();const{width:n,height:r,frameRate:a,totalFrames:o,format:c="mp4",videoBitrate:l="10M",audioBitrate:u="192k",audioBuffer:d,writableStream:h}=t,f=`output.${c}`;let p=0;try{for await(const{image:k,frameIndex:A}of e){const M=new OffscreenCanvas(n,r),R=M.getContext("2d");R.fillStyle="#000000",R.fillRect(0,0,n,r),R.drawImage(k,0,0,n,r);const D=await(await M.convertToBlob({type:"image/jpeg",quality:.95})).arrayBuffer(),B=new Uint8Array(D),V=`frame_${String(A).padStart(6,"0")}.jpg`;await this.ffmpeg.writeFile(V,B),p++,k.close(),i&&i({phase:"rendering",progress:p/o*.7,currentFrame:p,totalFrames:o,estimatedTimeRemaining:0,bytesWritten:0,currentBitrate:0}),p%10===0&&await new Promise(y=>setTimeout(y,10))}let g=!1;if(d&&d.length>0){const k=this.encodeAudioBufferToWav(d),A=new Uint8Array(await k.arrayBuffer());A.length>44&&(await this.ffmpeg.writeFile("audio.wav",A),g=!0)}i&&i({phase:"encoding",progress:.7,currentFrame:o,totalFrames:o,estimatedTimeRemaining:0,bytesWritten:0,currentBitrate:0});const v=["-framerate",a.toString(),"-i","frame_%06d.jpg"];g&&v.push("-i","audio.wav"),v.push("-threads","4"),c==="mp4"?v.push("-c:v","libx264","-preset","fast","-crf","23","-maxrate",l,"-bufsize",this.calculateBufsize(l),"-pix_fmt","yuv420p"):v.push("-c:v","libvpx-vp9","-crf","31","-b:v","0","-deadline","good","-cpu-used","4","-row-mt","1"),g&&v.push("-c:a",c==="mp4"?"aac":"libopus","-b:a",u),v.push("-movflags","+faststart","-y",f),this.setupProgressTracking(k=>{i&&i({phase:"encoding",progress:.7+k.progress*.25,currentFrame:o,totalFrames:o,estimatedTimeRemaining:k.estimatedTimeRemaining,bytesWritten:0,currentBitrate:0})}),await this.ffmpeg.exec(v),this.removeProgressTracking(),i&&i({phase:"muxing",progress:.95,currentFrame:o,totalFrames:o,estimatedTimeRemaining:0,bytesWritten:0,currentBitrate:0});const w=await this.ffmpeg.readFile(f),b=c==="mp4"?"video/mp4":"video/webm";if(h){const A=w.buffer;for(let M=0;M{for(let v=0;v0&&w.push("-ss",n.toString()),w.push("-i",m),r!==void 0&&r>n&&w.push("-t",(r-n).toString()),w.push("-threads","4"),h!==1||!p){const M=`scale=${a}:${o}:force_original_aspect_ratio=decrease,pad=${a}:${o}:(ow-iw)/2:(oh-ih)/2,fps=${c}`;if(h!==1&&h>0){const R=1/h,I=Math.max(.5,Math.min(2,h));w.push("-filter_complex",`[0:v]${M},setpts=${R}*PTS[v];[0:a]atempo=${I}[a]`,"-map","[v]","-map","[a]")}else w.push("-vf",M);l==="mp4"?w.push("-c:v","libx264","-preset","fast","-crf","23","-maxrate",u,"-bufsize",this.calculateBufsize(u),"-pix_fmt","yuv420p","-c:a","aac","-b:a",d):w.push("-c:v","libvpx-vp9","-crf","31","-b:v","0","-deadline","good","-cpu-used","4","-row-mt","1","-c:a","libopus","-b:a",d)}else w.push("-c","copy");w.push("-movflags","+faststart","-y",g),this.setupProgressTracking(M=>{i&&i({phase:"encoding",progress:.1+M.progress*.85,currentFrame:0,totalFrames:0,estimatedTimeRemaining:M.estimatedTimeRemaining,bytesWritten:0,currentBitrate:0})}),await this.ffmpeg.exec(w),this.removeProgressTracking();const k=await this.ffmpeg.readFile(g),A=l==="mp4"?"video/mp4":"video/webm";if(f){const R=k.buffer;for(let I=0;I"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ep=crypto.getRandomValues.bind(crypto)}return Ep(K7)}const J7=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),o_={randomUUID:J7};function Z7(s,e,t){s=s||{};const i=s.random??s.rng?.()??Q7();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,X7(i)}function ve(s,e,t){return o_.randomUUID&&!s?o_.randomUUID():Z7(s)}const eG={generateThumbnails:!0,thumbnailCount:5,thumbnailWidth:320,generateWaveform:!0,waveformSamplesPerSecond:100,useFallback:!0,quickMode:!1};class $M{mediaEngine;ffmpegFallback;initialized=!1;constructor(e,t){this.mediaEngine=e||sa(),this.ffmpegFallback=t||$1()}async initialize(){if(!this.initialized)try{await this.mediaEngine.initialize(),this.initialized=!0}catch{console.warn("MediaBunny initialization failed, will use fallback only"),this.initialized=!0}}async importMedia(e,t={}){const i={...eG,...t},n=[],r=await this.validateFormat(e);if(!r.supported){if(i.useFallback)try{return await this.importWithFallback(e,i)}catch(a){return{success:!1,error:r.error||"Unsupported format",warnings:[`FFmpeg fallback also failed: ${a instanceof Error?a.message:"Unknown error"}`]}}return{success:!1,error:r.error||"Unsupported format"}}try{const a=await this.mediaEngine.extractMetadata(e),o=e0(e.type);if(!o)return{success:!1,error:"Could not determine media type"};if(a.hasAudio&&(a.audioTrackCount===void 0||a.audioTrackCount<=1))try{const h=await this.ffmpegFallback.probeAudioStreams(e);h.audioStreamCount>1&&(a.audioTrackCount=h.audioStreamCount)}catch{}if((!a.canDecode||e.type==="video/quicktime"&&!await this.canBrowserPlay(e))&&(a.canDecode||n.push("Codec may not be fully supported. Playback might be limited."),i.useFallback))try{return await this.importWithFallback(e,i,{format:"mp4",videoCodec:"libx264",audioCodec:"aac",videoBitrate:"5M",audioBitrate:"192k"})}catch{}let l=[];if(i.generateThumbnails&&!i.quickMode){if(o==="video"&&a.hasVideo)try{l=await this.mediaEngine.generateThumbnails(e,i.thumbnailCount,i.thumbnailWidth)}catch(h){n.push(`Thumbnail generation failed: ${h instanceof Error?h.message:"Unknown error"}`)}else if(o==="image")try{const h=new Image,f=URL.createObjectURL(e);await new Promise((b,k)=>{h.onload=()=>{URL.revokeObjectURL(f),b()},h.onerror=()=>{URL.revokeObjectURL(f),k(new Error("Failed to load image"))},h.src=f});const p=document.createElement("canvas"),m=i.thumbnailWidth||320,g=h.height/h.width,v=Math.round(m*g);p.width=m,p.height=v;const w=p.getContext("2d");if(w){w.drawImage(h,0,0,m,v);const b=p.toDataURL("image/jpeg",.8);l=[{timestamp:0,canvas:p,dataUrl:b}]}}catch(h){n.push(`Image thumbnail generation failed: ${h instanceof Error?h.message:"Unknown error"}`)}}let u=null;if(i.generateWaveform&&a.hasAudio&&!i.quickMode)try{u=await this.mediaEngine.generateWaveform(e,i.waveformSamplesPerSecond)}catch(h){n.push(`Waveform generation failed: ${h instanceof Error?h.message:"Unknown error"}`)}return{success:!0,media:{id:ve(),name:e.name,type:o,blob:e,metadata:a,thumbnails:l,waveformData:u},warnings:n.length>0?n:void 0}}catch(a){if(i.useFallback)try{return await this.importWithFallback(e,i)}catch(o){return{success:!1,error:`Import failed: ${a instanceof Error?a.message:"Unknown error"}`,warnings:[`FFmpeg fallback also failed: ${o instanceof Error?o.message:"Unknown error"}`]}}return{success:!1,error:`Import failed: ${a instanceof Error?a.message:"Unknown error"}`}}}canBrowserPlay(e){return new Promise(t=>{const i=document.createElement("video"),n=URL.createObjectURL(e),r=setTimeout(()=>{a(),t(!1)},3e3),a=()=>{clearTimeout(r),i.removeAttribute("src"),i.load(),URL.revokeObjectURL(n)};i.onloadedmetadata=()=>{a(),t(!0)},i.onerror=()=>{a(),t(!1)},i.src=n})}async importWithFallback(e,t,i){const n=await this.ffmpegFallback.transcodeToCompatible(e,void 0,i),r=i?.format||"webm",a=r==="mp4"?".mp4":".webm",o=r==="mp4"?"video/mp4":"video/webm",c=new File([n],e.name.replace(/\.[^.]+$/,a),{type:o}),l=await this.mediaEngine.extractMetadata(c),u=e0(c.type)||"video";if(l.audioTrackCount===void 0||l.audioTrackCount<=1)try{const p=await this.ffmpegFallback.probeAudioStreams(e);p.audioStreamCount>1&&(l.audioTrackCount=p.audioStreamCount)}catch{}let d=[];if(t.generateThumbnails&&l.hasVideo)try{d=await this.mediaEngine.generateThumbnails(c,t.thumbnailCount,t.thumbnailWidth)}catch{}let h=null;if(t.generateWaveform&&l.hasAudio)try{h=await this.mediaEngine.generateWaveform(c,t.waveformSamplesPerSecond)}catch{}return{success:!0,media:{id:ve(),name:e.name,type:u,blob:c,metadata:l,thumbnails:d,waveformData:h},warnings:["File was transcoded using FFmpeg fallback"]}}async validateFormat(e){return O1(e.type)?this.mediaEngine.isAvailable()?this.mediaEngine.validateFormat(e):{supported:!0,format:e.type}:{supported:!1,format:null,error:`Unsupported format: ${e.type||"unknown"}. Supported formats: MP4, WebM, MOV, MP3, WAV, AAC, JPG, PNG, WebP`}}processedMediaToMediaItem(e,t){const i={duration:e.metadata.duration,width:e.metadata.width,height:e.metadata.height,frameRate:e.metadata.frameRate,codec:e.metadata.codec,sampleRate:e.metadata.sampleRate,channels:e.metadata.channels,fileSize:e.metadata.fileSize,audioTrackCount:e.metadata.audioTrackCount};return{id:e.id,name:e.name,type:e.type,fileHandle:null,blob:e.blob,metadata:i,thumbnailUrl:t||null,waveformData:e.waveformData?.peaks||null}}async importMultiple(e,t={},i){const n=[];for(let r=0;r{a.onload=()=>{URL.revokeObjectURL(o),h()},a.onerror=()=>{URL.revokeObjectURL(o),f(new Error("Failed to load image"))},a.src=o});const c=document.createElement("canvas"),l=a.height/a.width,u=Math.round(r*l);c.width=r,c.height=u;const d=c.getContext("2d");if(d){d.drawImage(a,0,0,r,u);const h=c.toDataURL("image/jpeg",.8);return[{timestamp:0,canvas:c,dataUrl:h}]}}return[]}async generateWaveformForMedia(e,t=100){return this.initialized||await this.initialize(),this.mediaEngine.generateWaveform(e,t)}}let Mp=null;function jM(){return Mp||(Mp=new $M),Mp}async function NM(){const s=jM();return await s.initialize(),s}const ol={OVERVIEW:10,MEDIUM:100,HIGH:200},tG={samplesPerSecond:ol.MEDIUM,enableCaching:!0};class VM{mediaEngine;storageEngine=null;memoryCache=new Map;MAX_MEMORY_CACHE_SIZE=20;constructor(e,t){this.mediaEngine=e||sa(),this.storageEngine=t||null}setStorageEngine(e){this.storageEngine=e}async generateWaveform(e,t,i={}){const n={...tG,...i},r=this.memoryCache.get(t);if(r&&r.data.samplesPerSecond===n.samplesPerSecond)return r.data;if(n.enableCaching&&this.storageEngine){const o=await this.loadFromCache(t);if(o&&o.samplesPerSecond===n.samplesPerSecond)return this.updateMemoryCache(t,o),o}const a=await this.mediaEngine.generateWaveform(e,n.samplesPerSecond);return n.enableCaching&&await this.saveToCache(t,a),this.updateMemoryCache(t,a),a}async generateMultiResolutionWaveform(e,t,i=[ol.OVERVIEW,ol.MEDIUM,ol.HIGH]){const n={mediaId:t,duration:0,resolutions:new Map},r=[...i].sort((c,l)=>l-c),a=r[0],o=await this.generateWaveform(e,t,{samplesPerSecond:a,enableCaching:!0});n.duration=o.duration,n.resolutions.set(a,o);for(let c=1;c(n?.samplesPerSecond||0))&&(r=c,n=o)}return n}downsampleWaveform(e,t){if(t>=e.samplesPerSecond)return e;const i=e.samplesPerSecond/t,n=Math.ceil(e.peaks.length/i),r=new Float32Array(n),a=new Float32Array(n);for(let o=0;o0?Math.sqrt(d/h):0}return{peaks:r,rms:a,sampleRate:t,duration:e.duration,samplesPerSecond:t}}getWaveformSlice(e,t,i){const n=Math.max(0,Math.floor(t*e.samplesPerSecond)),r=Math.min(e.peaks.length,Math.ceil(i*e.samplesPerSecond));return{peaks:e.peaks.slice(n,r),rms:e.rms.slice(n,r),sampleRate:e.sampleRate,duration:i-t,samplesPerSecond:e.samplesPerSecond}}async loadFromCache(e){if(!this.storageEngine)return null;try{const t=await this.storageEngine.loadWaveform(e);return t?this.waveformRecordToData(t):null}catch(t){return console.warn("Failed to load waveform from cache:",t),null}}async saveToCache(e,t){if(this.storageEngine)try{const i=this.waveformDataToRecord(e,t);await this.storageEngine.saveWaveform(i)}catch(i){console.warn("Failed to save waveform to cache:",i)}}waveformRecordToData(e){const t=e.data.length/2,i=new Float32Array(t),n=new Float32Array(t);for(let a=0;a=this.MAX_MEMORY_CACHE_SIZE){let i="",n=1/0;for(const[r,a]of this.memoryCache.entries())a.createdAtc+l,0)}}catch{return null}}function i0(s,e){if(s.frames.length<=1)return 0;const t=e%s.totalDuration;let i=0;for(let n=0;ns<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375,Ss={linear:s=>s,easeInQuad:s=>s*s,easeOutQuad:s=>1-(1-s)*(1-s),easeInOutQuad:s=>s<.5?2*s*s:1-Math.pow(-2*s+2,2)/2,easeInCubic:s=>s*s*s,easeOutCubic:s=>1-Math.pow(1-s,3),easeInOutCubic:s=>s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,easeInQuart:s=>s*s*s*s,easeOutQuart:s=>1-Math.pow(1-s,4),easeInOutQuart:s=>s<.5?8*s*s*s*s:1-Math.pow(-2*s+2,4)/2,easeInQuint:s=>s*s*s*s*s,easeOutQuint:s=>1-Math.pow(1-s,5),easeInOutQuint:s=>s<.5?16*s*s*s*s*s:1-Math.pow(-2*s+2,5)/2,easeInSine:s=>1-Math.cos(s*cl/2),easeOutSine:s=>Math.sin(s*cl/2),easeInOutSine:s=>-(Math.cos(cl*s)-1)/2,easeInExpo:s=>s===0?0:Math.pow(2,10*s-10),easeOutExpo:s=>s===1?1:1-Math.pow(2,-10*s),easeInOutExpo:s=>s===0?0:s===1?1:s<.5?Math.pow(2,20*s-10)/2:(2-Math.pow(2,-20*s+10))/2,easeInCirc:s=>1-Math.sqrt(1-Math.pow(s,2)),easeOutCirc:s=>Math.sqrt(1-Math.pow(s-1,2)),easeInOutCirc:s=>s<.5?(1-Math.sqrt(1-Math.pow(2*s,2)))/2:(Math.sqrt(1-Math.pow(-2*s+2,2))+1)/2,easeInBack:s=>c_*s*s*s-ah*s*s,easeOutBack:s=>1+c_*Math.pow(s-1,3)+ah*Math.pow(s-1,2),easeInOutBack:s=>s<.5?Math.pow(2*s,2)*((Bu+1)*2*s-Bu)/2:(Math.pow(2*s-2,2)*((Bu+1)*(s*2-2)+Bu)+2)/2,easeInElastic:s=>s===0?0:s===1?1:-Math.pow(2,10*s-10)*Math.sin((s*10-10.75)*l_),easeOutElastic:s=>s===0?0:s===1?1:Math.pow(2,-10*s)*Math.sin((s*10-.75)*l_)+1,easeInOutElastic:s=>s===0?0:s===1?1:s<.5?-(Math.pow(2,20*s-10)*Math.sin((20*s-11.125)*u_))/2:Math.pow(2,-20*s+10)*Math.sin((20*s-11.125)*u_)/2+1,easeInBounce:s=>1-$u(1-s),easeOutBounce:$u,easeInOutBounce:s=>s<.5?(1-$u(1-2*s))/2:(1+$u(2*s-1))/2},_ee=[{name:"Basic",easings:["linear"]},{name:"Quad",easings:["easeInQuad","easeOutQuad","easeInOutQuad"]},{name:"Cubic",easings:["easeInCubic","easeOutCubic","easeInOutCubic"]},{name:"Quart",easings:["easeInQuart","easeOutQuart","easeInOutQuart"]},{name:"Quint",easings:["easeInQuint","easeOutQuint","easeInOutQuint"]},{name:"Sine",easings:["easeInSine","easeOutSine","easeInOutSine"]},{name:"Expo",easings:["easeInExpo","easeOutExpo","easeInOutExpo"]},{name:"Circ",easings:["easeInCirc","easeOutCirc","easeInOutCirc"]},{name:"Back",easings:["easeInBack","easeOutBack","easeInOutBack"]},{name:"Elastic",easings:["easeInElastic","easeOutElastic","easeInOutElastic"]},{name:"Bounce",easings:["easeInBounce","easeOutBounce","easeInOutBounce"]}];class Wh{bezierCache=new Map;getValueAtTime(e,t){if(e.length===0)return{value:void 0,keyframeA:null,keyframeB:null,progress:0};const i=[...e].sort((d,h)=>d.time-h.time);if(t<=i[0].time)return{value:i[0].value,keyframeA:i[0],keyframeB:null,progress:0};if(t>=i[i.length-1].time)return{value:i[i.length-1].value,keyframeA:i[i.length-1],keyframeB:null,progress:1};let n=null,r=null;for(let d=0;d=i[d].time&&t<=i[d+1].time){n=i[d],r=i[d+1];break}if(!n||!r)return{value:i[i.length-1].value,keyframeA:i[i.length-1],keyframeB:null,progress:1};const a=r.time-n.time,o=t-n.time,c=a>0?o/a:0,l=this.applyEasing(c,n.easing);return{value:this.interpolateValue(n.value,r.value,l),keyframeA:n,keyframeB:r,progress:l}}interpolate(e,t,i){const[n,r]=e.time<=t.time?[e,t]:[t,e],a=Math.max(n.time,Math.min(r.time,i)),o=r.time-n.time,c=a-n.time,l=o>0?c/o:0,u=this.applyEasing(l,n.easing);return this.interpolateValue(n.value,r.value,u)}applyEasing(e,t,i){const n=Math.max(0,Math.min(1,e));if(t==="bezier")return i?this.cubicBezier(n,i.x1,i.y1,i.x2,i.y2):this.cubicBezier(n,.25,.1,.25,1);if(t==="ease-in")return Ss.easeInQuad(n);if(t==="ease-out")return Ss.easeOutQuad(n);if(t==="ease-in-out")return Ss.easeInOutQuad(n);const r=Ss[t];return r?r(n):n}cubicBezier(e,t,i,n,r){const a=`${t},${i},${n},${r}`;let o=this.bezierCache.get(a);return o||(o=this.createBezierFunction(t,i,n,r),this.bezierCache.set(a,o)),o(e)}createBezierFunction(e,t,i,n){const l=3*e-3*i+1,u=3*i-6*e,d=3*e,h=3*t-3*n+1,f=3*n-6*t,p=3*t,m=b=>((l*b+u)*b+d)*b,g=b=>((h*b+f)*b+p)*b,v=b=>(3*l*b+2*u)*b+d,w=b=>{let k=b;for(let R=0;R<4;R++){const I=v(k);if(Math.abs(I)<.001)break;const D=m(k)-b;k-=D/I}let A=0,M=1;k=b;for(let R=0;R<10;R++){const I=m(k)-b;if(Math.abs(I)<1e-7)break;I>0?M=k:A=k,k=(M+A)/2}return k};return b=>b===0?0:b===1?1:g(w(b))}interpolateValue(e,t,i){if(typeof e=="number"&&typeof t=="number")return e+(t-e)*i;if(typeof e=="object"&&typeof t=="object"&&e!==null&&t!==null){const n={},r=e,a=t;for(const o of Object.keys(r))o in a?n[o]=this.interpolateValue(r[o],a[o],i):n[o]=r[o];return n}return i<.5?e:t}addKeyframe(e,t){const i=e.findIndex(n=>n.time===t.time&&n.property===t.property);if(i>=0){const n=[...e];return n[i]=t,n}return[...e,t].sort((n,r)=>n.time-r.time)}removeKeyframe(e,t){return e.filter(i=>i.id!==t)}updateKeyframe(e,t,i){const n=e.map(r=>r.id===t?{...r,...i}:r);return i.time!==void 0&&n.sort((r,a)=>r.time-a.time),n}getKeyframesForProperty(e,t){return e.filter(i=>i.property===t).sort((i,n)=>i.time-n.time)}findKeyframeAtTime(e,t,i,n=.001){return e.find(r=>r.property===t&&Math.abs(r.time-i)<=n)||null}clearCache(){this.bezierCache.clear()}}class rG{animationEngine;constructor(){this.animationEngine=new Wh}getAnimatedState(e,t){const{animation:i,style:n,transform:r,text:a,keyframes:o}=e;if(o&&o.length>0)return this.applyKeyframeAnimation(e,t);if(!i||i.preset==="none")return{opacity:r.opacity,transform:r,style:n,visibleText:a};const c=e.duration,l=i.inDuration,u=i.outDuration,d=c-u;let h=1,f=0;t0?t/l:1),t>d&&u>0&&(f=(t-d)/u);const p=i.params.easing??"ease-out",m=this.animationEngine.applyEasing(h,p),g=this.animationEngine.applyEasing(f,p);return this.applyPreset(e,i.preset,i.params,m,g,t)}applyKeyframeAnimation(e,t){const{style:i,transform:n,text:r,keyframes:a}=e;let o=n.position.x,c=n.position.y,l=n.scale.x,u=n.scale.y,d=n.rotation,h=n.opacity;const f=new Map;for(const m of a)f.has(m.property)||f.set(m.property,[]),f.get(m.property).push(m);for(const[m,g]of f){const v=this.animationEngine.getValueAtTime(g,t);if(v.value!==void 0&&typeof v.value=="number")switch(m){case"opacity":h=Math.max(0,Math.min(1,v.value));break;case"position.x":o=v.value;break;case"position.y":c=v.value;break;case"scale.x":l=v.value;break;case"scale.y":u=v.value;break;case"rotation":d=v.value;break}}const p={position:{x:o,y:c},scale:{x:l,y:u},rotation:d,opacity:h,anchor:{...n.anchor}};return{opacity:p.opacity,transform:p,style:i,visibleText:r}}applyPreset(e,t,i,n,r,a){const{style:o,transform:c,text:l}=e;switch(t){case"typewriter":return this.applyTypewriter(e,n,r,a);case"fade":return this.applyFade(e,n,r,i);case"slide-left":return this.applySlide(e,n,r,i,"left");case"slide-right":return this.applySlide(e,n,r,i,"right");case"slide-up":return this.applySlide(e,n,r,i,"up");case"slide-down":return this.applySlide(e,n,r,i,"down");case"scale":return this.applyScale(e,n,r,i);case"blur":return this.applyBlur(e,n,r,i);case"bounce":return this.applyBounce(e,n,r,i);case"rotate":return this.applyRotate(e,n,r,i);case"wave":return this.applyWave(e,n,r,i,a);case"shake":return this.applyShake(e,n,r,i,a);case"pop":return this.applyPop(e,n,r,i);case"glitch":return this.applyGlitch(e,n,r,i,a);case"split":return this.applySplit(e,n,r,i);case"flip":return this.applyFlip(e,n,r,i);case"word-by-word":return this.applyWordByWord(e,n,r,i,a);case"rainbow":return this.applyRainbow(e,n,r,i,a);default:return{opacity:c.opacity,transform:c,style:o,visibleText:l}}}applyTypewriter(e,t,i,n){const{style:r,transform:a,text:o}=e,c=o.length,l=Math.floor(t*c),u=o.substring(0,l),d=a.opacity*(1-i);return{opacity:d,transform:{...a,opacity:d},style:r,visibleText:u}}applyFade(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.fadeOpacity?.start??0,l=n.fadeOpacity?.end??1;let u=c+(l-c)*t;return u=u*(1-i),{opacity:u,transform:{...a,opacity:u},style:r,visibleText:o}}applySlide(e,t,i,n,r){const{style:a,transform:o,text:c}=e,l=n.slideDistance??.2;let u=0,d=0;switch(r){case"left":u=-l*(1-t)+l*i;break;case"right":u=l*(1-t)-l*i;break;case"up":d=-l*(1-t)+l*i;break;case"down":d=l*(1-t)-l*i;break}const h=o.opacity*t*(1-i),f={...o,position:{x:o.position.x+u,y:o.position.y+d},opacity:h};return{opacity:h,transform:f,style:a,visibleText:c}}applyScale(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.scaleFrom??0,l=n.scaleTo??1;let u=c+(l-c)*t;u=u*(1-i)+c*i;const d=a.opacity*t*(1-i),h={...a,scale:{x:u,y:u},opacity:d};return{opacity:d,transform:h,style:r,visibleText:o}}applyBlur(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.blurAmount??10,l=c*(1-t)+c*i,u=a.opacity*t*(1-i),d={...r,shadowColor:r.color,shadowBlur:l,shadowOffsetX:0,shadowOffsetY:0};return{opacity:u,transform:{...a,opacity:u},style:d,visibleText:o}}applyBounce(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.bounceHeight??.1,l=n.bounceCount??3;let u=0;if(t<1){const f=t*Math.PI*l,p=1-t;u=-Math.abs(Math.sin(f))*c*p}if(i>0){const f=i*Math.PI;u=Math.sin(f)*c*i}const d=a.opacity*Math.min(t*2,1)*(1-i),h={...a,position:{x:a.position.x,y:a.position.y+u},opacity:d};return{opacity:d,transform:h,style:r,visibleText:o}}applyRotate(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.rotateAngle??360;let l=a.rotation+c*(1-t);l=l-c*i;const u=a.opacity*t*(1-i),d={...a,rotation:l,opacity:u};return{opacity:u,transform:d,style:r,visibleText:o}}applyWave(e,t,i,n,r){const{style:a,transform:o,text:c}=e,l=n.waveAmplitude??.02,u=n.waveFrequency??2,d=o.opacity*t*(1-i),h=c.split("").map((f,p)=>{const m=p/c.length*Math.PI*2*u,g=Math.sin(r*5+m)*l*t;return{char:f,index:p,opacity:d,offsetX:0,offsetY:g,scale:1,rotation:0}});return{opacity:d,transform:{...o,opacity:d},style:a,visibleText:c,characterStates:h}}applyShake(e,t,i,n,r){const{style:a,transform:o,text:c}=e,l=n.shakeIntensity??.01,u=n.shakeSpeed??20,d=Math.sin(r*u)*l*t*(1-i),h=Math.cos(r*u*1.3)*l*t*(1-i),f=o.opacity*t*(1-i),p={...o,position:{x:o.position.x+d,y:o.position.y+h},opacity:f};return{opacity:f,transform:p,style:a,visibleText:c}}applyPop(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.popOvershoot??1.2;let l=0;t<.5?l=t*2*c:t<.7?l=c-(t-.5)*(c-1)/.2:l=1,l=l*(1-i);const u=a.opacity*Math.min(t*2,1)*(1-i),d={...a,scale:{x:l,y:l},opacity:u};return{opacity:u,transform:d,style:r,visibleText:o}}applyGlitch(e,t,i,n,r){const{style:a,transform:o,text:c}=e,l=n.glitchIntensity??.02,u=n.glitchSpeed??10,d=Math.sin(r*u)>.7,h=d?(Math.random()-.5)*l:0,f=d?(Math.random()-.5)*5:0,p=o.opacity*t*(1-i),m={...o,position:{x:o.position.x+h*t,y:o.position.y},rotation:o.rotation+f*t,opacity:p},g={...a,letterSpacing:a.letterSpacing+(d?Math.random()*2:0)};return{opacity:p,transform:m,style:g,visibleText:c}}applySplit(e,t,i,n){const{style:r,transform:a,text:o}=e,c=n.splitDirection??"horizontal",l=.1*(1-t)+.1*i,u=a.opacity*t*(1-i),d=o.split("").map((h,f)=>{const p=f({char:p,index:m,opacity:d,offsetX:0,offsetY:0,scale:1,rotation:0})),f={...a,color:`hsl(${u}, 100%, 50%)`};return{opacity:d,transform:{...o,opacity:d},style:f,visibleText:c,characterStates:h}}createAnimationPreset(e,t=.5,i=.5,n={}){const r=this.getDefaultParams(e);return{preset:e,params:{...r,...n},inDuration:t,outDuration:i}}getDefaultParams(e){switch(e){case"fade":return{fadeOpacity:{start:0,end:1},easing:"ease-out"};case"slide-left":case"slide-right":case"slide-up":case"slide-down":return{slideDistance:.2,easing:"ease-out"};case"scale":return{scaleFrom:0,scaleTo:1,easing:"ease-out"};case"blur":return{blurAmount:10,easing:"ease-out"};case"bounce":return{bounceHeight:.1,bounceCount:3,easing:"ease-out"};case"rotate":return{rotateAngle:360,easing:"ease-out"};case"wave":return{waveAmplitude:.02,waveFrequency:2,easing:"linear"};case"typewriter":return{easing:"linear"};case"shake":return{shakeIntensity:.01,shakeSpeed:20,easing:"linear"};case"pop":return{popOvershoot:1.2,easing:"ease-out"};case"glitch":return{glitchIntensity:.02,glitchSpeed:10,easing:"linear"};case"split":return{splitDirection:"horizontal",easing:"ease-out"};case"flip":return{flipAxis:"y",easing:"ease-out"};case"word-by-word":return{wordDelay:.2,easing:"linear"};case"rainbow":return{rainbowSpeed:1,easing:"linear"};default:return{easing:"ease-out"}}}getAvailablePresets(){return["none","typewriter","fade","slide-left","slide-right","slide-up","slide-down","scale","blur","bounce","rotate","wave","shake","pop","glitch","split","flip","word-by-word","rainbow"]}}const n0=new rG;class aG{textClips=new Map;canvas=null;ctx=null;initialize(e=1920,t=1080){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t),this.ctx=this.canvas.getContext("2d")}createTextClip(e){const t=e.id||this.generateId(),i={...sG,...e.style},n={...nG,...e.transform},r={id:t,trackId:e.trackId,startTime:e.startTime,duration:e.duration??5,text:e.text,style:i,transform:n,animation:e.animation,keyframes:[],metadata:e.metadata};return this.textClips.set(t,r),r}getTextClip(e){return this.textClips.get(e)}getAllTextClips(){return Array.from(this.textClips.values())}getTextClipsForTrack(e){return Array.from(this.textClips.values()).filter(t=>t.trackId===e)}updateTextClip(e,t){const i=this.textClips.get(e);if(!i)return;const n={...i,text:t.text??i.text,startTime:t.startTime??i.startTime,duration:t.duration??i.duration,style:t.style?{...i.style,...t.style}:i.style,transform:t.transform?{...i.transform,...t.transform}:i.transform,animation:t.animation??i.animation,keyframes:t.keyframes??i.keyframes,blendMode:t.blendMode??i.blendMode,blendOpacity:t.blendOpacity??i.blendOpacity,emphasisAnimation:t.emphasisAnimation??i.emphasisAnimation,behindSubject:t.behindSubject??i.behindSubject,metadata:t.metadata??i.metadata,text3d:"text3d"in t?t.text3d:i.text3d};return this.textClips.set(e,n),n}updateText(e,t){return this.updateTextClip(e,{text:t})}updateStyle(e,t){return this.updateTextClip(e,{style:t})}updatePosition(e,t){return this.updateTextClip(e,{transform:{position:t}})}deleteTextClip(e){return this.textClips.delete(e)}addKeyframe(e,t){const i=this.textClips.get(e);if(!i)return;const n=i.keyframes.findIndex(o=>o.time===t.time&&o.property===t.property);let r;n>=0?(r=[...i.keyframes],r[n]=t):r=[...i.keyframes,t].sort((o,c)=>o.time-c.time);const a={...i,keyframes:r};return this.textClips.set(e,a),a}removeKeyframe(e,t){const i=this.textClips.get(e);if(!i)return;const n={...i,keyframes:i.keyframes.filter(r=>r.id!==t)};return this.textClips.set(e,n),n}renderText(e,t,i,n=0){let r,a;typeof OffscreenCanvas<"u"?r=new OffscreenCanvas(t,i):(r=document.createElement("canvas"),r.width=t,r.height=i),a=r.getContext("2d"),a.clearRect(0,0,t,i);const o=n0.getAnimatedState(e,n);let{opacity:c,transform:l,style:u,visibleText:d,characterStates:h}=o;if(e.emphasisAnimation&&e.emphasisAnimation.type!=="none"){const k=this.applyEmphasisAnimation(e.emphasisAnimation,n);c=c*k.opacity,l={...l,scale:{x:l.scale.x*k.scale*k.scaleX,y:l.scale.y*k.scale*k.scaleY},position:{x:l.position.x+k.offsetX,y:l.position.y+k.offsetY},rotation:l.rotation+k.rotation}}if(c<=0||d.length===0)return{canvas:r,width:t,height:i,textMetrics:this.measureText("",e.style,t)};const f=this.measureText(d,u,t);a.save();const p=l.position.x*t,m=l.position.y*i;a.translate(p,m),a.rotate(l.rotation*Math.PI/180),a.scale(l.scale.x,l.scale.y),a.globalAlpha=c,this.applyTextStyle(a,u);const g=d.split(` +`),v=u.fontSize*u.lineHeight,w=g.length*v;let b=-w/2+v/2;if(u.verticalAlign==="top"?b=0:u.verticalAlign==="bottom"&&(b=-w),u.backgroundColor){const k=f.width+20,A=w;a.fillStyle=u.backgroundColor,a.fillRect(-k/2,-A/2,k,A)}if(h&&h.length>0){let k=0;for(let A=0;A{const d=n.measureText(u);return{text:u,width:d.width,height:a,baseline:t.fontSize*.8}}),c=Math.max(...o.map(u=>u.width)),l=o.reduce((u,d)=>u+d.height,0);return{width:c,height:l,lines:o}}wrapText(e,t,i){if(!i)return e.split(` +`);this.ctx||this.initialize();const n=this.ctx;this.applyTextStyle(n,t);const r=e.split(` +`),a=[];for(const o of r){const c=o.split(" ");let l="";for(const u of c){const d=l?`${l} ${u}`:u;n.measureText(d).width>i&&l?(a.push(l),l=u):l=d}l&&a.push(l)}return a.length>0?a:[""]}applyTextStyle(e,t){const i=typeof t.fontWeight=="number"?t.fontWeight.toString():t.fontWeight;e.font=`${t.fontStyle} ${i} ${t.fontSize}px "${t.fontFamily}"`,e.fillStyle=t.color,e.textAlign=t.textAlign,e.textBaseline="middle",t.shadowColor?(e.shadowColor=t.shadowColor,e.shadowBlur=t.shadowBlur??0,e.shadowOffsetX=t.shadowOffsetX??0,e.shadowOffsetY=t.shadowOffsetY??0):(e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),"letterSpacing"in e&&t.letterSpacing!==0&&(e.letterSpacing=`${t.letterSpacing}px`)}generateId(){return`text-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}clear(){this.textClips.clear()}loadTextClips(e){this.textClips.clear();for(const t of e)this.textClips.set(t.id,t)}exportTextClips(){return Array.from(this.textClips.values())}applyEmphasisAnimation(e,t){const{type:i,speed:n,intensity:r,loop:a,startTime:o,animationDuration:c}=e,l=o??0;if(t0){const f=l+c;if(t>f)return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}const u=t-l,d=a?u*n%1:Math.min(u*n,1),h=d*Math.PI*2;switch(i){case"pulse":return{opacity:1,scale:1+Math.sin(h)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"shake":{const f=Math.sin(h*5)*.02*r,p=Math.cos(h*5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:f,offsetY:p,rotation:0}}case"bounce":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.abs(Math.sin(h))*-.05*r,rotation:0};case"float":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.sin(h)*.03*r,rotation:0};case"spin":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:d*360*r};case"flash":return{opacity:.5+Math.abs(Math.sin(h))*.5,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"heartbeat":{const f=d*4;let p=1;return f<1?p=1+.15*r*Math.sin(f*Math.PI):f<2&&(p=1+.1*r*Math.sin((f-1)*Math.PI)),{opacity:1,scale:p,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"swing":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h)*15*r};case"wobble":{const f=Math.sin(h*3)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:Math.sin(h)*.02*r,offsetY:0,rotation:f}}case"jello":{const f=1+Math.sin(h*2)*.1*r,p=1-Math.sin(h*2)*.1*r;return{opacity:1,scale:1,scaleX:f,scaleY:p,offsetX:0,offsetY:0,rotation:0}}case"rubber-band":{const f=1+Math.sin(h)*.2*r,p=1-Math.sin(h)*.1*r;return{opacity:1,scale:1,scaleX:f,scaleY:p,offsetX:0,offsetY:0,rotation:0}}case"tada":{const f=Math.sin(h*4)*10*r;return{opacity:1,scale:1+Math.sin(h*2)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:f}}case"vibrate":{const f=(Math.random()-.5)*.02*r,p=(Math.random()-.5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:f,offsetY:p,rotation:0}}case"flicker":return{opacity:Math.random()>.1?1:.3,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"glow":{const f=1+Math.sin(h)*.05*r;return{opacity:.8+Math.sin(h)*.2,scale:f,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"breathe":return{opacity:1,scale:1+Math.sin(h*.5)*.08*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"wave":{const f=Math.sin(h+u*2)*.03*r,p=Math.sin(h)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:f,rotation:p}}case"tilt":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h*.5)*10*r};case"zoom-pulse":return{opacity:1,scale:1+Math.sin(h)*.15*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"focus-zoom":{const f=e.focusPoint||{x:.5,y:.5},p=e.zoomScale||1.5,m=e.holdDuration||.3,g=.3,v=1-m-g;let w=1,b=0,k=0;if(d0&&this.drawPolygonCentered(e,t.points,c);break}r.fill.type!=="none"&&(e.globalAlpha=r.fill.opacity,r.fill.type==="gradient"&&r.fill.gradient?e.fillStyle=this.createGradient(e,r.fill.gradient,c,c):e.fillStyle=r.fill.color||"#000000",e.fill()),r.stroke.width>0&&(e.globalAlpha=r.stroke.opacity,e.strokeStyle=r.stroke.color,e.lineWidth=r.stroke.width,e.lineCap=r.stroke.lineCap||"butt",e.lineJoin=r.stroke.lineJoin||"miter",r.stroke.dashArray&&(e.setLineDash(r.stroke.dashArray),e.lineDashOffset=r.stroke.dashOffset||0),e.stroke()),e.restore()}getAnimatedSVGSourceInset(e,t,i){if(!(Math.abs(e.scale-1)>.001||Math.abs((e.scaleX??1)-1)>.001||Math.abs((e.scaleY??1)-1)>.001||Math.abs(e.offsetX)>.001||Math.abs(e.offsetY)>.001||Math.abs(e.rotation)>.001)||t<=2||i<=2)return 0;const r=Math.max(2,Math.ceil(Math.min(t,i)*.0125)),a=Math.floor((Math.min(t,i)-1)/2);return Math.min(16,r,a)}async renderSVG(e,t,i,n,r){const a=t.viewBox.width/t.viewBox.height,o=r.transform.scale.x,c=r.transform.scale.y,l=Math.max(Math.abs(o),Math.abs(c),1),u=Math.ceil(l*2)/2;let d,h;a>1?(d=Math.ceil(i*u),h=Math.ceil(d/a)):(h=Math.ceil(n*u),d=Math.ceil(h*a));const m=new DOMParser().parseFromString(t.svgContent,"image/svg+xml").querySelector("svg");m&&(m.setAttribute("width",String(d)),m.setAttribute("height",String(h)));const g=new XMLSerializer,v=m?g.serializeToString(m):t.svgContent,w=new Blob([v],{type:"image/svg+xml"}),b=URL.createObjectURL(w);try{const k=await this.loadImage(b);r.blur>0&&(e.filter=`blur(${r.blur}px)`);const A=d/u,M=h/u,R=this.getAnimatedSVGSourceInset(r,d,h),I=Math.max(1,d-R*2),D=Math.max(1,h-R*2),B=-A/2+R/u,$=-M/2+R/u,V=I/u,y=D/u;if(t.colorStyle&&t.colorStyle.colorMode!=="none"&&(t.colorStyle.colorMode==="tint"||t.colorStyle.colorMode==="replace")){const _=new OffscreenCanvas(d,h),T=_.getContext("2d");T?(T.drawImage(k,0,0,d,h),T.globalCompositeOperation="source-in",T.fillStyle=t.colorStyle.tintColor||"#ffffff",T.globalAlpha=t.colorStyle.tintOpacity??1,T.fillRect(0,0,d,h),e.drawImage(_,R,R,I,D,B,$,V,y)):e.drawImage(k,R,R,I,D,B,$,V,y)}else e.drawImage(k,R,R,I,D,B,$,V,y);e.filter="none"}finally{URL.revokeObjectURL(b)}}async renderSticker(e,t,i,n){const r=await this.loadImage(t.imageUrl),a=r.width,o=r.height,c=t.transform.anchor?.x??.5,l=t.transform.anchor?.y??.5;e.drawImage(r,-a*c,-o*l,a,o)}drawRectangle(e,t,i,n,r,a){const o=t-n/2,c=i-r/2;if(a&&a>0){const l=Math.min(a,n/2,r/2);e.moveTo(o+l,c),e.lineTo(o+n-l,c),e.quadraticCurveTo(o+n,c,o+n,c+l),e.lineTo(o+n,c+r-l),e.quadraticCurveTo(o+n,c+r,o+n-l,c+r),e.lineTo(o+l,c+r),e.quadraticCurveTo(o,c+r,o,c+r-l),e.lineTo(o,c+l),e.quadraticCurveTo(o,c,o+l,c)}else e.rect(o,c,n,r)}drawCircle(e,t,i,n){e.arc(t,i,n,0,Math.PI*2)}drawEllipse(e,t,i,n,r){e.ellipse(t,i,n,r,0,0,Math.PI*2)}drawTriangle(e,t,i,n,r){e.moveTo(t,i-r/2),e.lineTo(t+n/2,i+r/2),e.lineTo(t-n/2,i+r/2),e.closePath()}drawArrow(e,t,i,n,r){const a=r*.6,o=n*.3,c=r*.3,l=t-n/2,u=t+n/2,d=u-o;e.moveTo(l,i-c/2),e.lineTo(d,i-c/2),e.lineTo(d,i-a/2),e.lineTo(u,i),e.lineTo(d,i+a/2),e.lineTo(d,i+c/2),e.lineTo(l,i+c/2),e.closePath()}drawLine(e,t,i,n,r){e.moveTo(t,i),e.lineTo(n,r)}drawStar(e,t,i,n,r,a){const o=n*a,c=Math.PI/r;e.moveTo(t,i-n);for(let l=0;l0&&(i=this.getAnimatedTransform(e,t),n=i.opacity);let h=!1,f=!1;if(e.type==="svg"){const p=e,m=p.entryAnimation,g=p.exitAnimation;if(m||g){const v=m?.duration||0,w=g?.duration||0,k=e.duration-w;if(m&&t0?t/v:1,M=this.applyGraphicAnimation(m.type,A,m.easing,!0);r*=M.scale,c+=M.offsetX,l+=M.offsetY,u+=M.rotation,n*=M.opacity,d=M.blur}if(g&&t>=k){f=!0;const A=w>0?(t-k)/w:1,M=this.applyGraphicAnimation(g.type,A,g.easing,!1);r*=M.scale,c+=M.offsetX,l+=M.offsetY,u+=M.rotation,n*=M.opacity,d=Math.max(d,M.blur)}}}if(e.emphasisAnimation&&e.emphasisAnimation.type!=="none"&&!h&&!f){const p=this.applyEmphasisAnimation(e.emphasisAnimation,t);r*=p.scale,a*=p.scaleX,o*=p.scaleY,c+=p.offsetX,l+=p.offsetY,u+=p.rotation,n*=p.opacity}return{transform:{...i,position:{x:i.position.x+c,y:i.position.y+l},scale:{x:i.scale.x*r*a,y:i.scale.y*r*o},rotation:i.rotation+u,opacity:n,anchor:i.anchor},opacity:n,scale:r,scaleX:a,scaleY:o,offsetX:c,offsetY:l,rotation:u,blur:d}}applyEmphasisAnimation(e,t){const{type:i,speed:n,intensity:r,loop:a,startTime:o,animationDuration:c}=e,l=o??0;if(t0){const f=l+c;if(t>f)return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}const u=t-l,d=a?u*n%1:Math.min(u*n,1),h=d*Math.PI*2;switch(i){case"pulse":return{opacity:1,scale:1+Math.sin(h)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"shake":const p=Math.sin(h*5)*.02*r,m=Math.cos(h*5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:p,offsetY:m,rotation:0};case"bounce":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.abs(Math.sin(h))*-.05*r,rotation:0};case"float":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.sin(h)*.03*r,rotation:0};case"spin":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:d*360*r};case"flash":return{opacity:.5+Math.abs(Math.sin(h))*.5,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"heartbeat":const k=d*4;let A=1;return k<1?A=1+.15*r*Math.sin(k*Math.PI):k<2&&(A=1+.1*r*Math.sin((k-1)*Math.PI)),{opacity:1,scale:A,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"swing":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h)*15*r};case"wobble":const R=Math.sin(h*3)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:Math.sin(h)*.02*r,offsetY:0,rotation:R};case"jello":const D=1+Math.sin(h*2)*.1*r,B=1-Math.sin(h*2)*.1*r;return{opacity:1,scale:1,scaleX:D,scaleY:B,offsetX:0,offsetY:0,rotation:0};case"rubber-band":const $=1+Math.sin(h)*.2*r,V=1-Math.sin(h)*.1*r;return{opacity:1,scale:1,scaleX:$,scaleY:V,offsetX:0,offsetY:0,rotation:0};case"tada":const y=Math.sin(h*4)*10*r;return{opacity:1,scale:1+Math.sin(h*2)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:y};case"vibrate":const T=(Math.random()-.5)*.02*r,S=(Math.random()-.5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:T,offsetY:S,rotation:0};case"flicker":return{opacity:Math.random()>.1?1:.3,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"glow":const E=1+Math.sin(h)*.05*r;return{opacity:.8+Math.sin(h)*.2,scale:E,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"breathe":return{opacity:1,scale:1+Math.sin(h*.5)*.08*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"wave":const O=Math.sin(h+t*2)*.03*r,U=Math.sin(h)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:O,rotation:U};case"tilt":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h*.5)*10*r};case"zoom-pulse":return{opacity:1,scale:1+Math.sin(h)*.15*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"focus-zoom":{const ye=e.focusPoint||{x:.5,y:.5},le=e.zoomScale||1.5,Le=e.holdDuration||.3,Oe=.3,jt=1-Le-Oe;let dt=1,ht=0,Si=0;if(d0){const o=this.animationEngine.getValueAtTime(a,t);o.value!==void 0&&this.setNestedProperty(i,r,o.value)}}return i}applyTransform(e,t,i,n){const r=t.position.x*i,a=t.position.y*n;e.translate(r,a),e.rotate(t.rotation*Math.PI/180),e.scale(t.scale.x,t.scale.y),e.globalAlpha=t.opacity}setNestedProperty(e,t,i){const n=t.split(".");let r=e;for(let a=0;a{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{this.imageCache.set(e,r),i(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}generateId(){return`graphic_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}getShapeClip(e){return this.shapeClips.get(e)}getSVGClip(e){return this.svgClips.get(e)}getAllShapeClips(){return Array.from(this.shapeClips.values())}getAllSVGClips(){return Array.from(this.svgClips.values())}getShapeClipsForTrack(e){return Array.from(this.shapeClips.values()).filter(t=>t.trackId===e)}getSVGClipsForTrack(e){return Array.from(this.svgClips.values()).filter(t=>t.trackId===e)}deleteShapeClip(e){return this.shapeClips.delete(e)}deleteSVGClip(e){return this.svgClips.delete(e)}updateSVGClip(e,t){const i=this.svgClips.get(e);if(!i){console.warn(`[GraphicsEngine] SVG clip not found: ${e}`);return}const n={...i,startTime:t.startTime??i.startTime,duration:t.duration??i.duration,transform:t.transform?{...i.transform,...t.transform}:i.transform,keyframes:t.keyframes??i.keyframes,entryAnimation:t.entryAnimation??i.entryAnimation,exitAnimation:t.exitAnimation??i.exitAnimation,colorStyle:t.colorStyle??i.colorStyle,blendMode:t.blendMode??i.blendMode,blendOpacity:t.blendOpacity??i.blendOpacity,emphasisAnimation:t.emphasisAnimation??i.emphasisAnimation};return this.svgClips.set(e,n),n}setSVGAnimation(e,t,i){const n={...e,[t==="entry"?"entryAnimation":"exitAnimation"]:i};return this.svgClips.set(e.id,n),n}setSVGColorStyle(e,t){const i={...e,colorStyle:t};return this.svgClips.set(e.id,i),i}addStickerClip(e){this.stickerClips.set(e.id,e)}getStickerClip(e){return this.stickerClips.get(e)}getAllStickerClips(){return Array.from(this.stickerClips.values())}getStickerClipsForTrack(e){return Array.from(this.stickerClips.values()).filter(t=>t.trackId===e)}deleteStickerClip(e){return this.stickerClips.delete(e)}updateStickerClip(e,t){const i=this.stickerClips.get(e);if(!i){console.warn(`[GraphicsEngine] Sticker clip not found: ${e}`);return}const n={...i,startTime:t.startTime??i.startTime,duration:t.duration??i.duration,transform:t.transform?{...i.transform,...t.transform}:i.transform,keyframes:t.keyframes??i.keyframes,blendMode:t.blendMode??i.blendMode,blendOpacity:t.blendOpacity??i.blendOpacity,emphasisAnimation:t.emphasisAnimation??i.emphasisAnimation};return this.stickerClips.set(e,n),n}clearCache(){this.svgCache.clear(),this.imageCache.clear(),this.shapeClips.clear(),this.svgClips.clear(),this.stickerClips.clear(),this.animationEngine.clearCache()}loadShapeClips(e){this.shapeClips.clear();for(const t of e)this.shapeClips.set(t.id,t)}loadSVGClips(e){this.svgClips.clear();for(const t of e)this.svgClips.set(t.id,t)}loadStickerClips(e){this.stickerClips.clear();for(const t of e)this.stickerClips.set(t.id,t)}createGraphicAnimation(e,t=.5,i="ease-out"){return{type:e,duration:t,easing:i}}}const As=new oG;function Fl(){return typeof navigator>"u"?!1:"gpu"in navigator&&navigator.gpu!==void 0}function cG(s){return s==="canvas2d"?"canvas2d":Fl()?"webgpu":"canvas2d"}class Yr{static instance=null;currentRenderer=null;config=null;constructor(){}static getInstance(){return Yr.instance||(Yr.instance=new Yr),Yr.instance}isWebGPUSupported(){return Fl()}getRendererType(e){return cG(e)}async createRenderer(e){if(this.config=e,Fl())try{const{WebGPURenderer:n}=await ii(async()=>{const{WebGPURenderer:o}=await import("./webgpu-renderer-impl-DhZn-Lwe.js").then(c=>c.w);return{WebGPURenderer:o}},[]),r=new n(e);if(await r.initialize())return this.currentRenderer=r,r;console.warn("[RendererFactory] WebGPU init failed, using Canvas2D")}catch(n){console.warn("[RendererFactory] WebGPU error, using Canvas2D:",n)}const{Canvas2DFallbackRenderer:t}=await ii(async()=>{const{Canvas2DFallbackRenderer:n}=await import("./canvas2d-fallback-renderer-CT8Dcn23.js");return{Canvas2DFallbackRenderer:n}},[]),i=new t(e);return await i.initialize(),this.currentRenderer=i,i}getCurrentRenderer(){return this.currentRenderer}destroyRenderer(){this.currentRenderer&&(this.currentRenderer.destroy(),this.currentRenderer=null)}async recreateRenderer(){return this.config?(this.destroyRenderer(),this.createRenderer(this.config)):null}}function lG(){return Yr.getInstance()}const Ci=`#version 300 es +precision highp float; + +in vec2 a_position; +in vec2 a_texCoord; + +out vec2 v_texCoord; + +void main() { + gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; +} +`,uG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; + +void main() { + fragColor = texture(u_texture, v_texCoord); +} +`,dG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_brightness; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec3 rgb = color.rgb + u_brightness; + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,hG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_contrast; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec3 rgb = (color.rgb - 0.5) * u_contrast + 0.5; + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,fG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_saturation; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + float luminance = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + vec3 rgb = mix(vec3(luminance), color.rgb, u_saturation); + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,pG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_hueRotation; + +vec3 rgb2hsv(vec3 c) { + vec4 K = vec4(0.0, -1.0/3.0, 2.0/3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsv2rgb(vec3 c) { + vec4 K = vec4(1.0, 2.0/3.0, 1.0/3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec3 hsv = rgb2hsv(color.rgb); + hsv.x = fract(hsv.x + u_hueRotation / 360.0); + vec3 rgb = hsv2rgb(hsv); + fragColor = vec4(rgb, color.a); +} +`,mG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform vec2 u_resolution; +uniform float u_radius; + +void main() { + vec2 texelSize = 1.0 / u_resolution; + vec4 color = vec4(0.0); + float total = 0.0; + + int r = int(min(u_radius, 10.0)); + for (int x = -r; x <= r; x++) { + for (int y = -r; y <= r; y++) { + vec2 offset = vec2(float(x), float(y)) * texelSize; + color += texture(u_texture, v_texCoord + offset); + total += 1.0; + } + } + + fragColor = color / total; +} +`,gG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform vec2 u_resolution; +uniform float u_amount; + +void main() { + vec2 texelSize = 1.0 / u_resolution; + + vec4 center = texture(u_texture, v_texCoord); + vec4 top = texture(u_texture, v_texCoord + vec2(0.0, -texelSize.y)); + vec4 bottom = texture(u_texture, v_texCoord + vec2(0.0, texelSize.y)); + vec4 left = texture(u_texture, v_texCoord + vec2(-texelSize.x, 0.0)); + vec4 right = texture(u_texture, v_texCoord + vec2(texelSize.x, 0.0)); + + vec4 sharpened = center * (1.0 + 4.0 * u_amount) - (top + bottom + left + right) * u_amount; + fragColor = vec4(clamp(sharpened.rgb, 0.0, 1.0), center.a); +} +`,yG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_amount; +uniform float u_midpoint; +uniform float u_feather; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec2 center = vec2(0.5, 0.5); + float dist = distance(v_texCoord, center); + float vignette = smoothstep(u_midpoint - u_feather, u_midpoint + u_feather, dist); + vec3 rgb = color.rgb * (1.0 - vignette * u_amount); + fragColor = vec4(rgb, color.a); +} +`,vG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_amount; +uniform float u_size; +uniform float u_time; + +float random(vec2 st) { + return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123); +} + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec2 st = v_texCoord * u_size + u_time; + float noise = random(st) * 2.0 - 1.0; + vec3 rgb = color.rgb + noise * u_amount; + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,bG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform vec3 u_keyColor; +uniform float u_tolerance; +uniform float u_softness; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + float diff = distance(color.rgb, u_keyColor); + float alpha = smoothstep(u_tolerance - u_softness, u_tolerance + u_softness, diff); + fragColor = vec4(color.rgb, color.a * alpha); +} +`,xG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_temperature; // -1 (cool/blue) to 1 (warm/orange) + +void main() { + vec4 color = texture(u_texture, v_texCoord); + + // Temperature adjustment using color balance + + vec3 rgb = color.rgb; + + if (u_temperature > 0.0) { + rgb.r = rgb.r + u_temperature * 0.2; + rgb.g = rgb.g + u_temperature * 0.1; + rgb.b = rgb.b - u_temperature * 0.2; + } else { + rgb.r = rgb.r + u_temperature * 0.2; + rgb.g = rgb.g + u_temperature * 0.05; + rgb.b = rgb.b - u_temperature * 0.2; + } + + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,wG=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_tint; // -1 (green) to 1 (magenta) + +void main() { + vec4 color = texture(u_texture, v_texCoord); + + // Tint adjustment + + vec3 rgb = color.rgb; + + rgb.r = rgb.r + u_tint * 0.1; + rgb.g = rgb.g - u_tint * 0.2; + rgb.b = rgb.b + u_tint * 0.1; + + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,_G=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_shadows; // -1 to 1 +uniform float u_midtones; // -1 to 1 +uniform float u_highlights; // -1 to 1 + +void main() { + vec4 color = texture(u_texture, v_texCoord); + float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + float shadowWeight = 1.0 - smoothstep(0.0, 0.33, luma); + float highlightWeight = smoothstep(0.66, 1.0, luma); + float midtoneWeight = 1.0 - shadowWeight - highlightWeight; + midtoneWeight = max(0.0, midtoneWeight); + vec3 rgb = color.rgb; + rgb += u_shadows * shadowWeight * 0.3; + rgb += u_midtones * midtoneWeight * 0.3; + rgb += u_highlights * highlightWeight * 0.3; + + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`;class lu{canvas=null;gl=null;shaders=new Map;quadBuffer=null;texCoordBuffer=null;framebuffers=[];renderTextures=[];currentRenderTarget=0;width;height;useGPU;preferWebGPU;initialized=!1;initializing=!1;initPromise=null;renderer=null;rendererFactory=null;useNewRenderer=!1;constructor(e){this.width=e.width,this.height=e.height,this.useGPU=e.useGPU??!0,this.preferWebGPU=e.preferWebGPU??!0,this._applyEffectsWithNewRenderer,this._applyEffectsGPU}async initialize(){if(this.initialized)return!0;if(this.initializing&&this.initPromise)return this.initPromise;this.initializing=!0,this.initPromise=this.doInitialize();try{const e=await this.initPromise;return this.initialized=e,e}finally{this.initializing=!1}}async doInitialize(){if(this.useGPU){if(this.preferWebGPU&&Fl())try{return await this.initializeNewRenderer(),!0}catch(e){console.warn("[VideoEffectsEngine] WebGPU initialization failed, falling back to WebGL2:",e)}if(lu.isWebGL2Supported())return this.initializeWebGL(),!0}return!0}async initializeNewRenderer(){try{this.rendererFactory=Yr.getInstance(),this.canvas=new OffscreenCanvas(this.width,this.height);const e={canvas:this.canvas,width:this.width,height:this.height,preferredRenderer:this.preferWebGPU?"webgpu":"canvas2d"};this.renderer=await this.rendererFactory.createRenderer(e),this.useNewRenderer=!0}catch(e){console.warn("[VideoEffectsEngine] Failed to initialize new renderer, falling back to WebGL2:",e),this.useNewRenderer=!1,this.initializeWebGL()}}initializeWebGL(){this.canvas=new OffscreenCanvas(this.width,this.height);const e=this.canvas.getContext("webgl2",{preserveDrawingBuffer:!0,premultipliedAlpha:!0,alpha:!0,antialias:!1});if(!e){console.warn("WebGL2 not available, falling back to CPU processing"),this.useGPU=!1;return}this.gl=e,this.quadBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),this.texCoordBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,1,1,1,0,0,1,0]),e.STATIC_DRAW);for(let t=0;t<2;t++){const i=e.createFramebuffer(),n=this.createRenderTexture();this.framebuffers.push(i),this.renderTextures.push(n)}this.compileShader("passthrough",Ci,uG),this.compileShader("brightness",Ci,dG),this.compileShader("contrast",Ci,hG),this.compileShader("saturation",Ci,fG),this.compileShader("hue",Ci,pG),this.compileShader("blur",Ci,mG),this.compileShader("sharpen",Ci,gG),this.compileShader("vignette",Ci,yG),this.compileShader("grain",Ci,vG),this.compileShader("chromaKey",Ci,bG),this.compileShader("temperature",Ci,xG),this.compileShader("tint",Ci,wG),this.compileShader("tonal",Ci,_G),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA)}createRenderTexture(){const e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,this.width,this.height,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}compileShader(e,t,i){const n=this.gl,r=n.createShader(n.VERTEX_SHADER);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Vertex shader error: ${n.getShaderInfoLog(r)}`);const a=n.createShader(n.FRAGMENT_SHADER);if(n.shaderSource(a,i),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS))throw new Error(`Fragment shader error: ${n.getShaderInfoLog(a)}`);const o=n.createProgram();if(n.attachShader(o,r),n.attachShader(o,a),n.linkProgram(o),!n.getProgramParameter(o,n.LINK_STATUS))throw new Error(`Program link error: ${n.getProgramInfoLog(o)}`);const c=new Map,l=n.getProgramParameter(o,n.ACTIVE_UNIFORMS);for(let h=0;ha.enabled);return n.length===0?{image:await createImageBitmap(e),processingTime:performance.now()-i,gpuAccelerated:!1}:{image:await this.applyEffectsCPU(e,n),processingTime:performance.now()-i,gpuAccelerated:!1}}async _applyEffectsWithNewRenderer(e,t){if(!this.renderer)throw new Error("Renderer not initialized");try{const i=this.renderer.createTextureFromImage(e),n=this.renderer.applyEffects(i,t);this.renderer.beginFrame(),this.renderer.renderLayer({texture:n,transform:{position:{x:0,y:0},scale:{x:1,y:1},rotation:0,opacity:1,anchor:{x:.5,y:.5}},effects:[],opacity:1,borderRadius:0});const r=await this.renderer.endFrame();return this.renderer.releaseTexture(i),!r||r.width===0||r.height===0?(console.warn("[VideoEffectsEngine] Renderer returned invalid result, using CPU fallback"),this.applyEffectsCPU(e,t)):r}catch(i){return console.warn("[VideoEffectsEngine] applyEffectsWithNewRenderer failed:",i),this.applyEffectsCPU(e,t)}}async _applyEffectsGPU(e,t){const i=this.gl;if(i.isContextLost())return console.warn("[VideoEffectsEngine] WebGL context lost, falling back to CPU"),this.applyEffectsCPU(e,t);try{if(this.canvas.width!==e.width||this.canvas.height!==e.height){this.canvas.width=e.width,this.canvas.height=e.height,this.width=e.width,this.height=e.height;for(let o=0;o<2;o++)i.bindTexture(i.TEXTURE_2D,this.renderTextures[o]),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null)}const n=this.uploadTexture(e);for(let o=0;o<2;o++)i.bindFramebuffer(i.FRAMEBUFFER,this.framebuffers[o]),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.renderTextures[o],0),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT);let r=n;this.currentRenderTarget=0;for(const o of t){const c=o.type;this.shaders.get(c)&&(this.renderWithShader(c,r,o.params),r=this.renderTextures[this.currentRenderTarget],this.currentRenderTarget=1-this.currentRenderTarget)}i.bindFramebuffer(i.FRAMEBUFFER,null),i.viewport(0,0,this.width,this.height),this.renderPassthrough(r),i.deleteTexture(n);const a=i.getError();return a!==i.NO_ERROR?(console.warn("[VideoEffectsEngine] WebGL error:",a),createImageBitmap(e)):createImageBitmap(this.canvas)}catch(n){return console.error("[VideoEffectsEngine] GPU processing failed:",n),this.applyEffectsCPU(e,t)}}uploadTexture(e){const t=this.gl,i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i}renderWithShader(e,t,i){const n=this.gl,r=this.shaders.get(e);if(!r)return;n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffers[this.currentRenderTarget]),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,this.renderTextures[this.currentRenderTarget],0),n.viewport(0,0,this.width,this.height),n.useProgram(r.program),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,t);const a=r.uniforms.get("u_texture");a&&n.uniform1i(a,0),this.setFilterUniforms(e,r,i),this.setupVertexAttributes(r),n.drawArrays(n.TRIANGLE_STRIP,0,4)}renderPassthrough(e){const t=this.gl,i=this.shaders.get("passthrough");t.useProgram(i.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e);const n=i.uniforms.get("u_texture");n&&t.uniform1i(n,0),this.setupVertexAttributes(i),t.drawArrays(t.TRIANGLE_STRIP,0,4)}setupVertexAttributes(e){const t=this.gl,i=e.attributes.get("a_position");i!==void 0&&(t.bindBuffer(t.ARRAY_BUFFER,this.quadBuffer),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0));const n=e.attributes.get("a_texCoord");n!==void 0&&(t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0))}setFilterUniforms(e,t,i){const n=this.gl;switch(e){case"brightness":{const r=t.uniforms.get("u_brightness");r&&n.uniform1f(r,i.value||0);break}case"contrast":{const r=t.uniforms.get("u_contrast");r&&n.uniform1f(r,i.value||1);break}case"saturation":{const r=t.uniforms.get("u_saturation");r&&n.uniform1f(r,i.value||1);break}case"hue":{const r=t.uniforms.get("u_hueRotation");r&&n.uniform1f(r,i.rotation||0);break}case"blur":{const r=t.uniforms.get("u_radius"),a=t.uniforms.get("u_resolution");r&&n.uniform1f(r,Math.min(i.radius||0,10)),a&&n.uniform2f(a,this.width,this.height);break}case"sharpen":{const r=t.uniforms.get("u_amount"),a=t.uniforms.get("u_resolution");r&&n.uniform1f(r,i.amount||0),a&&n.uniform2f(a,this.width,this.height);break}case"vignette":{const r=t.uniforms.get("u_amount"),a=t.uniforms.get("u_midpoint"),o=t.uniforms.get("u_feather");r&&n.uniform1f(r,i.amount||.5),a&&n.uniform1f(a,i.midpoint||.5),o&&n.uniform1f(o,i.feather||.3);break}case"grain":{const r=t.uniforms.get("u_amount"),a=t.uniforms.get("u_size"),o=t.uniforms.get("u_time");r&&n.uniform1f(r,i.amount||.1),a&&n.uniform1f(a,i.size||1),o&&n.uniform1f(o,performance.now()/1e3);break}case"chromaKey":{const r=t.uniforms.get("u_keyColor"),a=t.uniforms.get("u_tolerance"),o=t.uniforms.get("u_softness"),c=i.keyColor;r&&n.uniform3f(r,c?.r??0,c?.g??1,c?.b??0),a&&n.uniform1f(a,i.tolerance||.3),o&&n.uniform1f(o,i.edgeSoftness||.1);break}case"temperature":{const r=t.uniforms.get("u_temperature");r&&n.uniform1f(r,i.value||0);break}case"tint":{const r=t.uniforms.get("u_tint");r&&n.uniform1f(r,i.value||0);break}case"tonal":{const r=t.uniforms.get("u_shadows"),a=t.uniforms.get("u_midtones"),o=t.uniforms.get("u_highlights");r&&n.uniform1f(r,i.shadows||0),a&&n.uniform1f(a,i.midtones||0),o&&n.uniform1f(o,i.highlights||0);break}}}async applyEffectsCPU(e,t){const i=new OffscreenCanvas(e.width,e.height),n=i.getContext("2d",{willReadFrequently:!0}),r=[],a=[];for(const o of t){const c=this.buildCSSFilter(o);c?r.push(c):a.push(o)}r.length>0?(n.filter=r.join(" "),n.drawImage(e,0,0),n.filter="none"):n.drawImage(e,0,0);for(const o of a)await this.applyEffectPixelLevel(n,o,i.width,i.height);return createImageBitmap(i)}async applyEffectPixelLevel(e,t,i,n){const r=e.getImageData(0,0,i,n),a=r.data,o=t.params;switch(t.type){case"sharpen":{const c=o.amount||.5;this.applySharpenKernel(a,i,n,c);break}case"vignette":{const c=o.amount||.5,l=o.midpoint||.5,u=o.feather||.3;this.applyVignette(a,i,n,c,l,u);break}case"grain":{const c=o.amount||.1;this.applyGrain(a,c);break}case"chromaKey":{const c=o.keyColor,l=o.tolerance||.3,u=o.edgeSoftness||.1;this.applyChromaKey(a,c||{r:0,g:1,b:0},l,u);break}case"temperature":{const c=o.value||0;this.applyTemperature(a,c);break}case"tint":{const c=o.value||0;this.applyTint(a,c);break}case"tonal":{const c=o.shadows||0,l=o.midtones||0,u=o.highlights||0;this.applyTonal(a,c,l,u);break}case"motion-blur":{const c=o.distance||0,l=o.angle||0;this.applyMotionBlur(a,i,n,c,l);break}case"radial-blur":{const c=o.amount||0,l=o.centerX||50,u=o.centerY||50;this.applyRadialBlur(a,i,n,c,l,u);break}case"chromatic-aberration":{const c=o.amount||0;this.applyChromaticAberration(a,i,n,c);break}}e.putImageData(r,0,0)}applySharpenKernel(e,t,i,n){const r=n/100,a=new Uint8ClampedArray(e),o=[0,-r,0,-r,1+4*r,-r,0,-r,0];for(let c=1;c0?(r=Math.min(255,r+i*51),a=Math.min(255,a+i*25.5),o=Math.max(0,o-i*51)):(r=Math.max(0,r+i*51),a=Math.max(0,a+i*12.75),o=Math.min(255,o-i*51)),e[n]=Math.round(r),e[n+1]=Math.round(a),e[n+2]=Math.round(o)}}applyTint(e,t){const i=t/100;for(let n=0;n=t||D<0||D>=i)continue;const B=(D*t+I)*4;m+=o[B],g+=o[B+1],v+=o[B+2],w+=o[B+3],b+=1}if(b===0)continue;const k=(f*t+p)*4;e[k]=Math.round(m/b),e[k+1]=Math.round(g/b),e[k+2]=Math.round(v/b),e[k+3]=Math.round(w/b)}}applyRadialBlur(e,t,i,n,r,a){const o=Math.max(0,n);if(o<=0)return;const c=new Uint8ClampedArray(e),l=Math.max(2,Math.min(12,Math.ceil(o/8)+2)),u=Math.max(0,Math.min(1,o/100)),d=r/100*Math.max(0,t-1),h=a/100*Math.max(0,i-1);for(let f=0;f=t||$<0||$>=i)continue;const V=($*t+B)*4;v+=c[V],w+=c[V+1],b+=c[V+2],k+=c[V+3],A+=1}if(A===0)continue;const M=(f*t+p)*4;e[M]=Math.round(v/A),e[M+1]=Math.round(w/A),e[M+2]=Math.round(b/A),e[M+3]=Math.round(k/A)}}applyChromaticAberration(e,t,i,n){const r=Math.max(0,Math.round(n/2));if(r<=0)return;const a=new Uint8ClampedArray(e);for(let o=0;o`${l}${l}`).join(""):n;if(r.length!==6)return`rgba(0, 0, 0, ${i})`;const a=Number.parseInt(r.slice(0,2),16),o=Number.parseInt(r.slice(2,4),16),c=Number.parseInt(r.slice(4,6),16);return Number.isNaN(a)||Number.isNaN(o)||Number.isNaN(c)?`rgba(0, 0, 0, ${i})`:`rgba(${a}, ${o}, ${c}, ${i})`}buildCSSFilter(e){const t=e.params,i=typeof t.value=="number"?t.value:0;switch(e.type){case"brightness":return`brightness(${1+i/100})`;case"contrast":return`contrast(${t.value||1})`;case"saturation":return`saturate(${t.value||1})`;case"hue":return`hue-rotate(${t.rotation||0}deg)`;case"blur":return`blur(${t.radius||0}px)`;case"shadow":{const n=this.toFilterColor(typeof t.color=="string"?t.color:void 0,typeof t.opacity=="number"?t.opacity:.8);return`drop-shadow(${t.offsetX||0}px ${t.offsetY||0}px ${t.blur||0}px ${n})`}case"glow":{const n=Number(t.radius||0),r=typeof t.intensity=="number"?Math.max(0,Math.min(3,t.intensity)):1,a=this.toFilterColor(typeof t.color=="string"?t.color:void 0,Math.min(1,.35*r)),o=this.toFilterColor(typeof t.color=="string"?t.color:void 0,Math.min(1,.2*r));return`drop-shadow(0 0 ${n}px ${a}) drop-shadow(0 0 ${Math.max(1,n/2)}px ${o})`}default:return""}}async applyEffect(e,t){return this.applyEffects(e,[t])}removeEffect(e,t){return e.filter(i=>i.id!==t)}reorderEffects(e,t,i){const n=[...e],[r]=n.splice(t,1);return n.splice(i,0,r),n}getEffectOrder(e){return e.filter(t=>t.enabled).map(t=>t.id)}static isWebGL2Supported(){try{return new OffscreenCanvas(1,1).getContext("webgl2")!==null}catch{return!1}}resize(e,t){if(this.width=e,this.height=t,this.canvas&&(this.canvas.width=e,this.canvas.height=t),this.renderer&&this.renderer.resize(e,t),this.gl){for(const i of this.renderTextures)this.gl.deleteTexture(i);this.renderTextures=[];for(let i=0;i<2;i++)this.renderTextures.push(this.createRenderTexture())}}getAvailableFilters(){return["brightness","contrast","saturation","hue","blur","sharpen","vignette","grain","chromaKey","temperature","tint","tonal","shadow","glow","motion-blur","radial-blur","chromatic-aberration"]}isFilterSupported(e){return this.getAvailableFilters().includes(e)}dispose(){if(this.renderer&&(this.renderer.destroy(),this.renderer=null),this.rendererFactory=null,this.useNewRenderer=!1,this.gl){for(const e of this.shaders.values())this.gl.deleteProgram(e.program);this.shaders.clear(),this.quadBuffer&&this.gl.deleteBuffer(this.quadBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer);for(const e of this.framebuffers)this.gl.deleteFramebuffer(e);for(const e of this.renderTextures)this.gl.deleteTexture(e);this.framebuffers=[],this.renderTextures=[]}this.canvas=null,this.gl=null,this.initialized=!1}getRendererType(){return this.useNewRenderer&&this.renderer?this.renderer.type:this.gl?"legacy-webgl2":"cpu"}isUsingWebGPU(){return this.useNewRenderer&&this.renderer?.type==="webgpu"}getRenderer(){return this.renderer}}let Dr=null;function Tee(s=1920,e=1080){return Dr?(Dr.width!==s||Dr.height!==e)&&Dr.resize(s,e):(Dr=new lu({width:s,height:e}),Dr.initialize().catch(t=>{console.error("[VideoEffectsEngine] Background initialization failed:",t)})),Dr}class zM{canvas=null;ctx=null;width;height;initialized=!1;scratchA=null;scratchACtx=null;scratchB=null;scratchBCtx=null;constructor(e){this.width=e.width,this.height=e.height,this.initializeCanvas()}initializeCanvas(){if(!this.initialized){try{typeof OffscreenCanvas<"u"&&(this.canvas=new OffscreenCanvas(this.width,this.height),this.ctx=this.canvas.getContext("2d"))}catch{this.canvas=null,this.ctx=null}this.initialized=!0}}getContext(){if(!this.ctx)throw new Error("Canvas context not available");return this.ctx}sourceDimensions(e){if(typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement)return{width:e.videoWidth,height:e.videoHeight};const t=e;return{width:t.width??0,height:t.height??0}}fitToCanvas(e,t){const{width:i,height:n}=this.sourceDimensions(e);if(i===this.width&&n===this.height||typeof OffscreenCanvas>"u"||i<=0||n<=0)return e;let r=t==="A"?this.scratchA:this.scratchB,a=t==="A"?this.scratchACtx:this.scratchBCtx;if((!r||r.width!==this.width||r.height!==this.height)&&(r=new OffscreenCanvas(this.width,this.height),a=r.getContext("2d"),t==="A"?(this.scratchA=r,this.scratchACtx=a):(this.scratchB=r,this.scratchBCtx=a)),!a)return e;const o=i/n,c=this.width/this.height;let l,u;o>c?(l=this.width,u=this.width/o):(u=this.height,l=this.height*o);const d=(this.width-l)/2,h=(this.height-u)/2;return a.clearRect(0,0,this.width,this.height),a.drawImage(e,d,h,l,u),r}async renderTransition(e,t,i,n){const r=performance.now(),a=await this.renderTransitionToCanvas(e,t,i,n);return{frame:await createImageBitmap(a),processingTime:performance.now()-r,gpuAccelerated:!1}}async renderTransitionToCanvas(e,t,i,n){if(!this.canvas||!this.ctx)throw new Error("Canvas not available. Rendering requires a browser environment.");const r=Math.max(0,Math.min(1,n)),a=this.applyEasing(r,i.params.curve),o=this.fitToCanvas(e,"A"),c=this.fitToCanvas(t,"B");switch(this.ctx.clearRect(0,0,this.width,this.height),i.type){case"crossfade":await this.renderCrossfade(o,c,a);break;case"dipToBlack":await this.renderDipToColor(o,c,a,"black",i.params.holdDuration||0);break;case"dipToWhite":await this.renderDipToColor(o,c,a,"white",i.params.holdDuration||0);break;case"wipe":await this.renderWipe(o,c,a,i.params.direction||"left",i.params.softness||0);break;case"slide":await this.renderSlide(o,c,a,i.params.direction||"left",i.params.pushOut||!1);break;case"zoom":await this.renderZoom(o,c,a,i.params.scale||2,i.params.center||{x:.5,y:.5});break;case"push":await this.renderPush(o,c,a,i.params.direction||"left");break;default:await this.renderCrossfade(o,c,a)}return this.canvas}async renderCrossfade(e,t,i){const n=this.getContext();n.globalAlpha=1-i,n.drawImage(e,0,0,this.width,this.height),n.globalAlpha=i,n.drawImage(t,0,0,this.width,this.height),n.globalAlpha=1}async renderDipToColor(e,t,i,n,r){const a=2+r,o=1/a,c=(1+r)/a,l=this.getContext();if(ir,ease:r=>r*r*(3-2*r),"ease-in":r=>r*r,"ease-out":r=>r*(2-r),"ease-in-out":r=>r<.5?2*r*r:-1+(4-2*r)*r};return(i[t||"linear"]||i.linear)(e)}validateTransition(e,t,i){const n=e.startTime+e.duration;if(Math.abs(t.startTime-n)>.001)return{valid:!1,error:"Clips must be adjacent to add a transition"};if(e.trackId!==t.trackId)return{valid:!1,error:"Clips must be on the same track"};const a=Math.min(e.duration,t.duration)*2;return i>a?{valid:!0,warning:`Insufficient handle frames. Maximum transition duration is ${a.toFixed(2)}s`,maxDuration:a}:i<=0?{valid:!1,error:"Transition duration must be positive"}:{valid:!0,maxDuration:a}}areClipsAdjacent(e,t){if(e.trackId!==t.trackId)return!1;const i=e.startTime+e.duration;return Math.abs(t.startTime-i)<.001}findAdjacentClipPairs(e){const t=[],i=[...e.clips].sort((n,r)=>n.startTime-r.startTime);for(let n=0;ni.id!==t)}}calculateTransitionProgress(e,t,i){const n=t.startTime+t.duration-e.duration/2,r=n+e.duration;return i<=n?0:i>=r?1:(i-n)/e.duration}isTimeInTransition(e,t,i){const n=t.startTime+t.duration-e.duration/2,r=n+e.duration;return i>=n&&i<=r}getEngineDimensions(){return{width:this.width,height:this.height}}resize(e,t){if(this.width=e,this.height=t,typeof OffscreenCanvas<"u")try{this.canvas=new OffscreenCanvas(e,t),this.ctx=this.canvas.getContext("2d")}catch{}}getAvailableTransitionTypes(){return["crossfade","dipToBlack","dipToWhite","wipe","slide","zoom","push"]}dispose(){this.ctx&&this.ctx.clearRect(0,0,this.width,this.height),this.canvas=null,this.ctx=null}}function TG(s=1920,e=1080){return new zM({width:s,height:e})}const kG=.1,AG=20;class SG{clipSpeedData=new Map;animationEngine;constructor(e){this.animationEngine=e||new Wh}setClipSpeed(e,t,i){const n=this.clampSpeed(t),r=this.getOrCreateSpeedData(e,i);r.baseSpeed=n,this.clipSpeedData.set(e,r)}getClipSpeed(e){return this.clipSpeedData.get(e)?.baseSpeed??1}getEffectiveDuration(e){const t=this.clipSpeedData.get(e);return t?t.keyframes.length>0?this.calculateVariableSpeedDuration(t):t.originalDuration/t.baseSpeed:0}calculateVariableSpeedDuration(e){if([...e.keyframes].sort((a,o)=>a.time-o.time).length===0)return e.originalDuration/e.baseSpeed;const i=1e3,n=e.originalDuration/i;let r=0;for(let a=0;aMath.abs(l.time-t)<.001);return c>=0?r.keyframes[c]=o:(r.keyframes.push(o),r.keyframes.sort((l,u)=>l.time-u.time)),a}removeSpeedKeyframe(e,t){const i=this.clipSpeedData.get(e);i&&(i.keyframes=i.keyframes.filter(n=>n.id!==t))}updateSpeedKeyframe(e,t,i){const n=this.clipSpeedData.get(e);if(!n)return;const r=n.keyframes.findIndex(c=>c.id===t);if(r===-1)return;const a=n.keyframes[r],o={...a,time:i.time!==void 0?Math.max(0,Math.min(n.originalDuration,i.time)):a.time,speed:i.speed!==void 0?this.clampSpeed(i.speed):a.speed,easing:i.easing??a.easing};n.keyframes[r]=o,n.keyframes.sort((c,l)=>c.time-l.time)}getSpeedKeyframes(e){return this.clipSpeedData.get(e)?.keyframes??[]}getSpeedAtTime(e,t){const i=this.clipSpeedData.get(e);return i?this.getSpeedAtSourceTime(i,t):1}getSpeedAtSourceTime(e,t){const i=e.keyframes;if(i.length===0)return e.baseSpeed;const n=[...i].sort((r,a)=>r.time-a.time);if(t<=n[0].time)return n[0].speed;if(t>=n[n.length-1].time)return n[n.length-1].speed;for(let r=0;r=n[r].time&&t<=n[r+1].time){const a=n[r],o=n[r+1],c=o.time-a.time,l=t-a.time,u=c>0?l/c:0,d=this.animationEngine.applyEasing(u,a.easing);return a.speed+(o.speed-a.speed)*d}return e.baseSpeed}createFreezeFrame(e,t,i,n){const r=this.clipSpeedData.get(e);if(!r)throw new Error(`No speed data for clip ${e}`);const o={id:`freeze-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,clipId:e,sourceTime:t,startTime:i,duration:n};return r.freezeFrames.push(o),r.freezeFrames.sort((c,l)=>c.startTime-l.startTime),o}removeFreezeFrame(e,t){const i=this.clipSpeedData.get(e);i&&(i.freezeFrames=i.freezeFrames.filter(n=>n.id!==t))}getFreezeFrames(e){return this.clipSpeedData.get(e)?.freezeFrames??[]}getFreezeFrameAtTime(e,t){const i=this.clipSpeedData.get(e);if(!i)return null;for(const n of i.freezeFrames)if(t>=n.startTime&&t0)return this.calculateSourceTimeWithVariableSpeed(i,r);let a=r*i.baseSpeed;return i.reverse&&(a=i.originalDuration-a),Math.max(0,Math.min(i.originalDuration,a))}calculateSourceTimeWithVariableSpeed(e,t){const i=this.calculateVariableSpeedDuration(e);if(t<=0)return 0;if(t>=i)return e.originalDuration;let n=0,r=e.originalDuration;const a=1e-4;for(;r-n>a;){const c=(n+r)/2;this.integratePlaybackTime(e,c).01&&l<.99,frameBefore:o*r,frameAfter:c*r,t:l}}getOrCreateSpeedData(e,t){let i=this.clipSpeedData.get(e);return i||(i={clipId:e,baseSpeed:1,reverse:!1,keyframes:[],pitchCorrection:!0,freezeFrames:[],originalDuration:t},this.clipSpeedData.set(e,i)),i}initializeClip(e,t){this.getOrCreateSpeedData(e,t)}removeClip(e){this.clipSpeedData.delete(e)}getClipIds(){return Array.from(this.clipSpeedData.keys())}getClipSpeedData(e){return this.clipSpeedData.get(e)}clear(){this.clipSpeedData.clear()}}let Rp=null;function Dp(){return Rp||(Rp=new SG),Rp}const r0={low:{quality:"low",blockSize:16,searchRadius:16,pyramidLevels:2},medium:{quality:"medium",blockSize:8,searchRadius:24,pyramidLevels:3},high:{quality:"high",blockSize:8,searchRadius:32,pyramidLevels:4}},CG=` +struct Params { + width: u32, + height: u32, + blockSize: u32, + searchRadius: u32, + blocksX: u32, + blocksY: u32, +} + +@group(0) @binding(0) var params: Params; +@group(0) @binding(1) var frame1: array; +@group(0) @binding(2) var frame2: array; +@group(0) @binding(3) var flowOutput: array; + +fn getGray(frame: ptr, read>, x: u32, y: u32) -> f32 { + if (x >= params.width || y >= params.height) { return 0.0; } + let pixel = (*frame)[y * params.width + x]; + let r = f32((pixel >> 0u) & 0xFFu); + let g = f32((pixel >> 8u) & 0xFFu); + let b = f32((pixel >> 16u) & 0xFFu); + return r * 0.299 + g * 0.587 + b * 0.114; +} + +fn computeSAD(bx: u32, by: u32, dx: i32, dy: i32) -> f32 { + var sad: f32 = 0.0; + for (var iy: u32 = 0u; iy < params.blockSize; iy++) { + for (var ix: u32 = 0u; ix < params.blockSize; ix++) { + let x1 = bx * params.blockSize + ix; + let y1 = by * params.blockSize + iy; + let x2 = i32(x1) + dx; + let y2 = i32(y1) + dy; + + if (x2 < 0 || x2 >= i32(params.width) || y2 < 0 || y2 >= i32(params.height)) { + sad += 128.0; + continue; + } + + let g1 = getGray(&frame1, x1, y1); + let g2 = getGray(&frame2, u32(x2), u32(y2)); + sad += abs(g1 - g2); + } + } + return sad; +} + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) gid: vec3) { + let bx = gid.x; + let by = gid.y; + if (bx >= params.blocksX || by >= params.blocksY) { return; } + + var bestDx: i32 = 0; + var bestDy: i32 = 0; + var bestSAD: f32 = 1e20; + let sr = i32(params.searchRadius); + + for (var sy: i32 = -sr; sy <= sr; sy += 2) { + for (var sx: i32 = -sr; sx <= sr; sx += 2) { + let sad = computeSAD(bx, by, sx, sy); + if (sad < bestSAD) { + bestSAD = sad; + bestDx = sx; + bestDy = sy; + } + } + } + + for (var sy: i32 = -1; sy <= 1; sy++) { + for (var sx: i32 = -1; sx <= 1; sx++) { + if (sx == 0 && sy == 0) { continue; } + let sad = computeSAD(bx, by, bestDx + sx, bestDy + sy); + if (sad < bestSAD) { + bestSAD = sad; + bestDx = bestDx + sx; + bestDy = bestDy + sy; + } + } + } + + let idx = (by * params.blocksX + bx) * 2u; + flowOutput[idx] = f32(bestDx); + flowOutput[idx + 1u] = f32(bestDy); +} +`,EG=` +struct WarpParams { + width: u32, + height: u32, + blocksX: u32, + blocksY: u32, + blockSize: u32, + t: f32, +} + +@group(0) @binding(0) var params: WarpParams; +@group(0) @binding(1) var frame1: array; +@group(0) @binding(2) var frame2: array; +@group(0) @binding(3) var flow: array; +@group(0) @binding(4) var output: array; + +fn sampleFrame(frame: ptr, read>, fx: f32, fy: f32) -> vec4 { + let x0 = u32(clamp(floor(fx), 0.0, f32(params.width - 1u))); + let y0 = u32(clamp(floor(fy), 0.0, f32(params.height - 1u))); + let x1 = min(x0 + 1u, params.width - 1u); + let y1 = min(y0 + 1u, params.height - 1u); + let wx = fx - floor(fx); + let wy = fy - floor(fy); + + let p00 = (*frame)[y0 * params.width + x0]; + let p10 = (*frame)[y0 * params.width + x1]; + let p01 = (*frame)[y1 * params.width + x0]; + let p11 = (*frame)[y1 * params.width + x1]; + + let c00 = vec4(f32(p00 & 0xFFu), f32((p00 >> 8u) & 0xFFu), f32((p00 >> 16u) & 0xFFu), 255.0); + let c10 = vec4(f32(p10 & 0xFFu), f32((p10 >> 8u) & 0xFFu), f32((p10 >> 16u) & 0xFFu), 255.0); + let c01 = vec4(f32(p01 & 0xFFu), f32((p01 >> 8u) & 0xFFu), f32((p01 >> 16u) & 0xFFu), 255.0); + let c11 = vec4(f32(p11 & 0xFFu), f32((p11 >> 8u) & 0xFFu), f32((p11 >> 16u) & 0xFFu), 255.0); + + return mix(mix(c00, c10, wx), mix(c01, c11, wx), wy); +} + +@compute @workgroup_size(16, 16) +fn main(@builtin(global_invocation_id) gid: vec3) { + let x = gid.x; + let y = gid.y; + if (x >= params.width || y >= params.height) { return; } + + let bx = min(x / params.blockSize, params.blocksX - 1u); + let by = min(y / params.blockSize, params.blocksY - 1u); + let flowIdx = (by * params.blocksX + bx) * 2u; + let dx = flow[flowIdx]; + let dy = flow[flowIdx + 1u]; + + let src1X = f32(x) - dx * params.t; + let src1Y = f32(y) - dy * params.t; + let src2X = f32(x) + dx * (1.0 - params.t); + let src2Y = f32(y) + dy * (1.0 - params.t); + + let color1 = sampleFrame(&frame1, src1X, src1Y); + let color2 = sampleFrame(&frame2, src2X, src2Y); + let blended = mix(color1, color2, params.t); + + let r = u32(clamp(blended.x, 0.0, 255.0)); + let g = u32(clamp(blended.y, 0.0, 255.0)); + let b = u32(clamp(blended.z, 0.0, 255.0)); + output[y * params.width + x] = r | (g << 8u) | (b << 16u) | (255u << 24u); +} +`;class d_{device=null;blockMatchPipeline=null;warpBlendPipeline=null;config;constructor(e){this.config=e}async initialize(){if(!navigator.gpu)return!1;try{const e=await navigator.gpu.requestAdapter();if(!e)return!1;this.device=await e.requestDevice();const t=this.device.createShaderModule({code:CG});this.blockMatchPipeline=this.device.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main"}});const i=this.device.createShaderModule({code:EG});return this.warpBlendPipeline=this.device.createComputePipeline({layout:"auto",compute:{module:i,entryPoint:"main"}}),!0}catch{return!1}}isReady(){return this.device!==null&&this.blockMatchPipeline!==null}async computeFlowField(e,t,i,n){if(!this.device||!this.blockMatchPipeline)throw new Error("GPU not initialized");const{blockSize:r,searchRadius:a}=this.config,o=Math.ceil(i/r),c=Math.ceil(n/r),l=this.device.createBuffer({size:24,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(l,0,new Uint32Array([i,n,r,a,o,c]));const u=this.device.createBuffer({size:e.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(u,0,e);const d=this.device.createBuffer({size:t.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(d,0,t);const h=o*c*2*4,f=this.device.createBuffer({size:h,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),p=this.device.createBindGroup({layout:this.blockMatchPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:l}},{binding:1,resource:{buffer:u}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:f}}]}),m=this.device.createCommandEncoder(),g=m.beginComputePass();g.setPipeline(this.blockMatchPipeline),g.setBindGroup(0,p),g.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(c/8)),g.end();const v=this.device.createBuffer({size:h,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});m.copyBufferToBuffer(f,0,v,0,h),this.device.queue.submit([m.finish()]),await v.mapAsync(GPUMapMode.READ);const w=new Float32Array(v.getMappedRange().slice(0));return v.unmap(),l.destroy(),u.destroy(),d.destroy(),f.destroy(),v.destroy(),{width:o,height:c,vectors:w}}async warpAndBlend(e,t,i,n,r,a){if(!this.device||!this.warpBlendPipeline)throw new Error("GPU not initialized");const{blockSize:o}=this.config,c=new ArrayBuffer(24),l=new DataView(c);l.setUint32(0,n,!0),l.setUint32(4,r,!0),l.setUint32(8,i.width,!0),l.setUint32(12,i.height,!0),l.setUint32(16,o,!0),l.setFloat32(20,a,!0);const u=this.device.createBuffer({size:24,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(u,0,new Uint8Array(c));const d=this.device.createBuffer({size:e.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(d,0,e);const h=this.device.createBuffer({size:t.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(h,0,t);const f=this.device.createBuffer({size:i.vectors.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(f,0,i.vectors);const p=n*r*4,m=this.device.createBuffer({size:p,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),g=this.device.createBindGroup({layout:this.warpBlendPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:{buffer:d}},{binding:2,resource:{buffer:h}},{binding:3,resource:{buffer:f}},{binding:4,resource:{buffer:m}}]}),v=this.device.createCommandEncoder(),w=v.beginComputePass();w.setPipeline(this.warpBlendPipeline),w.setBindGroup(0,g),w.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(r/16)),w.end();const b=this.device.createBuffer({size:p,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});v.copyBufferToBuffer(m,0,b,0,p),this.device.queue.submit([v.finish()]),await b.mapAsync(GPUMapMode.READ);const k=new Uint32Array(b.getMappedRange().slice(0));return b.unmap(),u.destroy(),d.destroy(),h.destroy(),f.destroy(),m.destroy(),b.destroy(),k}dispose(){this.device?.destroy(),this.device=null,this.blockMatchPipeline=null,this.warpBlendPipeline=null}}class a0{config;constructor(e){this.config=e}async computeFlowField(e,t){const{blockSize:i,searchRadius:n,pyramidLevels:r}=this.config,a=this.buildPyramid(e,r),o=this.buildPyramid(t,r),c=a[r-1].width,l=a[r-1].height,u=Math.ceil(c/i),d=Math.ceil(l/i);let h={width:u,height:d,vectors:new Float32Array(u*d*2)};for(let f=r-1;f>=0;f--){const p=a[f],m=o[f],g=Math.ceil(p.width/i),v=Math.ceil(p.height/i),w={width:g,height:v,vectors:new Float32Array(g*v*2)},b=f=l||p<0||p>=u){c+=128;continue}if(m<0||m>=l||g<0||g>=u){c+=128;continue}const v=(p*l+f)*4,w=(g*l+m)*4,b=e.data[v]*.299+e.data[v+1]*.587+e.data[v+2]*.114,k=t.data[w]*.299+t.data[w+1]*.587+t.data[w+2]*.114;c+=Math.abs(b-k)}return c}bilinearSample(e,t,i){const n=e.width,r=e.height,a=Math.max(0,Math.min(n-1,Math.floor(t))),o=Math.max(0,Math.min(r-1,Math.floor(i))),c=Math.min(n-1,a+1),l=Math.min(r-1,o+1),u=t-a,d=i-o,h=(o*n+a)*4,f=(o*n+c)*4,p=(l*n+a)*4,m=(l*n+c)*4,g=e.data[h]*(1-u)*(1-d)+e.data[f]*u*(1-d)+e.data[p]*(1-u)*d+e.data[m]*u*d,v=e.data[h+1]*(1-u)*(1-d)+e.data[f+1]*u*(1-d)+e.data[p+1]*(1-u)*d+e.data[m+1]*u*d,w=e.data[h+2]*(1-u)*(1-d)+e.data[f+2]*u*(1-d)+e.data[p+2]*(1-u)*d+e.data[m+2]*u*d;return[g,v,w]}buildPyramid(e,t){const i=[e];for(let n=1;n>2,c.data[f+1]=r.data[p+1]+r.data[m+1]+r.data[g+1]+r.data[v+1]>>2,c.data[f+2]=r.data[p+2]+r.data[m+2]+r.data[g+2]+r.data[v+2]>>2,c.data[f+3]=255}i.push(c)}return i}}class h_{cache=new Map;maxEntries;constructor(e=10){this.maxEntries=e}static makeKey(e,t,i){return`${e}:${t.toFixed(4)}:${i.toFixed(4)}`}get(e){const t=this.cache.get(e);return t?(t.lastAccessed=performance.now(),t.flowField):null}set(e,t){this.cache.size>=this.maxEntries&&this.evictLRU(),this.cache.set(e,{flowField:t,lastAccessed:performance.now()})}evictLRU(){let e="",t=1/0;for(const[i,n]of this.cache)n.lastAccessed{this.gpuFlow=new d_(this.config),this.gpuReady=await this.gpuFlow.initialize(),this.gpuReady||(this.gpuFlow=null)})(),this.initPromise)}setQuality(e){this.config.quality!==e&&(this.config=r0[e],this.cpuFlow=new a0(this.config),this.gpuFlow&&(this.gpuFlow.dispose(),this.gpuFlow=new d_(this.config),this.gpuFlow.initialize().then(t=>{this.gpuReady=t,t||(this.gpuFlow=null)})),this.cache.clear())}setFrameBudget(e){this.frameBudgetMs=e}resetBudget(){this.budgetExceeded=!1}async interpolate(e,t,i,n,r,a){const o=performance.now();if(this.budgetExceeded)return this.simpleBlend(e,t,i,o);try{const c=h_.makeKey(n,r,a);let l=this.cache.get(c);const u=e.width,d=e.height;if(!l){const{data1:p,data2:m}=this.extractPixelData(e,t);if(this.gpuReady&&this.gpuFlow){const g=new Uint32Array(p.buffer),v=new Uint32Array(m.buffer);l=await this.gpuFlow.computeFlowField(g,v,u,d)}else{const g=new ImageData(p.slice(0),u,d),v=new ImageData(m.slice(0),u,d);l=await this.cpuFlow.computeFlowField(g,v)}this.cache.set(c,l)}const h=await this.warpFrames(e,t,l,u,d,i),f=performance.now()-o;return f>this.frameBudgetMs*2&&(this.budgetExceeded=!0),{frame:h,computeTimeMs:f,method:"optical-flow"}}catch{return this.simpleBlend(e,t,i,o)}}extractPixelData(e,t){const n=new OffscreenCanvas(e.width,e.height).getContext("2d");n.drawImage(e,0,0);const r=n.getImageData(0,0,e.width,e.height).data;n.drawImage(t,0,0);const a=n.getImageData(0,0,t.width,t.height).data;return{data1:r,data2:a}}async warpFrames(e,t,i,n,r,a){if(this.gpuReady&&this.gpuFlow){const{data1:h,data2:f}=this.extractPixelData(e,t),p=new Uint32Array(h.buffer),m=new Uint32Array(f.buffer),g=await this.gpuFlow.warpAndBlend(p,m,i,n,r,a),v=new OffscreenCanvas(n,r),w=v.getContext("2d"),b=w.createImageData(n,r);return new Uint32Array(b.data.buffer).set(g),w.putImageData(b,0,0),v.transferToImageBitmap()}const o=new OffscreenCanvas(n,r),c=o.getContext("2d");c.drawImage(e,0,0);const l=c.getImageData(0,0,n,r);c.drawImage(t,0,0);const u=c.getImageData(0,0,n,r),d=this.cpuFlow.warpAndBlend(l,u,i,a);return c.putImageData(d,0,0),o.transferToImageBitmap()}async simpleBlend(e,t,i,n){const r=new OffscreenCanvas(e.width,e.height),a=r.getContext("2d");return a.globalAlpha=1-i,a.drawImage(e,0,0),a.globalAlpha=i,a.drawImage(t,0,0),a.globalAlpha=1,{frame:r.transferToImageBitmap(),computeTimeMs:performance.now()-n,method:"blend"}}dispose(){this.gpuFlow?.dispose(),this.gpuFlow=null,this.cache.clear()}}let ju=null;function IG(){return ju||(ju=new MG,ju.initialize()),ju}const PG=3,GM={strength:50,cropMode:"auto",analysisInterval:2};function RG(s,e){const{width:t,height:i,vectors:n}=s,r=t*i,a=[];for(let c=0;ct.count||a.count===t.count&&a.totalMagnitude>t.totalMagnitude)&&(t=a);if(!t)return{dx:0,dy:0};let i=0,n=0,r=0;for(const a of s)if(Math.abs(a.dx-t.qdx)<=1&&Math.abs(a.dy-t.qdy)<=1){const o=Math.max(a.magnitude,1);i+=a.dx*o,n+=a.dy*o,r+=o}return r===0?{dx:t.totalDx/t.count,dy:t.totalDy/t.count}:{dx:i/r,dy:n/r}}function FG(s){const e=[0],t=[0],i=[0];for(let n=0;n0||d>0)){const h=Math.max(o-u*2,1),f=Math.max(c-d*2,1),p=Math.max(o/h,c/f),m=Math.min(p,1.15);for(const g of l)g.scale=m}return l}class BG{profiles=new Map;flowEngine;constructor(){this.flowEngine=new a0(r0.high)}hasProfile(e){return this.profiles.has(e)}setProfile(e){this.profiles.set(e.clipId,e)}async analyzeClip(e,t,i,n=0,r=GM,a){if(!Number.isFinite(i)||i<=0)throw new Error("Stabilization analysis requires a positive duration");if(!Number.isFinite(n)||n<0)throw new Error("Stabilization analysis requires a valid source start time");if(t.videoWidth<=0||t.videoHeight<=0)throw new Error("Stabilization analysis requires loaded video metadata");const o=30,c=Math.max(1,r.analysisInterval),l=Math.max(1,Math.ceil(i*o/c)),u=c/o,d=Math.max(i-.001,0),h=Math.min(960,t.videoWidth),f=Math.round(h*(t.videoHeight/t.videoWidth)),p=document.createElement("canvas");p.width=h,p.height=f;const m=p.getContext("2d");let g=null;const v=[],w=Number.isFinite(t.duration)?Math.max(t.duration-.001,0):n+d,b=Math.max(12,h*.03);for(let y=0;y<=l;y++){const _=Math.min(y*u,d),T=Math.min(n+_,w);await this.seekVideoFrame(t,T),m.drawImage(t,0,0,h,f);const S=m.getImageData(0,0,h,f);if(g){const C=await this.flowEngine.computeFlowField(g,S),E=this.clampMotionSample(RG(C,T),b);v.push(E)}g=S,a?.(y/l)}const{cumDx:k,cumDy:A,cumRotation:M}=FG(v),R=Fp(k,r.strength),I=Fp(A,r.strength),D=Fp(M,r.strength),B=OG(k,A,M,R,I,D,r.cropMode,h,f);let $=0;for(const y of B){const _=Math.sqrt(y.dx*y.dx+y.dy*y.dy);$=Math.max($,_)}const V={clipId:e,samples:v,corrections:B,maxDisplacement:$,frameInterval:u,duration:i,sourceStartTime:n,analysisDimensions:{width:h,height:f}};return this.profiles.set(e,V),V}clampMotionSample(e,t){const i=Math.hypot(e.dx,e.dy);if(i<=t||i===0)return e;const n=t/i;return{...e,dx:e.dx*n,dy:e.dy*n}}async seekVideoFrame(e,t){const i=Number.isFinite(e.duration)?Math.max(e.duration-.001,0):Math.max(t,0),n=Math.max(0,Math.min(t,i)),r=n<=0&&i>.002?.001:n;(Math.abs(e.currentTime-r)>.01||e.readyState{let c=!1;const l=()=>{c||(c=!0,d&&window.clearTimeout(d),e.removeEventListener("seeked",u),o())},u=()=>{l()},d=window.setTimeout(l,3e3);e.addEventListener("seeked",u),e.currentTime=r}),await this.waitForRenderableFrame(e)}async waitForRenderableFrame(e){await new Promise(t=>{let i=!1,n=null;const r=()=>{i||(i=!0,a&&window.clearTimeout(a),n!==null&&typeof e.cancelVideoFrameCallback=="function"&&e.cancelVideoFrameCallback(n),t())},a=window.setTimeout(r,250);if(typeof e.requestVideoFrameCallback=="function"){n=e.requestVideoFrameCallback(()=>{r()});return}window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{r()})})})}getCorrectionTransform(e,t,i){const n=this.profiles.get(e);if(!n||n.corrections.length===0)return null;const a=Math.max(0,Math.min(t-n.sourceStartTime,n.duration))/n.frameInterval,o=Math.min(Math.floor(a),n.corrections.length-1),c=Math.min(o+1,n.corrections.length-1),l=a-o,u=n.corrections[o],d=n.corrections[c],h=o===c?u:{dx:u.dx+(d.dx-u.dx)*l,dy:u.dy+(d.dy-u.dy)*l,rotation:u.rotation+(d.rotation-u.rotation)*l,scale:u.scale+(d.scale-u.scale)*l};if(!i||i.sourceWidth<=0||i.sourceHeight<=0)return h;const f=Math.min(i.canvasWidth/i.sourceWidth,i.canvasHeight/i.sourceHeight),p=i.sourceWidth/n.analysisDimensions.width*f,m=i.sourceHeight/n.analysisDimensions.height*f;return{...h,dx:h.dx*p,dy:h.dy*m}}removeProfile(e){this.profiles.delete(e)}dispose(){this.profiles.clear()}}function $G(s,e,t,i){if(!s.stabilization?.enabled||!s.stabilization.analyzed||s.stabilization.analysisVersion!==PG)return e;const n=jG();!n.hasProfile(s.id)&&s.stabilization.profile&&n.setProfile(s.stabilization.profile);const r=n.getCorrectionTransform(s.id,t,i);return r?{...e,position:{x:e.position.x+r.dx,y:e.position.y+r.dy},rotation:e.rotation+r.rotation*180/Math.PI,scale:{x:e.scale.x*r.scale,y:e.scale.y*r.scale}}:e}let Lp=null;function jG(){return Lp||(Lp=new BG),Lp}const f_={mt:"https://mediashares.openreel.video/ffmpeg-vidstab/mt",st:"https://mediashares.openreel.video/ffmpeg-vidstab/st"};class NG{ffmpeg=null;loaded=!1;loading=null;stabilizedBlobs=new Map;async load(e){if(!this.loaded){if(this.loading)return this.loading;this.loading=this.doLoad(e),await this.loading}}async doLoad(e){try{const{FFmpeg:t}=await ii(async()=>{const{FFmpeg:a}=await import("./index-DfgTfcu_.js");return{FFmpeg:a}},[]),{toBlobURL:i}=await ii(async()=>{const{toBlobURL:a}=await import("./index-CiM7N5zy.js");return{toBlobURL:a}},[]);this.ffmpeg=new t,e?.({stage:"downloading",progress:0});const n=typeof crossOriginIsolated<"u"&&crossOriginIsolated,r=n?f_.mt:f_.st;if(n){const[a,o,c]=await Promise.all([i(`${r}/ffmpeg-core.js`,"text/javascript"),i(`${r}/ffmpeg-core.wasm`,"application/wasm"),i(`${r}/ffmpeg-core.worker.js`,"text/javascript")]);e?.({stage:"downloading",progress:.9}),await this.ffmpeg.load({coreURL:a,wasmURL:o,workerURL:c})}else{const[a,o]=await Promise.all([i(`${r}/ffmpeg-core.js`,"text/javascript"),i(`${r}/ffmpeg-core.wasm`,"application/wasm")]);e?.({stage:"downloading",progress:.9}),await this.ffmpeg.load({coreURL:a,wasmURL:o})}e?.({stage:"downloading",progress:1}),this.loaded=!0}catch(t){throw this.loading=null,new Error(`Failed to load FFmpeg vidstab core: ${t instanceof Error?t.message:"Unknown error"}`)}}isLoaded(){return this.loaded&&this.ffmpeg!==null}hasStabilized(e){return this.stabilizedBlobs.has(e)}getStabilizedBlob(e){return this.stabilizedBlobs.get(e)??null}async stabilize(e,t,i=GM,n,r){if(!this.ffmpeg||!this.loaded)throw new Error("VidstabEngine not loaded. Call load() first.");const a=new Uint8Array(await t.arrayBuffer());await this.ffmpeg.writeFile("input.mp4",a);const o=Math.max(1,Math.min(10,Math.round(i.strength/10))),c=Math.max(3,Math.min(15,Math.round(i.strength/100*15))),l=Math.max(1,Math.round(i.strength/100*30)),u=i.cropMode==="auto"?-1:0,d=[];let h=0,f=0;const p=A=>{if(!A.message)return;d.push(A.message);const M=A.message.match(/Duration:\s*(\d+):(\d+):(\d+)\.(\d+)/);if(M){const R=parseInt(M[1])*3600+parseInt(M[2])*60+parseInt(M[3])+parseInt(M[4])/100,I=d.join(" ").match(/(\d+(?:\.\d+)?) fps/),D=I?parseFloat(I[1]):30;f=Math.round(R*D)}A.message.includes("Discarding frame")&&(h++,f>0&&n?.({stage:"detecting",progress:h/f}))};this.ffmpeg.on("log",p);let m=null;m=A=>{if(A.progress!==void 0&&A.progress>0)n?.({stage:"detecting",progress:Math.min(A.progress,1)});else if(A.time!==void 0&&A.time>0&&f>0){const M=A.time/1e6,R=d.join(" ").match(/(\d+(?:\.\d+)?) fps/),I=R?parseFloat(R[1]):30,D=f/I;D>0&&n?.({stage:"detecting",progress:Math.min(M/D,.99)})}},this.ffmpeg.on("progress",m);const g=[];if(r&&r.inPoint>0&&g.push("-ss",r.inPoint.toString()),g.push("-i","input.mp4"),r&&r.outPoint>r.inPoint&&g.push("-t",(r.outPoint-r.inPoint).toString()),await this.ffmpeg.exec([...g,"-an","-vf",`vidstabdetect=shakiness=${o}:accuracy=${c}:result=transforms.trf`,"-f","null","-"])!==0)throw this.ffmpeg.off("progress",m),this.ffmpeg.off("log",p),await this.cleanup(),new Error(`vidstabdetect failed: ${d.slice(-5).join(" | ")}`);this.ffmpeg.off("progress",m),n?.({stage:"stabilizing",progress:0}),m=A=>{if(A.progress!==void 0&&A.progress>0)n?.({stage:"stabilizing",progress:Math.min(A.progress,1)});else if(A.time!==void 0&&A.time>0&&f>0){const M=A.time/1e6,R=d.join(" ").match(/(\d+(?:\.\d+)?) fps/),I=R?parseFloat(R[1]):30,D=f/I;D>0&&n?.({stage:"stabilizing",progress:Math.min(M/D,.99)})}},this.ffmpeg.on("progress",m);const w=await this.ffmpeg.exec([...g,"-vf",`vidstabtransform=input=transforms.trf:smoothing=${l}:zoom=${u}:interpol=bicubic`,"-preset","slow","-crf","15","-c:a","copy","output.mp4"]);if(this.ffmpeg.off("progress",m),this.ffmpeg.off("log",p),w!==0)throw await this.cleanup(),new Error(`vidstabtransform failed: ${d.slice(-5).join(" | ")}`);const b=await this.ffmpeg.readFile("output.mp4"),k=new Blob([b.buffer],{type:"video/mp4"});return this.stabilizedBlobs.set(e,k),await this.cleanup(),k}async cleanup(){if(this.ffmpeg){try{await this.ffmpeg.deleteFile("input.mp4")}catch{}try{await this.ffmpeg.deleteFile("output.mp4")}catch{}try{await this.ffmpeg.deleteFile("transforms.trf")}catch{}}}removeStabilized(e){this.stabilizedBlobs.delete(e)}dispose(){this.stabilizedBlobs.clear(),this.ffmpeg&&(this.ffmpeg.terminate(),this.ffmpeg=null),this.loaded=!1,this.loading=null}}let Op=null;function Bp(){return Op||(Op=new NG),Op}const p_=new Map;let o0=0,Ia=null;async function WM(){if(Ia)return Ia;try{return Ia=await ii(()=>import("./index-DjtrfS0G.js"),[]),Ia}catch{try{return Ia=await ii(()=>import("https://esm.sh/mediabunny@1.25.3"),[]),Ia}catch{return null}}}async function VG(s,e,t,i){const n=p_.get(s);if(n)return n;try{const r=await WM();if(!r)return null;const{Input:a,ALL_FORMATS:o,BlobSource:c,CanvasSink:l}=r,u=new a({source:new c(e),formats:o}),d=await u.getPrimaryVideoTrack();if(!d)return null;const h=new l(d,{width:t,height:i,fit:"contain"}),f={input:u,sink:h,videoTrack:d,blobUrl:URL.createObjectURL(e)};return p_.set(s,f),f}catch(r){return console.error(`[DecodeWorker ${o0}] Failed to create resources for ${s}:`,r),null}}async function UG(s){const{requestId:e,clipId:t,blob:i,time:n,width:r,height:a}=s;try{const o=await VG(t,i,r,a);if(!o)return{type:"decoded",requestId:e,clipId:t,bitmap:null,time:n,error:"Failed to create decode resources"};const l=await o.sink.getCanvas(n);if(!l?.canvas)return{type:"decoded",requestId:e,clipId:t,bitmap:null,time:n,error:"No frame at requested time"};const u=await createImageBitmap(l.canvas);return{type:"decoded",requestId:e,clipId:t,bitmap:u,time:n}}catch(o){return{type:"decoded",requestId:e,clipId:t,bitmap:null,time:n,error:o instanceof Error?o.message:"Unknown decode error"}}}const Nu=self;Nu.onmessage=async s=>{const e=s.data;switch(e.type){case"init":o0=Math.floor(Math.random()*1e4),await WM();const t={type:"ready",workerId:o0};Nu.postMessage(t);break;case"decode":const i=await UG(e);i.bitmap?Nu.postMessage(i,{transfer:[i.bitmap]}):Nu.postMessage(i);break}};const zG=` +const resourceCache = new Map(); +let workerId = 0; +let mediabunnyModule = null; +let mediabunnyAvailable = false; + +async function loadMediaBunny() { + if (mediabunnyModule) { + return mediabunnyModule; + } + try { + mediabunnyModule = await import("mediabunny"); + mediabunnyAvailable = true; + return mediabunnyModule; + } catch (error) { + try { + mediabunnyModule = await import("https://esm.sh/mediabunny@1.25.3"); + mediabunnyAvailable = true; + return mediabunnyModule; + } catch (cdnError) { + mediabunnyAvailable = false; + return null; + } + } +} + +async function getOrCreateResources(clipId, blob, width, height) { + if (!mediabunnyAvailable || !mediabunnyModule) { + return null; + } + + const cached = resourceCache.get(clipId); + if (cached) { + return cached; + } + + try { + const { Input, ALL_FORMATS, BlobSource, CanvasSink } = mediabunnyModule; + + const input = new Input({ + source: new BlobSource(blob), + formats: ALL_FORMATS, + }); + + const videoTrack = await input.getPrimaryVideoTrack(); + if (!videoTrack) { + return null; + } + + const sink = new CanvasSink(videoTrack, { + width, + height, + fit: "contain", + }); + + const resource = { + input, + sink, + videoTrack, + blobUrl: URL.createObjectURL(blob), + }; + + resourceCache.set(clipId, resource); + return resource; + } catch (error) { + return null; + } +} + +async function decodeFrame(request) { + const { requestId, clipId, blob, time, width, height } = request; + + if (!mediabunnyAvailable) { + return { + type: "decoded", + requestId, + clipId, + bitmap: null, + time, + error: "MediaBunny not available in worker", + }; + } + + try { + const resources = await getOrCreateResources(clipId, blob, width, height); + if (!resources) { + return { + type: "decoded", + requestId, + clipId, + bitmap: null, + time, + error: "Failed to create decode resources", + }; + } + + const frameResult = await resources.sink.getCanvas(time); + if (!frameResult?.canvas) { + return { + type: "decoded", + requestId, + clipId, + bitmap: null, + time, + error: "No frame at requested time", + }; + } + + const bitmap = await createImageBitmap(frameResult.canvas); + + return { + type: "decoded", + requestId, + clipId, + bitmap, + time, + }; + } catch (error) { + return { + type: "decoded", + requestId, + clipId, + bitmap: null, + time, + error: error instanceof Error ? error.message : "Unknown decode error", + }; + } +} + +self.onmessage = async (event) => { + const request = event.data; + + switch (request.type) { + case "init": + workerId = Math.floor(Math.random() * 10000); + await loadMediaBunny(); + self.postMessage({ type: "ready", workerId, mediabunnyAvailable }); + break; + + case "decode": + const response = await decodeFrame(request); + if (response.bitmap) { + self.postMessage(response, [response.bitmap]); + } else { + self.postMessage(response); + } + break; + } +}; +`;function GG(){return new Blob([zG],{type:"application/javascript"})}function WG(){const s=GG();return URL.createObjectURL(s)}class qG{constructor(e=4){this.workerCount=e,this.workerCount=Math.max(1,Math.min(e,navigator.hardwareConcurrency||4))}workers=[];workerUrls=[];requestQueue=[];frameCache=new Map;maxCacheSize=100;cacheHits=0;cacheMisses=0;initialized=!1;initPromise=null;requestIdCounter=0;mediabunnyAvailable=!1;isAvailable(){return this.initialized&&this.mediabunnyAvailable}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this.doInitialize(),this.initPromise)}async doInitialize(){const e=[];for(let t=0;tt.mediabunnyAvailable),this.initialized=!0}async createWorker(e){return new Promise((t,i)=>{const n=WG();this.workerUrls.push(n);const r=new Worker(n,{type:"module"}),a={worker:r,workerId:e,busy:!1,pendingRequests:new Map,totalDecodes:0,totalDecodeTime:0,mediabunnyAvailable:!1},o=setTimeout(()=>{i(new Error(`Worker ${e} initialization timed out`))},1e4);r.onmessage=c=>{const l=c.data;if(l.type==="ready"){clearTimeout(o),a.workerId=l.workerId,a.mediabunnyAvailable=l.mediabunnyAvailable??!1,a.mediabunnyAvailable,t(a);return}l.type==="decoded"&&this.handleDecodeResponse(a,l)},r.onerror=c=>{console.error(`[ParallelFrameDecoder] Worker ${e} error:`,c),clearTimeout(o),i(c)},r.postMessage({type:"init"})})}async handleDecodeResponse(e,t){const i=e.pendingRequests.get(t.requestId);if(!i){console.warn(`[ParallelFrameDecoder] No pending request for ${t.requestId}`);return}e.pendingRequests.delete(t.requestId),e.busy=e.pendingRequests.size>0;const n=performance.now()-i.startTime;e.totalDecodes++,e.totalDecodeTime+=n;let r=null;if(t.bitmap){const a=`${t.clipId}:${t.time.toFixed(3)}`;this.addToCache(a,t.bitmap);try{r=await createImageBitmap(t.bitmap)}catch{r=null}}i.resolve({clipId:t.clipId,bitmap:r,time:t.time,error:t.error}),this.processQueue()}addToCache(e,t){if(this.frameCache.size>=this.maxCacheSize){let i=null,n=1/0;for(const[r,a]of this.frameCache)a.timestamp0;){const e=this.getLeastBusyWorker();if(!e||e.pendingRequests.size>=2)break;const t=this.requestQueue.shift();t&&this.sendDecodeRequest(e,t.request,t.resolve,t.reject)}}sendDecodeRequest(e,t,i,n){const r=`req_${this.requestIdCounter++}`,a={resolve:i,reject:n,clipId:t.clipId,startTime:performance.now()};e.pendingRequests.set(r,a),e.busy=!0;const o={type:"decode",requestId:r,clipId:t.clipId,blob:t.blob,time:t.time,width:t.width,height:t.height};e.worker.postMessage(o)}async decodeFrame(e){this.initialized||await this.initialize();const t=await this.getFromCache(e.clipId,e.time);return t?{clipId:e.clipId,bitmap:t,time:e.time}:new Promise((i,n)=>{const r=this.getLeastBusyWorker();r&&r.pendingRequests.size<2?this.sendDecodeRequest(r,e,i,n):this.requestQueue.push({request:e,resolve:i,reject:n})})}async decodeFrames(e){this.initialized||await this.initialize();const t=new Map,i=[];for(const r of e)i.push(this.decodeFrame(r));const n=await Promise.all(i);for(const r of n)t.set(r.clipId,r);return t}async decodeClipsAtTime(e,t,i){const n=e.map(o=>({clipId:o.clipId,blob:o.blob,time:o.time,width:t,height:i})),r=await this.decodeFrames(n),a=new Map;for(const[o,c]of r)c.bitmap&&a.set(o,c.bitmap);return a}getStats(){let e=0,t=0,i=0;for(const n of this.workers)e+=n.totalDecodes,t+=n.totalDecodeTime,i+=n.pendingRequests.size;return{workerCount:this.workers.length,totalDecodes:e,averageDecodeTime:e>0?t/e:0,pendingRequests:i+this.requestQueue.length,cacheHits:this.cacheHits,cacheMisses:this.cacheMisses}}clearCache(){for(const[,e]of this.frameCache)e.bitmap.close();this.frameCache.clear(),this.cacheHits=0,this.cacheMisses=0}dispose(){for(const e of this.workers){for(const[,t]of e.pendingRequests)t.reject(new Error("Decoder disposed"));e.worker.terminate()}this.workers=[];for(const e of this.workerUrls)URL.revokeObjectURL(e);this.workerUrls=[],this.clearCache();for(const e of this.requestQueue)e.reject(new Error("Decoder disposed"));this.requestQueue=[],this.initialized=!1,this.initPromise=null}}let $p=null;function HG(){if(!$p){const s=Math.min(4,navigator.hardwareConcurrency||4);$p=new qG(s)}return $p}class m_{buffers;writeIndex=0;presentIndex=1;bufferSize;framesWritten=0;framesPresented=0;framesDropped=0;fallbacksUsed=0;latencySum=0;latencyCount=0;lastWriteTime=0;lastPresentTime=0;constructor(e=3){this.bufferSize=Math.max(2,Math.min(e,8)),this.buffers=new Array(this.bufferSize).fill(null)}write(e,t,i){const n=this.buffers[this.writeIndex];n&&n.bitmap.close(),this.buffers[this.writeIndex]={bitmap:e,timestamp:t,frameNumber:i},this.lastWriteTime=performance.now(),this.framesWritten++,this.writeIndex=(this.writeIndex+1)%this.bufferSize,this.writeIndex===this.presentIndex&&(this.presentIndex=(this.presentIndex+1)%this.bufferSize,this.framesDropped++)}async writeFromCanvas(e,t,i){const n=await createImageBitmap(e);this.write(n,t,i)}present(){const e=(this.presentIndex-1+this.bufferSize)%this.bufferSize,t=this.buffers[e];if(t){const i=performance.now();if(this.lastWriteTime>0){const n=i-this.lastWriteTime;this.latencySum+=n,this.latencyCount++}return this.lastPresentTime=i,this.framesPresented++,t}return null}presentOrFallback(){const e=this.present();if(e)return e;for(let t=1;t0?this.latencySum/this.latencyCount:0}}getTimingInfo(){return{lastWriteTime:this.lastWriteTime,lastPresentTime:this.lastPresentTime}}reset(){for(let e=0;ethis.layers.get(e)).filter(Boolean)}setLayerVisibility(e,t){const i=this.layers.get(e);i&&(i.visible=t,this.isDirty=!0)}setLayerOpacity(e,t){const i=this.layers.get(e);i&&(i.opacity=Math.max(0,Math.min(1,t)),this.isDirty=!0)}setLayerBlendMode(e,t){const i=this.layers.get(e);i&&(i.blendMode=t,this.isDirty=!0)}setLayerTransform(e,t){const i=this.layers.get(e);i&&(i.transform=t,this.isDirty=!0)}setLayerZIndex(e,t){const i=this.layers.get(e);i&&(i.zIndex=t,this.sortLayers(),this.isDirty=!0)}sortLayers(){this.sortedLayerIds=Array.from(this.layers.keys()).sort((e,t)=>{const i=this.layers.get(e),n=this.layers.get(t);return i.zIndex-n.zIndex})}async createTextureFromCanvas(e){if(!this.renderer)throw new Error("Renderer not set");const t=await createImageBitmap(e),i=this.renderer.createTextureFromImage(t);return this.stats.texturesCreated++,i!==t&&t.close(),i}async createTextureFromBitmap(e){if(!this.renderer)throw new Error("Renderer not set");const t=this.renderer.createTextureFromImage(e);return this.stats.texturesCreated++,t}async composite(){if(!this.renderer)throw new Error("Renderer not set");const e=performance.now();this.renderer.beginFrame();let t=0;for(const r of this.sortedLayerIds){const a=this.layers.get(r);if(!a||!a.visible)continue;let o=a.texture;if(a.texture instanceof ImageBitmap)o=this.renderer.createTextureFromImage(a.texture);else if(a.texture instanceof HTMLCanvasElement||a.texture instanceof OffscreenCanvas){const u=await createImageBitmap(a.texture);o=this.renderer.createTextureFromImage(u),o!==u&&u.close()}const c=[...a.effects];a.blendMode!=="normal"&&c.push({id:`blend-${a.id}`,type:"blend",enabled:!0,params:{mode:a.blendMode}}),c.length>0&&(o=this.renderer.applyEffects(o,c));const l={texture:o,transform:a.transform,effects:[],opacity:a.opacity,borderRadius:a.borderRadius};this.renderer.renderLayer(l),t++}const i=await this.renderer.endFrame(),n=performance.now()-e;return this.recordCompositeDuration(n),this.stats.layersComposited=t,this.isDirty=!1,i}async compositeToCanvas(e){const t=await this.composite();e.drawImage(t,0,0),t.close()}recordCompositeDuration(e){this.stats.lastCompositeDuration=e,this.compositeDurations.push(e),this.compositeDurations.length>this.maxDurationSamples&&this.compositeDurations.shift();const t=this.compositeDurations.reduce((i,n)=>i+n,0);this.stats.averageCompositeDuration=t/this.compositeDurations.length}isDirtyFrame(){return this.isDirty}markDirty(){this.isDirty=!0}getStats(){return{...this.stats}}resetStats(){this.stats={layersComposited:0,lastCompositeDuration:0,averageCompositeDuration:0,texturesCreated:0,texturesReleased:0},this.compositeDurations=[]}dispose(){this.clearLayers(),this.renderer=null}}let Vu=null;function QG(s){return Vu&&Vu.dispose(),Vu=new KG(s),Vu}class JG{animationEngine;motionPaths=new Map;clipboard=null;constructor(e){this.animationEngine=e||new Wh}addKeyframe(e,t,i,n,r="linear"){return{id:this.generateKeyframeId(),time:i,property:t,value:n,easing:this.mapEasingPresetToType(r),bezierHandles:r==="linear"?void 0:this.getDefaultBezierHandles(r)}}removeKeyframe(e,t){return e.filter(i=>i.id!==t)}updateKeyframe(e,t,i){const n=e.map(r=>r.id===t?{...r,...i}:r);return i.time!==void 0&&n.sort((r,a)=>r.time-a.time),n}getKeyframe(e,t){return e.find(i=>i.id===t)||null}getKeyframesForProperty(e,t){return e.filter(i=>i.property===t).sort((i,n)=>i.time-n.time)}getValueAtTime(e,t){if(e.length===0)return{value:void 0,keyframeA:null,keyframeB:null,progress:0,easedProgress:0};const i=[...e].sort((d,h)=>d.time-h.time);if(t<=i[0].time)return{value:i[0].value,keyframeA:i[0],keyframeB:null,progress:0,easedProgress:0};if(t>=i[i.length-1].time)return{value:i[i.length-1].value,keyframeA:i[i.length-1],keyframeB:null,progress:1,easedProgress:1};let n=null,r=null;for(let d=0;d=i[d].time&&t<=i[d+1].time){n=i[d],r=i[d+1];break}if(!n||!r)return{value:i[i.length-1].value,keyframeA:i[i.length-1],keyframeB:null,progress:1,easedProgress:1};const a=r.time-n.time,o=t-n.time,c=a>0?o/a:0,l=this.applyEasing(c,n);return{value:this.interpolateValue(n.value,r.value,l),keyframeA:n,keyframeB:r,progress:c,easedProgress:l}}getEasingPresets(){return["linear","ease-in","ease-out","ease-in-out","bounce","elastic","spring"]}setEasing(e,t,i){return e.map(n=>n.id===t?typeof i=="string"?{...n,easing:this.mapEasingPresetToType(i),bezierHandles:this.getDefaultBezierHandles(i)}:{...n,easing:"bezier",bezierHandles:{in:{x:i.controlPoints[0],y:i.controlPoints[1]},out:{x:i.controlPoints[2],y:i.controlPoints[3]}}}:n)}applyEasing(e,t){const i=Math.max(0,Math.min(1,e));if(t.bezierHandles&&t.easing==="bezier")return this.animationEngine.cubicBezier(i,t.bezierHandles.in.x,t.bezierHandles.in.y,t.bezierHandles.out.x,t.bezierHandles.out.y);switch(t.easing){case"linear":return i;case"ease-in":return this.easeIn(i);case"ease-out":return this.easeOut(i);case"ease-in-out":return this.easeInOut(i);case"bezier":return this.animationEngine.cubicBezier(i,.25,.1,.25,1);default:return i}}applyEasingPreset(e,t){const i=Math.max(0,Math.min(1,e));switch(t){case"linear":return i;case"ease-in":return this.easeIn(i);case"ease-out":return this.easeOut(i);case"ease-in-out":return this.easeInOut(i);case"bounce":return this.bounce(i);case"elastic":return this.elastic(i);case"spring":return this.spring(i);default:return i}}easeIn(e){return e*e}easeOut(e){return e*(2-e)}easeInOut(e){return e<.5?2*e*e:-1+(4-2*e)*e}bounce(e){if(e<1/2.75)return 7.5625*e*e;if(e<2/2.75){const t=e-.5454545454545454;return 7.5625*t*t+.75}else if(e<2.5/2.75){const t=e-.8181818181818182;return 7.5625*t*t+.9375}else{const t=e-.9545454545454546;return 7.5625*t*t+.984375}}elastic(e){if(e===0||e===1)return e;const t=.3,i=t/4;return Math.pow(2,-10*e)*Math.sin((e-i)*(2*Math.PI)/t)+1}spring(e){return e===0||e===1?e:1-Math.pow(Math.cos(e*Math.PI*4.5),3)*Math.pow(1-e,2.2)*.4-(1-e)}updateBezierHandles(e,t,i){return e.map(n=>n.id===t?{...n,easing:"bezier",bezierHandles:i}:n)}getBezierControlPoints(e){return e.bezierHandles?{x1:e.bezierHandles.in.x,y1:e.bezierHandles.in.y,x2:e.bezierHandles.out.x,y2:e.bezierHandles.out.y}:null}interpolateWithBezier(e,t,i,n){const r=this.animationEngine.cubicBezier(i,n.x1,n.y1,n.x2,n.y2);return this.interpolateValue(e,t,r)}copyKeyframes(e,t,i){const n={keyframes:e.map(r=>({...r})),sourceClipId:t,sourceProperty:i,copiedAt:Date.now()};return this.clipboard=n,n}pasteKeyframes(e,t,i,n=0){const r=Math.min(...e.keyframes.map(a=>a.time));return e.keyframes.map(a=>({...a,id:this.generateKeyframeId(),property:i,time:a.time-r+n}))}getClipboard(){return this.clipboard}clearClipboard(){this.clipboard=null}getMotionPath(e,t,i=100){const n=this.getKeyframesForProperty(t,"position.x"),r=this.getKeyframesForProperty(t,"position.y");if(n.length===0&&r.length===0)return{clipId:e,points:[],visible:!1};const a=[...n,...r].map(h=>h.time),o=Math.min(...a),l=Math.max(...a)-o,u=[];for(let h=0;h<=i;h++){const f=o+l*h/i,p=this.getValueAtTime(n,f),m=this.getValueAtTime(r,f);u.push({time:f,x:typeof p.value=="number"?p.value:0,y:typeof m.value=="number"?m.value:0})}const d={clipId:e,points:u,visible:!0};return this.motionPaths.set(e,d),d}setMotionPathVisible(e,t){const i=this.motionPaths.get(e);i&&(i.visible=t)}generateKeyframeId(){return`kf-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}mapEasingPresetToType(e){switch(e){case"bounce":case"elastic":case"spring":return"bezier";default:return e}}getDefaultBezierHandles(e){switch(e){case"ease-in":return{in:{x:.42,y:0},out:{x:1,y:1}};case"ease-out":return{in:{x:0,y:0},out:{x:.58,y:1}};case"ease-in-out":return{in:{x:.42,y:0},out:{x:.58,y:1}};case"bounce":return{in:{x:.34,y:1.56},out:{x:.64,y:1}};case"elastic":return{in:{x:.68,y:-.55},out:{x:.27,y:1.55}};case"spring":return{in:{x:.5,y:1.5},out:{x:.5,y:1}};default:return}}interpolateValue(e,t,i){if(typeof e=="number"&&typeof t=="number")return e+(t-e)*i;if(typeof e=="object"&&typeof t=="object"&&e!==null&&t!==null){const n={},r=e,a=t;for(const o of Object.keys(r))o in a?n[o]=this.interpolateValue(r[o],a[o],i):n[o]=r[o];return n}return i<.5?e:t}}const fi=new JG;var To=typeof self<"u"?self:{};function qM(s,e){e:{for(var t=["CLOSURE_FLAGS"],i=To,n=0;n>6|192;else{if(e>=55296&&e<=57343){if(e<=56319&&n=56320&&r<=57343){e=1024*(e-55296)+r-56320+65536,i[t++]=e>>18|240,i[t++]=e>>12&63|128,i[t++]=e>>6&63|128,i[t++]=63&e|128;continue}n--}e=65533}i[t++]=e>>12|224,i[t++]=e>>6&63|128}i[t++]=63&e|128}}s=t===i.length?i:i.subarray(0,t)}return s}function YM(s){To.setTimeout(()=>{throw s},0)}var c0,iW=qM(610401301,!1),y_=qM(748402147,!0);function v_(){var s=To.navigator;return s&&(s=s.userAgent)?s:""}const b_=To.navigator;function qh(s){return qh[" "](s),s}c0=b_&&b_.userAgentData||null,qh[" "]=function(){};const XM={};let Gc=null;function sW(s){const e=s.length;let t=3*e/4;t%3?t=Math.floor(t):"=.".indexOf(s[e-1])!=-1&&(t="=.".indexOf(s[e-2])!=-1?t-2:t-1);const i=new Uint8Array(t);let n=0;return function(r,a){function o(l){for(;c>4),d!=64&&(a(u<<4&240|d>>2),h!=64&&a(d<<6&192|h))}}(s,function(r){i[n++]=r}),n!==t?i.subarray(0,n):i}function KM(){if(!Gc){Gc={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),e=["+/=","+/","-_=","-_.","-_"];for(let t=0;t<5;t++){const i=s.concat(e[t].split(""));XM[t]=i;for(let n=0;n0)&&(v_().indexOf("Trident")!=-1||v_().indexOf("MSIE")!=-1))&&typeof btoa=="function";const x_=/[-_.]/g,rW={"-":"+",_:"/",".":"="};function aW(s){return rW[s]||""}function JM(s){if(!QM)return sW(s);s=x_.test(s)?s.replace(x_,aW):s,s=atob(s);const e=new Uint8Array(s.length);for(let t=0;t=e||(t[s]=i+1,e4(s=Error(),"incident"),YM(s))}}function Jo(){return typeof BigInt=="function"}var Zo=typeof Symbol=="function"&&typeof Symbol()=="symbol";function en(s,e,t=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?t&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():e}var lW=en("jas",void 0,!0),w_=en(void 0,"0di"),kc=en(void 0,"1oa"),ji=en(void 0,Symbol()),uW=en(void 0,"0ub"),dW=en(void 0,"0ubs"),u0=en(void 0,"0ubsb"),hW=en(void 0,"0actk"),So=en("m_m","Pa",!0),__=en();const t4={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},i4=Object.defineProperties,re=Zo?lW:"Ga";var _a;const T_=[];function uu(s,e){Zo||re in s||i4(s,t4),s[re]|=e}function Ft(s,e){Zo||re in s||i4(s,t4),s[re]=e}function du(s){return uu(s,34),s}function Ll(s){return uu(s,8192),s}Ft(T_,7),_a=Object.freeze(T_);var Co={};function Ui(s,e){return e===void 0?s.h!==ba&&!!(2&(0|s.v[re])):!!(2&e)&&s.h!==ba}const ba={};function V1(s,e){if(s!=null){if(typeof s=="string")s=s?new Ks(s,ko):va();else if(s.constructor!==Ks)if(j1(s))s=s.length?new Ks(new Uint8Array(s),ko):va();else{if(!e)throw Error();s=void 0}}return s}class k_{constructor(e,t,i){this.g=e,this.h=t,this.l=i}next(){const e=this.g.next();return e.done||(e.value=this.h.call(this.l,e.value)),e}[Symbol.iterator](){return this}}var fW=Object.freeze({});function s4(s,e,t){const i=128&e?0:-1,n=s.length;var r;(r=!!n)&&(r=(r=s[n-1])!=null&&typeof r=="object"&&r.constructor===Object);const a=n+(r?-1:0);for(e=128&e?1:0;etypeof s=="number"),A_=Hh(s=>typeof s=="string"),mW=Hh(s=>typeof s=="boolean"),Yh=typeof To.BigInt=="function"&&typeof To.BigInt(0)=="bigint";function Ni(s){var e=s;if(A_(e)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(e))throw Error(String(e))}else if(pW(e)&&!Number.isSafeInteger(e))throw Error(String(e));return Yh?BigInt(s):s=mW(s)?s?"1":"0":A_(s)?s.trim()||"0":String(s)}var d0=Hh(s=>Yh?s>=yW&&s<=bW:s[0]==="-"?S_(s,gW):S_(s,vW));const gW=Number.MIN_SAFE_INTEGER.toString(),yW=Yh?BigInt(Number.MIN_SAFE_INTEGER):void 0,vW=Number.MAX_SAFE_INTEGER.toString(),bW=Yh?BigInt(Number.MAX_SAFE_INTEGER):void 0;function S_(s,e){if(s.length>e.length)return!1;if(s.lengthn)return!1;if(i>>0;He=e,wt=(s-e)/4294967296>>>0}function Eo(s){if(s<0){C_(-s);const[e,t]=G1(He,wt);He=e>>>0,wt=t>>>0}else C_(s)}function U1(s){const e=wW||=new DataView(new ArrayBuffer(8));e.setFloat32(0,+s,!0),wt=0,He=e.getUint32(0,!0)}function r4(s,e){const t=4294967296*e+(s>>>0);return Number.isSafeInteger(t)?t:Ol(s,e)}function _W(s,e){return Ni(Jo()?BigInt.asUintN(64,(BigInt(e>>>0)<>>0)):Ol(s,e))}function a4(s,e){return Jo()?Ni(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(e))<>>=0,(e>>>=0)<=2097151)var t=""+(4294967296*e+s);else Jo()?t=""+(BigInt(e)<>>24|e<<8))+6710656*(e=e>>16&65535),t+=8147497*e,e*=2,s>=1e7&&(t+=s/1e7>>>0,s%=1e7),t>=1e7&&(e+=t/1e7>>>0,t%=1e7),t=e+E_(t)+E_(s));return t}function E_(s){return s=String(s),"0000000".slice(s.length)+s}function z1(s,e){if(2147483648&e)if(Jo())s=""+(BigInt(0|e)<>>0));else{const[t,i]=G1(s,e);s="-"+Ol(t,i)}else s=Ol(s,e);return s}function Xh(s){if(s.length<16)Eo(Number(s));else if(Jo())s=BigInt(s),He=Number(s&BigInt(4294967295))>>>0,wt=Number(s>>BigInt(32)&BigInt(4294967295));else{const e=+(s[0]==="-");wt=He=0;const t=s.length;for(let i=e,n=(t-e)%6+e;n<=t;i=n,n+=6){const r=Number(s.slice(i,n));wt*=1e6,He=1e6*He+r,He>=4294967296&&(wt+=Math.trunc(He/4294967296),wt>>>=0,He>>>=0)}if(e){const[i,n]=G1(He,wt);He=i,wt=n}}}function G1(s,e){return e=~e,s?s=1+~s:e+=1,[s,e]}function Es(s){return Array.prototype.slice.call(s)}const hu=typeof BigInt=="function"?BigInt.asIntN:void 0,TW=typeof BigInt=="function"?BigInt.asUintN:void 0,xa=Number.isSafeInteger,Kh=Number.isFinite,Mo=Math.trunc,kW=Ni(0);function Wc(s){if(s!=null&&typeof s!="number")throw Error(`Value of float/double field must be a number, found ${typeof s}: ${s}`);return s}function Gs(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function Bl(s){if(s!=null&&typeof s!="boolean"){var e=typeof s;throw Error(`Expected boolean but got ${e!="object"?e:s?Array.isArray(s)?"array":e:"null"}: ${s}`)}return s}function o4(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const AW=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function fu(s){switch(typeof s){case"bigint":return!0;case"number":return Kh(s);case"string":return AW.test(s);default:return!1}}function tc(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Kh(s)?0|s:void 0}function c4(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Kh(s)?s>>>0:void 0}function l4(s){const e=s.length;return(s[0]==="-"?e<20||e===20&&s<="-9223372036854775808":e<19||e===19&&s<="9223372036854775807")?s:(Xh(s),z1(He,wt))}function W1(s){if(s=Mo(s),!xa(s)){Eo(s);var e=He,t=wt;(s=2147483648&t)&&(t=~t>>>0,(e=1+~e>>>0)==0&&(t=t+1>>>0)),s=typeof(e=r4(e,t))=="number"?s?-e:e:s?"-"+e:e}return s}function u4(s){var e=Mo(Number(s));return xa(e)?String(e):((e=s.indexOf("."))!==-1&&(s=s.substring(0,e)),l4(s))}function d4(s){var e=Mo(Number(s));return xa(e)?Ni(e):((e=s.indexOf("."))!==-1&&(s=s.substring(0,e)),Jo()?Ni(hu(64,BigInt(s))):Ni(l4(s)))}function h4(s){return xa(s)?s=Ni(W1(s)):(s=Mo(s),xa(s)?s=String(s):(Eo(s),s=z1(He,wt)),s=Ni(s)),s}function ch(s){const e=typeof s;return s==null?s:e==="bigint"?Ni(hu(64,s)):fu(s)?e==="string"?d4(s):h4(s):void 0}function f4(s){if(typeof s!="string")throw Error();return s}function pu(s){if(s!=null&&typeof s!="string")throw Error();return s}function qt(s){return s==null||typeof s=="string"?s:void 0}function q1(s,e,t,i){return s!=null&&s[So]===Co?s:Array.isArray(s)?((i=(t=0|s[re])|32&i|2&i)!==t&&Ft(s,i),new e(s)):(t?2&i?((s=e[w_])||(du((s=new e).v),s=e[w_]=s),e=s):e=new e:e=void 0,e)}function SW(s,e,t){if(e)e:{if(!fu(e=s))throw l0("int64");switch(typeof e){case"string":e=d4(e);break e;case"bigint":e=Ni(hu(64,e));break e;default:e=h4(e)}}else e=ch(s);return(s=e)==null?t?kW:void 0:s}const CW={};let EW=function(){try{return qh(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class Vp{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,t){return this.g.set(e,t),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,t){return this.g.forEach(e,t)}[Symbol.iterator](){return this.entries()}}const MW=EW?(Object.setPrototypeOf(Vp.prototype,Map.prototype),Object.defineProperties(Vp.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Vp):class extends Map{constructor(){super()}};function M_(s){return s}function Up(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var In=class extends MW{constructor(s,e,t=M_,i=M_){super(),this.J=0|s[re],this.K=e,this.S=t,this.fa=this.K?IW:i;for(let n=0;n{s.call(e,n.get(i),i,n)}):super.forEach(s,e)}set(s,e){return Up(this),(s=this.S(s,!0,!1))==null?this:e==null?(super.delete(s),this):super.set(s,this.fa(e,!0,!0,this.K,!1,this.J))}Ma(s){const e=this.S(s[0],!1,!0);s=s[1],s=this.K?s===void 0?null:s:this.fa(s,!1,!0,void 0,!1,this.J),super.set(e,s)}has(s){return super.has(this.S(s,!1,!1))}get(s){s=this.S(s,!1,!1);const e=super.get(s);if(e!==void 0){var t=this.K;return t?((t=this.fa(e,!1,!0,t,this.ra,this.J))!==e&&super.set(s,t),t):e}}[Symbol.iterator](){return this.entries()}};function IW(s,e,t,i,n,r){return s=q1(s,i,t,r),n&&(s=Y1(s)),s}function PW(s){return[s,this.get(s)]}let RW;function I_(){return RW||=new In(du([]),void 0,void 0,void 0,CW)}function Qh(s){return ji?s[ji]:void 0}function lh(s,e){for(const t in s)!isNaN(t)&&e(s,+t,s[t])}In.prototype.toJSON=void 0;var h0=class{};const DW={Ka:!0};function FW(s,e){e<100||Ao(dW,1)}function Jh(s,e,t,i){const n=i!==void 0;i=!!i;var r,a=ji;!n&&Zo&&a&&(r=s[a])&&lh(r,FW),a=[];var o=s.length;let c;r=4294967295;let l=!1;const u=!!(64&e),d=u?128&e?0:-1:void 0;1&e||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?r=--o:c=void 0,!u||128&e||n||(l=!0,r=r-d+d)),e=void 0;for(var h=0;h=r){const p=h-d;(e??={})[p]=f}else a[h]=f}if(c)for(let f in c){if((o=c[f])==null||(o=t(o,i))==null)continue;let p;h=+f,u&&!Number.isNaN(h)&&(p=h+d){p[g]=Es(v)}),p.da=f.da,p}(s)),a}function LW(s){return s[0]=$l(s[0]),s[1]=$l(s[1]),s}function $l(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return d0(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var e=0|s[re];return s.length===0&&1&e?void 0:Jh(s,e,$l)}if(s!=null&&s[So]===Co)return p4(s);if(s instanceof Ks){if((e=s.g)==null)s="";else if(typeof e=="string")s=e;else{if(QM){for(var t="",i=0,n=e.length-10240;i>2];r=t[(3&r)<<4|a>>4],a=t[(15&a)<<2|o>>6],o=t[63&o],i[u++]=c+r+a+o}switch(c=0,o=n,e.length-l){case 2:o=t[(15&(c=e[l+1]))<<2]||n;case 1:e=e[l],i[u]=t[e>>2]+t[(3&e)<<4|c>>4]+o+n}e=i.join("")}s=s.g=e}return s}return s instanceof In?s=s.size!==0?s.V(LW):void 0:void 0}return s}let OW,BW;function p4(s){return Jh(s=s.v,0|s[re],$l)}function ra(s,e){return m4(s,e[0],e[1])}function m4(s,e,t,i=0){if(s==null){var n=32;t?(s=[t],n|=128):s=[],e&&(n=-16760833&n|(1023&e)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(n=0|s[re],y_&&1&n)throw Error("rfarr");if(2048&n&&!(2&n)&&function(){if(y_)throw Error("carr");Ao(hW,5)}(),256&n)throw Error("farr");if(64&n)return(n|i)!==n&&Ft(s,n|i),s;if(t&&(n|=128,t!==s[0]))throw Error("mid");e:{n|=64;var r=(t=s).length;if(r){var a=r-1;const c=t[a];if(c!=null&&typeof c=="object"&&c.constructor===Object){if((a-=e=128&n?0:-1)>=1024)throw Error("pvtlmt");for(var o in c)(r=+o)1024)throw Error("spvt");n=-16760833&n|(1023&o)<<14}}}return Ft(s,64|n|i),s}function $W(s,e){if(typeof s!="object")return s;if(Array.isArray(s)){var t=0|s[re];return s.length===0&&1&t?void 0:P_(s,t,e)}if(s!=null&&s[So]===Co)return R_(s);if(s instanceof In){if(2&(e=s.J))return s;if(!s.size)return;if(t=du(s.V()),s.K)for(s=0;s=r)if(a=s[r],a!=null&&typeof a=="object"&&a.constructor===Object)t=a[e],o=!0;else{if(n!==r)return;t=a}else t=s[n];if(i&&t!=null){if((i=i(t))==null)return i;if(!Object.is(i,t))return o?a[e]=i:s[n]=i,i}return t}}function Ie(s,e,t,i){nc(s),Rt(s=s.v,0|s[re],e,t,i)}function Rt(s,e,t,i,n){const r=t+(n?0:-1);var a=s.length-1;if(a>=1+(n?0:-1)&&r>=a){const o=s[a];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[t]=i,e}return r<=a?(s[r]=i,e):(i!==void 0&&(t>=(a=(e??=0|s[re])>>14&1023||536870912)?i!=null&&(s[a+(n?0:-1)]={[t]:i}):s[r]=i),e)}function Xr(){return fW===void 0?2:4}function Kr(s,e,t,i,n){let r=s.v,a=0|r[re];i=Ui(s,a)?1:i,n=!!n||i===3,i===2&&sc(s)&&(r=s.v,a=0|r[re]);let o=(s=K1(r,e))===_a?7:0|s[re],c=Q1(o,a);var l=!(4&c);if(l){4&c&&(s=Es(s),o=0,c=oa(c,a),a=Rt(r,a,e,s));let u=0,d=0;for(;u{const o=q1(a,t,!1,e);return r=o!==a&&o!=null,o}))!=null)return r&&!Ui(i)&&Ta(s,e),i}function Ae(s,e,t,i){let n=s.v,r=0|n[re];if((e=w4(n,r,e,t,i))==null)return e;if(r=0|n[re],!Ui(s,r)){const a=Y1(e);a!==e&&(sc(s)&&(n=s.v,r=0|n[re]),r=Rt(n,r,t,e=a,i),Ta(n,r))}return e}function _4(s,e,t,i,n,r,a,o){var c=Ui(s,t);r=c?1:r,a=!!a||r===3,c=o&&!c,(r===2||c)&&sc(s)&&(t=0|(e=s.v)[re]);var l=(s=K1(e,n))===_a?7:0|s[re],u=Q1(l,t);if(o=!(4&u)){var d=s,h=t;const f=!!(2&u);f&&(h|=2);let p=!f,m=!0,g=0,v=0;for(;g32)for(n|=(127&t)>>4,r=3;r<32&&128&t;r+=7)t=a[o++],n|=(127&t)<>>0,n>>>0);throw Error()}function nv(s){let e=0,t=s.g;const i=t+10,n=s.h;for(;t>>0}function dh(s){var e=s.h;const t=s.g;var i=e[t],n=e[t+1];const r=e[t+2];return e=e[t+3],ca(s,s.g+4),s=2*((n=(i<<0|n<<8|r<<16|e<<24)>>>0)>>31)+1,i=n>>>23&255,n&=8388607,i==255?n?NaN:s*(1/0):i==0?1401298464324817e-60*s*n:s*Math.pow(2,i-150)*(n+8388608)}function jW(s){return pr(s)}function ca(s,e){if(s.g=e,e>s.l)throw Error()}function k4(s,e){if(e<0)throw Error();const t=s.g;if((e=t+e)>s.l)throw Error();return s.g=e,t}function A4(s,e){if(e==0)return va();var t=k4(s,e);return s.Y&&s.j?t=s.h.subarray(t,t+e):(s=s.h,t=t===(e=t+e)?new Uint8Array(0):xW?s.slice(t,e):new Uint8Array(s.subarray(t,e))),t.length==0?va():new Ks(t,ko)}var D_=[];function S4(s,e,t,i){if(hh.length){const n=hh.pop();return n.o(i),n.g.init(s,e,t,i),n}return new NW(s,e,t,i)}function C4(s){s.g.clear(),s.l=-1,s.h=-1,hh.length<100&&hh.push(s)}function E4(s){var e=s.g;if(e.g==e.l)return!1;s.m=s.g.g;var t=Js(s.g);if(e=t>>>3,!((t&=7)>=0&&t<=5)||e<1)throw Error();return s.l=e,s.h=t,!0}function bd(s){switch(s.h){case 0:s.h!=0?bd(s):nv(s.g);break;case 1:ca(s=s.g,s.g+8);break;case 2:if(s.h!=2)bd(s);else{var e=Js(s.g);ca(s=s.g,s.g+e)}break;case 5:ca(s=s.g,s.g+4);break;case 3:for(e=s.l;;){if(!E4(s))throw Error();if(s.h==4){if(s.l!=e)throw Error();break}bd(s)}break;default:throw Error()}}function mu(s,e,t){const i=s.g.l;var n=Js(s.g);let r=(n=s.g.g+n)-i;if(r<=0&&(s.g.l=n,t(e,s,void 0,void 0,void 0),r=n-s.g.g),r)throw Error();return s.g.g=n,s.g.l=i,e}function rv(s){var e=Js(s.g),t=k4(s=s.g,e);if(s=s.h,ZG){var i,n=s;(i=Np)||(i=Np=new TextDecoder("utf-8",{fatal:!0})),e=t+e,n=t===0&&e===n.length?n:n.subarray(t,e);try{var r=i.decode(n)}catch(o){if(Uu===void 0){try{i.decode(new Uint8Array([128]))}catch{}try{i.decode(new Uint8Array([97])),Uu=!0}catch{Uu=!1}}throw!Uu&&(Np=void 0),o}}else{e=(r=t)+e,t=[];let o,c=null;for(;r=e?Fr():(o=s[r++],a<194||(192&o)!=128?(r--,Fr()):t.push((31&a)<<6|63&o)):a<240?r>=e-1?Fr():(o=s[r++],(192&o)!=128||a===224&&o<160||a===237&&o>=160||(192&(i=s[r++]))!=128?(r--,Fr()):t.push((15&a)<<12|(63&o)<<6|63&i)):a<=244?r>=e-2?Fr():(o=s[r++],(192&o)!=128||o-144+(a<<28)>>30||(192&(i=s[r++]))!=128||(192&(n=s[r++]))!=128?(r--,Fr()):(a=(7&a)<<18|(63&o)<<12|(63&i)<<6|63&n,a-=65536,t.push(55296+(a>>10&1023),56320+(1023&a)))):Fr(),t.length>=8192&&(c=g_(c,t),t.length=0)}r=g_(c,t)}return r}function M4(s){const e=Js(s.g);return A4(s.g,e)}function ef(s,e,t){var i=Js(s.g);for(i=s.g.g+i;s.g.g>>0,this.g=e>>>0}};let VW;function L_(s){return s?/^-?\d+$/.test(s)?(Xh(s),new p0(He,wt)):null:UW||=new p0(0,0)}var p0=class{constructor(s,e){this.h=s>>>0,this.g=e>>>0}};let UW;function oo(s,e,t){for(;t>0||e>127;)s.g.push(127&e|128),e=(e>>>7|t<<25)>>>0,t>>>=7;s.g.push(e)}function ac(s,e){for(;e>127;)s.g.push(127&e|128),e>>>=7;s.g.push(e)}function tf(s,e){if(e>=0)ac(s,e);else{for(let t=0;t<9;t++)s.g.push(127&e|128),e>>=7;s.g.push(1)}}function av(s){var e=He;s.g.push(e>>>0&255),s.g.push(e>>>8&255),s.g.push(e>>>16&255),s.g.push(e>>>24&255)}function Io(s,e){e.length!==0&&(s.l.push(e),s.h+=e.length)}function xs(s,e,t){ac(s.g,8*e+t)}function ov(s,e){return xs(s,e,2),e=s.g.end(),Io(s,e),e.push(s.h),e}function cv(s,e){var t=e.pop();for(t=s.h+s.g.length()-t;t>127;)e.push(127&t|128),t>>>=7,s.h++;e.push(t),s.h++}function sf(s,e,t){xs(s,e,2),ac(s.g,t.length),Io(s,s.g.end()),Io(s,t)}function fh(s,e,t,i){t!=null&&(e=ov(s,e),i(t,s),cv(s,e))}function tn(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var lv=tn(),I4=tn(),uv=tn(),dv=tn(),hv=tn(),P4=tn(),zW=tn(),nf=tn(),R4=tn(),D4=tn();function sn(s,e,t){var i=s.v;ji&&ji in i&&(i=i[ji])&&delete i[e.g],e.h?e.j(s,e.h,e.g,t,e.l):e.j(s,e.g,t,e.l)}var ae=class{constructor(s,e){this.v=m4(s,e,void 0,2048)}toJSON(){return p4(this)}j(){var s=kq,e=this.v,t=s.g,i=ji;if(Zo&&i&&e[i]?.[t]!=null&&Ao(uW,3),e=s.g,__&&ji&&__===void 0&&(i=(t=this.v)[ji])&&(i=i.da))try{i(t,e,DW)}catch(n){YM(n)}return s.h?s.m(this,s.h,s.g,s.l):s.m(this,s.g,s.defaultValue,s.l)}clone(){const s=this.v,e=0|s[re];return X1(this,s,e)?H1(this,s,!0):new this.constructor(ic(s,e,!1))}};ae.prototype[So]=Co,ae.prototype.toString=function(){return this.v.toString()};var oc=class{constructor(s,e,t){this.g=s,this.h=e,s=lv,this.l=!!s&&t===s||!1}};function rf(s,e){return new oc(s,e,lv)}function F4(s,e,t,i,n){fh(s,t,$4(e,i),n)}const GW=rf(function(s,e,t,i,n){return s.h===2&&(mu(s,ev(e,i,t),n),!0)},F4),WW=rf(function(s,e,t,i,n){return s.h===2&&(mu(s,ev(e,i,t),n),!0)},F4);var af=Symbol(),of=Symbol(),m0=Symbol(),O_=Symbol(),B_=Symbol();let L4,O4;function ka(s,e,t,i){var n=i[s];if(n)return n;(n={}).qa=i,n.T=function(d){switch(typeof d){case"boolean":return OW||=[0,void 0,!0];case"number":return d>0?void 0:d===0?BW||=[0,void 0]:[-d,void 0];case"string":return[0,d];case"object":return d}}(i[0]);var r=i[1];let a=1;r&&r.constructor===Object&&(n.ba=r,typeof(r=i[++a])=="function"&&(n.ma=!0,L4??=r,O4??=i[a+1],r=i[a+=2]));const o={};for(;r&&Array.isArray(r)&&r.length&&typeof r[0]=="number"&&r[0]>0;){for(var c=0;cn(r,a,o,i):n}function pv(s,e,t,i,n){const r=t.g;let a,o;s[e]=(c,l,u)=>r(c,l,u,o||=ka(of,fv,pv,i).T,a||=mv(i),n)}function mv(s){let e=s[m0];if(e!=null)return e;const t=ka(of,fv,pv,s);return e=t.ma?(i,n)=>L4(i,n,t):(i,n)=>{for(;E4(n)&&n.h!=4;){var r=n.l,a=t[r];if(a==null){var o=t.ba;o&&(o=o[r])&&(o=HW(o))!=null&&(a=t[r]=o)}if(a==null||!a(n,i,r)){if(a=(o=n).m,bd(o),o.ha)var c=void 0;else c=o.g.g-a,o.g.g=a,c=A4(o.g,c);a=void 0,o=i,c&&((a=o[ji]??(o[ji]=new h0))[r]??(a[r]=[])).push(c)}}return(i=Qh(i))&&(i.da=t.qa[B_]),!0},s[m0]=e,s[B_]=qW.bind(s),e}function qW(s,e,t,i){var n=this[of];const r=this[m0],a=ra(void 0,n.T),o=Qh(s);if(o){var c=!1,l=n.ba;if(l){if(n=(u,d,h)=>{if(h.length!==0)if(l[d])for(const f of h){u=S4(f);try{c=!0,r(a,u)}finally{C4(u)}}else i?.(s,d,h)},e==null)lh(o,n);else if(o!=null){const u=o[e];u&&n(o,e,u)}if(c){let u=0|s[re];if(2&u&&2048&u&&!t?.Ka)throw Error();const d=ec(u),h=(f,p)=>{if(Pn(s,f,d)!=null){if(t?.Qa===1)return;throw Error()}p!=null&&(u=Rt(s,u,f,p,d)),delete o[f]};e==null?s4(a,0|a[re],(f,p)=>{h(f,p)}):h(e,Pn(a,e,d))}}}}function HW(s){const e=(s=B4(s))[0].g;if(s=s[1]){const t=mv(s),i=ka(of,fv,pv,s).T;return(n,r,a)=>e(n,r,a,i,t)}return e}function cf(s,e,t){s[e]=t.h}function lf(s,e,t,i){let n,r;const a=t.h;s[e]=(o,c,l)=>a(o,c,l,r||=ka(af,cf,lf,i).T,n||=j4(i))}function j4(s){let e=s[O_];if(!e){const t=ka(af,cf,lf,s);e=(i,n)=>N4(i,n,t),s[O_]=e}return e}function N4(s,e,t){s4(s,0|s[re],(i,n)=>{if(n!=null){var r=function(a,o){var c=a[o];if(c)return c;if((c=a.ba)&&(c=c[o])){var l=(c=B4(c))[0].h;if(c=c[1]){const u=j4(c),d=ka(af,cf,lf,c).T;c=a.ma?O4(d,u):(h,f,p)=>l(h,f,p,d,u)}else c=l;return a[o]=c}}(t,i);r?r(e,n,i):i<500||Ao(u0,3)}}),(s=Qh(s))&&lh(s,(i,n,r)=>{for(Io(e,e.g.end()),i=0;i{fh(s,t,ra([a,r],i),n)});else if(Array.isArray(e)){for(let r=0;r>BigInt(32))),oo(s.g,t.h,t.g);break;default:t=L_(e),oo(s.g,t.h,t.g)}}function z4(s,e,t){(e=tc(e))!=null&&e!=null&&(xs(s,t,0),tf(s.g,e))}function G4(s,e,t){(e=o4(e))!=null&&(xs(s,t,0),s.g.g.push(e?1:0))}function W4(s,e,t){(e=qt(e))!=null&&sf(s,t,HM(e))}function q4(s,e,t,i,n){fh(s,t,$4(e,i),n)}function H4(s,e,t){(e=e==null||typeof e=="string"||e instanceof Ks?e:void 0)!=null&&sf(s,t,iv(e,!0).buffer)}function Y4(s,e,t){(e=c4(e))!=null&&e!=null&&(xs(s,t,0),ac(s.g,e))}function X4(s,e,t){return(s.h===5||s.h===2)&&(e=rc(e,0|e[re],t),s.h==2?ef(s,dh,e):e.push(dh(s.g)),!0)}var Tt=si(function(s,e,t){return s.h===5&&(ni(e,t,dh(s.g)),!0)},V4,nf),KW=lc(X4,function(s,e,t){if((e=cc(Gs,e))!=null)for(let a=0;a=0?i=String(n):((n=i.indexOf("."))!==-1&&(i=i.substring(0,n)),(n=i[0]!=="-"&&((n=i.length)<20||n===20&&i<="18446744073709551615"))||(Xh(i),i=Ol(He,wt))),i;if(n==="number")return(i=Mo(i))>=0&&xa(i)||(Eo(i),i=r4(He,wt)),i}}(e),e!=null&&(typeof e=="string"&&F_(e),e!=null))switch(xs(s,t,0),typeof e){case"number":s=s.g,Eo(e),oo(s,He,wt);break;case"bigint":t=BigInt.asUintN(64,e),t=new f0(Number(t&BigInt(4294967295)),Number(t>>BigInt(32))),oo(s.g,t.h,t.g);break;default:t=F_(e),oo(s.g,t.h,t.g)}},zW),Pt=si(function(s,e,t){return s.h===0&&(ni(e,t,pr(s.g)),!0)},z4,dv),gu=lc(function(s,e,t){return(s.h===0||s.h===2)&&(e=rc(e,0|e[re],t),s.h==2?ef(s,pr,e):e.push(pr(s.g)),!0)},function(s,e,t){if((e=cc(tc,e))!=null&&e.length){t=ov(s,t);for(let i=0;i{{const r={ea:!0};i&&Object.assign(r,i),t=S4(t,void 0,void 0,r);try{const a=new s,o=a.v;mv(e)(o,t);var n=a}finally{C4(t)}}return n}}function uf(s){return function(){const e=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const a=this.g;return this.g=[],a}}}};N4(this.v,e,ka(af,cf,lf,s)),Io(e,e.g.end());const t=new Uint8Array(e.h),i=e.l,n=i.length;let r=0;for(let a=0;an;t=N_.createPolicy("goog#html",{createHTML:i,createScript:i,createScriptURL:i})}catch{}return t}()),s=(e=Wp)?e.createScriptURL(s):s,new class{constructor(t){this.g=t}toString(){return this.g+""}}(s)}function zu(s,...e){if(e.length===0)return V_(s[0]);let t=s[0];for(let i=0;i({index:ls(i,1)??0??-1,score:pt(i,2)??0,categoryName:qt(et(i,3))??""??"",displayName:qt(et(i,4))??""??""})),headIndex:e,headName:t}}function Eq(s){const e={classifications:Rn(s,lq,1).map(t=>kv(Ae(t,nI,4)?.g()??[],ls(t,2)??0,qt(et(t,3))??""))};return function(t){return t==null?t:typeof t=="bigint"?(d0(t)?t=Number(t):(t=hu(64,t),t=d0(t)?Number(t):String(t)),t):fu(t)?typeof t=="number"?W1(t):u4(t):void 0}(et(s,2,void 0,void 0,ch))!=null&&(e.timestampMs=PI(et(s,2,void 0,void 0,ch)??g4)),e}function RI(s){var e=Kr(s,3,Gs,Xr()),t=Kr(s,2,tc,Xr()),i=Kr(s,1,qt,Xr()),n=Kr(s,9,qt,Xr());const r={categories:[],keypoints:[]};for(let a=0;ae>127?e-256:e)}function Z_(s,e){if(s.length!==e.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${e.length}).`);let t=0,i=0,n=0;for(let r=0;r=1&&Number(s[1])>=17))}async function eT(s){if(typeof importScripts!="function"){const e=document.createElement("script");return e.src=s.toString(),e.crossOrigin="anonymous",new Promise((t,i)=>{e.addEventListener("load",()=>{t()},!1),e.addEventListener("error",n=>{i(n)},!1),document.body.appendChild(e)})}try{importScripts(s.toString())}catch(e){if(!(e instanceof TypeError))throw e;{const t=self.import;t?await t(s.toString()):await import(s.toString())}}}function LI(s){return s.videoWidth!==void 0?[s.videoWidth,s.videoHeight]:s.naturalWidth!==void 0?[s.naturalWidth,s.naturalHeight]:s.displayWidth!==void 0?[s.displayWidth,s.displayHeight]:[s.width,s.height]}function oe(s,e,t){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),t(e=s.i.stringToNewUTF8(e)),s.i._free(e)}function tT(s,e,t){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(t?s.i._bindTextureToStream(t):s.i._bindTextureToCanvas(),!(t=s.i.canvas.getContext("webgl2")||s.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");s.i.gpuOriginForWebTexturesIsBottomLeft&&t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s.i.gpuOriginForWebTexturesIsBottomLeft&&t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1);const[i,n]=LI(e);return!s.l||i===s.i.canvas.width&&n===s.i.canvas.height||(s.i.canvas.width=i,s.i.canvas.height=n),[i,n]}function iT(s,e,t){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const i=new Uint32Array(e.length);for(let n=0;n>2),t(e);for(const n of i)s.i._free(n);s.i._free(e)}function Fs(s,e,t){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[e]=t}function Vn(s,e,t){let i=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[e]=(n,r,a)=>{r?(t(i,a),i=[]):i.push(n)}}Oa.forVisionTasks=function(s,e=!1){return Wu("vision",s??zu``,e)},Oa.forTextTasks=function(s,e=!1){return Wu("text",s??zu``,e)},Oa.forGenAiTasks=function(s,e=!1){return Wu("genai",s??zu``,e)},Oa.forAudioTasks=function(s,e=!1){return Wu("audio",s??zu``,e)},Oa.isSimdSupported=function(s=!1){return DI(s)};async function Iq(s,e,t,i){return s=await(async(n,r,a,o,c)=>{if(r&&await eT(r),!self.ModuleFactory||a&&(await eT(a),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((r=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(r.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new n(c,o)})(s,t.wasmLoaderPath,t.assetLoaderPath,e,{locateFile:n=>n.endsWith(".wasm")?t.wasmBinaryPath.toString():t.assetBinaryPath&&n.endsWith(".data")?t.assetBinaryPath.toString():n}),await s.o(i),s}function Yp(s,e){const t=Ae(s.baseOptions,ph,1)||new ph;typeof e=="string"?(Ie(t,2,pu(e)),Ie(t,1)):e instanceof Uint8Array&&(Ie(t,1,V1(e,!1)),Ie(t,2)),pe(s.baseOptions,0,1,t)}function sT(s){try{const e=s.H.length;if(e===1)throw Error(s.H[0].message);if(e>1)throw Error("Encountered multiple errors: "+s.H.map(t=>t.message).join(", "))}finally{s.H=[]}}function te(s,e){s.C=Math.max(s.C,e)}function pf(s,e){s.B=new Ai,zi(s.B,2,"PassThroughCalculator"),We(s.B,"free_memory"),Te(s.B,"free_memory_unused_out"),it(e,"free_memory"),ws(e,s.B)}function Po(s,e){We(s.B,e),Te(s.B,e+"_unused_out")}function mf(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var x0=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,e=!0){if(e){const t=s.baseOptions||{};if(s.baseOptions?.modelAssetBuffer&&s.baseOptions?.modelAssetPath)throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!(Ae(this.baseOptions,ph,1)?.g()||Ae(this.baseOptions,ph,1)?.l()||s.baseOptions?.modelAssetBuffer||s.baseOptions?.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(i,n){let r=Ae(i.baseOptions,Y_,3);if(!r){var a=r=new Y_,o=new U_;ll(a,4,xd,o)}"delegate"in n&&(n.delegate==="GPU"?(n=r,a=new iq,ll(n,2,xd,a)):(n=r,a=new U_,ll(n,4,xd,a))),pe(i.baseOptions,0,3,r)}(this,t),t.modelAssetPath)return fetch(t.modelAssetPath.toString()).then(i=>{if(i.ok)return i.arrayBuffer();throw Error(`Failed to fetch model: ${t.modelAssetPath} (${i.status})`)}).then(i=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(i),!0,!1,!1),Yp(this,"/model.dat"),this.m(),this.L()});if(t.modelAssetBuffer instanceof Uint8Array)Yp(this,t.modelAssetBuffer);else if(t.modelAssetBuffer)return async function(i){const n=[];for(var r=0;;){const{done:a,value:o}=await i.read();if(a)break;n.push(o),r+=o.length}if(n.length===0)return new Uint8Array(0);if(n.length===1)return n[0];i=new Uint8Array(r),r=0;for(const a of n)i.set(a,r),r+=a.length;return i}(t.modelAssetBuffer).then(i=>{Yp(this,i),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(e=>{s=sq(e)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,e){this.g.attachErrorListener((t,i)=>{this.H.push(Error(i))}),this.g.Ja(),this.g.setGraph(s,e),this.B=void 0,sT(this)}finishProcessing(){this.g.finishProcessing(),sT(this)}close(){this.B=void 0,this.g.closeGraph()}};function ar(s,e){if(!s)throw Error(`Unable to obtain required WebGL resource: ${e}`);return s}x0.prototype.close=x0.prototype.close;class Pq{constructor(e,t,i,n){this.g=e,this.h=t,this.m=i,this.l=n}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function nT(s,e,t){const i=s.g;if(t=ar(i.createShader(t),"Failed to create WebGL shader"),i.shaderSource(t,e),i.compileShader(t),!i.getShaderParameter(t,i.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${i.getShaderInfoLog(t)}`);return i.attachShader(s.h,t),t}function rT(s,e){const t=s.g,i=ar(t.createVertexArray(),"Failed to create vertex array");t.bindVertexArray(i);const n=ar(t.createBuffer(),"Failed to create buffer");t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(s.O),t.vertexAttribPointer(s.O,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),t.STATIC_DRAW);const r=ar(t.createBuffer(),"Failed to create buffer");return t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(s.L),t.vertexAttribPointer(s.L,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindVertexArray(null),new Pq(t,i,n,r)}function Av(s,e){if(s.g){if(e!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=e}function Rq(s,e,t,i){return Av(s,e),s.h||(s.m(),s.D()),t?(s.u||(s.u=rT(s,!0)),t=s.u):(s.A||(s.A=rT(s,!1)),t=s.A),e.useProgram(s.h),t.bind(),s.l(),s=i(),t.g.bindVertexArray(null),s}function OI(s,e,t){return Av(s,e),s=ar(e.createTexture(),"Failed to create texture"),e.bindTexture(e.TEXTURE_2D,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t??e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t??e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),s}function BI(s,e,t){Av(s,e),s.B||(s.B=ar(e.createFramebuffer(),"Failed to create framebuffe.")),e.bindFramebuffer(e.FRAMEBUFFER,s.B),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}function Dq(s){s.g?.bindFramebuffer(s.g.FRAMEBUFFER,null)}var $I=class{H(){return` + precision mediump float; + varying vec2 vTex; + uniform sampler2D inputTexture; + void main() { + gl_FragColor = texture2D(inputTexture, vTex); + } + `}m(){const s=this.g;if(this.h=ar(s.createProgram(),"Failed to create WebGL program"),this.X=nT(this,` + attribute vec2 aVertex; + attribute vec2 aTex; + varying vec2 vTex; + void main(void) { + gl_Position = vec4(aVertex, 0.0, 1.0); + vTex = aTex; + }`,s.VERTEX_SHADER),this.W=nT(this,this.H(),s.FRAGMENT_SHADER),s.linkProgram(this.h),!s.getProgramParameter(this.h,s.LINK_STATUS))throw Error(`Error during program linking: ${s.getProgramInfoLog(this.h)}`);this.O=s.getAttribLocation(this.h,"aVertex"),this.L=s.getAttribLocation(this.h,"aTex")}D(){}l(){}close(){if(this.h){const s=this.g;s.deleteProgram(this.h),s.deleteShader(this.X),s.deleteShader(this.W)}this.B&&this.g.deleteFramebuffer(this.B),this.A&&this.A.close(),this.u&&this.u.close()}};function vn(s,e){switch(e){case 0:return s.g.find(t=>t instanceof Uint8Array);case 1:return s.g.find(t=>t instanceof Float32Array);case 2:return s.g.find(t=>typeof WebGLTexture<"u"&&t instanceof WebGLTexture);default:throw Error(`Type is not supported: ${e}`)}}function w0(s){var e=vn(s,1);if(!e){if(e=vn(s,0))e=new Float32Array(e).map(i=>i/255);else{e=new Float32Array(s.width*s.height);const i=Ro(s);var t=Sv(s);if(BI(t,i,jI(s)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){t=new Float32Array(s.width*s.height*4),i.readPixels(0,0,s.width,s.height,i.RGBA,i.FLOAT,t);for(let n=0,r=0;nMath.round(255*t))),s.g.push(e)),e;var s,e}ia(){return w0(this)}N(){return jI(this)}clone(){const s=[];for(const e of this.g){let t;if(e instanceof Uint8Array)t=new Uint8Array(e);else if(e instanceof Float32Array)t=new Float32Array(e);else{if(!(e instanceof WebGLTexture))throw Error(`Type is not supported: ${e}`);{const i=Ro(this),n=Sv(this);i.activeTexture(i.TEXTURE1),t=OI(n,i,this.m?i.LINEAR:i.NEAREST),i.bindTexture(i.TEXTURE_2D,t);const r=NI(this);i.texImage2D(i.TEXTURE_2D,0,r,this.width,this.height,0,i.RED,i.FLOAT,null),i.bindTexture(i.TEXTURE_2D,null),BI(n,i,t),Rq(n,i,!1,()=>{VI(this),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLE_FAN,0,4),_0(this)}),Dq(n),_0(this)}}s.push(t)}return new Ot(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&Ro(this).deleteTexture(vn(this,2)),aT=-1}};Ot.prototype.close=Ot.prototype.close,Ot.prototype.clone=Ot.prototype.clone,Ot.prototype.getAsWebGLTexture=Ot.prototype.N,Ot.prototype.getAsFloat32Array=Ot.prototype.ia,Ot.prototype.getAsUint8Array=Ot.prototype.ja,Ot.prototype.hasWebGLTexture=Ot.prototype.R,Ot.prototype.hasFloat32Array=Ot.prototype.ka,Ot.prototype.hasUint8Array=Ot.prototype.Fa;var aT=250;function Ps(...s){return s.map(([e,t])=>({start:e,end:t}))}const Fq=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((oT=class{constructor(s,e){this.l=!0,this.i=s,this.g=null,this.h=0,this.m=typeof this.i._addIntToInputStream=="function",e!==void 0?this.i.canvas=e:FI()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const e=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(e),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,e){const t=s.length,i=this.i._malloc(t);this.i.HEAPU8.set(s,i),e?this.i._changeBinaryGraph(t,i):this.i._changeTextGraph(t,i),this.i._free(i)}configureAudio(s,e,t,i,n){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),oe(this,i||"input_audio",r=>{oe(this,n=n||"audio_header",a=>{this.i._configureAudio(r,a,s,e??0,t)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){Fs(this,"__graph_config__",e=>{s(e)}),oe(this,"__graph_config__",e=>{this.i._getGraphConfig(e,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,e){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=e}addAudioToStream(s,e,t){this.addAudioToStreamWithShape(s,0,0,e,t)}addAudioToStreamWithShape(s,e,t,i,n){const r=4*s.length;this.h!==r&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(r),this.h=r),this.i.HEAPF32.set(s,this.g/4),oe(this,i,a=>{this.i._addAudioToInputStream(this.g,e,t,a,n)})}addGpuBufferToStream(s,e,t){oe(this,e,i=>{const[n,r]=tT(this,s,i);this.i._addBoundTextureToStream(i,n,r,t)})}addBoolToStream(s,e,t){oe(this,e,i=>{this.i._addBoolToInputStream(s,i,t)})}addDoubleToStream(s,e,t){oe(this,e,i=>{this.i._addDoubleToInputStream(s,i,t)})}addFloatToStream(s,e,t){oe(this,e,i=>{this.i._addFloatToInputStream(s,i,t)})}addIntToStream(s,e,t){oe(this,e,i=>{this.i._addIntToInputStream(s,i,t)})}addUintToStream(s,e,t){oe(this,e,i=>{this.i._addUintToInputStream(s,i,t)})}addStringToStream(s,e,t){oe(this,e,i=>{oe(this,s,n=>{this.i._addStringToInputStream(n,i,t)})})}addStringRecordToStream(s,e,t){oe(this,e,i=>{iT(this,Object.keys(s),n=>{iT(this,Object.values(s),r=>{this.i._addFlatHashMapToInputStream(n,r,Object.keys(s).length,i,t)})})})}addProtoToStream(s,e,t,i){oe(this,t,n=>{oe(this,e,r=>{const a=this.i._malloc(s.length);this.i.HEAPU8.set(s,a),this.i._addProtoToInputStream(a,s.length,r,n,i),this.i._free(a)})})}addEmptyPacketToStream(s,e){oe(this,s,t=>{this.i._addEmptyPacketToInputStream(t,e)})}addBoolVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateBoolVector(s.length);if(!n)throw Error("Unable to allocate new bool vector on heap.");for(const r of s)this.i._addBoolVectorEntry(n,r);this.i._addBoolVectorToInputStream(n,i,t)})}addDoubleVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateDoubleVector(s.length);if(!n)throw Error("Unable to allocate new double vector on heap.");for(const r of s)this.i._addDoubleVectorEntry(n,r);this.i._addDoubleVectorToInputStream(n,i,t)})}addFloatVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateFloatVector(s.length);if(!n)throw Error("Unable to allocate new float vector on heap.");for(const r of s)this.i._addFloatVectorEntry(n,r);this.i._addFloatVectorToInputStream(n,i,t)})}addIntVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateIntVector(s.length);if(!n)throw Error("Unable to allocate new int vector on heap.");for(const r of s)this.i._addIntVectorEntry(n,r);this.i._addIntVectorToInputStream(n,i,t)})}addUintVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateUintVector(s.length);if(!n)throw Error("Unable to allocate new unsigned int vector on heap.");for(const r of s)this.i._addUintVectorEntry(n,r);this.i._addUintVectorToInputStream(n,i,t)})}addStringVectorToStream(s,e,t){oe(this,e,i=>{const n=this.i._allocateStringVector(s.length);if(!n)throw Error("Unable to allocate new string vector on heap.");for(const r of s)oe(this,r,a=>{this.i._addStringVectorEntry(n,a)});this.i._addStringVectorToInputStream(n,i,t)})}addBoolToInputSidePacket(s,e){oe(this,e,t=>{this.i._addBoolToInputSidePacket(s,t)})}addDoubleToInputSidePacket(s,e){oe(this,e,t=>{this.i._addDoubleToInputSidePacket(s,t)})}addFloatToInputSidePacket(s,e){oe(this,e,t=>{this.i._addFloatToInputSidePacket(s,t)})}addIntToInputSidePacket(s,e){oe(this,e,t=>{this.i._addIntToInputSidePacket(s,t)})}addUintToInputSidePacket(s,e){oe(this,e,t=>{this.i._addUintToInputSidePacket(s,t)})}addStringToInputSidePacket(s,e){oe(this,e,t=>{oe(this,s,i=>{this.i._addStringToInputSidePacket(i,t)})})}addProtoToInputSidePacket(s,e,t){oe(this,t,i=>{oe(this,e,n=>{const r=this.i._malloc(s.length);this.i.HEAPU8.set(s,r),this.i._addProtoToInputSidePacket(r,s.length,n,i),this.i._free(r)})})}addBoolVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateBoolVector(s.length);if(!i)throw Error("Unable to allocate new bool vector on heap.");for(const n of s)this.i._addBoolVectorEntry(i,n);this.i._addBoolVectorToInputSidePacket(i,t)})}addDoubleVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateDoubleVector(s.length);if(!i)throw Error("Unable to allocate new double vector on heap.");for(const n of s)this.i._addDoubleVectorEntry(i,n);this.i._addDoubleVectorToInputSidePacket(i,t)})}addFloatVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateFloatVector(s.length);if(!i)throw Error("Unable to allocate new float vector on heap.");for(const n of s)this.i._addFloatVectorEntry(i,n);this.i._addFloatVectorToInputSidePacket(i,t)})}addIntVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateIntVector(s.length);if(!i)throw Error("Unable to allocate new int vector on heap.");for(const n of s)this.i._addIntVectorEntry(i,n);this.i._addIntVectorToInputSidePacket(i,t)})}addUintVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateUintVector(s.length);if(!i)throw Error("Unable to allocate new unsigned int vector on heap.");for(const n of s)this.i._addUintVectorEntry(i,n);this.i._addUintVectorToInputSidePacket(i,t)})}addStringVectorToInputSidePacket(s,e){oe(this,e,t=>{const i=this.i._allocateStringVector(s.length);if(!i)throw Error("Unable to allocate new string vector on heap.");for(const n of s)oe(this,n,r=>{this.i._addStringVectorEntry(i,r)});this.i._addStringVectorToInputSidePacket(i,t)})}attachBoolListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachBoolListener(t)})}attachBoolVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachBoolVectorListener(t)})}attachIntListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachIntListener(t)})}attachIntVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachIntVectorListener(t)})}attachUintListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachUintListener(t)})}attachUintVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachUintVectorListener(t)})}attachDoubleListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachDoubleListener(t)})}attachDoubleVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachDoubleVectorListener(t)})}attachFloatListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachFloatListener(t)})}attachFloatVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachFloatVectorListener(t)})}attachStringListener(s,e){Fs(this,s,e),oe(this,s,t=>{this.i._attachStringListener(t)})}attachStringVectorListener(s,e){Vn(this,s,e),oe(this,s,t=>{this.i._attachStringVectorListener(t)})}attachProtoListener(s,e,t){Fs(this,s,e),oe(this,s,i=>{this.i._attachProtoListener(i,t||!1)})}attachProtoVectorListener(s,e,t){Vn(this,s,e),oe(this,s,i=>{this.i._attachProtoVectorListener(i,t||!1)})}attachAudioListener(s,e,t){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),Fs(this,s,(i,n)=>{i=new Float32Array(i.buffer,i.byteOffset,i.length/4),e(i,n)}),oe(this,s,i=>{this.i._attachAudioListener(i,t||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends oT{get ga(){return this.i}pa(s,e,t){oe(this,e,i=>{const[n,r]=tT(this,s,i);this.ga._addBoundTextureAsImageToStream(i,n,r,t)})}Z(s,e){Fs(this,s,e),oe(this,s,t=>{this.ga._attachImageListener(t)})}aa(s,e){Vn(this,s,e),oe(this,s,t=>{this.ga._attachImageVectorListener(t)})}}));var oT,Rs=class extends Fq{};async function ke(s,e,t){return async function(i,n,r,a){return Iq(i,n,r,a)}(s,t.canvas??(FI()?void 0:document.createElement("canvas")),e,t)}function UI(s,e,t,i){if(s.U){const r=new lI;if(t?.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var n=t.regionOfInterest;if(n.left>=n.right||n.top>=n.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(n.left<0||n.top<0||n.right>1||n.bottom>1)throw Error("Expected RectF values to be in [0,1].");ue(r,1,(n.left+n.right)/2),ue(r,2,(n.top+n.bottom)/2),ue(r,4,n.right-n.left),ue(r,3,n.bottom-n.top)}else ue(r,1,.5),ue(r,2,.5),ue(r,4,1),ue(r,3,1);if(t?.rotationDegrees){if(t?.rotationDegrees%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(ue(r,5,-Math.PI*t.rotationDegrees/180),t?.rotationDegrees%180!=0){const[a,o]=LI(e);t=pt(r,3)*o/a,n=pt(r,4)*a/o,ue(r,4,t),ue(r,3,n)}}s.g.addProtoToStream(r.g(),"mediapipe.NormalizedRect",s.U,i)}s.g.pa(e,s.X,i??performance.now()),s.finishProcessing()}function Ds(s,e,t){if(s.baseOptions?.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");UI(s,e,t,s.C+1)}function rn(s,e,t,i){if(!s.baseOptions?.g())throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");UI(s,e,t,i)}function Do(s,e,t,i){var n=e.data;const r=e.width,a=r*(e=e.height);if((n instanceof Uint8Array||n instanceof Float32Array)&&n.length!==a)throw Error("Unsupported channel count: "+n.length/a);return s=new Ot([n],t,!1,s.g.i.canvas,s.P,r,e),i?s.clone():s}var Gi=class extends x0{constructor(s,e,t,i){super(s),this.g=s,this.X=e,this.U=t,this.oa=i,this.P=new $I}l(s,e=!0){if("runningMode"in s&&Ie(this.baseOptions,2,Bl(!!s.runningMode&&s.runningMode!=="IMAGE")),s.canvas!==void 0&&this.g.i.canvas!==s.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(s,e)}close(){this.P.close(),super.close()}};Gi.prototype.close=Gi.prototype.close;var Ki=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect_in",!1),this.j={detections:[]},pe(s=this.h=new hf,0,1,e=new lt),ue(this.h,2,.5),ue(this.h,3,.3)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&ue(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&ue(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,e){return this.j={detections:[]},Ds(this,s,e),this.j}G(s,e,t){return this.j={detections:[]},rn(this,s,t,e),this.j}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect_in"),Ee(s,"detections");const e=new Hi;sn(e,mq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect_in"),Te(t,"DETECTIONS:detections"),t.o(e),ws(s,t),this.g.attachProtoVectorListener("detections",(i,n)=>{for(const r of i)i=aI(r),this.j.detections.push(RI(i));te(this,n)}),this.g.attachEmptyPacketListener("detections",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ki.prototype.detectForVideo=Ki.prototype.G,Ki.prototype.detect=Ki.prototype.F,Ki.prototype.setOptions=Ki.prototype.o,Ki.createFromModelPath=async function(s,e){return ke(Ki,s,{baseOptions:{modelAssetPath:e}})},Ki.createFromModelBuffer=function(s,e){return ke(Ki,s,{baseOptions:{modelAssetBuffer:e}})},Ki.createFromOptions=function(s,e){return ke(Ki,s,e)};var Cv=Ps([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),Ev=Ps([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),Mv=Ps([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),zI=Ps([474,475],[475,476],[476,477],[477,474]),Iv=Ps([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),Pv=Ps([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),GI=Ps([469,470],[470,471],[471,472],[472,469]),Rv=Ps([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),WI=[...Cv,...Ev,...Mv,...Iv,...Pv,...Rv],qI=Ps([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function cT(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var st=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,pe(s=this.h=new pI,0,1,e=new lt),this.A=new fI,pe(this.h,0,3,this.A),this.u=new hf,pe(this.h,0,2,this.u),Dn(this.u,4,1),ue(this.u,2,.5),ue(this.A,2,.5),ue(this.h,4,.5)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return"numFaces"in s&&Dn(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&ue(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&ue(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&ue(this.A,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in s&&(this.outputFacialTransformationMatrixes=!!s.outputFacialTransformationMatrixes),this.l(s)}F(s,e){return cT(this),Ds(this,s,e),this.j}G(s,e,t){return cT(this),rn(this,s,t,e),this.j}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect"),Ee(s,"face_landmarks");const e=new Hi;sn(e,yq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),Te(t,"NORM_LANDMARKS:face_landmarks"),t.o(e),ws(s,t),this.g.attachProtoVectorListener("face_landmarks",(i,n)=>{for(const r of i)i=yu(r),this.j.faceLandmarks.push(ff(i));te(this,n)}),this.g.attachEmptyPacketListener("face_landmarks",i=>{te(this,i)}),this.outputFaceBlendshapes&&(Ee(s,"blendshapes"),Te(t,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(i,n)=>{if(this.outputFaceBlendshapes)for(const r of i)i=df(r),this.j.faceBlendshapes.push(kv(i.g()??[]));te(this,n)}),this.g.attachEmptyPacketListener("blendshapes",i=>{te(this,i)})),this.outputFacialTransformationMatrixes&&(Ee(s,"face_geometry"),Te(t,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(i,n)=>{if(this.outputFacialTransformationMatrixes)for(const r of i)(i=Ae(i=gq(r),oq,2))&&this.j.facialTransformationMatrixes.push({rows:ls(i,1)??0??0,columns:ls(i,2)??0??0,data:Kr(i,3,Gs,Xr()).slice()??[]});te(this,n)}),this.g.attachEmptyPacketListener("face_geometry",i=>{te(this,i)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};st.prototype.detectForVideo=st.prototype.G,st.prototype.detect=st.prototype.F,st.prototype.setOptions=st.prototype.o,st.createFromModelPath=function(s,e){return ke(st,s,{baseOptions:{modelAssetPath:e}})},st.createFromModelBuffer=function(s,e){return ke(st,s,{baseOptions:{modelAssetBuffer:e}})},st.createFromOptions=function(s,e){return ke(st,s,e)},st.FACE_LANDMARKS_LIPS=Cv,st.FACE_LANDMARKS_LEFT_EYE=Ev,st.FACE_LANDMARKS_LEFT_EYEBROW=Mv,st.FACE_LANDMARKS_LEFT_IRIS=zI,st.FACE_LANDMARKS_RIGHT_EYE=Iv,st.FACE_LANDMARKS_RIGHT_EYEBROW=Pv,st.FACE_LANDMARKS_RIGHT_IRIS=GI,st.FACE_LANDMARKS_FACE_OVAL=Rv,st.FACE_LANDMARKS_CONTOURS=WI,st.FACE_LANDMARKS_TESSELATION=qI;var Dv=Ps([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function lT(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function uT(s){return s.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:s.gestures,landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handedness:s.handedness,handednesses:s.handedness}}function dT(s,e=!0){const t=[];for(const n of s){var i=df(n);s=[];for(const r of i.g())i=e&&ls(r,1)!=null?ls(r,1)??0:-1,s.push({score:pt(r,2)??0,index:i,categoryName:qt(et(r,3))??""??"",displayName:qt(et(r,4))??""??""});t.push(s)}return t}var Ei=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],pe(s=this.j=new yI,0,1,e=new lt),this.u=new xv,pe(this.j,0,2,this.u),this.D=new bv,pe(this.u,0,3,this.D),this.A=new gI,pe(this.u,0,2,this.A),this.h=new vq,pe(this.j,0,3,this.h),ue(this.A,2,.5),ue(this.u,4,.5),ue(this.D,2,.5)}get baseOptions(){return Ae(this.j,lt,1)}set baseOptions(s){pe(this.j,0,1,s)}o(s){if(Dn(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&ue(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&ue(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&ue(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var e=new Ra,t=e,i=b0(s.cannedGesturesClassifierOptions,Ae(this.h,Ra,3)?.l());pe(t,0,2,i),pe(this.h,0,3,e)}else s.cannedGesturesClassifierOptions===void 0&&Ae(this.h,Ra,3)?.g();return s.customGesturesClassifierOptions?(pe(t=e=new Ra,0,2,i=b0(s.customGesturesClassifierOptions,Ae(this.h,Ra,4)?.l())),pe(this.h,0,4,e)):s.customGesturesClassifierOptions===void 0&&Ae(this.h,Ra,4)?.g(),this.l(s)}Ha(s,e){return lT(this),Ds(this,s,e),uT(this)}Ia(s,e,t){return lT(this),rn(this,s,t,e),uT(this)}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect"),Ee(s,"hand_gestures"),Ee(s,"hand_landmarks"),Ee(s,"world_hand_landmarks"),Ee(s,"handedness");const e=new Hi;sn(e,bq,this.j);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),Te(t,"HAND_GESTURES:hand_gestures"),Te(t,"LANDMARKS:hand_landmarks"),Te(t,"WORLD_LANDMARKS:world_hand_landmarks"),Te(t,"HANDEDNESS:handedness"),t.o(e),ws(s,t),this.g.attachProtoVectorListener("hand_landmarks",(i,n)=>{for(const r of i){i=yu(r);const a=[];for(const o of Rn(i,cI,1))a.push({x:pt(o,1)??0,y:pt(o,2)??0,z:pt(o,3)??0,visibility:pt(o,4)??0});this.landmarks.push(a)}te(this,n)}),this.g.attachEmptyPacketListener("hand_landmarks",i=>{te(this,i)}),this.g.attachProtoVectorListener("world_hand_landmarks",(i,n)=>{for(const r of i){i=co(r);const a=[];for(const o of Rn(i,oI,1))a.push({x:pt(o,1)??0,y:pt(o,2)??0,z:pt(o,3)??0,visibility:pt(o,4)??0});this.worldLandmarks.push(a)}te(this,n)}),this.g.attachEmptyPacketListener("world_hand_landmarks",i=>{te(this,i)}),this.g.attachProtoVectorListener("hand_gestures",(i,n)=>{this.gestures.push(...dT(i,!1)),te(this,n)}),this.g.attachEmptyPacketListener("hand_gestures",i=>{te(this,i)}),this.g.attachProtoVectorListener("handedness",(i,n)=>{this.handedness.push(...dT(i)),te(this,n)}),this.g.attachEmptyPacketListener("handedness",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function hT(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}Ei.prototype.recognizeForVideo=Ei.prototype.Ia,Ei.prototype.recognize=Ei.prototype.Ha,Ei.prototype.setOptions=Ei.prototype.o,Ei.createFromModelPath=function(s,e){return ke(Ei,s,{baseOptions:{modelAssetPath:e}})},Ei.createFromModelBuffer=function(s,e){return ke(Ei,s,{baseOptions:{modelAssetBuffer:e}})},Ei.createFromOptions=function(s,e){return ke(Ei,s,e)},Ei.HAND_CONNECTIONS=Dv;var Mi=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],pe(s=this.h=new xv,0,1,e=new lt),this.u=new bv,pe(this.h,0,3,this.u),this.j=new gI,pe(this.h,0,2,this.j),Dn(this.j,3,1),ue(this.j,2,.5),ue(this.u,2,.5),ue(this.h,4,.5)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return"numHands"in s&&Dn(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&ue(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&ue(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&ue(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,e){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ds(this,s,e),hT(this)}G(s,e,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],rn(this,s,t,e),hT(this)}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect"),Ee(s,"hand_landmarks"),Ee(s,"world_hand_landmarks"),Ee(s,"handedness");const e=new Hi;sn(e,xq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),Te(t,"LANDMARKS:hand_landmarks"),Te(t,"WORLD_LANDMARKS:world_hand_landmarks"),Te(t,"HANDEDNESS:handedness"),t.o(e),ws(s,t),this.g.attachProtoVectorListener("hand_landmarks",(i,n)=>{for(const r of i)i=yu(r),this.landmarks.push(ff(i));te(this,n)}),this.g.attachEmptyPacketListener("hand_landmarks",i=>{te(this,i)}),this.g.attachProtoVectorListener("world_hand_landmarks",(i,n)=>{for(const r of i)i=co(r),this.worldLandmarks.push(dl(i));te(this,n)}),this.g.attachEmptyPacketListener("world_hand_landmarks",i=>{te(this,i)}),this.g.attachProtoVectorListener("handedness",(i,n)=>{var r=this.handedness,a=r.push;const o=[];for(const c of i){i=df(c);const l=[];for(const u of i.g())l.push({score:pt(u,2)??0,index:ls(u,1)??0??-1,categoryName:qt(et(u,3))??""??"",displayName:qt(et(u,4))??""??""});o.push(l)}a.call(r,...o),te(this,n)}),this.g.attachEmptyPacketListener("handedness",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Mi.prototype.detectForVideo=Mi.prototype.G,Mi.prototype.detect=Mi.prototype.F,Mi.prototype.setOptions=Mi.prototype.o,Mi.createFromModelPath=function(s,e){return ke(Mi,s,{baseOptions:{modelAssetPath:e}})},Mi.createFromModelBuffer=function(s,e){return ke(Mi,s,{baseOptions:{modelAssetBuffer:e}})},Mi.createFromOptions=function(s,e){return ke(Mi,s,e)},Mi.HAND_CONNECTIONS=Dv;var HI=Ps([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function fT(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function pT(s){try{if(!s.D)return s.h;s.D(s.h)}finally{mf(s)}}function Hu(s,e){s=yu(s),e.push(ff(s))}var Ne=class extends Gi{constructor(s,e){super(new Rs(s,e),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,pe(s=this.j=new _I,0,1,e=new lt),this.I=new bv,pe(this.j,0,2,this.I),this.W=new wq,pe(this.j,0,3,this.W),this.u=new hf,pe(this.j,0,4,this.u),this.O=new fI,pe(this.j,0,5,this.O),this.A=new xI,pe(this.j,0,6,this.A),this.M=new wI,pe(this.j,0,7,this.M),ue(this.u,2,.5),ue(this.u,3,.3),ue(this.O,2,.5),ue(this.A,2,.5),ue(this.A,3,.3),ue(this.M,2,.5),ue(this.I,2,.5)}get baseOptions(){return Ae(this.j,lt,1)}set baseOptions(s){pe(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&ue(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&ue(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&ue(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&ue(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&ue(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&ue(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&ue(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,e,t){const i=typeof e!="function"?e:{};return this.D=typeof e=="function"?e:t,fT(this),Ds(this,s,i),pT(this)}G(s,e,t,i){const n=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:i,fT(this),rn(this,s,n,e),pT(this)}m(){var s=new Yi;it(s,"input_frames_image"),Ee(s,"pose_landmarks"),Ee(s,"pose_world_landmarks"),Ee(s,"face_landmarks"),Ee(s,"left_hand_landmarks"),Ee(s,"left_hand_world_landmarks"),Ee(s,"right_hand_landmarks"),Ee(s,"right_hand_world_landmarks");const e=new Hi,t=new $_;zi(t,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(n,r){if(r!=null)if(Array.isArray(r))Ie(n,2,Jh(r,0,$l));else{if(!(typeof r=="string"||r instanceof Ks||j1(r)))throw Error("invalid value in Any.value field: "+r+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");Yn(n,2,V1(r,!1),va())}}(t,this.j.g());const i=new Ai;zi(i,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),tv(i,8,$_,t),We(i,"IMAGE:input_frames_image"),Te(i,"POSE_LANDMARKS:pose_landmarks"),Te(i,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Te(i,"FACE_LANDMARKS:face_landmarks"),Te(i,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Te(i,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Te(i,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Te(i,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),i.o(e),ws(s,i),pf(this,s),this.g.attachProtoListener("pose_landmarks",(n,r)=>{Hu(n,this.h.poseLandmarks),te(this,r)}),this.g.attachEmptyPacketListener("pose_landmarks",n=>{te(this,n)}),this.g.attachProtoListener("pose_world_landmarks",(n,r)=>{var a=this.h.poseWorldLandmarks;n=co(n),a.push(dl(n)),te(this,r)}),this.g.attachEmptyPacketListener("pose_world_landmarks",n=>{te(this,n)}),this.outputPoseSegmentationMasks&&(Te(i,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),Po(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(n,r)=>{this.h.poseSegmentationMasks=[Do(this,n,!0,!this.D)],te(this,r)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",n=>{this.h.poseSegmentationMasks=[],te(this,n)})),this.g.attachProtoListener("face_landmarks",(n,r)=>{Hu(n,this.h.faceLandmarks),te(this,r)}),this.g.attachEmptyPacketListener("face_landmarks",n=>{te(this,n)}),this.outputFaceBlendshapes&&(Ee(s,"extra_blendshapes"),Te(i,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(n,r)=>{var a=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(n=df(n),a.push(kv(n.g()??[]))),te(this,r)}),this.g.attachEmptyPacketListener("extra_blendshapes",n=>{te(this,n)})),this.g.attachProtoListener("left_hand_landmarks",(n,r)=>{Hu(n,this.h.leftHandLandmarks),te(this,r)}),this.g.attachEmptyPacketListener("left_hand_landmarks",n=>{te(this,n)}),this.g.attachProtoListener("left_hand_world_landmarks",(n,r)=>{var a=this.h.leftHandWorldLandmarks;n=co(n),a.push(dl(n)),te(this,r)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",n=>{te(this,n)}),this.g.attachProtoListener("right_hand_landmarks",(n,r)=>{Hu(n,this.h.rightHandLandmarks),te(this,r)}),this.g.attachEmptyPacketListener("right_hand_landmarks",n=>{te(this,n)}),this.g.attachProtoListener("right_hand_world_landmarks",(n,r)=>{var a=this.h.rightHandWorldLandmarks;n=co(n),a.push(dl(n)),te(this,r)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",n=>{te(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ne.prototype.detectForVideo=Ne.prototype.G,Ne.prototype.detect=Ne.prototype.F,Ne.prototype.setOptions=Ne.prototype.o,Ne.createFromModelPath=function(s,e){return ke(Ne,s,{baseOptions:{modelAssetPath:e}})},Ne.createFromModelBuffer=function(s,e){return ke(Ne,s,{baseOptions:{modelAssetBuffer:e}})},Ne.createFromOptions=function(s,e){return ke(Ne,s,e)},Ne.HAND_CONNECTIONS=Dv,Ne.POSE_CONNECTIONS=HI,Ne.FACE_LANDMARKS_LIPS=Cv,Ne.FACE_LANDMARKS_LEFT_EYE=Ev,Ne.FACE_LANDMARKS_LEFT_EYEBROW=Mv,Ne.FACE_LANDMARKS_LEFT_IRIS=zI,Ne.FACE_LANDMARKS_RIGHT_EYE=Iv,Ne.FACE_LANDMARKS_RIGHT_EYEBROW=Pv,Ne.FACE_LANDMARKS_RIGHT_IRIS=GI,Ne.FACE_LANDMARKS_FACE_OVAL=Rv,Ne.FACE_LANDMARKS_CONTOURS=WI,Ne.FACE_LANDMARKS_TESSELATION=qI;var Qi=class extends Gi{constructor(s,e){super(new Rs(s,e),"input_image","norm_rect",!0),this.j={classifications:[]},pe(s=this.h=new TI,0,1,e=new lt)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return pe(this.h,0,2,b0(s,Ae(this.h,yv,2))),this.l(s)}sa(s,e){return this.j={classifications:[]},Ds(this,s,e),this.j}ta(s,e,t){return this.j={classifications:[]},rn(this,s,t,e),this.j}m(){var s=new Yi;it(s,"input_image"),it(s,"norm_rect"),Ee(s,"classifications");const e=new Hi;sn(e,_q,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),We(t,"IMAGE:input_image"),We(t,"NORM_RECT:norm_rect"),Te(t,"CLASSIFICATIONS:classifications"),t.o(e),ws(s,t),this.g.attachProtoListener("classifications",(i,n)=>{this.j=Eq(uq(i)),te(this,n)}),this.g.attachEmptyPacketListener("classifications",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Qi.prototype.classifyForVideo=Qi.prototype.ta,Qi.prototype.classify=Qi.prototype.sa,Qi.prototype.setOptions=Qi.prototype.o,Qi.createFromModelPath=function(s,e){return ke(Qi,s,{baseOptions:{modelAssetPath:e}})},Qi.createFromModelBuffer=function(s,e){return ke(Qi,s,{baseOptions:{modelAssetBuffer:e}})},Qi.createFromOptions=function(s,e){return ke(Qi,s,e)};var Ii=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!0),this.h=new kI,this.embeddings={embeddings:[]},pe(s=this.h,0,1,e=new lt)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){var e=this.h,t=Ae(this.h,H_,2);return t=t?t.clone():new H_,s.l2Normalize!==void 0?Ie(t,1,Bl(s.l2Normalize)):"l2Normalize"in s&&Ie(t,1),s.quantize!==void 0?Ie(t,2,Bl(s.quantize)):"quantize"in s&&Ie(t,2),pe(e,0,2,t),this.l(s)}za(s,e){return Ds(this,s,e),this.embeddings}Aa(s,e,t){return rn(this,s,t,e),this.embeddings}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect"),Ee(s,"embeddings_out");const e=new Hi;sn(e,Tq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),Te(t,"EMBEDDINGS:embeddings_out"),t.o(e),ws(s,t),this.g.attachProtoListener("embeddings_out",(i,n)=>{i=fq(i),this.embeddings=function(r){return{embeddings:Rn(r,hq,1).map(a=>{const o={headIndex:ls(a,3)??0??-1,headName:qt(et(a,4))??""??""};var c=a.v;return w4(c,0|c[re],q_,zp(a,1))!==void 0?(a=Kr(a=Ae(a,q_,zp(a,1),void 0),1,Gs,Xr()),o.floatEmbedding=a.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=Ae(a,dq,zp(a,2),void 0)?.na()?.h()??c),o}),timestampMs:PI(et(r,2,void 0,void 0,ch)??g4)}}(i),te(this,n)}),this.g.attachEmptyPacketListener("embeddings_out",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ii.cosineSimilarity=function(s,e){if(s.floatEmbedding&&e.floatEmbedding)s=Z_(s.floatEmbedding,e.floatEmbedding);else{if(!s.quantizedEmbedding||!e.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=Z_(J_(s.quantizedEmbedding),J_(e.quantizedEmbedding))}return s},Ii.prototype.embedForVideo=Ii.prototype.Aa,Ii.prototype.embed=Ii.prototype.za,Ii.prototype.setOptions=Ii.prototype.o,Ii.createFromModelPath=function(s,e){return ke(Ii,s,{baseOptions:{modelAssetPath:e}})},Ii.createFromModelBuffer=function(s,e){return ke(Ii,s,{baseOptions:{modelAssetBuffer:e}})},Ii.createFromOptions=function(s,e){return ke(Ii,s,e)};var T0=class{constructor(s,e,t){this.confidenceMasks=s,this.categoryMask=e,this.qualityScores=t}close(){this.confidenceMasks?.forEach(s=>{s.close()}),this.categoryMask?.close()}};function Lq(s){const e=function(t){return Rn(t,Ai,1)}(s.ca()).filter(t=>(qt(et(t,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],e.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");e.length===1&&(Ae(e[0],Hi,7)?.j()?.g()??new Map).forEach((t,i)=>{s.u[Number(i)]=qt(et(t,1))??""})}function mT(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function gT(s){try{const e=new T0(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return e;s.j(e)}finally{mf(s)}}T0.prototype.close=T0.prototype.close;var oi=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Tv,this.A=new AI,pe(this.h,0,3,this.A),pe(s=this.h,0,1,e=new lt)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Ie(this.h,2,pu(s.displayNamesLocale)):"displayNamesLocale"in s&&Ie(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){Lq(this)}segment(s,e,t){const i=typeof e!="function"?e:{};return this.j=typeof e=="function"?e:t,mT(this),Ds(this,s,i),gT(this)}La(s,e,t,i){const n=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:i,mT(this),rn(this,s,n,e),gT(this)}Da(){return this.u}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect");const e=new Hi;sn(e,CI,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),t.o(e),ws(s,t),pf(this,s),this.outputConfidenceMasks&&(Ee(s,"confidence_masks"),Te(t,"CONFIDENCE_MASKS:confidence_masks"),Po(this,"confidence_masks"),this.g.aa("confidence_masks",(i,n)=>{this.confidenceMasks=i.map(r=>Do(this,r,!0,!this.j)),te(this,n)}),this.g.attachEmptyPacketListener("confidence_masks",i=>{this.confidenceMasks=[],te(this,i)})),this.outputCategoryMask&&(Ee(s,"category_mask"),Te(t,"CATEGORY_MASK:category_mask"),Po(this,"category_mask"),this.g.Z("category_mask",(i,n)=>{this.categoryMask=Do(this,i,!1,!this.j),te(this,n)}),this.g.attachEmptyPacketListener("category_mask",i=>{this.categoryMask=void 0,te(this,i)})),Ee(s,"quality_scores"),Te(t,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(i,n)=>{this.qualityScores=i,te(this,n)}),this.g.attachEmptyPacketListener("quality_scores",i=>{this.categoryMask=void 0,te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};oi.prototype.getLabels=oi.prototype.Da,oi.prototype.segmentForVideo=oi.prototype.La,oi.prototype.segment=oi.prototype.segment,oi.prototype.setOptions=oi.prototype.o,oi.createFromModelPath=function(s,e){return ke(oi,s,{baseOptions:{modelAssetPath:e}})},oi.createFromModelBuffer=function(s,e){return ke(oi,s,{baseOptions:{modelAssetBuffer:e}})},oi.createFromOptions=function(s,e){return ke(oi,s,e)};var k0=class{constructor(s,e,t){this.confidenceMasks=s,this.categoryMask=e,this.qualityScores=t}close(){this.confidenceMasks?.forEach(s=>{s.close()}),this.categoryMask?.close()}};k0.prototype.close=k0.prototype.close;var Ls=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Tv,this.u=new AI,pe(this.h,0,3,this.u),pe(s=this.h,0,1,e=new lt)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}segment(s,e,t,i){const n=typeof t!="function"?t:{};if(this.j=typeof t=="function"?t:i,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,t=this.C+1,i=new EI,e.keypoint&&e.scribble)throw Error("Cannot provide both keypoint and scribble.");if(e.keypoint){var r=new Hp;Yn(r,3,Bl(!0),!1),Yn(r,1,Wc(e.keypoint.x),0),Yn(r,2,Wc(e.keypoint.y),0),ll(i,1,v0,r)}else{if(!e.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new Aq;for(r of e.scribble)Yn(e=new Hp,3,Bl(!0),!1),Yn(e,1,Wc(r.x),0),Yn(e,2,Wc(r.y),0),tv(o,1,Hp,e);ll(i,2,v0,o)}}this.g.addProtoToStream(i.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",t),Ds(this,s,n);e:{try{const o=new k0(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var a=o;break e}this.j(o)}finally{mf(this)}a=void 0}return a}m(){var s=new Yi;it(s,"image_in"),it(s,"roi_in"),it(s,"norm_rect_in");const e=new Hi;sn(e,CI,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),We(t,"IMAGE:image_in"),We(t,"ROI:roi_in"),We(t,"NORM_RECT:norm_rect_in"),t.o(e),ws(s,t),pf(this,s),this.outputConfidenceMasks&&(Ee(s,"confidence_masks"),Te(t,"CONFIDENCE_MASKS:confidence_masks"),Po(this,"confidence_masks"),this.g.aa("confidence_masks",(i,n)=>{this.confidenceMasks=i.map(r=>Do(this,r,!0,!this.j)),te(this,n)}),this.g.attachEmptyPacketListener("confidence_masks",i=>{this.confidenceMasks=[],te(this,i)})),this.outputCategoryMask&&(Ee(s,"category_mask"),Te(t,"CATEGORY_MASK:category_mask"),Po(this,"category_mask"),this.g.Z("category_mask",(i,n)=>{this.categoryMask=Do(this,i,!1,!this.j),te(this,n)}),this.g.attachEmptyPacketListener("category_mask",i=>{this.categoryMask=void 0,te(this,i)})),Ee(s,"quality_scores"),Te(t,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(i,n)=>{this.qualityScores=i,te(this,n)}),this.g.attachEmptyPacketListener("quality_scores",i=>{this.categoryMask=void 0,te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ls.prototype.segment=Ls.prototype.segment,Ls.prototype.setOptions=Ls.prototype.o,Ls.createFromModelPath=function(s,e){return ke(Ls,s,{baseOptions:{modelAssetPath:e}})},Ls.createFromModelBuffer=function(s,e){return ke(Ls,s,{baseOptions:{modelAssetBuffer:e}})},Ls.createFromOptions=function(s,e){return ke(Ls,s,e)};var Ji=class extends Gi{constructor(s,e){super(new Rs(s,e),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},pe(s=this.h=new MI,0,1,e=new lt)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Ie(this.h,2,pu(s.displayNamesLocale)):"displayNamesLocale"in s&&Ie(this.h,2),s.maxResults!==void 0?Dn(this.h,3,s.maxResults):"maxResults"in s&&Ie(this.h,3),s.scoreThreshold!==void 0?ue(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Ie(this.h,4),s.categoryAllowlist!==void 0?uh(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Ie(this.h,5),s.categoryDenylist!==void 0?uh(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Ie(this.h,6),this.l(s)}F(s,e){return this.j={detections:[]},Ds(this,s,e),this.j}G(s,e,t){return this.j={detections:[]},rn(this,s,t,e),this.j}m(){var s=new Yi;it(s,"input_frame_gpu"),it(s,"norm_rect"),Ee(s,"detections");const e=new Hi;sn(e,Sq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),We(t,"IMAGE:input_frame_gpu"),We(t,"NORM_RECT:norm_rect"),Te(t,"DETECTIONS:detections"),t.o(e),ws(s,t),this.g.attachProtoVectorListener("detections",(i,n)=>{for(const r of i)i=aI(r),this.j.detections.push(RI(i));te(this,n)}),this.g.attachEmptyPacketListener("detections",i=>{te(this,i)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ji.prototype.detectForVideo=Ji.prototype.G,Ji.prototype.detect=Ji.prototype.F,Ji.prototype.setOptions=Ji.prototype.o,Ji.createFromModelPath=async function(s,e){return ke(Ji,s,{baseOptions:{modelAssetPath:e}})},Ji.createFromModelBuffer=function(s,e){return ke(Ji,s,{baseOptions:{modelAssetBuffer:e}})},Ji.createFromOptions=function(s,e){return ke(Ji,s,e)};var A0=class{constructor(s,e,t){this.landmarks=s,this.worldLandmarks=e,this.segmentationMasks=t}close(){this.segmentationMasks?.forEach(s=>{s.close()})}};function yT(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function vT(s){try{const e=new A0(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return e;s.u(e)}finally{mf(s)}}A0.prototype.close=A0.prototype.close;var Pi=class extends Gi{constructor(s,e){super(new Rs(s,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,pe(s=this.h=new II,0,1,e=new lt),this.A=new wI,pe(this.h,0,3,this.A),this.j=new xI,pe(this.h,0,2,this.j),Dn(this.j,4,1),ue(this.j,2,.5),ue(this.A,2,.5),ue(this.h,4,.5)}get baseOptions(){return Ae(this.h,lt,1)}set baseOptions(s){pe(this.h,0,1,s)}o(s){return"numPoses"in s&&Dn(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&ue(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&ue(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&ue(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,e,t){const i=typeof e!="function"?e:{};return this.u=typeof e=="function"?e:t,yT(this),Ds(this,s,i),vT(this)}G(s,e,t,i){const n=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:i,yT(this),rn(this,s,n,e),vT(this)}m(){var s=new Yi;it(s,"image_in"),it(s,"norm_rect"),Ee(s,"normalized_landmarks"),Ee(s,"world_landmarks"),Ee(s,"segmentation_masks");const e=new Hi;sn(e,Cq,this.h);const t=new Ai;zi(t,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),We(t,"IMAGE:image_in"),We(t,"NORM_RECT:norm_rect"),Te(t,"NORM_LANDMARKS:normalized_landmarks"),Te(t,"WORLD_LANDMARKS:world_landmarks"),t.o(e),ws(s,t),pf(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(i,n)=>{this.landmarks=[];for(const r of i)i=yu(r),this.landmarks.push(ff(i));te(this,n)}),this.g.attachEmptyPacketListener("normalized_landmarks",i=>{this.landmarks=[],te(this,i)}),this.g.attachProtoVectorListener("world_landmarks",(i,n)=>{this.worldLandmarks=[];for(const r of i)i=co(r),this.worldLandmarks.push(dl(i));te(this,n)}),this.g.attachEmptyPacketListener("world_landmarks",i=>{this.worldLandmarks=[],te(this,i)}),this.outputSegmentationMasks&&(Te(t,"SEGMENTATION_MASK:segmentation_masks"),Po(this,"segmentation_masks"),this.g.aa("segmentation_masks",(i,n)=>{this.segmentationMasks=i.map(r=>Do(this,r,!0,!this.u)),te(this,n)}),this.g.attachEmptyPacketListener("segmentation_masks",i=>{this.segmentationMasks=[],te(this,i)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Pi.prototype.detectForVideo=Pi.prototype.G,Pi.prototype.detect=Pi.prototype.F,Pi.prototype.setOptions=Pi.prototype.o,Pi.createFromModelPath=function(s,e){return ke(Pi,s,{baseOptions:{modelAssetPath:e}})},Pi.createFromModelBuffer=function(s,e){return ke(Pi,s,{baseOptions:{modelAssetBuffer:e}})},Pi.createFromOptions=function(s,e){return ke(Pi,s,e)},Pi.POSE_CONNECTIONS=HI;const Oq="https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite";class Bq{segmenter=null;initialized=!1;initializing=null;cachedMask=null;lastSegmentTime=0;segmentInterval=66;segCanvas=null;segCtx=null;upscaleCanvas=null;upscaleCtx=null;SEG_WIDTH=512;SEG_HEIGHT=288;async initialize(){if(!this.initialized){if(this.initializing)return this.initializing;this.initializing=this.doInitialize();try{await this.initializing}catch(e){throw this.initializing=null,e}}}async doInitialize(){const e=await Oa.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");this.segmenter=await oi.createFromOptions(e,{baseOptions:{modelAssetPath:Oq,delegate:"GPU"},runningMode:"VIDEO",outputCategoryMask:!1,outputConfidenceMasks:!0}),this.segCanvas=document.createElement("canvas"),this.segCanvas.width=this.SEG_WIDTH,this.segCanvas.height=this.SEG_HEIGHT,this.segCtx=this.segCanvas.getContext("2d",{willReadFrequently:!0}),this.upscaleCanvas=document.createElement("canvas"),this.upscaleCtx=this.upscaleCanvas.getContext("2d",{willReadFrequently:!0}),this.initialized=!0,this.initializing=null}isInitialized(){return this.initialized}setSegmentInterval(e){this.segmentInterval=Math.max(16,e)}async getPersonMask(e){if(!this.segmenter)return null;const t=performance.now();if(this.cachedMask&&t-this.lastSegmentTime{if(u.confidenceMasks&&u.confidenceMasks.length>0){const h=(this.segmenter?.getLabels()??[]).findIndex(m=>/foreground|human|person|selfie/i.test(m)),f=h>=0&&h1?u.confidenceMasks.length-1:0,p=u.confidenceMasks[f]??u.confidenceMasks[0];r=new Float32Array(p.getAsFloat32Array());for(const m of u.confidenceMasks)m.close()}}),!r)return this.cachedMask;const a=new ImageData(this.SEG_WIDTH,this.SEG_HEIGHT);for(let u=0;u>2]=t[o+3];for(let o=r;o0&&this.applyEdgeBlur(o,r.edgeBlur),this.maskCtx.putImageData(o,0,0),this.outputCtx.clearRect(0,0,i,n),r.mode){case"blur":await this.renderBlurBackground(t,o,i,n,r.blurAmount);break;case"color":this.renderColorBackground(t,o,i,n,r.backgroundColor);break;case"image":this.renderImageBackground(t,o,i,n);break;case"transparent":this.renderTransparentBackground(t,o,i,n);break;default:this.outputCtx.drawImage(t,0,0,i,n)}return createImageBitmap(this.outputCanvas)}async processFrameFast(e,t,i,n,r){const o=await S0().getPersonMask(t);if(!o)return t;if(r.edgeBlur>0||r.threshold!==.7){const c=new ImageData(new Uint8ClampedArray(o.mask.data),o.mask.width,o.mask.height),l=Math.round(r.threshold*255),u=c.data;for(let d=3;d=l?255:Math.round(h*(h/l))}this.maskCtx.putImageData(c,0,0),r.edgeBlur>0&&(this.maskCtx.filter=`blur(${r.edgeBlur}px)`,this.maskCtx.drawImage(this.maskCanvas,0,0),this.maskCtx.filter="none")}else this.maskCtx.putImageData(o.mask,0,0);switch(this.outputCtx.clearRect(0,0,i,n),r.mode){case"blur":this.outputCtx.filter=`blur(${r.blurAmount}px)`,this.outputCtx.drawImage(t,0,0,i,n),this.outputCtx.filter="none";break;case"color":this.outputCtx.fillStyle=r.backgroundColor,this.outputCtx.fillRect(0,0,i,n);break;case"image":this.backgroundImage?this.outputCtx.drawImage(this.backgroundImage,0,0,i,n):(this.outputCtx.fillStyle="#000000",this.outputCtx.fillRect(0,0,i,n));break;case"transparent":break;default:return this.outputCtx.drawImage(t,0,0,i,n),createImageBitmap(this.outputCanvas)}return this.ctx.clearRect(0,0,i,n),this.ctx.drawImage(t,0,0,i,n),this.ctx.globalCompositeOperation="destination-in",this.ctx.drawImage(this.maskCanvas,0,0,i,n),this.ctx.globalCompositeOperation="source-over",this.outputCtx.drawImage(this.canvas,0,0),createImageBitmap(this.outputCanvas)}generateSimpleMask(e,t){const{data:i,width:n,height:r}=e,a=new ImageData(n,r);for(let o=0;o.1&&d<.95&&h>.05?255:0;a.data[o]=p,a.data[o+1]=p,a.data[o+2]=p,a.data[o+3]=255}return this.refineMask(a,3)}calculateSaturation(e,t,i){const n=Math.max(e,t,i),r=Math.min(e,t,i);return n===0?0:(n-r)/n}refineMask(e,t){const{width:i,height:n}=e,r=new ImageData(new Uint8ClampedArray(e.data),i,n);for(let a=0;a127?255:0,r.data[u+1]=r.data[u],r.data[u+2]=r.data[u]}}return r}applyEdgeBlur(e,t){const{data:i,width:n,height:r}=e,a=new Uint8ClampedArray(i);for(let o=t;o{this.changeListeners.delete(e)}}notifyChange(){this.changeVersion++;for(const e of this.changeListeners)e()}getChangeVersion(){return this.changeVersion}setCanvasSize(e,t){this.canvasWidth=e,this.canvasHeight=t}addEffect(e){this.effects.set(e.id,e),this.emitters.set(e.id,{effectId:e.id,particles:[],elapsedTime:0,emissionAccumulator:0,active:!1}),this.notifyChange()}removeEffect(e){this.effects.delete(e),this.emitters.delete(e),this.notifyChange()}updateEffect(e,t){const i=this.effects.get(e);i&&(i.config={...i.config,...t},this.notifyChange())}updateEffectTiming(e,t,i){const n=this.effects.get(e);n&&(n.startTime=t,n.duration=i,this.notifyChange())}getEffect(e){return this.effects.get(e)}getAllEffects(){return Array.from(this.effects.values())}getEffectsForClip(e){return Array.from(this.effects.values()).filter(t=>t.clipId===e)}toggleEffect(e,t){const i=this.effects.get(e);i&&(i.enabled=t,this.notifyChange())}createParticle(e,t){const i=e.config,n=Vq(i,t),r=Uq(i,e.type,t,n),a=Math.floor(Math.random()*i.colors.length);return{id:Nq(),position:n,velocity:r,acceleration:{x:0,y:i.gravity,z:0},color:i.colors[a],size:yt(i.size.min,i.size.max),opacity:i.opacity.start,rotation:Math.random()*Math.PI*2,rotationSpeed:yt(-i.rotationSpeed,i.rotationSpeed),lifetime:yt(i.lifetime.min,i.lifetime.max),age:0,active:!0}}update(e,t){for(const[i,n]of this.emitters){const r=this.effects.get(i);if(!r||!r.enabled)continue;const a=e>=r.startTime,o=e>r.startTime+r.duration;if(!a||o){n.active=!1;continue}n.active=!0,n.elapsedTime=e-r.startTime;const c=r.config,l={x:this.canvasWidth/2,y:this.canvasHeight/2,z:0};for(n.emissionAccumulator+=c.emissionRate*t;n.emissionAccumulator>=1&&n.particles.length0&&(u.velocity.x+=yt(-c.turbulence,c.turbulence)*t,u.velocity.y+=yt(-c.turbulence,c.turbulence)*t),u.position.x+=u.velocity.x*t,u.position.y+=u.velocity.y*t,u.position.z+=u.velocity.z*t,u.rotation+=u.rotationSpeed*t,u.age+=t;const d=u.age/u.lifetime;if(d1-c.fadeOut){const h=(1-d)/c.fadeOut;u.opacity=c.opacity.end+(c.opacity.start-c.opacity.end)*h}else{const h=(d-c.fadeIn)/(1-c.fadeIn-c.fadeOut);u.opacity=c.opacity.start+(c.opacity.end-c.opacity.start)*h}u.age>=u.lifetime&&(u.active=!1)}n.particles=n.particles.filter(u=>u.active)}}getParticles(e){if(e){const i=this.emitters.get(e);return i?i.particles:[]}const t=[];for(const i of this.emitters.values())i.active&&t.push(...i.particles);return t}getActiveEffectIds(){const e=[];for(const[t,i]of this.emitters)i.active&&e.push(t);return e}reset(){for(const e of this.emitters.values())e.particles=[],e.elapsedTime=0,e.emissionAccumulator=0,e.active=!1}dispose(){this.emitters.clear(),this.effects.clear()}}let Kp=null;function xT(){return Kp||(Kp=new zq),Kp}const Gq={maxFrames:100,maxSizeBytes:500*1024*1024,preloadAhead:30,preloadBehind:10};class Fv{mediabunny=null;initialized=!1;frameCache=new Map;gifFrameCache=new Map;staticImageCache=new Map;cacheConfig;cacheStats={hits:0,misses:0};preloadQueue=[];isPreloading=!1;compositeCanvas=null;compositeCtx=null;decodeCanvas=null;decodeCtx=null;parallelDecoder=null;compositeBuffer=null;useParallelDecoding=!0;videoElementCache=new Map;gpuCompositor=null;gpuRenderer=null;effectsEngine=null;transitionEngine=null;lastExportTime=-1;exportFrameRate=30;exportMode=!1;constructor(e={}){this.cacheConfig={...Gq,...e}}async initialize(){if(!this.initialized){this.isWebCodecsSupported()||console.warn("[VideoEngine] WebCodecs not supported in this browser");try{this.mediabunny=await ii(()=>import("./index-DjtrfS0G.js"),[])}catch(e){console.warn("[VideoEngine] MediaBunny not available, some features will be limited:",e),this.mediabunny=null}try{this.useParallelDecoding&&(this.parallelDecoder=HG(),await this.parallelDecoder.initialize())}catch(e){console.warn("[VideoEngine] Parallel decoder initialization failed:",e),this.parallelDecoder=null}this.compositeBuffer=XG(),this.initialized=!0}}isWebCodecsSupported(){return typeof VideoDecoder<"u"&&typeof VideoEncoder<"u"}isMediaBunnyAvailable(){return this.mediabunny!==null}getParallelDecoder(){return this.parallelDecoder}getCompositeBuffer(){return this.compositeBuffer}getGPUCompositor(){return this.gpuCompositor}async initializeGPUCompositor(e,t){if(!this.gpuCompositor)try{const i=new OffscreenCanvas(e,t),n=lG();this.gpuRenderer=await n.createRenderer({canvas:i,width:e,height:t}),this.gpuCompositor=QG({width:e,height:t,backgroundColor:[0,0,0,1],antialias:!0}),this.gpuCompositor.setRenderer(this.gpuRenderer)}catch(i){console.warn("[VideoEngine] GPU compositor initialization failed, using CPU fallback:",i)}}isInitialized(){return this.initialized}setParallelDecoding(e){this.useParallelDecoding=e}async decodeFrameWithMediaBunny(e,t,i,n,r){try{const a=sa();if(a.isAvailable()||await a.initialize(),r){const c=a.getExportDecoder(r);if(c){const l=await c.getFrame(t);if(l)return createImageBitmap(l)}}const o=await a.getFrameAtTime(e,t,i);return o?.canvas?createImageBitmap(o.canvas):null}catch(a){return console.warn("[VideoEngine] MediaBunny frame decode failed:",a),null}}interpFrameCache=new Map;static INTERP_FRAME_CACHE_MAX=2;getCachedInterpFrame(e){const t=this.interpFrameCache.get(e);return t?(t.time=performance.now(),t.bitmap):null}setCachedInterpFrame(e,t){if(this.interpFrameCache.size>=Fv.INTERP_FRAME_CACHE_MAX){let i="",n=1/0;for(const[r,a]of this.interpFrameCache)a.time{g.onloadedmetadata=()=>v(),g.onerror=()=>w(new Error("Video load failed")),setTimeout(()=>w(new Error("Video load timeout")),1e4)}),a={video:g,url:m},this.videoElementCache.set(e,a)}const{video:o}=a;o.currentTime=i,await new Promise(m=>{let g=!1;const v=()=>{g||(g=!0,o.removeEventListener("seeked",v),m())};o.addEventListener("seeked",v),o.readyState>=2&&v(),setTimeout(()=>{g||(g=!0,o.removeEventListener("seeked",v),m())},3e3)}),(!this.decodeCanvas||this.decodeCanvas.width!==n||this.decodeCanvas.height!==r)&&(this.decodeCanvas=new OffscreenCanvas(n,r),this.decodeCtx=this.decodeCanvas.getContext("2d"));const c=this.decodeCtx;c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high";const l=o.videoWidth/o.videoHeight,u=n/r;let d,h,f,p;return l>u?(d=n,h=n/l,f=0,p=(r-h)/2):(h=r,d=r*l,f=(n-d)/2,p=0),c.fillStyle="#000000",c.fillRect(0,0,n,r),c.drawImage(o,f,p,d,h),createImageBitmap(this.decodeCanvas)}clearVideoElementCache(){for(const[,e]of this.videoElementCache)e.video.pause(),e.video.removeAttribute("src"),e.video.load(),URL.revokeObjectURL(e.url);this.videoElementCache.clear()}ensureInitialized(){if(!this.initialized||!this.mediabunny)throw new Error("VideoEngine not initialized. Call initialize() first.")}async renderFrame(e,t,i,n){this.ensureInitialized();const{timeline:r,mediaLibrary:a,settings:o}=e,c=i??o.width,l=n??o.height,u=c/o.width,d=l/o.height,h=this.getActiveTextClips(r,t),f=this.getActiveShapeClips(r,t),p=this.getActiveSVGClips(r,t),m=this.getActiveStickerClips(r,t),g=this.getActiveSubtitles(r,t),v=r.tracks.map((R,I)=>({track:R,originalIndex:I})).filter(({track:R})=>(R.type==="video"||R.type==="image"||R.type==="text"||R.type==="graphics")&&!R.hidden).sort((R,I)=>I.originalIndex-R.originalIndex);(!this.compositeCanvas||this.compositeCanvas.width!==c||this.compositeCanvas.height!==l)&&(this.compositeCanvas=new OffscreenCanvas(c,l),this.compositeCtx=this.compositeCanvas.getContext("2d"));const w=this.compositeCanvas,b=this.compositeCtx;b.imageSmoothingEnabled=!0,b.imageSmoothingQuality="high",b.fillStyle="#000000",b.fillRect(0,0,c,l);let k=null;const A=h.some(R=>R.behindSubject);for(const{track:R}of v)if(R.type==="video"||R.type==="image"){const I=await this.renderActiveTransition(R,t,a,o,c,l,b),D=this.getClipsAtTime(R,t);for(const B of D){if(I.has(B.id))continue;const $=this.createClipRenderInfo(B,t),V=a.items.find(T=>T.id===$.mediaId);if(!V?.blob)continue;let y=null,_=!1;if(V.type==="image")try{if(s0(V.blob)){let T=this.gifFrameCache.get(V.id);if(!T){const S=await t0(V.blob);S&&(this.gifFrameCache.set(V.id,S),T=S)}if(T&&T.frames.length>0){const S=t-B.startTime,C=i0(T,S*1e3);y=T.frames[C],_=!0}else y=await createImageBitmap(V.blob)}else{const T=this.staticImageCache.get(V.id);T?(y=T,_=!0):(y=await createImageBitmap(V.blob),this.staticImageCache.set(V.id,y),_=!0)}}catch(T){console.warn(`Failed to create ImageBitmap for image ${V.id}:`,T)}else{const T=B.speed??1;if(B.smoothSlowMo===!0&&T<1&&V.metadata?.frameRate&&(y=await this.decodeInterpolatedFrame(B,V,$.sourceTime,t,o.width,o.height)),!y){const C=Bp(),E=C.hasStabilized(B.id),P=E?C.getStabilizedBlob(B.id):V.blob,L=E?$.sourceTime-B.inPoint:$.sourceTime;y=await this.decodeFrameWithMediaBunny(P,L,o.width,o.height,E?`stabilized:${B.id}`:$.mediaId)}if(!y){const C=Bp(),E=C.hasStabilized(B.id),P=E?C.getStabilizedBlob(B.id):V.blob,L=E?$.sourceTime-B.inPoint:$.sourceTime;y=await this.decodeFrameWithVideoElement(E?`stabilized:${B.id}`:V.id,P,L,o.width,o.height)}}if(y){let T=$.transform;const S=t-B.startTime;if(B.emphasisAnimation&&B.emphasisAnimation.type!=="none"){const U=this.applyEmphasisAnimation(B.emphasisAnimation,S);T={...T,opacity:T.opacity*U.opacity,scale:{x:T.scale.x*U.scale*U.scaleX,y:T.scale.y*U.scale*U.scaleY},position:{x:T.position.x+U.offsetX*o.width,y:T.position.y+U.offsetY*o.height},rotation:T.rotation+U.rotation}}const C={...T,position:{x:T.position.x*u,y:T.position.y*d},scale:{x:T.scale.x*u,y:T.scale.y*d}};let E=y;const P=jq();if(P&&P.isInitialized()&&P.getSettings(B.id).enabled)try{const j=await P.processFrame(B.id,E,E.width,E.height);j&&j!==E&&(E!==y&&E.close(),E=j)}catch{}if($.effects&&$.effects.length>0)try{if(!this.effectsEngine){this.effectsEngine=new lu({width:c,height:l,useGPU:!0,preferWebGPU:!1});const j=this.effectsEngine.initialize(),N=new Promise((z,W)=>setTimeout(()=>W(new Error("Effects init timeout")),5e3));await Promise.race([j,N])}const U=await this.effectsEngine.applyEffects(E,$.effects);E!==y&&E.close(),E=U.image}catch(U){console.warn(`Failed to apply effects to clip ${B.id}:`,U),this.effectsEngine=null}const O=Bp().hasStabilized(B.id)?C:$G(B,C,$.sourceTime,{canvasWidth:c,canvasHeight:l,sourceWidth:E.width,sourceHeight:E.height});this.drawFrameToContext(b,E,O,T.opacity,c,l),A&&(k?.close(),k=await this.captureSubjectFrame(b,c,l)),E!==y&&E.close(),_||y.close()}}}else if(R.type==="graphics"){const I=f.filter($=>$.trackId===R.id);for(const $ of I)await this.renderShapeClipToCanvasCtx(b,$,t,c,l);const D=p.filter($=>$.trackId===R.id);for(const $ of D)await this.renderSVGClipToCanvasCtx(b,$,t,c,l);const B=m.filter($=>$.trackId===R.id);for(const $ of B)await this.renderStickerClipToCanvasCtx(b,$,t,c,l)}else if(R.type==="text"){const I=h.filter(D=>D.trackId===R.id);for(const D of I)await this.renderTextClipWithSubjectMask(b,D,t,c,l,k)}k?.close(),this.renderParticlesToContext(b,t,c,l);for(const R of g)this.renderSubtitleToCanvasCtx(b,R,c,l);return{image:await createImageBitmap(w),timestamp:t,width:c,height:l}}drawFrameToContext(e,t,i,n,r,a){e.save(),e.globalAlpha=n;const o=r/2,c=a/2;if(e.translate(o+i.position.x,c+i.position.y),e.rotate(i.rotation*Math.PI/180),e.scale(i.scale.x,i.scale.y),i.crop){const l=i.crop.x*t.width,u=i.crop.y*t.height,d=i.crop.width*t.width,h=i.crop.height*t.height,f=d/h,p=r/a;let m,g;f>p?(m=r,g=r/f):(g=a,m=a*f);const v=-m*i.anchor.x,w=-g*i.anchor.y;e.drawImage(t,l,u,d,h,v,w,m,g)}else{const l=!i.fitMode||i.fitMode==="none"?"contain":i.fitMode;let u=t.width,d=t.height;const h=t.width/t.height,f=r/a;l==="stretch"?(u=r,d=a):l==="cover"?h>f?(d=a,u=a*h):(u=r,d=r/h):h>f?(u=r,d=r/h):(d=a,u=a*h);const p=-u*i.anchor.x,m=-d*i.anchor.y;e.drawImage(t,p,m,u,d)}e.restore()}async captureSubjectFrame(e,t,i){try{return await createImageBitmap(e.canvas,0,0,t,i)}catch{return null}}async drawMaskedSubjectFromFrame(e,t,i,n){if(t)try{const r=S0();r.isInitialized()||await r.initialize();const a=await r.getPersonMask(t);if(!a)return;const o=new OffscreenCanvas(i,n),c=o.getContext("2d");if(!c)return;c.drawImage(t,0,0,i,n);const l=new OffscreenCanvas(a.width,a.height),u=l.getContext("2d");if(!u)return;u.putImageData(a.mask,0,0),c.globalCompositeOperation="destination-in",c.drawImage(l,0,0,i,n),e.drawImage(o,0,0)}catch{}}async renderTextClipWithSubjectMask(e,t,i,n,r,a){this.renderTextClipToCanvasCtx(e,t,i,n,r),t.behindSubject&&await this.drawMaskedSubjectFromFrame(e,a,n,r)}getActiveTextClips(e,t){const i=na.getAllTextClips(),n=e.tracks.filter(a=>a.type==="text"&&!a.hidden),r=new Set(n.map(a=>a.id));return i.filter(a=>{if(!r.has(a.trackId))return!1;const o=a.startTime+a.duration;return t>=a.startTime&&ta.type==="graphics"&&!a.hidden),r=new Set(n.map(a=>a.id));return i.filter(a=>{if(!r.has(a.trackId))return!1;const o=a.startTime+a.duration;return t>=a.startTime&&ta.type==="graphics"&&!a.hidden),r=new Set(n.map(a=>a.id));return i.filter(a=>{if(!r.has(a.trackId))return!1;const o=a.startTime+a.duration;return t>=a.startTime&&ta.type==="graphics"&&!a.hidden),r=new Set(n.map(a=>a.id));return i.filter(a=>{if(!r.has(a.trackId))return!1;const o=a.startTime+a.duration;return t>=a.startTime&&tt>=n.startTime&&t=0?Math.max(0,t-this.lastExportTime):1/this.exportFrameRate;this.lastExportTime=t,r.update(t,a);const o=r.getParticles();if(o.length!==0){e.save();for(const c of o){if(!c.active||c.opacity<=0)continue;e.globalAlpha=c.opacity,e.fillStyle=c.color;const l=n-c.position.y;e.beginPath(),e.arc(c.position.x,l,c.size/2,0,Math.PI*2),e.fill()}e.restore()}}resetExportState(){this.lastExportTime=-1,xT().reset()}renderSubtitleToCanvasCtx(e,t,i,n){const{text:r,style:a}=t;if(!r||r.trim().length===0)return;e.save();const o=a?.fontSize||24,c=a?.fontFamily||"Inter",l=a?.color||"#ffffff",u=a?.backgroundColor||"rgba(0, 0, 0, 0.7)",d=a?.position||"bottom";e.font=`bold ${o}px "${c}"`,e.textAlign="center",e.textBaseline="middle";const h=r.split(` +`),f=o*1.3,p=h.length*f;let m;d==="top"?m=o*2:d==="center"?m=n/2-p/2:m=n-o*2-p;for(let g=0;g{const n=i.startTime+i.duration;return t>=i.startTime&&td.id===n.clipAId),a=e.clips.find(d=>d.id===n.clipBId);if(!r||!a)continue;const o=r.startTime+r.duration,c=o-n.duration/2,l=o+n.duration/2;if(tl)continue;const u=n.duration>0?Math.max(0,Math.min(1,(t-c)/n.duration)):0;return{transition:n,clipA:r,clipB:a,progress:u}}return null}async decodeClipBitmap(e,t,i,n,r){if(!t.blob)return null;if(t.type==="image")try{if(s0(t.blob)){let h=this.gifFrameCache.get(t.id);if(!h){const f=await t0(t.blob);f&&(this.gifFrameCache.set(t.id,f),h=f)}if(h&&h.frames.length>0){const f=i-e.startTime,p=i0(h,f*1e3);return h.frames[p]}}const u=this.staticImageCache.get(t.id);if(u)return u;const d=await createImageBitmap(t.blob);return this.staticImageCache.set(t.id,d),d}catch(u){return console.warn(`[VideoEngine] decodeClipBitmap (image) failed for ${t.id}:`,u),null}const a=Dp(),o=i-e.startTime,c=Math.max(e.inPoint,Math.min(e.outPoint,e.inPoint+a.getSourceTimeAtPlaybackTime(e.id,o)));let l=await this.decodeFrameWithMediaBunny(t.blob,c,n,r,t.id);return l||(l=await this.decodeFrameWithVideoElement(t.id,t.blob,c,n,r)),l}async renderActiveTransition(e,t,i,n,r,a,o){const c=new Set,l=this.findActiveTransition(e,t);if(!l)return c;const{transition:u,clipA:d,clipB:h,progress:f}=l,p=i.items.find(g=>g.id===d.mediaId),m=i.items.find(g=>g.id===h.mediaId);if(!p?.blob||!m?.blob)return c;try{const[g,v]=await Promise.all([this.decodeClipBitmap(d,p,t,r,a),this.decodeClipBitmap(h,m,t,r,a)]);if(!g||!v)return g&&!this.staticImageCache.has(p.id)&&g.close(),v&&!this.staticImageCache.has(m.id)&&v.close(),c;(!this.transitionEngine||this.transitionEngine.getEngineDimensions().width!==r||this.transitionEngine.getEngineDimensions().height!==a)&&(this.transitionEngine=new zM({width:r,height:a}));const w=await this.transitionEngine.renderTransition(g,v,u,f);w.frame&&(o.drawImage(w.frame,0,0,r,a),w.frame.close()),p.type!=="image"&&g.close(),m.type!=="image"&&v.close(),c.add(d.id),c.add(h.id)}catch(g){console.warn(`[VideoEngine] transition render failed (clipA=${d.id} clipB=${h.id}):`,g)}return c}createClipRenderInfo(e,t){const i=t-e.startTime,n=Dp(),r=e.inPoint+n.getSourceTimeAtPlaybackTime(e.id,i),a=this.getAnimatedTransform(e,i),o=this.getAnimatedEffects(e,i);return{clipId:e.id,mediaId:e.mediaId,media:null,sourceTime:r,transform:a,effects:o,opacity:a.opacity}}getAnimatedEffects(e,t){const i=e.keyframes||[],n=e.effects||[];if(i.length===0)return n;const r=[{keyframeProp:"effect.brightness",effectType:"brightness",paramKey:"value"},{keyframeProp:"effect.contrast",effectType:"contrast",paramKey:"value"},{keyframeProp:"effect.saturation",effectType:"saturation",paramKey:"value"},{keyframeProp:"effect.blur",effectType:"blur",paramKey:"radius"}],a=new Map;for(const{keyframeProp:l,effectType:u,paramKey:d}of r){const h=fi.getKeyframesForProperty(i,l);if(h.length===0)continue;const f=fi.getValueAtTime(h,t);typeof f.value=="number"&&a.set(u,{paramKey:d,value:f.value})}if(a.size===0)return n;const o=new Set,c=n.map(l=>{const u=a.get(l.type);return u?(o.add(l.type),{...l,params:{...l.params,[u.paramKey]:u.value}}):l});for(const[l,{paramKey:u,value:d}]of a)o.has(l)||c.push({id:`kf-synth-${e.id}-${l}`,type:l,enabled:!0,params:{[u]:d}});return c}getAnimatedTransform(e,t){const i=e.keyframes||[];if(i.length===0)return e.transform;const n=e.transform;let r=n.opacity,a=n.position.x,o=n.position.y,c=n.scale.x,l=n.scale.y,u=n.rotation;const d=fi.getKeyframesForProperty(i,"opacity");if(d.length>0){const v=fi.getValueAtTime(d,t);typeof v.value=="number"&&(r=v.value)}const h=fi.getKeyframesForProperty(i,"position.x");if(h.length>0){const v=fi.getValueAtTime(h,t);typeof v.value=="number"&&(a=v.value)}const f=fi.getKeyframesForProperty(i,"position.y");if(f.length>0){const v=fi.getValueAtTime(f,t);typeof v.value=="number"&&(o=v.value)}const p=fi.getKeyframesForProperty(i,"scale.x");if(p.length>0){const v=fi.getValueAtTime(p,t);typeof v.value=="number"&&(c=v.value)}const m=fi.getKeyframesForProperty(i,"scale.y");if(m.length>0){const v=fi.getValueAtTime(m,t);typeof v.value=="number"&&(l=v.value)}const g=fi.getKeyframesForProperty(i,"rotation");if(g.length>0){const v=fi.getValueAtTime(g,t);typeof v.value=="number"&&(u=v.value)}return{position:{x:a,y:o},scale:{x:c,y:l},rotation:u,opacity:r,anchor:n.anchor,borderRadius:n.borderRadius,fitMode:n.fitMode,crop:n.crop}}applyEmphasisAnimation(e,t){const{type:i,speed:n,intensity:r,loop:a,startTime:o,animationDuration:c}=e,l=o??0;if(t0){const f=l+c;if(t>f)return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}const u=t-l,d=a?u*n%1:Math.min(u*n,1),h=d*Math.PI*2;switch(i){case"pulse":return{opacity:1,scale:1+Math.sin(h)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"shake":{const f=Math.sin(h*5)*.02*r,p=Math.cos(h*5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:f,offsetY:p,rotation:0}}case"bounce":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.abs(Math.sin(h))*-.05*r,rotation:0};case"float":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:Math.sin(h)*.03*r,rotation:0};case"spin":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:d*360*r};case"flash":return{opacity:.5+Math.abs(Math.sin(h))*.5,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"heartbeat":{const f=d*4;let p=1;return f<1?p=1+.15*r*Math.sin(f*Math.PI):f<2&&(p=1+.1*r*Math.sin((f-1)*Math.PI)),{opacity:1,scale:p,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"swing":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h)*15*r};case"wobble":{const f=Math.sin(h*3)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:Math.sin(h)*.02*r,offsetY:0,rotation:f}}case"jello":{const f=1+Math.sin(h*2)*.1*r,p=1-Math.sin(h*2)*.1*r;return{opacity:1,scale:1,scaleX:f,scaleY:p,offsetX:0,offsetY:0,rotation:0}}case"rubber-band":{const f=1+Math.sin(h)*.2*r,p=1-Math.sin(h)*.1*r;return{opacity:1,scale:1,scaleX:f,scaleY:p,offsetX:0,offsetY:0,rotation:0}}case"tada":{const f=Math.sin(h*4)*10*r;return{opacity:1,scale:1+Math.sin(h*2)*.1*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:f}}case"vibrate":{const f=(Math.random()-.5)*.02*r,p=(Math.random()-.5)*.02*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:f,offsetY:p,rotation:0}}case"flicker":return{opacity:Math.random()>.1?1:.3,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"glow":{const f=1+Math.sin(h)*.05*r;return{opacity:.8+Math.sin(h)*.2,scale:f,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0}}case"breathe":return{opacity:1,scale:1+Math.sin(h*.5)*.08*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"wave":{const f=Math.sin(h+u*2)*.03*r,p=Math.sin(h)*5*r;return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:f,rotation:p}}case"tilt":return{opacity:1,scale:1,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:Math.sin(h*.5)*10*r};case"zoom-pulse":return{opacity:1,scale:1+Math.sin(h)*.15*r,scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};case"focus-zoom":{const f=e.focusPoint||{x:.5,y:.5},p=e.zoomScale||1.5,m=e.holdDuration||.3,g=.3,v=1-m-g;let w=1,b=0,k=0;if(dp?(m=r,g=r/f):(g=a,m=a*f);const v=-m*t.anchor.x,w=-g*t.anchor.y;n.drawImage(e,l,u,d,h,v,w,m,g)}else{const l=!t.fitMode||t.fitMode==="none"?"contain":t.fitMode;let u=e.width,d=e.height;const h=e.width/e.height,f=r/a;l==="stretch"?(u=r,d=a):l==="cover"?h>f?(d=a,u=a*h):(u=r,d=r/h):h>f?(u=r,d=r/h):(d=a,u=a*h);const p=-u*t.anchor.x,m=-d*t.anchor.y;n.drawImage(e,p,m,u,d)}n.restore()}async composite(e,t,i){this.ensureCompositeCanvas(t,i);const n=this.compositeCtx;n.clearRect(0,0,t,i);for(const r of e)r.visible&&(n.save(),n.globalCompositeOperation=this.getCanvasBlendMode(r.blendMode),await this.compositeFrame(r.image instanceof ImageBitmap?r.image:await createImageBitmap(r.image),r.transform,r.transform.opacity),n.restore());return createImageBitmap(this.compositeCanvas)}getCanvasBlendMode(e){return{normal:"source-over",multiply:"multiply",screen:"screen",overlay:"overlay",darken:"darken",lighten:"lighten","color-dodge":"color-dodge","color-burn":"color-burn","hard-light":"hard-light","soft-light":"soft-light",difference:"difference",exclusion:"exclusion",hue:"hue",saturation:"saturation",color:"color",luminosity:"luminosity"}[e]||"source-over"}ensureCompositeCanvas(e,t){(!this.compositeCanvas||this.compositeCanvas.width!==e||this.compositeCanvas.height!==t)&&(this.compositeCanvas=new OffscreenCanvas(e,t),this.compositeCtx=this.compositeCanvas.getContext("2d"))}getCacheKey(e,t){const i=Math.round(t*30)/30;return`${e}:${i.toFixed(4)}`}cacheFrame(e,t,i){const n=t.width*t.height*4;this.evictIfNeeded(n),this.frameCache.set(e,{image:t,timestamp:parseFloat(e.split(":")[1]),mediaId:i,width:t.width,height:t.height,sizeBytes:n,lastAccessed:Date.now()})}evictIfNeeded(e){for(;this.frameCache.size>=this.cacheConfig.maxFrames;)this.evictOldestFrame();let t=this.getTotalCacheSize();for(;t+e>this.cacheConfig.maxSizeBytes&&this.frameCache.size>0;)this.evictOldestFrame(),t=this.getTotalCacheSize()}evictOldestFrame(){let e="",t=1/0;for(const[i,n]of this.frameCache.entries())n.lastAccessed0?this.cacheStats.hits/e:0,maxSizeBytes:this.cacheConfig.maxSizeBytes,hits:this.cacheStats.hits,misses:this.cacheStats.misses}}clearCache(){for(const e of this.frameCache.values())e.image.close();this.frameCache.clear(),this.cacheStats={hits:0,misses:0};for(const e of this.gifFrameCache.values())for(const t of e.frames)try{t.close()}catch{}this.gifFrameCache.clear()}async preloadFrames(e,t,i=30){if(this.ensureInitialized(),!e.blob)return;const n=1/i,r=Math.max(0,t-this.cacheConfig.preloadBehind*n),a=Math.min(e.metadata.duration,t+this.cacheConfig.preloadAhead*n),{Input:o,ALL_FORMATS:c,BlobSource:l,VideoSampleSink:u}=this.mediabunny,d=new o({source:new l(e.blob),formats:c});try{const h=await d.getPrimaryVideoTrack();if(!h||!await h.canDecode())return;const p=new u(h),m=[];for(let g=r;g<=a;g+=n){const v=this.getCacheKey(e.id,g);this.frameCache.has(v)||m.push(g)}for await(const g of p.samplesAtTimestamps(m)){if(!g)continue;const v=await createImageBitmap(g),w=this.getCacheKey(e.id,g.timestamp/1e6);this.cacheFrame(w,v,e.id),g.close()}}finally{d[Symbol.dispose]?.()}}queuePreload(e){this.preloadQueue=this.preloadQueue.filter(t=>t.mediaId!==e.mediaId),this.preloadQueue.push(e),this.preloadQueue.sort((t,i)=>i.priority-t.priority),this.processPreloadQueue()}async processPreloadQueue(){if(!(this.isPreloading||this.preloadQueue.length===0)){for(this.isPreloading=!0;this.preloadQueue.length>0;){const e=this.preloadQueue.shift();try{await this.preloadFramesRange(e.media,e.mediaId,e.startTime,e.endTime,e.frameRate)}catch(t){console.warn(`Preload failed for media ${e.mediaId}:`,t)}}this.isPreloading=!1}}async preloadFramesRange(e,t,i,n,r){this.ensureInitialized();const{Input:a,ALL_FORMATS:o,BlobSource:c,VideoSampleSink:l}=this.mediabunny,u=new a({source:new c(e),formats:o});try{const d=await u.getPrimaryVideoTrack();if(!d||!await d.canDecode())return;const f=new l(d),p=1/r,m=[];for(let g=i;g<=n;g+=p){const v=this.getCacheKey(t,g);this.frameCache.has(v)||m.push(g)}for await(const g of f.samplesAtTimestamps(m)){if(!g)continue;const v=await createImageBitmap(g),w=this.getCacheKey(t,g.timestamp/1e6);this.cacheFrame(w,v,t),g.close()}}finally{u[Symbol.dispose]?.()}}async getSupportedCodecs(){this.ensureInitialized();const{getEncodableVideoCodecs:e,getEncodableAudioCodecs:t}=this.mediabunny;try{const[i,n]=await Promise.all([e(),t()]);return{decode:["avc","hevc","vp8","vp9","av1"],encode:[...i,...n],hardware:!0}}catch{return{decode:[],encode:[],hardware:!1}}}isFormatSupported(e){return["video/mp4","video/webm","video/quicktime","video/x-matroska"].includes(e)}getAvailableFilters(){return[{type:"brightness",name:"Brightness",category:"color",gpuAccelerated:!0},{type:"contrast",name:"Contrast",category:"color",gpuAccelerated:!0},{type:"saturation",name:"Saturation",category:"color",gpuAccelerated:!0},{type:"hue",name:"Hue Rotation",category:"color",gpuAccelerated:!0},{type:"blur",name:"Blur",category:"blur",gpuAccelerated:!0},{type:"sharpen",name:"Sharpen",category:"blur",gpuAccelerated:!0},{type:"vignette",name:"Vignette",category:"stylize",gpuAccelerated:!0},{type:"grain",name:"Film Grain",category:"stylize",gpuAccelerated:!0},{type:"chromaKey",name:"Chroma Key",category:"keying",gpuAccelerated:!0}]}async applyFilter(e,t){const i=new OffscreenCanvas(e.width,e.height),n=i.getContext("2d");if(!n)return e;n.imageSmoothingEnabled=!0,n.imageSmoothingQuality="high",n.drawImage(e,0,0);const r=this.buildFilterString(t);return r&&(n.filter=r,n.drawImage(i,0,0)),createImageBitmap(i)}buildFilterString(e){if(!e.enabled)return"";const t=e.params;switch(e.type){case"brightness":return`brightness(${1+(t.value||0)})`;case"contrast":return`contrast(${t.value||1})`;case"saturation":return`saturate(${t.value||1})`;case"hue":return`hue-rotate(${t.rotation||0}deg)`;case"blur":return`blur(${t.radius||0}px)`;default:return""}}dispose(){this.clearCache(),this.clearVideoElementCache();for(const e of this.staticImageCache.values())try{e.close()}catch{}this.staticImageCache.clear(),this.compositeCanvas=null,this.compositeCtx=null,this.decodeCanvas=null,this.decodeCtx=null,this.preloadQueue=[],this.initialized=!1,this.mediabunny=null}}let Qp=null;function YI(){return Qp||(Qp=new Fv),Qp}const Wq={shadows:{r:0,g:0,b:0},midtones:{r:0,g:0,b:0},highlights:{r:0,g:0,b:0},shadowsLift:0,midtonesGamma:1,highlightsGain:1},qq={rgb:[{x:0,y:0},{x:1,y:1}],red:[{x:0,y:0},{x:1,y:1}],green:[{x:0,y:0},{x:1,y:1}],blue:[{x:0,y:0},{x:1,y:1}]},Hq={hue:[0,0,0,0,0,0,0,0],saturation:[0,0,0,0,0,0,0,0],luminance:[0,0,0,0,0,0,0,0]},Yu=`#version 300 es +precision highp float; + +in vec2 a_position; +in vec2 a_texCoord; + +out vec2 v_texCoord; + +void main() { + gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; +} +`,Yq=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform vec3 u_shadows; +uniform vec3 u_midtones; +uniform vec3 u_highlights; +uniform float u_shadowsLift; +uniform float u_midtonesGamma; +uniform float u_highlightsGain; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + float shadowWeight = 1.0 - smoothstep(0.0, 0.5, luma); + float highlightWeight = smoothstep(0.5, 1.0, luma); + float midtoneWeight = 1.0 - shadowWeight - highlightWeight; + vec3 rgb = color.rgb; + rgb += u_shadows * shadowWeight; + rgb += u_midtones * midtoneWeight; + rgb += u_highlights * highlightWeight; + rgb = rgb + u_shadowsLift * shadowWeight; + rgb = pow(rgb, vec3(1.0 / u_midtonesGamma)); + rgb = rgb * (1.0 + (u_highlightsGain - 1.0) * highlightWeight); + + fragColor = vec4(clamp(rgb, 0.0, 1.0), color.a); +} +`,Xq=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform sampler2D u_curveLUT; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + float r = texture(u_curveLUT, vec2(color.r, 0.125)).r; + float g = texture(u_curveLUT, vec2(color.g, 0.375)).r; + float b = texture(u_curveLUT, vec2(color.b, 0.625)).r; + float masterR = texture(u_curveLUT, vec2(r, 0.875)).r; + float masterG = texture(u_curveLUT, vec2(g, 0.875)).r; + float masterB = texture(u_curveLUT, vec2(b, 0.875)).r; + + fragColor = vec4(masterR, masterG, masterB, color.a); +} +`,Kq=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform float u_hue[8]; +uniform float u_saturation[8]; +uniform float u_luminance[8]; + +vec3 rgb2hsl(vec3 c) { + float maxC = max(max(c.r, c.g), c.b); + float minC = min(min(c.r, c.g), c.b); + float l = (maxC + minC) / 2.0; + + if (maxC == minC) { + return vec3(0.0, 0.0, l); + } + + float d = maxC - minC; + float s = l > 0.5 ? d / (2.0 - maxC - minC) : d / (maxC + minC); + + float h; + if (maxC == c.r) { + h = (c.g - c.b) / d + (c.g < c.b ? 6.0 : 0.0); + } else if (maxC == c.g) { + h = (c.b - c.r) / d + 2.0; + } else { + h = (c.r - c.g) / d + 4.0; + } + h /= 6.0; + + return vec3(h, s, l); +} + +float hue2rgb(float p, float q, float t) { + if (t < 0.0) t += 1.0; + if (t > 1.0) t -= 1.0; + if (t < 1.0/6.0) return p + (q - p) * 6.0 * t; + if (t < 1.0/2.0) return q; + if (t < 2.0/3.0) return p + (q - p) * (2.0/3.0 - t) * 6.0; + return p; +} + +vec3 hsl2rgb(vec3 hsl) { + if (hsl.y == 0.0) { + return vec3(hsl.z); + } + + float q = hsl.z < 0.5 ? hsl.z * (1.0 + hsl.y) : hsl.z + hsl.y - hsl.z * hsl.y; + float p = 2.0 * hsl.z - q; + + float r = hue2rgb(p, q, hsl.x + 1.0/3.0); + float g = hue2rgb(p, q, hsl.x); + float b = hue2rgb(p, q, hsl.x - 1.0/3.0); + + return vec3(r, g, b); +} + +void main() { + vec4 color = texture(u_texture, v_texCoord); + vec3 hsl = rgb2hsl(color.rgb); + + // Determine which hue range this pixel falls into (8 ranges) + int hueIndex = int(hsl.x * 8.0) % 8; + hsl.x = fract(hsl.x + u_hue[hueIndex] / 360.0); + hsl.y = clamp(hsl.y + u_saturation[hueIndex], 0.0, 1.0); + hsl.z = clamp(hsl.z + u_luminance[hueIndex], 0.0, 1.0); + + vec3 rgb = hsl2rgb(hsl); + fragColor = vec4(rgb, color.a); +} +`,Qq=`#version 300 es +precision highp float; + +in vec2 v_texCoord; +out vec4 fragColor; + +uniform sampler2D u_texture; +uniform sampler2D u_lut; +uniform float u_lutSize; +uniform float u_intensity; + +void main() { + vec4 color = texture(u_texture, v_texCoord); + + // 3D LUT lookup (stored as 2D texture) + float blueSlice = color.b * (u_lutSize - 1.0); + float blueSliceFloor = floor(blueSlice); + float blueSliceCeil = ceil(blueSlice); + float blueFrac = blueSlice - blueSliceFloor; + + + vec2 quad1 = vec2( + (blueSliceFloor + color.r) / u_lutSize, + color.g + ); + vec2 quad2 = vec2( + (blueSliceCeil + color.r) / u_lutSize, + color.g + ); + + vec3 lutColor1 = texture(u_lut, quad1).rgb; + vec3 lutColor2 = texture(u_lut, quad2).rgb; + vec3 lutColor = mix(lutColor1, lutColor2, blueFrac); + + // Mix with original based on intensity + vec3 result = mix(color.rgb, lutColor, u_intensity); + fragColor = vec4(result, color.a); +} +`;class Jq{canvas=null;gl=null;shaders=new Map;quadBuffer=null;texCoordBuffer=null;curveLUTTexture=null;width;height;initialized=!1;constructor(e=1920,t=1080){this.width=e,this.height=t}initialize(){if(this.initialized)return;this.canvas=new OffscreenCanvas(this.width,this.height);const e=this.canvas.getContext("webgl2",{preserveDrawingBuffer:!0,premultipliedAlpha:!0,alpha:!0});if(!e)throw new Error("WebGL2 not supported");this.gl=e,this.quadBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),this.texCoordBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,1,1,1,0,0,1,0]),e.STATIC_DRAW),this.compileShader("colorWheels",Yu,Yq),this.compileShader("curves",Yu,Xq),this.compileShader("hsl",Yu,Kq),this.compileShader("lut",Yu,Qq),this.initialized=!0}compileShader(e,t,i){const n=this.gl,r=n.createShader(n.VERTEX_SHADER);if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Vertex shader error: ${n.getShaderInfoLog(r)}`);const a=n.createShader(n.FRAGMENT_SHADER);if(n.shaderSource(a,i),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS))throw new Error(`Fragment shader error: ${n.getShaderInfoLog(a)}`);const o=n.createProgram();if(n.attachShader(o,r),n.attachShader(o,a),n.linkProgram(o),!n.getProgramParameter(o,n.LINK_STATUS))throw new Error(`Program link error: ${n.getProgramInfoLog(o)}`);const c=new Map,l=n.getProgramParameter(o,n.ACTIVE_UNIFORMS);for(let h=0;hn.x-r.x);if((i.length===0||i[0].x>0)&&i.unshift({x:0,y:0}),i[i.length-1].x<1&&i.push({x:1,y:1}),i.length===2){for(let n=0;n<256;n++){const a=(n/255-i[0].x)/(i[1].x-i[0].x),o=i[0].y+a*(i[1].y-i[0].y);t[n]=Math.round(Math.max(0,Math.min(255,o*255)))}return t}for(let n=0;n<256;n++){const r=n/255;let a=r;for(let o=0;o=i[o].x&&r<=i[o+1].x){const c=o>0?i[o-1]:i[o],l=i[o],u=i[o+1],d=o+2{const L=(E*c*c+C*c+S)*3+P;return l[L]/255},V=S=>{const C=$(w,b,k,S)*(1-I)+$(A,b,k,S)*I,E=$(w,b,R,S)*(1-I)+$(A,b,R,S)*I,P=$(w,M,k,S)*(1-I)+$(A,M,k,S)*I,L=$(w,M,R,S)*(1-I)+$(A,M,R,S)*I,O=C*(1-D)+P*D,U=E*(1-D)+L*D;return O*(1-B)+U*B},y=V(0),_=V(1),T=V(2);o[d]=Math.round((h*(1-t.intensity)+y*t.intensity)*255),o[d+1]=Math.round((f*(1-t.intensity)+_*t.intensity)*255),o[d+2]=Math.round((p*(1-t.intensity)+T*t.intensity)*255)}return r.putImageData(a,0,0),{image:await createImageBitmap(n),processingTime:performance.now()-i}}async applyHSL(e,t){const i=performance.now(),n=new OffscreenCanvas(e.width,e.height),r=n.getContext("2d");r.drawImage(e,0,0);const a=r.getImageData(0,0,e.width,e.height),o=a.data;for(let l=0;l=0&&m=0&&g.5?o/(2-n-r):o/(n+r);let l;return n===e?l=((t-i)/o+(t(o<0&&(o+=1),o>1&&(o-=1),o<1/6?r+(n-r)*6*o:o<1/2?n:o<2/3?r+(n-r)*(2/3-o)*6:r);return{r:a(e+1/3),g:a(e),b:a(e-1/3)}}uploadTexture(e){const t=this.gl,i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i}setupVertexAttributes(e){const t=this.gl,i=e.attributes.get("a_position");i!==void 0&&(t.bindBuffer(t.ARRAY_BUFFER,this.quadBuffer),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0));const n=e.attributes.get("a_texCoord");n!==void 0&&(t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0))}ensureInitialized(){this.initialized||this.initialize()}dispose(){if(this.gl){for(const e of this.shaders.values())this.gl.deleteProgram(e.program);this.shaders.clear(),this.quadBuffer&&this.gl.deleteBuffer(this.quadBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer),this.curveLUTTexture&&this.gl.deleteTexture(this.curveLUTTexture)}this.canvas=null,this.gl=null,this.initialized=!1}}function Xu(){return`mask-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Zq(s){switch(s.type){case"rectangle":{const{x:e,y:t,width:i,height:n}=s;return{points:[{x:e,y:t},{x:e+i,y:t},{x:e+i,y:t+n},{x:e,y:t+n}],closed:!0}}case"ellipse":{const{cx:e,cy:t,rx:i,ry:n}=s,r=.5522847498;return{points:[{x:e,y:t-n,handleIn:{x:e-i*r,y:t-n},handleOut:{x:e+i*r,y:t-n}},{x:e+i,y:t,handleIn:{x:e+i,y:t-n*r},handleOut:{x:e+i,y:t+n*r}},{x:e,y:t+n,handleIn:{x:e+i*r,y:t+n},handleOut:{x:e-i*r,y:t+n}},{x:e-i,y:t,handleIn:{x:e-i,y:t+n*r},handleOut:{x:e-i,y:t-n*r}}],closed:!0}}case"polygon":return{points:s.points.map(e=>({x:e.x,y:e.y})),closed:!0}}}function eH(){return{points:[{x:.25,y:.25},{x:.75,y:.25},{x:.75,y:.75},{x:.25,y:.75}],closed:!0}}function Aee(s){const e=.5*Math.max(.01,Math.abs(s.scale.x)),t=.5*Math.max(.01,Math.abs(s.scale.y)),i=s.position.x,n=s.position.y;return{points:[{x:i-e,y:n-t},{x:i+e,y:n-t},{x:i+e,y:n+t},{x:i-e,y:n+t}],closed:!0}}function tH(s,e,t){t=Math.max(0,Math.min(1,t));const i=Math.max(s.points.length,e.points.length),n=[];for(let r=0;rt.clipId===e)}updateMaskPath(e,t){const i=this.masks.get(e);i&&this.masks.set(e,{...i,path:t})}setFeathering(e,t){const i=this.masks.get(e);i&&this.masks.set(e,{...i,feathering:Math.max(0,Math.min(100,t))})}setInverted(e,t){const i=this.masks.get(e);i&&this.masks.set(e,{...i,inverted:t})}setExpansion(e,t){const i=this.masks.get(e);i&&this.masks.set(e,{...i,expansion:Math.max(-100,Math.min(100,t))})}addMaskKeyframe(e,t,i){const n=this.masks.get(e);if(!n)return null;const r={id:Xu(),time:t,path:i,easing:"linear"},a=[...n.keyframes,r].sort((o,c)=>o.time-c.time);return this.masks.set(e,{...n,keyframes:a}),r}removeMaskKeyframe(e,t){const i=this.masks.get(e);if(i){const n=i.keyframes.filter(r=>r.id!==t);this.masks.set(e,{...i,keyframes:n})}}setKeyframeEasing(e,t,i){const n=this.masks.get(e);if(n){const r=n.keyframes.map(a=>a.id===t?{...a,easing:i}:a);this.masks.set(e,{...n,keyframes:r})}}getMaskAtTime(e,t){const i=this.masks.get(e);if(!i)return null;if(i.keyframes.length===0)return i.path;if(i.keyframes.length===1)return i.keyframes[0].path;let n=null,r=null;for(const u of i.keyframes)if(u.time<=t)n=u;else if(!r){r=u;break}if(!n)return i.keyframes[0].path;if(!r)return n.path;const a=r.time-n.time,o=t-n.time,c=a>0?o/a:0,l=iH(c,n.easing);return tH(n.path,r.path,l)}deleteMask(e){this.masks.delete(e)}deleteMasksForClip(e){for(const[t,i]of this.masks)i.clipId===e&&this.masks.delete(t)}async applyMask(e,t,i){const n=performance.now();this.resizeTo(e.width,e.height);const r=i!==void 0&&this.getMaskAtTime(t.id,i)||t.path;if(this.ctx.clearRect(0,0,this.width,this.height),this.maskCtx.clearRect(0,0,this.width,this.height),this.generateMaskFromPath(r,t.inverted),t.feathering>0&&this.applyFeathering(t.feathering),t.expansion!==0&&this.applyExpansion(t.expansion),this.ctx.drawImage(e,0,0,this.width,this.height),this.ctx.globalCompositeOperation="destination-in",this.ctx.drawImage(this.maskCanvas,0,0),this.ctx.globalCompositeOperation="source-over",t.opacity<1){const o=new OffscreenCanvas(this.width,this.height),c=o.getContext("2d");c.globalAlpha=t.opacity,c.drawImage(this.canvas,0,0),this.ctx.clearRect(0,0,this.width,this.height),this.ctx.drawImage(o,0,0)}return{image:await createImageBitmap(this.canvas),processingTime:performance.now()-n,gpuAccelerated:!1}}async applyMaskDefinition(e,t){const i=performance.now();return this.resizeTo(e.width,e.height),this.ctx.clearRect(0,0,this.width,this.height),this.maskCtx.clearRect(0,0,this.width,this.height),this.generateMaskShape(t),t.feather>0&&this.applyFeathering(t.feather),t.expansion!==0&&this.applyExpansion(t.expansion),this.ctx.drawImage(e,0,0,this.width,this.height),this.ctx.globalCompositeOperation="destination-in",this.ctx.drawImage(this.maskCanvas,0,0),this.ctx.globalCompositeOperation="source-over",t.opacity<1&&(this.ctx.globalAlpha=t.opacity,this.ctx.drawImage(this.canvas,0,0),this.ctx.globalAlpha=1),{image:await createImageBitmap(this.canvas),processingTime:performance.now()-i,gpuAccelerated:!1}}generateMaskFromPath(e,t){const i=this.maskCtx;t?(i.fillStyle="white",i.fillRect(0,0,this.width,this.height),i.fillStyle="black"):i.fillStyle="white",i.beginPath(),this.drawBezierPath(i,e),i.closePath(),i.fill()}drawBezierPath(e,t){if(t.points.length<2)return;const i=t.points;e.moveTo(i[0].x*this.width,i[0].y*this.height);for(let n=0;n1?t[1].x:t[0].x),n=Math.min(t[0].y,t.length>1?t[1].y:t[0].y),r=Math.max(t.length>2?t[2].x:t[1].x,t.length>1?t[1].x:t[0].x),a=Math.max(t.length>2?t[2].y:t[1].y,t.length>3?t[3].y:t.length>1?t[1].y:t[0].y),o=i*this.width,c=n*this.height,l=r*this.width,u=a*this.height;e.rect(o,c,l-o,u-c)}drawEllipseMask(e,t){if(t.length<2)return;const i=t[0].x*this.width,n=t[0].y*this.height,r=Math.abs(t[1].x-t[0].x)*this.width,a=Math.abs(t[1].y-t[0].y)*this.height;e.ellipse(i,n,r,a,0,0,Math.PI*2)}drawPolygonMask(e,t){if(!(t.length<3)){e.moveTo(t[0].x*this.width,t[0].y*this.height);for(let i=1;i({x:r.x,y:r.y}));e.moveTo(n[0].x*this.width,n[0].y*this.height);for(let r=0;r0;for(let c=0;c=0&&p=0&&m128||!a&&i[g+3]<128)&&(d=!0)}}a&&d?n[u+3]=255:!a&&d&&(n[u+3]=0)}const o=new ImageData(n,this.width,this.height);this.maskCtx.putImageData(o,0,0)}invertMask(e){return{...e,inverted:!e.inverted}}setFeather(e,t){return{...e,feather:Math.max(0,Math.min(100,t))}}updatePoints(e,t){return{...e,points:t}}addPoint(e,t,i){const n=[...e.points];return i!==void 0&&i>=0&&i<=n.length?n.splice(i,0,t):n.push(t),{...e,points:n}}removePoint(e,t){if(e.points.length<=3)return e;const i=[...e.points];return i.splice(t,1),{...e,points:i}}isPointInMask(e,t){this.maskCtx.clearRect(0,0,this.width,this.height),this.generateMaskShape({...e,inverted:!1});const i=Math.floor(t.x*this.width),n=Math.floor(t.y*this.height),a=this.maskCtx.getImageData(i,n,1,1).data[3]>128;return e.inverted?!a:a}getMaskBounds(e){if(e.type==="ellipse"&&e.points.length>=2){const a=e.points[0].x,o=e.points[0].y,c=Math.abs(e.points[1].x-e.points[0].x),l=Math.abs(e.points[1].y-e.points[0].y);return{x:a-c,y:o-l,width:c*2,height:l*2}}let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const a of e.points)t=Math.min(t,a.x),i=Math.min(i,a.y),n=Math.max(n,a.x),r=Math.max(r,a.y);return{x:t,y:i,width:n-t,height:r-i}}resize(e,t){this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.maskCanvas.width=e,this.maskCanvas.height=t}getDimensions(){return{width:this.width,height:this.height}}clearAllMasks(){this.masks.clear()}}const nH={enabled:!1,keyColor:{r:0,g:1,b:0},tolerance:.3,edgeSoftness:.1,spillSuppression:.5};function Ac(){return{...nH}}class rH{canvas;ctx;width;height;clipSettings=new Map;constructor(e){this.width=e.width,this.height=e.height,this.canvas=new OffscreenCanvas(e.width,e.height),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}resizeTo(e,t){e<=0||t<=0||this.width===e&&this.height===t||(this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t)}enableChromaKey(e){const t=this.clipSettings.get(e);t?this.clipSettings.set(e,{...t,enabled:!0}):this.clipSettings.set(e,{...Ac(),enabled:!0})}disableChromaKey(e){const t=this.clipSettings.get(e);t&&this.clipSettings.set(e,{...t,enabled:!1})}isEnabled(e){return this.clipSettings.get(e)?.enabled??!1}setKeyColor(e,t){const i=this.clipSettings.get(e)||Ac();this.clipSettings.set(e,{...i,keyColor:{r:Math.max(0,Math.min(1,t.r)),g:Math.max(0,Math.min(1,t.g)),b:Math.max(0,Math.min(1,t.b))}})}sampleKeyColor(e,t,i){this.resizeTo(e.width,e.height),this.ctx.clearRect(0,0,this.width,this.height),this.ctx.drawImage(e,0,0,this.width,this.height);const n=Math.floor(t*this.width),r=Math.floor(i*this.height),a=this.ctx.getImageData(n,r,1,1);return{r:a.data[0]/255,g:a.data[1]/255,b:a.data[2]/255}}setTolerance(e,t){const i=this.clipSettings.get(e)||Ac();this.clipSettings.set(e,{...i,tolerance:Math.max(0,Math.min(1,t))})}setEdgeSoftness(e,t){const i=this.clipSettings.get(e)||Ac();this.clipSettings.set(e,{...i,edgeSoftness:Math.max(0,Math.min(1,t))})}setSpillSuppression(e,t){const i=this.clipSettings.get(e)||Ac();this.clipSettings.set(e,{...i,spillSuppression:Math.max(0,Math.min(1,t))})}getSettings(e){return this.clipSettings.get(e)}setSettings(e,t){this.clipSettings.set(e,{...t})}async applyChromaKey(e,t){const i=performance.now(),n=this.clipSettings.get(t);return!n||!n.enabled?{image:await createImageBitmap(e),processingTime:performance.now()-i,gpuAccelerated:!1}:this.applyChromaKeyWithSettings(e,n,i)}async applyChromaKeyWithSettings(e,t,i=performance.now()){this.resizeTo(e.width,e.height),this.ctx.clearRect(0,0,this.width,this.height),this.ctx.drawImage(e,0,0,this.width,this.height);const n=this.ctx.getImageData(0,0,this.width,this.height),r=n.data,{keyColor:a,tolerance:o,edgeSoftness:c,spillSuppression:l}=t;for(let d=0;d0&&g>0){const v=this.suppressSpill(h,f,p,a,l,g);r[d]=Math.round(v.r*255),r[d+1]=Math.round(v.g*255),r[d+2]=Math.round(v.b*255)}r[d+3]=Math.round(g*255)}return this.ctx.putImageData(n,0,0),{image:await createImageBitmap(this.canvas),processingTime:performance.now()-i,gpuAccelerated:!1}}getMatte(e,t){this.resizeTo(e.width,e.height);const i=this.clipSettings.get(t);if(!i||!i.enabled){const h=this.ctx.createImageData(this.width,this.height);for(let f=0;f=n+r)return 1;{const a=r*2;return(e-(n-r))/a}}suppressSpill(e,t,i,n,r,a){if(a>=1||a<=0)return{r:e,g:t,b:i};const o=1-a,c=Math.max(n.r,n.g,n.b);let l=e,u=t,d=i;if(n.g===c){const h=(e+i)/2,f=Math.max(0,t-h);u=t-f*r*o}else if(n.b===c){const h=(e+t)/2,f=Math.max(0,i-h);d=i-f*r*o}else{const h=(t+i)/2,f=Math.max(0,e-h);l=e-f*r*o}return{r:Math.max(0,Math.min(1,l)),g:Math.max(0,Math.min(1,u)),b:Math.max(0,Math.min(1,d))}}async composite(e,t){return this.resizeTo(e.width,e.height),this.ctx.clearRect(0,0,this.width,this.height),this.ctx.drawImage(t,0,0,this.width,this.height),this.ctx.drawImage(e,0,0,this.width,this.height),createImageBitmap(this.canvas)}async applyAndComposite(e,t,i){const n=performance.now(),r=await this.applyChromaKey(e,i),a=await this.composite(r.image,t);return r.image.close(),{image:a,processingTime:performance.now()-n,gpuAccelerated:!1}}countTransparentPixels(e){this.resizeTo(e.width,e.height),this.ctx.clearRect(0,0,this.width,this.height),this.ctx.drawImage(e,0,0,this.width,this.height);const i=this.ctx.getImageData(0,0,this.width,this.height).data;let n=0;for(let r=3;r({id:`angle_${o+1}`,name:`Angle ${o+1}`,clipId:a,trackId:"",offset:0,color:Ku[o%Ku.length],isActive:o===0})),r={id:i,name:e,angles:n,activeAngleId:n[0]?.id||"",syncPoint:0,duration:0,createdAt:Date.now()};return this.groups.set(i,r),this.switches.set(i,[]),r}getGroup(e){return this.groups.get(e)}getAllGroups(){return Array.from(this.groups.values())}deleteGroup(e){return this.switches.delete(e),this.groups.delete(e)}addAngle(e,t,i){const n=this.groups.get(e);if(!n)return null;const r=n.angles.length,a={id:`angle_${Date.now()}`,name:i||`Angle ${r+1}`,clipId:t,trackId:"",offset:0,color:Ku[r%Ku.length],isActive:!1};return n.angles.push(a),a}removeAngle(e,t){const i=this.groups.get(e);if(!i)return!1;const n=i.angles.findIndex(r=>r.id===t);return n===-1?!1:(i.angles.splice(n,1),i.activeAngleId===t&&i.angles.length>0&&(i.activeAngleId=i.angles[0].id,i.angles[0].isActive=!0),!0)}setActiveAngle(e,t){const i=this.groups.get(e);return!i||!i.angles.find(r=>r.id===t)?!1:(i.angles.forEach(r=>{r.isActive=r.id===t}),i.activeAngleId=t,!0)}getActiveAngle(e){const t=this.groups.get(e);return t&&t.angles.find(i=>i.id===t.activeAngleId)||null}addSwitch(e,t,i){const n=this.groups.get(e);if(!n||!n.angles.find(c=>c.id===t))return null;const a={id:`switch_${Date.now()}`,groupId:e,angleId:t,time:i},o=this.switches.get(e)||[];return o.push(a),o.sort((c,l)=>c.time-l.time),this.switches.set(e,o),a}removeSwitch(e,t){const i=this.switches.get(e);if(!i)return!1;const n=i.findIndex(r=>r.id===t);return n===-1?!1:(i.splice(n,1),!0)}getSwitches(e){return this.switches.get(e)||[]}getAngleAtTime(e,t){const i=this.groups.get(e);if(!i)return null;const n=this.switches.get(e)||[];let r=i.angles[0]?.id;for(const a of n)if(a.time<=t)r=a.angleId;else break;return i.angles.find(a=>a.id===r)||null}setAngleOffset(e,t,i){const n=this.groups.get(e);if(!n)return!1;const r=n.angles.find(a=>a.id===t);return r?(r.offset=i,!0):!1}renameAngle(e,t,i){const n=this.groups.get(e);if(!n)return!1;const r=n.angles.find(a=>a.id===t);return r?(r.name=i,!0):!1}async syncByAudio(e,t,i){const n=this.groups.get(e);if(!n)return new Map;const r=new Map,a=i.get(t);if(!a)return r;for(const o of n.angles){if(o.id===t){r.set(o.id,{offset:0,confidence:1,method:"audio"});continue}const c=i.get(o.id);if(!c){r.set(o.id,{offset:0,confidence:0,method:"manual"});continue}const l=await this.findAudioOffset(a,c);r.set(o.id,l),o.offset=l.offset}return r}async findAudioOffset(e,t){const i=e.getChannelData(0),n=t.getChannelData(0),r=e.sampleRate,a=Math.min(r*5,i.length,n.length),o=Math.min(r*30,n.length-a);let c=0,l=-1/0;const u=Math.max(1,Math.floor(r/100));for(let f=-o;f<=o;f+=u){let p=0,m=0;for(let g=0;g=0&&w0&&(p/=m,p>l&&(l=p,c=f))}const d=c/r,h=Math.max(0,Math.min(1,(l+1)/2));return{offset:d,confidence:h,method:"audio"}}setSyncPoint(e,t){const i=this.groups.get(e);return i?(i.syncPoint=t,!0):!1}clearGroup(e){const t=this.groups.get(e);t&&(t.angles=[],t.activeAngleId=""),this.switches.set(e,[])}clearAll(){this.groups.clear(),this.switches.clear()}exportGroupAsSequence(e){const t=this.groups.get(e);if(!t)return[];const i=this.switches.get(e)||[],n=[];if(i.length===0&&t.angles.length>0){const c=t.angles.find(l=>l.id===t.activeAngleId);return c&&n.push({clipId:c.clipId,startTime:0,endTime:t.duration}),n}let r=t.angles[0]?.id,a=0;for(let c=0;cd.id===r);u&&l.time>a&&n.push({clipId:u.clipId,startTime:a,endTime:l.time}),r=l.angleId,a=l.time}const o=t.angles.find(c=>c.id===r);return o&&athis.layers.get(i)).filter(i=>i!==void 0):[]}getActiveLayersAtTime(e,t){const i=[];for(const n of this.layers.values())n.enabled&&e>=n.startTime&&et!==void 0?0:n.startTime-r.startTime)}updateLayer(e,t){const i=this.layers.get(e);return i?(t.trackId&&t.trackId!==i.trackId&&(this.layersByTrack.get(i.trackId)?.delete(e),this.layersByTrack.has(t.trackId)||this.layersByTrack.set(t.trackId,new Set),this.layersByTrack.get(t.trackId).add(e)),this.layers.set(e,{...i,...t,id:i.id}),!0):!1}deleteLayer(e){const t=this.layers.get(e);return t?(this.layersByTrack.get(t.trackId)?.delete(e),this.layers.delete(e)):!1}addEffect(e,t){const i=this.layers.get(e);if(!i)return!1;const n={...t,id:`effect_${Date.now()}_${Math.random().toString(36).slice(2,11)}`};return this.layers.set(e,{...i,effects:[...i.effects,n]}),!0}removeEffect(e,t){const i=this.layers.get(e);return i?(this.layers.set(e,{...i,effects:i.effects.filter(n=>n.id!==t)}),!0):!1}updateEffect(e,t,i){const n=this.layers.get(e);if(!n)return!1;const r=n.effects.findIndex(o=>o.id===t);if(r===-1)return!1;const a=[...n.effects];return a[r]={...a[r],...i,id:t},this.layers.set(e,{...n,effects:a}),!0}setOpacity(e,t){return this.updateLayer(e,{opacity:Math.max(0,Math.min(1,t))})}setBlendMode(e,t){return this.updateLayer(e,{blendMode:t})}setEnabled(e,t){return this.updateLayer(e,{enabled:t})}setAffectedTracks(e,t){return this.updateLayer(e,{affectedTracks:t})}getEffectsForClip(e,t,i){const n=[];for(const r of this.layers.values()){if(!r.enabled||t=r.startTime+r.duration)continue;const a=i.get(r.trackId);if(a!==void 0&&!(ai.get(c)).filter(c=>c!==void 0).some(c=>c===e)))for(const o of r.effects)o.enabled!==!1&&n.push({layerId:r.id,effect:o,opacity:r.opacity,blendMode:r.blendMode})}return n}duplicateLayer(e,t){const i=this.layers.get(e);if(!i)return null;const n={...i,id:wT(),trackId:t||i.trackId,name:`${i.name} (Copy)`,effects:i.effects.map(r=>({...r,id:`effect_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}))};return this.layers.set(n.id,n),this.layersByTrack.has(n.trackId)||this.layersByTrack.set(n.trackId,new Set),this.layersByTrack.get(n.trackId).add(n.id),n}getBlendModes(){return Object.entries(oH).map(([e,t])=>({id:e,...t}))}clearAll(){this.layers.clear(),this.layersByTrack.clear()}}const _T={enabled:!1,quality:"balanced",sharpening:.3},lH=` +struct Dimensions { + srcWidth: u32, + srcHeight: u32, + dstWidth: u32, + dstHeight: u32, + direction: u32, + padding: vec3, +}; + +@group(0) @binding(0) var inputTexture: texture_2d; +@group(0) @binding(1) var outputTexture: texture_storage_2d; +@group(0) @binding(2) var dims: Dimensions; + +const PI: f32 = 3.14159265359; +const LANCZOS_A: f32 = 3.0; + +fn sinc(x: f32) -> f32 { + if (abs(x) < 0.0001) { + return 1.0; + } + let pix = PI * x; + return sin(pix) / pix; +} + +fn lanczosWeight(x: f32) -> f32 { + if (abs(x) >= LANCZOS_A) { + return 0.0; + } + return sinc(x) * sinc(x / LANCZOS_A); +} + +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let dstX = global_id.x; + let dstY = global_id.y; + + var targetWidth: u32; + var targetHeight: u32; + var srcWidth: u32; + var srcHeight: u32; + + if (dims.direction == 0u) { + targetWidth = dims.dstWidth; + targetHeight = dims.srcHeight; + srcWidth = dims.srcWidth; + srcHeight = dims.srcHeight; + } else { + targetWidth = dims.dstWidth; + targetHeight = dims.dstHeight; + srcWidth = dims.dstWidth; + srcHeight = dims.srcHeight; + } + + if (dstX >= targetWidth || dstY >= targetHeight) { + return; + } + + var scale: f32; + var srcPos: f32; + + if (dims.direction == 0u) { + scale = f32(srcWidth) / f32(targetWidth); + srcPos = (f32(dstX) + 0.5) * scale - 0.5; + } else { + scale = f32(srcHeight) / f32(targetHeight); + srcPos = (f32(dstY) + 0.5) * scale - 0.5; + } + + let srcCenter = i32(floor(srcPos)); + let kernelRadius = i32(ceil(LANCZOS_A * max(1.0, scale))); + + var colorSum = vec4(0.0); + var weightSum: f32 = 0.0; + + for (var i = -kernelRadius; i <= kernelRadius; i = i + 1) { + let srcIdx = srcCenter + i; + var sampleCoords: vec2; + + if (dims.direction == 0u) { + let clampedX = clamp(srcIdx, 0, i32(srcWidth) - 1); + sampleCoords = vec2(clampedX, i32(dstY)); + } else { + let clampedY = clamp(srcIdx, 0, i32(srcHeight) - 1); + sampleCoords = vec2(i32(dstX), clampedY); + } + + let dist = (f32(srcIdx) + 0.5 - srcPos) / max(1.0, scale); + let weight = lanczosWeight(dist); + + if (weight > 0.0001) { + colorSum = colorSum + textureLoad(inputTexture, sampleCoords, 0) * weight; + weightSum = weightSum + weight; + } + } + + var finalColor: vec4; + if (weightSum > 0.0001) { + finalColor = colorSum / weightSum; + } else { + if (dims.direction == 0u) { + finalColor = textureLoad(inputTexture, vec2(clamp(srcCenter, 0, i32(srcWidth) - 1), i32(dstY)), 0); + } else { + finalColor = textureLoad(inputTexture, vec2(i32(dstX), clamp(srcCenter, 0, i32(srcHeight) - 1)), 0); + } + } + + finalColor = clamp(finalColor, vec4(0.0), vec4(1.0)); + textureStore(outputTexture, vec2(i32(dstX), i32(dstY)), finalColor); +} +`,uH=` +struct Dimensions { + width: u32, + height: u32, + padding: vec2, +}; + +@group(0) @binding(0) var inputTexture: texture_2d; +@group(0) @binding(1) var outputTexture: texture_storage_2d; +@group(0) @binding(2) var dims: Dimensions; + +fn getLuminance(color: vec3) -> f32 { + return dot(color, vec3(0.299, 0.587, 0.114)); +} + +fn sampleLuminance(coords: vec2) -> f32 { + let clampedCoords = vec2( + clamp(coords.x, 0, i32(dims.width) - 1), + clamp(coords.y, 0, i32(dims.height) - 1) + ); + return getLuminance(textureLoad(inputTexture, clampedCoords, 0).rgb); +} + +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let x = global_id.x; + let y = global_id.y; + + if (x >= dims.width || y >= dims.height) { + return; + } + + let coords = vec2(i32(x), i32(y)); + + let tl = sampleLuminance(coords + vec2(-1, -1)); + let tc = sampleLuminance(coords + vec2(0, -1)); + let tr = sampleLuminance(coords + vec2(1, -1)); + let ml = sampleLuminance(coords + vec2(-1, 0)); + let mr = sampleLuminance(coords + vec2(1, 0)); + let bl = sampleLuminance(coords + vec2(-1, 1)); + let bc = sampleLuminance(coords + vec2(0, 1)); + let br = sampleLuminance(coords + vec2(1, 1)); + + let gx = -tl - 2.0 * ml - bl + tr + 2.0 * mr + br; + let gy = -tl - 2.0 * tc - tr + bl + 2.0 * bc + br; + + let magnitude = sqrt(gx * gx + gy * gy); + + var angle: f32 = 0.0; + if (abs(gx) > 0.001 || abs(gy) > 0.001) { + angle = atan2(gy, gx); + angle = (angle + 3.14159265359) / (2.0 * 3.14159265359); + } + + let normalizedMagnitude = clamp(magnitude, 0.0, 1.0); + + textureStore(outputTexture, coords, vec4( + normalizedMagnitude, + angle, + gx * 0.5 + 0.5, + gy * 0.5 + 0.5 + )); +} +`,dH=` +struct Dimensions { + width: u32, + height: u32, + padding: vec2, +}; + +@group(0) @binding(0) var colorTexture: texture_2d; +@group(0) @binding(1) var edgeTexture: texture_2d; +@group(0) @binding(2) var outputTexture: texture_storage_2d; +@group(0) @binding(3) var dims: Dimensions; + +fn sampleColor(coords: vec2) -> vec4 { + let clampedCoords = vec2( + clamp(coords.x, 0, i32(dims.width) - 1), + clamp(coords.y, 0, i32(dims.height) - 1) + ); + return textureLoad(colorTexture, clampedCoords, 0); +} + +fn sampleEdge(coords: vec2) -> vec4 { + let clampedCoords = vec2( + clamp(coords.x, 0, i32(dims.width) - 1), + clamp(coords.y, 0, i32(dims.height) - 1) + ); + return textureLoad(edgeTexture, clampedCoords, 0); +} + +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let x = global_id.x; + let y = global_id.y; + + if (x >= dims.width || y >= dims.height) { + return; + } + + let coords = vec2(i32(x), i32(y)); + let color = sampleColor(coords); + let edge = sampleEdge(coords); + + let magnitude = edge.r; + let gx = edge.b * 2.0 - 1.0; + let gy = edge.a * 2.0 - 1.0; + + let edgeThreshold = 0.05; + + if (magnitude < edgeThreshold) { + textureStore(outputTexture, coords, color); + return; + } + + let gradLen = sqrt(gx * gx + gy * gy); + var perpX: f32 = 0.0; + var perpY: f32 = 0.0; + + if (gradLen > 0.001) { + perpX = -gy / gradLen; + perpY = gx / gradLen; + } + + let sampleDist = 1.0; + let offset = vec2(perpX * sampleDist, perpY * sampleDist); + + let sample1Coords = coords + vec2(i32(round(offset.x)), i32(round(offset.y))); + let sample2Coords = coords - vec2(i32(round(offset.x)), i32(round(offset.y))); + + let sample1 = sampleColor(sample1Coords); + let sample2 = sampleColor(sample2Coords); + + let blendFactor = clamp(magnitude * 2.0, 0.0, 1.0); + let edgeColor = (sample1 + sample2) * 0.5; + let refinedColor = mix(color, edgeColor, blendFactor * 0.3); + + textureStore(outputTexture, coords, refinedColor); +} +`,hH=` +struct Uniforms { + width: u32, + height: u32, + strength: f32, + padding: u32, +}; + +@group(0) @binding(0) var inputTexture: texture_2d; +@group(0) @binding(1) var outputTexture: texture_storage_2d; +@group(0) @binding(2) var uniforms: Uniforms; + +fn sampleColor(coords: vec2) -> vec4 { + let clampedCoords = vec2( + clamp(coords.x, 0, i32(uniforms.width) - 1), + clamp(coords.y, 0, i32(uniforms.height) - 1) + ); + return textureLoad(inputTexture, clampedCoords, 0); +} + +fn getLuminance(color: vec3) -> f32 { + return dot(color, vec3(0.299, 0.587, 0.114)); +} + +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let x = global_id.x; + let y = global_id.y; + + if (x >= uniforms.width || y >= uniforms.height) { + return; + } + + let coords = vec2(i32(x), i32(y)); + let center = sampleColor(coords); + + if (uniforms.strength < 0.001) { + textureStore(outputTexture, coords, center); + return; + } + + let top = sampleColor(coords + vec2(0, -1)); + let bottom = sampleColor(coords + vec2(0, 1)); + let left = sampleColor(coords + vec2(-1, 0)); + let right = sampleColor(coords + vec2(1, 0)); + + let blur = (top + bottom + left + right) * 0.25; + + let highPass = center - blur; + + let localContrast = abs(getLuminance(highPass.rgb)); + let adaptiveStrength = uniforms.strength * (1.0 - localContrast * 0.5); + + let sharpened = center + highPass * adaptiveStrength; + + let finalColor = clamp(sharpened, vec4(0.0), vec4(1.0)); + + textureStore(outputTexture, coords, finalColor); +} +`;function TT(s,e,t,i,n){const r=new ArrayBuffer(32),a=new Uint32Array(r);return a[0]=s,a[1]=e,a[2]=t,a[3]=i,a[4]=n,a[5]=0,a[6]=0,a[7]=0,r}function kT(s,e){const t=new ArrayBuffer(16),i=new Uint32Array(t);return i[0]=s,i[1]=e,i[2]=0,i[3]=0,t}function fH(s,e,t){const i=new ArrayBuffer(16),n=new Uint32Array(i),r=new Float32Array(i);return n[0]=s,n[1]=e,r[2]=t,n[3]=0,i}const pH=4;class mH{device=null;initialized=!1;lanczosBindGroupLayout=null;edgeDetectBindGroupLayout=null;edgeDirectedBindGroupLayout=null;sharpenBindGroupLayout=null;lanczosPipeline=null;edgeDetectPipeline=null;edgeDirectedPipeline=null;sharpenPipeline=null;texturePool=new Map;lastProcessingTime=0;async initialize(e){if(this.initialized&&this.device===e.device)return!0;this.device=e.device;try{return this.createBindGroupLayouts(),await this.createPipelines(),this.initialized=!0,!0}catch(t){return console.error("[UpscalingEngine] Initialization failed:",t),!1}}createBindGroupLayouts(){this.device&&(this.lanczosBindGroupLayout=this.device.createBindGroupLayout({label:"Lanczos Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.edgeDetectBindGroupLayout=this.device.createBindGroupLayout({label:"Edge Detect Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.edgeDirectedBindGroupLayout=this.device.createBindGroupLayout({label:"Edge Directed Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.sharpenBindGroupLayout=this.device.createBindGroupLayout({label:"Sharpen Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}))}async createPipelines(){if(!this.device)return;const e=this.device.createShaderModule({label:"Lanczos Shader",code:lH}),t=this.device.createShaderModule({label:"Edge Detect Shader",code:uH}),i=this.device.createShaderModule({label:"Edge Directed Shader",code:dH}),n=this.device.createShaderModule({label:"Sharpen Shader",code:hH});this.lanczosPipeline=this.device.createComputePipeline({label:"Lanczos Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.lanczosBindGroupLayout]}),compute:{module:e,entryPoint:"main"}}),this.edgeDetectPipeline=this.device.createComputePipeline({label:"Edge Detect Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.edgeDetectBindGroupLayout]}),compute:{module:t,entryPoint:"main"}}),this.edgeDirectedPipeline=this.device.createComputePipeline({label:"Edge Directed Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.edgeDirectedBindGroupLayout]}),compute:{module:i,entryPoint:"main"}}),this.sharpenPipeline=this.device.createComputePipeline({label:"Sharpen Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.sharpenBindGroupLayout]}),compute:{module:n,entryPoint:"main"}})}shouldUpscale(e,t,i,n){return i>e||n>t}async upscale(e,t,i,n=_T){if(!this.initialized||!this.device)throw new Error("UpscalingEngine not initialized");const r=performance.now(),a=e.width,o=e.height;if(!this.shouldUpscale(a,o,t,i))return e;let c;switch(n.quality){case"fast":c=await this.upscaleFast(e,t,i);break;case"balanced":c=await this.upscaleBalanced(e,t,i);break;case"quality":c=await this.upscaleQuality(e,t,i,n.sharpening);break;default:c=await this.upscaleBalanced(e,t,i)}return this.lastProcessingTime=performance.now()-r,c}async upscaleFast(e,t,i){return this.applyLanczos(e,t,i)}async upscaleBalanced(e,t,i){const n=await this.applyLanczos(e,t,i),r=await this.applyEdgeDetection(n),a=await this.applyEdgeDirected(n,r);return this.releaseTexture(r),a}async upscaleQuality(e,t,i,n){const r=await this.applyLanczos(e,t,i),a=await this.applyEdgeDetection(r),o=await this.applyEdgeDirected(r,a);if(this.releaseTexture(a),n>.01){const c=await this.applySharpen(o,n);return this.releaseTexture(o),c}return o}async applyLanczos(e,t,i){if(!this.device||!this.lanczosPipeline||!this.lanczosBindGroupLayout)throw new Error("Lanczos pipeline not ready");const n=e.width,r=e.height,a=this.getPooledTexture(t,r),o=this.device.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(o,0,TT(n,r,t,i,0));const c=this.device.createBindGroup({layout:this.lanczosBindGroupLayout,entries:[{binding:0,resource:e.createView()},{binding:1,resource:a.createView()},{binding:2,resource:{buffer:o}}]}),l=this.device.createCommandEncoder(),u=l.beginComputePass();u.setPipeline(this.lanczosPipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(Math.ceil(t/16),Math.ceil(r/16)),u.end();const d=this.getPooledTexture(t,i),h=this.device.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(h,0,TT(t,r,t,i,1));const f=this.device.createBindGroup({layout:this.lanczosBindGroupLayout,entries:[{binding:0,resource:a.createView()},{binding:1,resource:d.createView()},{binding:2,resource:{buffer:h}}]}),p=l.beginComputePass();return p.setPipeline(this.lanczosPipeline),p.setBindGroup(0,f),p.dispatchWorkgroups(Math.ceil(t/16),Math.ceil(i/16)),p.end(),this.device.queue.submit([l.finish()]),this.releaseTexture(a),o.destroy(),h.destroy(),d}async applyEdgeDetection(e){if(!this.device||!this.edgeDetectPipeline||!this.edgeDetectBindGroupLayout)throw new Error("Edge detect pipeline not ready");const t=e.width,i=e.height,n=this.getPooledTexture(t,i),r=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(r,0,kT(t,i));const a=this.device.createBindGroup({layout:this.edgeDetectBindGroupLayout,entries:[{binding:0,resource:e.createView()},{binding:1,resource:n.createView()},{binding:2,resource:{buffer:r}}]}),o=this.device.createCommandEncoder(),c=o.beginComputePass();return c.setPipeline(this.edgeDetectPipeline),c.setBindGroup(0,a),c.dispatchWorkgroups(Math.ceil(t/16),Math.ceil(i/16)),c.end(),this.device.queue.submit([o.finish()]),r.destroy(),n}async applyEdgeDirected(e,t){if(!this.device||!this.edgeDirectedPipeline||!this.edgeDirectedBindGroupLayout)throw new Error("Edge directed pipeline not ready");const i=e.width,n=e.height,r=this.getPooledTexture(i,n),a=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(a,0,kT(i,n));const o=this.device.createBindGroup({layout:this.edgeDirectedBindGroupLayout,entries:[{binding:0,resource:e.createView()},{binding:1,resource:t.createView()},{binding:2,resource:r.createView()},{binding:3,resource:{buffer:a}}]}),c=this.device.createCommandEncoder(),l=c.beginComputePass();return l.setPipeline(this.edgeDirectedPipeline),l.setBindGroup(0,o),l.dispatchWorkgroups(Math.ceil(i/16),Math.ceil(n/16)),l.end(),this.device.queue.submit([c.finish()]),a.destroy(),r}async applySharpen(e,t){if(!this.device||!this.sharpenPipeline||!this.sharpenBindGroupLayout)throw new Error("Sharpen pipeline not ready");const i=e.width,n=e.height,r=this.getPooledTexture(i,n),a=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(a,0,fH(i,n,t));const o=this.device.createBindGroup({layout:this.sharpenBindGroupLayout,entries:[{binding:0,resource:e.createView()},{binding:1,resource:r.createView()},{binding:2,resource:{buffer:a}}]}),c=this.device.createCommandEncoder(),l=c.beginComputePass();return l.setPipeline(this.sharpenPipeline),l.setBindGroup(0,o),l.dispatchWorkgroups(Math.ceil(i/16),Math.ceil(n/16)),l.end(),this.device.queue.submit([c.finish()]),a.destroy(),r}getPooledTexture(e,t){if(!this.device)throw new Error("Device not available");const i=`${e}x${t}`,n=this.texturePool.get(i);return n&&n.length>0?n.pop().texture:this.device.createTexture({label:`Upscaling Texture ${i}`,size:{width:e,height:t},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST})}releaseTexture(e){const t=`${e.width}x${e.height}`;this.texturePool.has(t)||this.texturePool.set(t,[]);const i=this.texturePool.get(t);i.lengthu.time-d.time),a=new OfflineAudioContext(e.numberOfChannels,e.length,e.sampleRate),o=a.createBufferSource();o.buffer=e;const c=a.createGain();return this.scheduleVolumeKeyframes(c,r,n,e.duration),o.connect(c),c.connect(a.destination),o.start(0),{buffer:await a.startRendering(),appliedKeyframes:r.length}}scheduleVolumeKeyframes(e,t,i,n){const r=t[0],a=r&&r.time===0?Ct(r.value):i;e.gain.setValueAtTime(a,0);for(let c=0;c0?t[c-1]:null,f=h?Ct(h.value):i,p=h?h.time:0;this.applyInterpolation(e,f,u,p,l.time,d,l.bezierControls)}const o=t[t.length-1];o&&o.timed.time-h.time);if(e<=n[0].time)return Ct(n[0].value);if(e>=n[n.length-1].time)return Ct(n[n.length-1].value);let r=n[0],a=n[1];for(let d=0;d=n[d].time&&eo;m&&l===null?l=p:!m&&l!==null&&(c.push({start:l,end:p}),l=null)}return l!==null&&c.push({start:l,end:e.duration}),c}generateDuckingKeyframes(e,t,i=1){const n=this.detectAudioPresence(e,t.threshold);if(n.length===0)return[];const r=[],a=Ct(i*(1-t.reduction)),o=Ct(i),c=this.mergePresenceRanges(n,t.holdTime);for(const l of c){const u=Math.max(0,l.start-t.attack),d=l.end+t.release;r.push({time:u,value:o,curve:"s-curve"}),r.push({time:l.start,value:a,curve:"s-curve"}),r.push({time:l.end,value:a,curve:"s-curve"}),r.push({time:d,value:o,curve:"s-curve"})}return this.deduplicateKeyframes(r)}mergePresenceRanges(e,t){if(e.length===0)return[];const i=[...e].sort((r,a)=>r.start-a.start),n=[i[0]];for(let r=1;rn.time-r.time),i=[];for(const n of t){const r=i[i.length-1];(!r||Math.abs(n.time-r.time)>.001)&&i.push(n)}return i}async applyDucking(e,t,i,n=1){this.ensureInitialized();const r=this.generateDuckingKeyframes(t,i,n);if(r.length===0){const c=new AT(this.audioContext);return await c.initialize(this.audioContext),(await c.applyVolumeAutomation(e,[],n)).buffer}const a=new AT(this.audioContext);return await a.initialize(this.audioContext),(await a.applyVolumeAutomation(e,r,n)).buffer}createRealtimeDucker(e,t,i){this.ensureInitialized();const n=this.audioContext,r=n.createAnalyser();r.fftSize=256,r.smoothingTimeConstant=.8;const a=n.createGain();a.gain.value=1;const o=n.createGain();e.connect(r),r.connect(o),t.connect(a),a.connect(o);const c=Math.pow(10,i.threshold/20),l=new Float32Array(r.frequencyBinCount),u=()=>{r.getFloatTimeDomainData(l);let d=0;for(let g=0;gc?1-i.reduction:1,p=a.gain.value,m=f(s??[]).filter(e=>Number.isFinite(e.time)&&e.time>=0&&Number.isFinite(e.value)).map(e=>({time:e.time,value:Ct(e.value)})).sort((e,t)=>e.time-t.time),ST=(s,e,t)=>{if(s.length===0)return t;let i=null;for(const n of s){if(Math.abs(n.time-e)<=1e-4)return n.value;if(n.time>e){if(!i)return t;const r=n.time-i.time;if(r<=1e-4)return n.value;const a=(e-i.time)/r;return Ct(i.value+(n.value-i.value)*a)}i=n}return i?i.value:t},wH=(s,e,t,i)=>{const n=xH(s),r=Ct(i);if(t<=0||n.length===0)return[];const a=Math.max(0,e),o=a+t,c=[{time:0,value:ST(n,a,r)}];for(const u of n)u.time<=a||u.time>=o||c.push({time:u.time-a,value:u.value});c.push({time:t,value:ST(n,o,r)});const l=[];for(const u of c){const d=l[l.length-1];if(d&&Math.abs(d.time-u.time)<=1e-4){l[l.length-1]=u;continue}l.push(u)}return l},C0=(s,e,t,i,n,r)=>{const a=Ct(t),o=wH(e,i,n,a);if(s.gain.cancelScheduledValues(r),o.length===0){s.gain.setValueAtTime(a,r);return}s.gain.setValueAtTime(o[0].value,r);for(let l=1;l>r&1;this.reverseTable[i]=n}}getSize(){return this.size}forward(e){const t=this.size,i=new Float32Array(t),n=new Float32Array(t);for(let r=0;rArray.isArray(s)&&s.length>0&&s.every(e=>typeof e=="number"&&Number.isFinite(e)),_H=(s,e)=>typeof s=="number"&&Number.isInteger(s)&&s>0&&(s&s-1)===0&&s/2===e,Lv=s=>{if(!s||typeof s!="object")return!1;const e=s;return Zp(e.frequencyBins)&&Zp(e.magnitudes)&&e.frequencyBins.length===e.magnitudes.length&&(e.standardDeviations===void 0||Zp(e.standardDeviations)&&e.standardDeviations.length===e.magnitudes.length)&&typeof e.sampleRate=="number"&&Number.isFinite(e.sampleRate)&&(e.fftSize===void 0||_H(e.fftSize,e.magnitudes.length))},TH=s=>s.filter(e=>e.metadata?.previewBypass!==!0),KI=s=>{const e=s.find(t=>t.type==="pan"&&typeof t.params.value=="number");return e?Math.max(-1,Math.min(1,e.params.value)):0},kH=s=>{const e=[],t=[];for(const i of s){if(i.type==="noiseReduction"&&Lv(i.params.profile)){e.push(i);continue}t.push(i)}return{profileAwareNoiseEffects:e,realtimeEffects:t}};let rt=null,em=null,Lr=0;async function AH(){if(typeof WebAssembly>"u")return null;try{const s=new URL("/assets/fft-_Y3kmDnt.wasm",import.meta.url),e=await fetch(s);if(!e.ok)return null;const t=await e.arrayBuffer(),{instance:i}=await WebAssembly.instantiate(t,{env:{abort:()=>{throw new Error("WASM abort")}}});return i.exports}catch{return null}}async function QI(){return rt?!0:(em||(em=AH()),rt=await em,rt!==null)}class JI{size;jsFFT;useWasm;real;imag;constructor(e){if(e<=0||e&e-1)throw new Error("FFT size must be a power of 2");this.size=e,this.jsFFT=new XI(e),this.useWasm=!1,this.real=new Float32Array(e),this.imag=new Float32Array(e),rt&&Lr!==e?(rt.init(e),Lr=e,this.useWasm=!0):rt&&Lr===e&&(this.useWasm=!0)}async ensureWasm(){return this.useWasm?!0:(await QI()&&rt&&(Lr!==this.size&&(rt.init(this.size),Lr=this.size),this.useWasm=!0),this.useWasm)}getSize(){return this.size}ensureWasmSize(){this.useWasm&&rt&&Lr!==this.size&&(rt.init(this.size),Lr=this.size)}forward(e){return this.useWasm&&rt?(this.ensureWasmSize(),rt.forward(e,this.real,this.imag),{real:this.real.slice(),imag:this.imag.slice()}):this.jsFFT.forward(e)}inverse(e,t){if(this.useWasm&&rt){this.ensureWasmSize();const i=new Float32Array(this.size);return rt.inverse(e,t,i),i}return this.jsFFT.inverse(e,t)}getMagnitude(e,t){if(this.useWasm&&rt){this.ensureWasmSize();const i=new Float32Array(this.size/2);return rt.getMagnitude(e,t,i),i}return this.jsFFT.getMagnitude(e,t)}getPower(e,t){return this.jsFFT.getPower(e,t)}getMagnitudeAndPhase(e,t){if(this.useWasm&&rt){this.ensureWasmSize();const i=new Float32Array(this.size/2),n=new Float32Array(this.size/2);return rt.getMagnitudeAndPhase(e,t,i,n),{magnitudes:i,phases:n}}return this.jsFFT.getMagnitudeAndPhase(e,t)}fromMagnitudeAndPhase(e,t){if(this.useWasm&&rt){this.ensureWasmSize();const i=new Float32Array(this.size),n=new Float32Array(this.size);return rt.fromMagnitudeAndPhase(e,t,i,n),{real:i,imag:n}}return this.jsFFT.fromMagnitudeAndPhase(e,t)}applyHannWindow(e){if(this.useWasm&&rt){this.ensureWasmSize();const t=new Float32Array(e.length);return rt.applyHannWindow(e,t),t}return this.jsFFT.applyHannWindow(e)}applySynthesisWindow(e){return this.jsFFT.applySynthesisWindow(e)}}let Qu=null,CT=0;function ET(s){return Qu&&CT===s||(Qu=new JI(s),CT=s),Qu}const SH={threshold:-40,reduction:.5,attack:10,release:100,smoothing:.5};class ZI{config;noiseProfile=null;fftSize;hopSize;fft;wasmInitialized=!1;constructor(e={}){this.config={...SH,...e},this.fftSize=2048,this.hopSize=this.fftSize/4,this.fft=ET(this.fftSize),this.initWasm()}async initWasm(){if(!this.wasmInitialized)try{await QI(),this.fft instanceof JI&&await this.fft.ensureWasm(),this.wasmInitialized=!0}catch{this.wasmInitialized=!1}}learnNoiseProfile(e){const t=e.getChannelData(0),i=e.sampleRate,n=Math.floor((t.length-this.fftSize)/this.hopSize)+1;if(n<1)throw new Error("Noise sample too short for analysis");const r=this.fftSize/2,a=new Float32Array(r),o=new Float32Array(r);for(let h=0;h1e-6?n[a]/o:e[a]}}extractFrame(e,t){const i=new Float32Array(this.fftSize);for(let n=0;n=t&&o.push({start:c,end:p}),c=null)}return c!==null&&s.duration-c>=t&&o.push({start:c,end:s.duration}),o}function MT(s,e,t,i){const n=Math.floor(e*s.sampleRate),a=Math.floor(t*s.sampleRate)-n,o=i.createBuffer(s.numberOfChannels,a,s.sampleRate);for(let c=0;c0){const r=t.reduce((a,o)=>{const c=o.end-o.start,l=a.end-a.start;return c>l?o:a});i=MT(s,r.start,r.end,e)}else{const r=EH(s,.5);if(!r||!MH(s,r))return null;i=MT(s,r.start,r.end,e)}return new ZI().learnNoiseProfile(i)}function EH(s,e){const t=s.getChannelData(0),i=s.sampleRate,n=Math.floor(i*.05),r=Math.max(1,Math.ceil(e/.05)),a=Math.floor(t.length/n);if(a{const i=e?.threshold??-40,n=e?.reduction??.5,r=eP[t],a=Math.min(1,Math.max(.15,(Math.abs(i)-18)/42)),o=[];for(let c=0;ceP[e].postFilters.map(i=>{const n=s.createBiquadFilter();return n.type=i.type,n.frequency.value=i.frequency,n.Q.value=i.q,typeof i.gain=="number"&&(n.gain.value=i.gain),n}),PH=s=>{let e=0;for(let n=0;n{const t=Math.min(s.length,Math.ceil(200/e));let i=0;for(let n=0;n{const n=Math.max(0,Math.floor(t/e)),r=Math.min(s.length-1,Math.ceil(i/e));if(r{const r=[],a=e.magnitudes,o=e.frequencyBins,{mean:c,stdDev:l}=PH(a),u=c+l*2,d=new Set;for(let M=2;Ma[M-2]&&R>a[M-1]&&R>a[M+1]&&R>a[M+2]&&R>u))continue;const B=s.createBiquadFilter();B.type="notch",B.frequency.value=Math.max(20,Math.min(2e4,I));const $=R/((a[M-1]+a[M+1])/2);B.Q.value=Math.min(30,Math.max(5,$*10)),r.push(B);for(let V=M-2;V<=M+2;V+=1)d.add(V)}const h=[125,250,500,1e3,2e3,4e3,8e3],f=e.sampleRate/(a.length*2),p=Math.max(c,1e-6),m=Math.max(...Array.from(a)),g=Math.min(1,Math.max(0,c/Math.max(m,1e-6))),v=tm(a,f,6e3,18e3),w=tm(a,f,250,4e3),b=tm(a,f,180,1200),k=v/Math.max(w,1e-6);for(const M of h){const R=Math.round(M/f);if(R>=a.length||d.has(R))continue;const I=Math.max(0,R-5),D=Math.min(a.length-1,R+5);let B=0;for(let y=I;y<=D;y+=1)B+=a[y];if(B/=D-I+1,B<=p*1.2)continue;const $=s.createBiquadFilter();$.type="peaking",$.frequency.value=M,$.Q.value=1.4;const V=(B-p)/p;$.gain.value=-t*Math.min(12,V*6),r.push($)}if(i==="whiteNoise"||g>.58||k>1.25){const M=s.createBiquadFilter();M.type="highshelf",M.frequency.value=5200,M.Q.value=.7,M.gain.value=-Math.min(12,5+t*7+Math.max(0,k-1)*2),r.push(M);const R=s.createBiquadFilter();R.type="peaking",R.frequency.value=9e3,R.Q.value=.8,R.gain.value=-Math.min(10,4+t*6),r.push(R)}if(i==="music"||b>p*1.35&&g<.58){const M=s.createBiquadFilter();M.type="lowshelf",M.frequency.value=220,M.Q.value=.8,M.gain.value=-Math.min(8,3+t*5),r.push(M);const R=s.createBiquadFilter();R.type="peaking",R.frequency.value=650,R.Q.value=1.05,R.gain.value=-Math.min(7,2.5+t*4.5),r.push(R);const I=s.createBiquadFilter();I.type="peaking",I.frequency.value=3e3,I.Q.value=.9,I.gain.value=1.5,r.push(I)}if(RH(a,f)>p*1.5){const M=s.createBiquadFilter();M.type="highpass",M.frequency.value=80,M.Q.value=.707,r.push(M)}if(n&&r.push(...tP(s,i)),r.length===0){const M=s.createBiquadFilter();M.type="highpass",M.frequency.value=60,M.Q.value=.5,r.push(M)}return r},sP=(s,e)=>{const t=e.params,i=t?.focus??"balanced",n=s.createGain(),r=s.createGain(),a=IH(s,t,i),o=[n,r];let c=n;if(t?.profile&&Lv(t.profile)){const u=iP(s,nP(t.profile),t.reduction??.5,i,!1);for(const d of u)o.push(d),c.connect(d),c=d}for(const u of a)o.push(u.filter,u.gate),c.connect(u.filter),u.filter.connect(u.gate),u.gate.connect(r);let l=r;for(const u of tP(s,i))o.push(u),l.connect(u),l=u;return{input:n,output:l,nodes:o}},nP=s=>({frequencyBins:new Float32Array(s.frequencyBins),magnitudes:new Float32Array(s.magnitudes),standardDeviations:s.standardDeviations?new Float32Array(s.standardDeviations):void 0,sampleRate:s.sampleRate,fftSize:s.fftSize}),DH=s=>{const e=s.standardDeviations?new Float32Array(s.standardDeviations):Float32Array.from(s.magnitudes,t=>t*.08);return{frequencyBins:new Float32Array(s.frequencyBins),magnitudes:new Float32Array(s.magnitudes),standardDeviations:e,sampleRate:s.sampleRate,fftSize:s.fftSize??s.magnitudes.length*2}},FH=(s,e)=>Math.max(.04,{balanced:.22,speech:.2,whiteNoise:.08,music:.12,heavy:.1,wind:.12,hum:.16}[s]-Math.max(0,e-.75)*.12),E0=s=>{let e=0;for(let t=0;t{let e=0,t=0;for(let i=0;i{if(s.length!==e.length||s.numberOfChannels!==e.numberOfChannels||s.sampleRate!==e.sampleRate)return!1;const i=E0(s),n=E0(e),r=mh(s),a=mh(e);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)?!1:n<1e-5&&a<1e-5?!0:i>=Math.max(1e-5,n*t)&&r>=Math.max(1e-5,a*t)},LH=(s,e)=>({balanced:1.18,speech:1.24,whiteNoise:1.42,music:1.28,heavy:1.34,wind:1.32,hum:1.22})[s]+Math.max(0,e-.7)*.3,OH=(s,e)=>{if(e<=1.001)return s;const i=new OfflineAudioContext(s.numberOfChannels,Math.max(1,s.length),s.sampleRate).createBuffer(s.numberOfChannels,Math.max(1,s.length),s.sampleRate);for(let n=0;n{const n=mh(s),r=mh(e),a=E0(e);if(!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)||n<1e-5||r<1e-5||a<1e-5)return e;const o=n*Math.max(.82,.92-Math.max(0,i-.55)*.22),c=.98/Math.max(a,1e-5),l=o/r,u=Math.max(1,Math.min(LH(t,i),c,l));return OH(e,u)};class rP{audioContext=null;impulseResponses=new Map;noiseProfiles=new Map;initialized=!1;constructor(e){this.audioContext=e||null}async initialize(e){e&&(this.audioContext=e),this.audioContext||(this.audioContext=new AudioContext({latencyHint:"interactive",sampleRate:48e3})),this.initialized=!0}isInitialized(){return this.initialized&&this.audioContext!==null}getAudioContext(){return this.ensureInitialized(),this.audioContext}ensureInitialized(){if(!this.initialized||!this.audioContext)throw new Error("AudioEffectsEngine not initialized. Call initialize() first.")}async applyEffectChain(e,t){this.ensureInitialized();const i=t.filter(u=>u.enabled);if(i.length===0)return{buffer:e,appliedEffects:[]};const n=new OfflineAudioContext(e.numberOfChannels,e.length,e.sampleRate),r=n.createBufferSource();r.buffer=e;const{firstNode:a,lastNode:o,appliedEffects:c}=await this.buildEffectChain(n,i);return a&&o?(r.connect(a),o.connect(n.destination)):r.connect(n.destination),r.start(0),{buffer:await n.startRendering(),appliedEffects:c}}async buildEffectChain(e,t){let i=null,n=null;const r=[];for(const a of t){if(!a.enabled)continue;const o=await this.createEffectNode(e,a);o&&(r.push(a.type),i||(i=o.input),n&&n.connect(o.input),n=o.output)}return{firstNode:i,lastNode:n,appliedEffects:r}}async createEffectNode(e,t){switch(t.type){case"eq":return this.createEQNodePair(e,t);case"compressor":return this.createCompressorNodePair(e,t);case"reverb":return await this.createReverbNode(e,t);case"delay":return this.createDelayNode(e,t);case"noiseReduction":return this.createNoiseReductionNodePair(e,t);case"gain":return this.createGainNodePair(e,t);default:return null}}createEQNodePair(e,t){const n=t.params?.bands;if(!n||n.length===0)return null;let r=null,a=null;for(const o of n){const c=e.createBiquadFilter();c.type=this.mapEQBandType(o.type),c.frequency.value=Math.max(20,Math.min(2e4,o.frequency)),c.gain.value=Math.max(-24,Math.min(24,o.gain)),c.Q.value=Math.max(.1,Math.min(18,o.q)),r||(r=c),a&&a.connect(c),a=c}return!r||!a?null:{input:r,output:a}}createEQNode(e,t){return this.createEQNodePair(e,t)?.input??null}mapEQBandType(e){return{lowshelf:"lowshelf",highshelf:"highshelf",peaking:"peaking",lowpass:"lowpass",highpass:"highpass",notch:"notch"}[e]||"peaking"}createCompressorNodePair(e,t){const i=this.createCompressorNode(e,t);return{input:i,output:i}}createCompressorNode(e,t){const i=t.params,n=e.createDynamicsCompressor();return n.threshold.value=Math.max(-60,Math.min(0,i?.threshold??-24)),n.ratio.value=Math.max(1,Math.min(20,i?.ratio??4)),n.attack.value=Math.max(.001,Math.min(1,i?.attack??.003)),n.release.value=Math.max(.01,Math.min(3,i?.release??.25)),n.knee.value=Math.max(0,Math.min(40,i?.knee??30)),n}async createReverbNode(e,t){const i=t.params,n=e.createGain(),r=e.createGain(),a=e.createGain(),o=e.createGain(),c=e.createConvolver();r.gain.value=i?.dryLevel??.7,a.gain.value=i?.wetLevel??.5;const l=await this.getOrCreateImpulseResponse(e,i?.roomSize??.5,i?.damping??.5);c.buffer=l;let u=null;return i?.preDelay&&i.preDelay>0&&(u=e.createDelay(.1),u.delayTime.value=Math.min(.1,i.preDelay/1e3)),n.connect(r),r.connect(o),u?(n.connect(u),u.connect(c)):n.connect(c),c.connect(a),a.connect(o),{input:n,output:o}}async getOrCreateImpulseResponse(e,t,i){const n=`${t.toFixed(2)}_${i.toFixed(2)}`;if(this.impulseResponses.has(n))return this.impulseResponses.get(n);const r=this.generateImpulseResponse(e,t,i);return this.impulseResponses.set(n,r),r}generateImpulseResponse(e,t,i){const n=e.sampleRate,r=.5+t*3.5,a=Math.floor(n*r),o=2,c=e.createBuffer(o,a,n);for(let l=0;lnew OfflineAudioContext(m,Math.max(1,g),v).createBuffer(m,Math.max(1,g),v)});if(!PT(c,e,.025))return e;const l=new OfflineAudioContext(c.numberOfChannels,c.length,c.sampleRate),u=l.createBufferSource();u.buffer=c;const d=l.createGain(),h=l.createGain(),f=iP(l,a,i,n);if(u.connect(d),f.length>0){let m=d;for(const g of f)m.connect(g),m=g;m.connect(h)}else d.connect(h);h.connect(l.destination),u.start(0);const p=await l.startRendering();return PT(p,c,.15)?RT(e,p,n,i):RT(e,c,n,i)}clearImpulseResponseCache(){this.impulseResponses.clear()}clearNoiseProfiles(){this.noiseProfiles.clear()}async dispose(){this.clearImpulseResponseCache(),this.clearNoiseProfiles(),this.audioContext&&"close"in this.audioContext&&await this.audioContext.close(),this.audioContext=null,this.initialized=!1}}let im=null;function BH(){return im||(im=new rP),im}async function Eee(s){const e=BH();return await e.initialize(s),e}const DT=.01,FT=s=>s.audioTrackIndex??0,$H=(s,e)=>e.id!==s.id&&e.mediaId===s.mediaId&&FT(e)===FT(s)&&Math.abs(e.startTime-s.startTime){if(s==="audio"){if(e==="video")return 0;if(e==="image")return 1}return e==="audio"?0:e==="video"?1:e==="image"?2:3},Ov=(s,e)=>{const t=e.tracks.find(n=>n.id===s.trackId),i=[];for(const n of e.tracks)if(n.id!==s.trackId)for(const r of n.clips)$H(s,r)&&i.push({clip:r,track:n});return i.sort((n,r)=>LT(t?.type,n.track.type)-LT(t?.type,r.track.type))},jH=(s,e)=>{const t=s.audioEffects??[];return t.length>0?t:Ov(s,e).find(n=>(n.clip.audioEffects??[]).length>0)?.clip.audioEffects??[]},NH=(s,e)=>{const t=s.automation?.volume??[];return t.length>0?t:Ov(s,e).find(n=>(n.clip.automation?.volume?.length??0)>0)?.clip.automation?.volume??[]},Mee=(s,e)=>s.volume>0?s:Ov(s,e).find(i=>i.track.type==="audio"&&i.clip.volume>0)?.clip??s,VH=120;class UH{constructor(e,t=0){this.file=e,this.audioTrackIndex=t}input=null;sink=null;initialized=!1;async initialize(){if(this.initialized)return!0;try{const{Input:e,ALL_FORMATS:t,BlobSource:i,AudioBufferSink:n}=await ii(async()=>{const{Input:c,ALL_FORMATS:l,BlobSource:u,AudioBufferSink:d}=await import("./index-DjtrfS0G.js");return{Input:c,ALL_FORMATS:l,BlobSource:u,AudioBufferSink:d}},[]);this.input=new e({source:new i(this.file),formats:t});const r=await this.input.getAudioTracks();let a=r[this.audioTrackIndex]??null;return!a&&this.audioTrackIndex===0&&(a=await this.input.getPrimaryAudioTrack()??r[0]??null),a?await a.canDecode()?(this.sink=new n(a),this.initialized=!0,!0):(this.dispose(),!1):(this.dispose(),!1)}catch{return this.dispose(),!1}}async*buffers(e,t){if(this.sink)for await(const i of this.sink.buffers(e,t))yield i}dispose(){this.input&&(this.input[Symbol.dispose]?.(),this.input=null),this.sink=null,this.initialized=!1}}class zH{audioContext=null;masterGain=null;initialized=!1;config;trackNodes=new Map;mediaBuffers=new Map;segmentedAudioDecoders=new Map;effectsEngine=null;constructor(e={}){this.config={...yH,...e}}async initialize(){if(!this.initialized)try{this.audioContext=new AudioContext({sampleRate:this.config.sampleRate,latencyHint:this.config.latencyHint}),this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination),this.effectsEngine=new rP,await this.effectsEngine.initialize(),this.initialized=!0}catch(e){throw new Error(`AudioEngine initialization failed: ${e instanceof Error?e.message:"Unknown error"}`)}}isInitialized(){return this.initialized}getAudioContext(){return this.ensureInitialized(),this.audioContext}ensureInitialized(){if(!this.initialized||!this.audioContext)throw new Error("AudioEngine not initialized. Call initialize() first.")}async renderAudio(e,t,i){this.ensureInitialized();const{timeline:n,mediaLibrary:r,settings:a}=e,o=a.sampleRate||this.config.sampleRate,c=a.channels||this.config.channels,l=Math.max(i,.001),u=Math.max(1,Math.ceil(l*o)),d=new OfflineAudioContext(c,u,o),h=this.getAudioTracksAtTime(n,t,i),f=h.some(m=>m.solo);for(const m of h)if(!this.isTrackMuted(m,f))for(const g of m.clips){const v=r.items.find(w=>w.id===g.mediaId);v&&await this.renderClipToContext(d,v,g,t)}return{buffer:await d.startRendering(),startTime:t,duration:i,channels:c,sampleRate:o}}isTrackMuted(e,t){return!!(e.muted||t&&!e.solo)}getEffectiveTrackAudibility(e){const t=new Map,i=e.some(n=>n.solo);for(const n of e){const r=!n.muted&&(!i||n.solo);t.set(n.id,r)}return t}getAudioTracksAtTime(e,t,i){const n=[],r=t+i;return e.tracks.forEach((a,o)=>{if(a.type!=="audio"&&a.type!=="video")return;const c=this.getClipsInRange(a,t,r);c.length!==0&&n.push({trackId:a.id,index:o,muted:a.muted,solo:a.solo,clips:c.map(l=>this.createClipRenderInfo(l,t,r,e))})}),n}getClipsInRange(e,t,i){return e.clips.filter(n=>{const r=n.startTime+n.duration;return n.startTimet})}createClipRenderInfo(e,t,i,n){const r=Math.max(e.startTime,t),a=Math.min(e.startTime+e.duration,i),o=r-e.startTime,c=e.inPoint+o,l=jH(e,n),u=KI(l.length>0?l:e.effects);return{clipId:e.id,mediaId:e.mediaId,sourceTime:c,clipOffset:o,timelineStartTime:r,duration:a-r,volume:e.volume,volumeAutomation:NH(e,n),pan:u,effects:l,fadeIn:e.fade?.fadeIn,fadeOut:e.fade?.fadeOut,speed:e.speed||1,reversed:e.reversed||!1,audioTrackIndex:e.audioTrackIndex}}async getAudioBuffer(e,t,i=0){const n=`${e.id}:${i}`,r=this.mediaBuffers.get(n);if(r)return r;if(!e.blob)return console.warn(`No blob available for media item ${e.id}`),null;try{const a=await this.extractAudioFromVideo(e,t,i);if(a)return this.mediaBuffers.set(n,a),a}catch{}if(i===0)try{const a=await e.blob.arrayBuffer(),o=await t.decodeAudioData(a);return this.mediaBuffers.set(n,o),o}catch{return null}return null}async extractAudioFromVideo(e,t,i=0){if(!e.blob)return null;try{const{getFFmpegFallback:n}=await ii(async()=>{const{getFFmpegFallback:c}=await Promise.resolve().then(()=>Y7);return{getFFmpegFallback:c}},void 0),o=await(await n().extractAudioAsWav(e.blob,i)).arrayBuffer();return await t.decodeAudioData(o)}catch{return null}}async renderClipToContext(e,t,i,n){if(this.shouldUseSegmentedAudioDecoding(t,i)&&await this.renderClipToContextFromSegments(e,t,i,n))return;const r=await this.getAudioBuffer(t,e,i.audioTrackIndex??0);if(!r)return;const{volumeGainNode:a,fadeGainNode:o}=this.createClipOutputNodes(e,i),c=e.createBufferSource(),l=i.speed||1,u=i.reversed||!1,d=await this.processClipBuffer(r,i);c.buffer=d.buffer,c.playbackRate.value=u?-l:l,c.connect(a);const h=Math.max(0,i.timelineStartTime-n);this.applyVolumeAutomation(a,i,h),this.applyFades(o,i,h);const f=u?d.buffer.duration-d.startOffset:d.startOffset;c.start(h,Math.max(0,f),Math.min(i.duration,d.renderDuration))}shouldUseSegmentedAudioDecoding(e,t){return e.metadata.duration>=VH&&(t.speed||1)===1&&!t.reversed&&!t.effects.some(i=>i.enabled)}async processClipBuffer(e,t){const i=t.effects.filter(c=>c.enabled&&c.type!=="pan"&&c.type!=="fadeIn"&&c.type!=="fadeOut");if(i.length===0||(t.speed??1)!==1||t.reversed||!this.effectsEngine)return{buffer:e,startOffset:t.sourceTime,renderDuration:t.duration};const n=this.extractAudioSegment(e,t.sourceTime,t.duration),{profileAwareNoiseEffects:r,realtimeEffects:a}=kH(i);let o=n;for(const c of r){const l=c.params;l.profile&&(o=await this.effectsEngine.applyNoiseReductionWithProfileData(o,l.profile,l.reduction??.5,l.focus??"balanced",l.threshold??-40))}return a.length>0&&(o=(await this.effectsEngine.applyEffectChain(o,a)).buffer),{buffer:o,startOffset:0,renderDuration:o.duration}}extractAudioSegment(e,t,i){const n=Math.max(0,Math.floor(t*e.sampleRate)),r=Math.max(1,Math.ceil(i*e.sampleRate)),a=this.audioContext.createBuffer(e.numberOfChannels,r,e.sampleRate);for(let o=0;o0&&(e.gain.setValueAtTime(0,i),e.gain.linearRampToValueAtTime(1,i+n)),r&&r>0){const o=i+a-r;e.gain.setValueAtTime(1,o),e.gain.linearRampToValueAtTime(0,i+a)}}async mixTracks(e,t,i){if(this.ensureInitialized(),e.length===0)return this.audioContext.createBuffer(this.config.channels,this.config.sampleRate,this.config.sampleRate);const n=Math.max(...e.map(o=>o.length)),r=e[0].sampleRate,a=new OfflineAudioContext(this.config.channels,n,r);for(let o=0;ot.type==="audio"||t.type==="video").map(t=>({trackId:t.id,volume:1,pan:0,muted:t.muted,solo:t.solo,peakLevel:0,rmsLevel:0}))}async applyEffect(e,t){if(this.ensureInitialized(),!t.enabled)return e;const i=new OfflineAudioContext(e.numberOfChannels,e.length,e.sampleRate),n=i.createBufferSource();n.buffer=e;const r=this.createEffectNode(i,t);return r?(n.connect(r),r.connect(i.destination)):n.connect(i.destination),n.start(0),i.startRendering()}createEffectNode(e,t){const i=t.params;switch(t.type){case"gain":const n=e.createGain();return n.gain.value=i.value??1,n;case"pan":const r=e.createStereoPanner();return r.pan.value=Math.max(-1,Math.min(1,i.value??0)),r;case"eq":return this.createEQNode(e,t);case"compressor":const a=e.createDynamicsCompressor();return a.threshold.value=i.threshold??-24,a.ratio.value=i.ratio??4,a.attack.value=i.attack??.003,a.release.value=i.release??.25,a.knee.value=i.knee??30,a;case"delay":const o=e.createDelay(2);return o.delayTime.value=i.time??.5,o;default:return null}}createEQNode(e,t){const i=t.params.bands;if(!i||i.length===0)return null;let n=null,r=null;for(const a of i){const o=e.createBiquadFilter();o.type=a.type,o.frequency.value=a.frequency,o.gain.value=a.gain,o.Q.value=a.q,n||(n=o),r&&r.connect(o),r=o}return n}detectSilence(e,t=-60){const i=[],n=e.getChannelData(0),r=e.sampleRate,a=Math.pow(10,t/20);let o=null;const c=Math.floor(r*.1);for(let l=0;lthis.loopStart&&t>=this.loopEnd){const i=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%i}return Math.max(0,Math.min(t,this.duration||1/0))}get isPlaying(){return this.state==="playing"}get isPaused(){return this.state==="paused"}get isStopped(){return this.state==="stopped"}get rate(){return this.playbackRate}get drift(){return this.driftMs}get lastReportedVideoTime(){return this._lastVideoTime}getAudioContext(){return this.audioContext}setDuration(e){this.duration=e}setLoop(e,t=0,i=0){this.loopEnabled=e,this.loopStart=t,this.loopEnd=i}setPlaybackRate(e){if(this.state==="playing"){const t=this.currentTime;this.startTimelineTime=t,this.startAudioContextTime=this.audioContext.currentTime}this.playbackRate=Math.max(.1,Math.min(e,16))}async play(){this.state!=="playing"&&(this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.startTimelineTime=this.pausedAt,this.startAudioContextTime=this.audioContext.currentTime,this.state="playing",this.notifyStateChange(),this.startUpdateLoop())}pause(){this.state==="playing"&&(this.pausedAt=this.currentTime,this.state="paused",this.stopUpdateLoop(),this.notifyStateChange())}stop(){this.pausedAt=0,this.state="stopped",this.stopUpdateLoop(),this.notifyStateChange(),this.notifyTimeUpdate(0)}seek(e){const t=Math.max(0,Math.min(e,this.duration||1/0));this.state==="playing"?(this.startTimelineTime=t,this.startAudioContextTime=this.audioContext.currentTime):this.pausedAt=t,this.notifyTimeUpdate(t)}seekRelative(e){this.seek(this.currentTime+e)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}reportVideoTime(e){this._lastVideoTime=e;const t=this.currentTime;this.driftMs=(t-e)*1e3}shouldSkipFrame(){return this.driftMs>this.frameDuration}shouldRepeatFrame(){return this.driftMs<-this.frameDuration}startUpdateLoop(){if(this.animationFrameId!==null)return;const e=()=>{if(this.state!=="playing")return;const t=this.currentTime;if(t>=this.duration&&!this.loopEnabled){this.stop();return}this.notifyTimeUpdate(t),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}stopUpdateLoop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}notifyTimeUpdate(e){for(const t of this.subscribers)try{t.onTimeUpdate(e)}catch(i){console.error("[MasterClock] Subscriber error:",i)}}notifyStateChange(){for(const e of this.subscribers)try{e.onStateChange?.(this.state)}catch(t){console.error("[MasterClock] Subscriber error:",t)}}dispose(){this.stopUpdateLoop(),this.subscribers.clear(),this.state="stopped"}}let Qr=null;function GH(){return Qr||(Qr=new oP),Qr}function WH(s={}){return Qr&&Qr.dispose(),Qr=new oP(s),Qr}class cP{audioContext;masterClock;masterGain;trackNodes=new Map;scheduledSources=new Map;trackConfigs=new Map;hasSoloTracks=!1;impulseResponseCache=new Map;isPlaying=!1;lastScheduledTime=0;seekPending=!1;scheduleAheadTime=.2;schedulerIntervalId=null;trackVolumeOverrides=new Map;trackPanOverrides=new Map;masterVolumeOverride=1;previewMuted=!1;constructor(e){this.masterClock=e||GH(),this.audioContext=this.masterClock.getAudioContext(),this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination)}getAudioContext(){return this.audioContext}getMasterGain(){return this.masterGain}setMasterVolume(e){this.masterVolumeOverride=Math.max(0,Math.min(4,e)),this.applyMasterGain()}setPreviewMuted(e){this.previewMuted=e,this.applyMasterGain()}applyMasterGain(){const e=this.previewMuted?0:this.masterVolumeOverride;this.masterGain.gain.setValueAtTime(e,this.audioContext.currentTime)}createTrack(e){this.removeTrack(e.trackId),e.volume=this.trackVolumeOverrides.get(e.trackId)??e.volume,e.pan=this.trackPanOverrides.get(e.trackId)??e.pan,this.trackConfigs.set(e.trackId,e);const t=this.audioContext.createGain(),i=this.audioContext.createStereoPanner();i.pan.value=Math.max(-1,Math.min(1,e.pan));const n=this.audioContext.createGain();n.gain.value=e.volume;const{effectChainInput:r,effectChainOutput:a,compressor:o,eqFilters:c,noiseReductionNodes:l,reverbNodes:u,delayNodes:d}=this.buildEffectChain(e.effects);t.connect(r),a.connect(i),i.connect(n),n.connect(this.masterGain);const h={inputGain:t,effectChainInput:r,effectChainOutput:a,panNode:i,outputGain:n,compressor:o,eqFilters:c,noiseReductionNodes:l,reverbNodes:u,delayNodes:d};this.trackNodes.set(e.trackId,h),this.scheduledSources.set(e.trackId,[]),this.updateTrackAudibility(e.trackId),this.updateSoloState()}buildEffectChain(e){const t=this.audioContext.createGain();let i=null;const n=[],r=[];let a=null,o=null;const c=e.filter(d=>d.enabled);if(c.length===0)return{effectChainInput:t,effectChainOutput:t,compressor:i,eqFilters:n,noiseReductionNodes:r,reverbNodes:a,delayNodes:o};let l=t,u=t;for(const d of c)switch(d.type){case"compressor":{i=this.createCompressorNode(d),l.connect(i),l=i;break}case"eq":{const h=this.createEQFilters(d);if(h.length>0){l.connect(h[0]);for(let f=1;fe.solo);for(const e of this.trackNodes.keys())this.updateTrackAudibility(e)}updateTrackAudibility(e){const t=this.trackNodes.get(e),i=this.trackConfigs.get(e);if(!t||!i)return;let n=!0;(i.muted||this.hasSoloTracks&&!i.solo)&&(n=!1);const r=n?i.volume:0;t.outputGain.gain.setValueAtTime(r,this.audioContext.currentTime)}updateTrackEffects(e,t){const i=this.trackConfigs.get(e);if(i){if(JSON.stringify(i.effects)===JSON.stringify(t))return;i.effects=t,this.createTrack(i)}}scheduleClip(e){const t=this.trackNodes.get(e.trackId),i=this.trackConfigs.get(e.trackId);t?i&&JSON.stringify(i.effects)!==JSON.stringify(e.effects)&&this.updateTrackEffects(e.trackId,e.effects):this.createTrack({trackId:e.trackId,volume:e.volume,pan:e.pan,muted:!1,solo:!1,effects:e.effects});const n=this.trackNodes.get(e.trackId);if(!n)return;const r=this.audioContext.createBufferSource();r.buffer=e.audioBuffer,r.playbackRate.value=e.speed;const a=this.audioContext.createGain();r.connect(a),a.connect(n.inputGain);const o=this.audioContext.currentTime+e.startTime-this.masterClock.currentTime,c=e.endTime-e.startTime;let l=o,u=0,d=c;if(o>this.audioContext.currentTime)C0(a,e.volumeAutomation,e.volume,u,d,l),r.start(o,e.mediaOffset,c);else{u=this.masterClock.currentTime-e.startTime;const p=u+e.mediaOffset;if(d=c-u,l=this.audioContext.currentTime,d>0&&p{const p=this.scheduledSources.get(e.trackId);if(p){const m=p.indexOf(h);m>-1&&p.splice(m,1)}}}scheduleClips(e){for(const t of e)this.scheduleClip(t)}stopAllClips(){for(const[,e]of this.scheduledSources){for(const t of e)try{t.source.stop(),t.source.disconnect()}catch{}e.length=0}}stopClip(e){for(const[,t]of this.scheduledSources){const i=t.findIndex(n=>n.clipId===e);if(i>-1){const n=t[i];try{n.source.stop(),n.source.disconnect()}catch{}t.splice(i,1);break}}}async resume(){this.audioContext.state==="suspended"&&await this.audioContext.resume()}async suspend(){this.stopAllClips(),this.audioContext.state==="running"&&await this.audioContext.suspend()}startScheduler(e){if(this.schedulerIntervalId!==null)return;this.isPlaying=!0,this.seekPending||(this.lastScheduledTime=this.masterClock.currentTime),this.seekPending=!1;const t=()=>{if(!this.isPlaying)return;const n=this.masterClock.currentTime+this.scheduleAheadTime;if(n>this.lastScheduledTime){const r=e(this.lastScheduledTime);for(const a of r)a.startTime<=n&&a.endTime>this.lastScheduledTime&&((this.scheduledSources.get(a.trackId)||[]).some(l=>l.clipId===a.clipId)||this.scheduleClip(a));this.lastScheduledTime=n}};this.schedulerIntervalId=window.setInterval(t,100),t()}stopScheduler(){this.isPlaying=!1,this.schedulerIntervalId!==null&&(window.clearInterval(this.schedulerIntervalId),this.schedulerIntervalId=null),this.stopAllClips()}seekTo(e){this.stopAllClips(),this.lastScheduledTime=e,this.seekPending=!0}dispose(){this.stopScheduler();for(const e of Array.from(this.trackNodes.keys()))this.removeTrack(e);this.impulseResponseCache.clear(),this.masterGain.disconnect()}}let Jr=null;function Iee(){return Jr||(Jr=new cP),Jr}function qH(s){return Jr&&Jr.dispose(),Jr=new cP(s),Jr}const HH={C1:32.7,D1:36.71,E1:41.2,F1:43.65,G1:49,A1:55,B1:61.74,C2:65.41,D2:73.42,E2:82.41,F2:87.31,G2:98,A2:110,B2:123.47,C3:130.81,D3:146.83,E3:164.81,F3:174.61,G3:196,A3:220,B3:246.94,C4:261.63,D4:293.66,E4:329.63,F4:349.23,G4:392,A4:440,B4:493.88,C5:523.25,D5:587.33,E5:659.25,F5:698.46,G5:783.99,A5:880,B5:987.77,C6:1046.5,D6:1174.66,E6:1318.51,F6:1396.91,G6:1567.98,A6:1760,B6:1975.53,"C#2":69.3,"D#2":77.78,"F#2":92.5,"G#2":103.83,"A#2":116.54,"C#3":138.59,"D#3":155.56,"F#3":185,"G#3":207.65,"A#3":233.08,"C#4":277.18,"D#4":311.13,"F#4":369.99,"G#4":415.3,"A#4":466.16,"C#5":554.37,"D#5":622.25,"F#5":739.99,"G#5":830.61,"A#5":932.33,Eb2:77.78,Bb2:116.54,Eb3:155.56,Bb3:233.08,Eb4:311.13,Bb4:466.16,Eb5:622.25,Bb5:932.33,Ab2:103.83,Ab3:207.65,Ab4:415.3,Ab5:830.61,Db3:138.59,Db4:277.18,Db5:554.37,Gb3:185,Gb4:369.99,Gb5:739.99},nm={pop:[["C4","E4","G4"],["G3","B3","D4"],["A3","C4","E4"],["F3","A3","C4"]],jazz:[["C4","E4","G4","B4"],["A3","C4","E4","G4"],["D4","F4","A4","C5"],["G3","B3","D4","F4"]],lofi:[["C4","Eb4","G4"],["Ab3","C4","Eb4"],["Bb3","D4","F4"],["G3","Bb3","D4"]],cinematic:[["C4","G4","C5"],["Ab3","Eb4","Ab4"],["Bb3","F4","Bb4"],["G3","D4","G4"]],electronic:[["A3","E4","A4"],["F3","C4","F4"],["G3","D4","G4"],["A3","E4","A4"]],ambient:[["C4","G4","D5","G5"],["A3","E4","B4","E5"],["F3","C4","G4","C5"],["G3","D4","A4","D5"]]},Sc={uplifting:[["C3","G3","C4","E4","G4"],["G2","D3","G3","B3","D4"],["A2","E3","A3","C4","E4"],["F2","C3","F3","A3","C4"]],emotional:[["A2","E3","A3","C4","E4"],["F2","C3","F3","A3","C4"],["C3","G3","C4","E4","G4"],["G2","D3","G3","B3","D4"]],chill:[["D3","A3","D4","F#4","A4"],["G2","D3","G3","B3","D4"],["E3","B3","E4","G4","B4"],["A2","E3","A3","C#4","E4"]],happy:[["G3","D4","G4","B4","D5"],["C3","G3","C4","E4","G4"],["D3","A3","D4","F#4","A4"],["E3","B3","E4","G4","B4"]],funky:[["E3","G3","B3","D4"],["A3","C4","E4","G4"],["D3","F3","A3","C4"],["G3","B3","D4","F4"]]},rm={bouncy:[0,0,4,4,7,4,2,0],flowing:[0,2,4,2,0,-1,0,2],energetic:[0,7,4,7,0,4,7,12]},YH={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],pentatonic:[0,2,4,7,9],blues:[0,3,5,6,7,10],dorian:[0,2,3,5,7,9,10]};class XH{cache=new Map;noteToFreq(e){return HH[e]||440}getScaleFrequencies(e,t,i=2){const n=[];for(let r=0;r{const u=e.createOscillator();u.type=l%2===0?"sine":"triangle",u.frequency.value=t,u.detune.value=c;const d=e.createBiquadFilter();d.type="lowpass",d.frequency.value=2e3+Math.sin(l)*500,d.Q.value=.5;const h=e.createGain(),f=.15,p=.3;h.gain.setValueAtTime(0,i),h.gain.linearRampToValueAtTime(r/o.length,i+f),h.gain.setValueAtTime(r/o.length*.7,i+n-p),h.gain.linearRampToValueAtTime(0,i+n),u.connect(d),d.connect(h),h.connect(a),u.start(i),u.stop(i+n)})}createPluckySynth(e,t,i,n,r,a){const o=e.createOscillator();o.type="sawtooth",o.frequency.value=t;const c=e.createOscillator();c.type="square",c.frequency.value=t*1.002;const l=e.createBiquadFilter();l.type="lowpass",l.frequency.setValueAtTime(t*8,i),l.frequency.exponentialRampToValueAtTime(t*2,i+.1),l.Q.value=2;const u=e.createGain();u.gain.setValueAtTime(0,i),u.gain.linearRampToValueAtTime(r,i+.01),u.gain.exponentialRampToValueAtTime(r*.3,i+.1),u.gain.exponentialRampToValueAtTime(.001,i+n),o.connect(l),c.connect(l),l.connect(u),u.connect(a),o.start(i),o.stop(i+n),c.start(i),c.stop(i+n)}createRichBass(e,t,i,n,r,a){const o=e.createOscillator();o.type="sine",o.frequency.value=t;const c=e.createOscillator();c.type="sawtooth",c.frequency.value=t*2;const l=e.createBiquadFilter();l.type="lowpass",l.frequency.setValueAtTime(800,i),l.frequency.exponentialRampToValueAtTime(200,i+n*.5);const u=e.createGain();u.gain.setValueAtTime(0,i),u.gain.linearRampToValueAtTime(r*.7,i+.02),u.gain.exponentialRampToValueAtTime(r*.4,i+n*.3),u.gain.linearRampToValueAtTime(0,i+n);const d=e.createGain();d.gain.setValueAtTime(0,i),d.gain.linearRampToValueAtTime(r*.3,i+.01),d.gain.exponentialRampToValueAtTime(.001,i+n*.5),o.connect(u),u.connect(a),c.connect(l),l.connect(d),d.connect(a),o.start(i),o.stop(i+n),c.start(i),c.stop(i+n)}createPunchyKick(e,t,i,n){const r=e.createOscillator();r.type="sine",r.frequency.setValueAtTime(150,t),r.frequency.exponentialRampToValueAtTime(40,t+.08);const a=e.createOscillator();a.type="triangle",a.frequency.value=1e3;const o=e.createGain();o.gain.setValueAtTime(i,t),o.gain.exponentialRampToValueAtTime(.001,t+.3);const c=e.createGain();c.gain.setValueAtTime(i*.3,t),c.gain.exponentialRampToValueAtTime(.001,t+.02);const l=e.createDynamicsCompressor();l.threshold.value=-10,l.ratio.value=4,l.attack.value=.003,l.release.value=.1,r.connect(o),a.connect(c),o.connect(l),c.connect(l),l.connect(n),r.start(t),r.stop(t+.3),a.start(t),a.stop(t+.02)}createCrispSnare(e,t,i,n){const r=e.createBuffer(1,e.sampleRate*.2,e.sampleRate),a=r.getChannelData(0);for(let h=0;h{const m=a.createOscillator();m.type="sine",m.frequency.value=f;const g=a.createGain(),v=p*.08;g.gain.setValueAtTime(0,v),g.gain.linearRampToValueAtTime(.3,v+.02),g.gain.exponentialRampToValueAtTime(.01,v+.15),m.connect(g),g.connect(a.destination),m.start(v),m.stop(v+.15)});const c=await a.startRendering(),l=await this.audioBufferToBlob(c),u=URL.createObjectURL(l),h={item:{id:e,name:t,category:"sfx",subcategory:"ui",duration:n,tags:["alert","bell","message"],previewUrl:u,downloadUrl:u,isBuiltin:!0,license:"royalty-free"},blob:l,dataUrl:u};return this.cache.set(e,h),h}async generateSuccess(e,t){const i=this.cache.get(e);if(i)return i;const n=.6,r=44100,a=new OfflineAudioContext(2,r*n,r);[523.25,659.25,783.99,1046.5].forEach((f,p)=>{const m=a.createOscillator();m.type="triangle",m.frequency.value=f;const g=a.createGain(),v=p*.1;g.gain.setValueAtTime(0,v),g.gain.linearRampToValueAtTime(.25,v+.03),g.gain.exponentialRampToValueAtTime(.01,v+.25),m.connect(g),g.connect(a.destination),m.start(v),m.stop(v+.25)});const c=await a.startRendering(),l=await this.audioBufferToBlob(c),u=URL.createObjectURL(l),h={item:{id:e,name:t,category:"sfx",subcategory:"ui",duration:n,tags:["complete","achievement","positive"],previewUrl:u,downloadUrl:u,isBuiltin:!0,license:"royalty-free"},blob:l,dataUrl:u};return this.cache.set(e,h),h}async generatePop(e,t){const i=this.cache.get(e);if(i)return i;const n=.15,r=44100,a=new OfflineAudioContext(2,r*n,r),o=a.createOscillator();o.type="sine",o.frequency.setValueAtTime(400,0),o.frequency.exponentialRampToValueAtTime(100,n);const c=a.createGain();c.gain.setValueAtTime(.6,0),c.gain.exponentialRampToValueAtTime(.01,n),o.connect(c),c.connect(a.destination),o.start();const l=await a.startRendering(),u=await this.audioBufferToBlob(l),d=URL.createObjectURL(u),f={item:{id:e,name:t,category:"sfx",subcategory:"cartoon",duration:n,tags:["bubble","appear","fun"],previewUrl:d,downloadUrl:d,isBuiltin:!0,license:"royalty-free"},blob:u,dataUrl:d};return this.cache.set(e,f),f}async generateBoing(e,t){const i=this.cache.get(e);if(i)return i;const n=.4,r=44100,a=new OfflineAudioContext(2,r*n,r),o=a.createOscillator();o.type="sine";const c=a.createOscillator();c.type="sine",c.frequency.value=12;const l=a.createGain();l.gain.setValueAtTime(200,0),l.gain.exponentialRampToValueAtTime(1,n),c.connect(l),l.connect(o.frequency),o.frequency.setValueAtTime(300,0),o.frequency.exponentialRampToValueAtTime(100,n);const u=a.createGain();u.gain.setValueAtTime(.5,0),u.gain.exponentialRampToValueAtTime(.01,n),o.connect(u),u.connect(a.destination),o.start(),c.start();const d=await a.startRendering(),h=await this.audioBufferToBlob(d),f=URL.createObjectURL(h),m={item:{id:e,name:t,category:"sfx",subcategory:"cartoon",duration:n,tags:["bounce","spring","funny"],previewUrl:f,downloadUrl:f,isBuiltin:!0,license:"royalty-free"},blob:h,dataUrl:f};return this.cache.set(e,m),m}async generateGlitch(e,t){const i=this.cache.get(e);if(i)return i;const n=.5,r=44100,a=new OfflineAudioContext(2,r*n,r);for(let h=0;h<8;h++){const f=h*.05+Math.random()*.02,p=.02+Math.random()*.03,m=a.createBuffer(2,r*p,r);for(let b=0;b<2;b++){const k=m.getChannelData(b);for(let A=0;A.5?1:0)}const g=a.createBufferSource();g.buffer=m;const v=a.createBiquadFilter();v.type="bandpass",v.frequency.value=1e3+Math.random()*3e3,v.Q.value=10;const w=a.createGain();w.gain.value=.3+Math.random()*.3,g.connect(v),v.connect(w),w.connect(a.destination),g.start(f)}const o=await a.startRendering(),c=await this.audioBufferToBlob(o),l=URL.createObjectURL(c),d={item:{id:e,name:t,category:"sfx",subcategory:"transitions",duration:n,tags:["digital","error","tech"],previewUrl:l,downloadUrl:l,isBuiltin:!0,license:"royalty-free"},blob:c,dataUrl:l};return this.cache.set(e,d),d}async generateRiser(e,t){const i=this.cache.get(e);if(i)return i;const n=2,r=44100,a=new OfflineAudioContext(2,r*n,r),o=a.createBuffer(2,r*n,r);for(let g=0;g<2;g++){const v=o.getChannelData(g);for(let w=0;w{const g=c.createOscillator();g.type="sine",g.frequency.value=m;const v=c.createOscillator();v.type="sine",v.frequency.value=m*1.002;const w=c.createBiquadFilter();w.type="lowpass",w.frequency.setValueAtTime(800,0),w.frequency.linearRampToValueAtTime(2e3,a*.5),w.frequency.linearRampToValueAtTime(600,a);const b=c.createGain();b.gain.setValueAtTime(0,0),b.gain.linearRampToValueAtTime(.08,a*.3),b.gain.setValueAtTime(.08,a*.7),b.gain.linearRampToValueAtTime(0,a),g.connect(w),v.connect(w),w.connect(b),b.connect(c.destination),g.start(),v.start()});const u=await c.startRendering(),d=await this.audioBufferToBlob(u),h=URL.createObjectURL(d),p={item:{id:e,name:t,category:"music",subcategory:i,duration:a,bpm:60,key:"C Major",tags:["ambient","pad","atmospheric"],mood:n,previewUrl:h,downloadUrl:h,isBuiltin:!0,license:"royalty-free"},blob:d,dataUrl:h};return this.cache.set(e,p),p}async generateChordProgression(e,t,i,n,r,a="pop"){const o=this.cache.get(e);if(o)return o;const c=16,l=44100,u=new OfflineAudioContext(2,l*c,l),d=nm[a]||nm.pop,h=4,f=60/i,p=h*f;d.forEach((k,A)=>{const M=A*p;k.forEach(R=>{const I=this.noteToFreq(R),D=u.createOscillator();D.type=n==="electronic"?"sawtooth":"triangle",D.frequency.value=I;const B=u.createOscillator();B.type="sine",B.frequency.value=I*1.001;const $=u.createBiquadFilter();$.type="lowpass",$.frequency.setValueAtTime(2e3,M),$.frequency.linearRampToValueAtTime(800,M+p),$.Q.value=1;const V=u.createGain();V.gain.setValueAtTime(0,M),V.gain.linearRampToValueAtTime(.12,M+.1),V.gain.setValueAtTime(.1,M+p-.2),V.gain.linearRampToValueAtTime(0,M+p),D.connect($),B.connect($),$.connect(V),V.connect(u.destination),D.start(M),D.stop(M+p),B.start(M),B.stop(M+p)})});const m=await u.startRendering(),g=await this.audioBufferToBlob(m),v=URL.createObjectURL(g),b={item:{id:e,name:t,category:"music",subcategory:n,duration:c,bpm:i,key:"C Major",tags:["chords","progression",n],mood:r,previewUrl:v,downloadUrl:v,isBuiltin:!0,license:"royalty-free"},blob:g,dataUrl:v};return this.cache.set(e,b),b}async generateMelody(e,t,i,n,r,a="pentatonic"){const o=this.cache.get(e);if(o)return o;const c=8,l=44100,u=new OfflineAudioContext(2,l*c,l),d=YH[a],f=this.getScaleFrequencies(261.63,d,2),g=60/i/2,v=Math.floor(c/g);let w=Math.floor(f.length/2);for(let I=0;I{const A=k*2*d;for(let M=0;M<8;M++){const R=M%b.length,I=A+M*f;if(I>=o)break;const D=this.noteToFreq(b[R]),B=l.createOscillator();B.type="sawtooth",B.frequency.value=D;const $=l.createBiquadFilter();$.type="lowpass",$.frequency.setValueAtTime(4e3,I),$.frequency.exponentialRampToValueAtTime(500,I+f),$.Q.value=5;const V=l.createGain();V.gain.setValueAtTime(0,I),V.gain.linearRampToValueAtTime(.15,I+.01),V.gain.exponentialRampToValueAtTime(.01,I+f*.8),B.connect($),$.connect(V),V.connect(l.destination),B.start(I),B.stop(I+f)}});const p=await l.startRendering(),m=await this.audioBufferToBlob(p),g=URL.createObjectURL(m),w={item:{id:e,name:t,category:"music",subcategory:n,duration:o,bpm:i,key:"A Minor",tags:["arpeggio","synth",n],mood:r,previewUrl:g,downloadUrl:g,isBuiltin:!0,license:"royalty-free"},blob:m,dataUrl:g};return this.cache.set(e,w),w}async generateBassline(e,t,i,n,r){const a=this.cache.get(e);if(a)return a;const o=8,c=44100,l=new OfflineAudioContext(2,c*o,c),u=["C2","C2","G2","G2","A2","A2","F2","F2"],d=60/i;u.forEach((v,w)=>{const b=w*d,k=this.noteToFreq(v),A=l.createOscillator();A.type="sawtooth",A.frequency.value=k;const M=l.createOscillator();M.type="sine",M.frequency.value=k/2;const R=l.createBiquadFilter();R.type="lowpass",R.frequency.setValueAtTime(800,b),R.frequency.exponentialRampToValueAtTime(200,b+d),R.Q.value=8;const I=l.createGain();I.gain.setValueAtTime(0,b),I.gain.linearRampToValueAtTime(.4,b+.02),I.gain.exponentialRampToValueAtTime(.1,b+d*.8);const D=l.createGain();D.gain.value=.3,A.connect(R),R.connect(I),M.connect(D),D.connect(I),I.connect(l.destination),A.start(b),A.stop(b+d),M.start(b),M.stop(b+d)});const h=await l.startRendering(),f=await this.audioBufferToBlob(h),p=URL.createObjectURL(f),g={item:{id:e,name:t,category:"music",subcategory:n,duration:o,bpm:i,key:"C Minor",tags:["bass","groove",n],mood:r,previewUrl:p,downloadUrl:p,isBuiltin:!0,license:"royalty-free"},blob:f,dataUrl:p};return this.cache.set(e,g),g}async generateDrumLoop(e,t,i,n,r,a="basic"){const o=this.cache.get(e);if(o)return o;const c=8,l=44100,u=new OfflineAudioContext(2,l*c,l),d=60/i,h=d/4,f=Math.floor(c/(d*4));for(let b=0;b=c)break;const R=A===0||A===8||a==="complex"&&(A===6||A===14),I=A===4||A===12,D=a!=="minimal"||A%4===0,B=A===2||A===10;if(R){const $=u.createOscillator();$.type="sine",$.frequency.setValueAtTime(150,M),$.frequency.exponentialRampToValueAtTime(30,M+.15);const V=u.createGain();V.gain.setValueAtTime(.8,M),V.gain.exponentialRampToValueAtTime(.01,M+.2);const y=u.createOscillator();y.type="triangle",y.frequency.setValueAtTime(1e3,M),y.frequency.exponentialRampToValueAtTime(100,M+.03);const _=u.createGain();_.gain.setValueAtTime(.3,M),_.gain.exponentialRampToValueAtTime(.01,M+.03),$.connect(V),V.connect(u.destination),y.connect(_),_.connect(u.destination),$.start(M),$.stop(M+.2),y.start(M),y.stop(M+.03)}if(I){const $=u.createBuffer(1,l*.15,l),V=$.getChannelData(0);for(let E=0;E{const U=this.noteToFreq(L);O<2?(this.createWarmPad(l,U,T,d,.12,f),this.createWarmPad(l,U,T,d,.08,m)):this.createWarmPad(l,U,T,d,.06,f)});const S=_[0],C=this.noteToFreq(S);if(n==="hip-hop"||n==="electronic")for(let L=0;L<4;L++){const O=T+L*u;(L===0||L===2)&&this.createRichBass(l,C,O,u*.8,.4,m)}else for(let L=0;L<4;L++){const O=T+L*u;this.createRichBass(l,C,O,u*.7,.3,m)}const E=v?rm.bouncy:w?rm.energetic:rm.flowing,P=this.noteToFreq(_[2]||_[1]);V%2===0&&E.forEach((L,O)=>{const U=T+O*u/2;if(U{const g=this.noteToFreq(p),v=m*.05,w=o.createOscillator();w.type="triangle",w.frequency.value=g;const b=o.createOscillator();b.type="sine",b.frequency.value=g*2;const k=o.createGain();k.gain.setValueAtTime(0,v),k.gain.linearRampToValueAtTime(.2,v+.05),k.gain.setValueAtTime(.15,v+.5),k.gain.exponentialRampToValueAtTime(.01,r);const A=o.createGain();A.gain.setValueAtTime(0,v),A.gain.linearRampToValueAtTime(.08,v+.05),A.gain.exponentialRampToValueAtTime(.01,v+1.5),w.connect(k),b.connect(A),k.connect(o.destination),A.connect(o.destination),w.start(v),w.stop(r),b.start(v),b.stop(v+1.5)});const l=await o.startRendering(),u=await this.audioBufferToBlob(l),d=URL.createObjectURL(u),f={item:{id:e,name:t,category:"sfx",subcategory:"musical",duration:r,tags:["stinger","logo","intro"],mood:i,previewUrl:d,downloadUrl:d,isBuiltin:!0,license:"royalty-free"},blob:u,dataUrl:d};return this.cache.set(e,f),f}async generateCinematicHit(e,t){const i=this.cache.get(e);if(i)return i;const n=4,r=44100,a=new OfflineAudioContext(2,r*n,r),o=a.createOscillator();o.type="sine",o.frequency.setValueAtTime(60,0),o.frequency.exponentialRampToValueAtTime(20,n);const c=a.createGain();c.gain.setValueAtTime(.8,0),c.gain.exponentialRampToValueAtTime(.01,n),o.connect(c),c.connect(a.destination),o.start(0),o.stop(n);const l=a.createBuffer(2,r*.5,r);for(let b=0;b<2;b++){const k=l.getChannelData(b);for(let A=0;A{const k=a.createOscillator();k.type="sawtooth",k.frequency.value=b;const A=a.createBiquadFilter();A.type="lowpass",A.frequency.setValueAtTime(1e3,0),A.frequency.exponentialRampToValueAtTime(100,2);const M=a.createGain();M.gain.setValueAtTime(.15,0),M.gain.exponentialRampToValueAtTime(.01,3),k.connect(A),A.connect(M),M.connect(a.destination),k.start(0),k.stop(3)});const p=await a.startRendering(),m=await this.audioBufferToBlob(p),g=URL.createObjectURL(m),w={item:{id:e,name:t,category:"sfx",subcategory:"impacts",duration:n,tags:["cinematic","hit","epic","trailer"],mood:["tense","dark"],previewUrl:g,downloadUrl:g,isBuiltin:!0,license:"royalty-free"},blob:m,dataUrl:g};return this.cache.set(e,w),w}async generateTypingSound(e,t){const i=this.cache.get(e);if(i)return i;const n=.08,r=44100,a=new OfflineAudioContext(2,r*n,r),o=a.createOscillator();o.type="square",o.frequency.setValueAtTime(800+Math.random()*400,0),o.frequency.exponentialRampToValueAtTime(200,n);const c=a.createBiquadFilter();c.type="bandpass",c.frequency.value=2e3,c.Q.value=2;const l=a.createGain();l.gain.setValueAtTime(.2,0),l.gain.exponentialRampToValueAtTime(.01,n),o.connect(c),c.connect(l),l.connect(a.destination),o.start();const u=await a.startRendering(),d=await this.audioBufferToBlob(u),h=URL.createObjectURL(d),p={item:{id:e,name:t,category:"sfx",subcategory:"ui",duration:n,tags:["keyboard","typing","click"],previewUrl:h,downloadUrl:h,isBuiltin:!0,license:"royalty-free"},blob:d,dataUrl:h};return this.cache.set(e,p),p}async generateErrorSound(e,t){const i=this.cache.get(e);if(i)return i;const n=.4,r=44100,a=new OfflineAudioContext(2,r*n,r);[0,.15].forEach(h=>{const f=a.createOscillator();f.type="square",f.frequency.value=220;const p=a.createGain();p.gain.setValueAtTime(0,h),p.gain.linearRampToValueAtTime(.25,h+.02),p.gain.linearRampToValueAtTime(0,h+.12),f.connect(p),p.connect(a.destination),f.start(h),f.stop(h+.12)});const o=await a.startRendering(),c=await this.audioBufferToBlob(o),l=URL.createObjectURL(c),d={item:{id:e,name:t,category:"sfx",subcategory:"ui",duration:n,tags:["error","warning","alert"],previewUrl:l,downloadUrl:l,isBuiltin:!0,license:"royalty-free"},blob:c,dataUrl:l};return this.cache.set(e,d),d}async generateCountdown(e,t){const i=this.cache.get(e);if(i)return i;const n=4,r=44100,a=new OfflineAudioContext(2,r*n,r);for(let h=0;h<4;h++){const f=h,p=h===3,m=p?880:440,g=a.createOscillator();g.type="sine",g.frequency.value=m;const v=a.createGain();v.gain.setValueAtTime(0,f),v.gain.linearRampToValueAtTime(p?.4:.3,f+.02),v.gain.exponentialRampToValueAtTime(.01,f+(p?.8:.15)),g.connect(v),v.connect(a.destination),g.start(f),g.stop(f+(p?.8:.15))}const o=await a.startRendering(),c=await this.audioBufferToBlob(o),l=URL.createObjectURL(c),d={item:{id:e,name:t,category:"sfx",subcategory:"ui",duration:n,tags:["countdown","timer","beep"],previewUrl:l,downloadUrl:l,isBuiltin:!0,license:"royalty-free"},blob:c,dataUrl:l};return this.cache.set(e,d),d}async audioBufferToBlob(e){const t=e.numberOfChannels,i=e.sampleRate,n=1,r=16,a=r/8,o=t*a,c=i*o,l=e.length*o,d=44+l,h=new ArrayBuffer(d),f=new DataView(h),p=(v,w)=>{for(let b=0;be.category==="music")}getSFX(){return this.getAllSounds().filter(e=>e.category==="sfx")}getByCategory(e){return this.getAllSounds().filter(t=>t.category===e)}getBySubcategory(e){return this.getAllSounds().filter(t=>t.subcategory===e)}search(e){let t=this.getAllSounds();if(e.category&&(t=t.filter(i=>i.category===e.category)),e.subcategory&&(t=t.filter(i=>i.subcategory===e.subcategory)),e.mood&&e.mood.length>0&&(t=t.filter(i=>i.mood?.some(n=>e.mood.includes(n)))),e.minDuration!==void 0&&(t=t.filter(i=>i.duration>=e.minDuration)),e.maxDuration!==void 0&&(t=t.filter(i=>i.duration<=e.maxDuration)),e.minBpm!==void 0&&(t=t.filter(i=>i.bpm&&i.bpm>=e.minBpm)),e.maxBpm!==void 0&&(t=t.filter(i=>i.bpm&&i.bpm<=e.maxBpm)),e.searchQuery){const i=e.searchQuery.toLowerCase();t=t.filter(n=>n.name.toLowerCase().includes(i)||n.tags.some(r=>r.toLowerCase().includes(i)))}return t}getSound(e){return this.sounds.get(e)||null}async previewSound(e){if(this.stopPreview(),!!e.previewUrl)try{this.audioContext||(this.audioContext=new AudioContext);const i=await(await fetch(e.previewUrl)).arrayBuffer(),n=await this.audioContext.decodeAudioData(i);this.previewSource=this.audioContext.createBufferSource(),this.previewSource.buffer=n,this.previewGain=this.audioContext.createGain(),this.previewGain.gain.value=.7,this.previewSource.connect(this.previewGain),this.previewGain.connect(this.audioContext.destination),this.previewSource.start()}catch(t){console.error("[SoundLibrary] Preview failed:",t)}}stopPreview(){if(this.previewSource){try{this.previewSource.stop()}catch{}this.previewSource.disconnect(),this.previewSource=null}this.previewGain&&(this.previewGain.disconnect(),this.previewGain=null)}async analyzeAudio(e){const t=e.getChannelData(0),i=e.sampleRate,n=this.generateWaveform(t,200),{bpm:r,beats:a}=this.detectBeats(t,i),o=this.detectKey(t,i);return{bpm:r,key:o,beats:a,waveform:n}}generateWaveform(e,t){const i=[],n=Math.floor(e.length/t);for(let r=0;rc&&(c=u)}i.push(c)}return i}detectBeats(e,t){const i=[],n=Math.floor(t*.02),r=Math.floor(t*.01),a=[];for(let d=0;dd+h,0)/a.length,c=o*1.5;let l=-.5;for(let d=1;dc&&a[d]>a[d-1]&&a[d]>a[d+1]&&h-l>.2&&(i.push({time:h,strength:Math.min(a[d]/o,2),type:i.length%4===0?"downbeat":"beat"}),l=h)}let u=120;if(i.length>=4){const d=[];for(let f=1;ff+p,0)/d.length;u=Math.round(60/h),u=Math.max(60,Math.min(200,u))}return{bpm:u,beats:i}}detectKey(e,t){const i=["C Major","G Major","D Major","A Major","E Major","A Minor","E Minor","D Minor","B Minor","F Major"];return i[Math.floor(Math.random()*i.length)]}addCustomSound(e){const t={...e,isBuiltin:!1};return this.sounds.set(t.id,t),t}removeSound(e){const t=this.sounds.get(e);return t&&!t.isBuiltin?(this.sounds.delete(e),!0):!1}dispose(){this.stopPreview(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.sounds.clear()}}const JH={frameRate:30,audioBufferSize:4096,frameBufferAhead:5,audioLookahead:.1,frameRenderTimeout:100,enableAudio:!0,enableVideo:!0};class ZH{videoEngine=null;audioEngine=null;project=null;config;masterClock;clockUnsubscribe=null;realtimeAudioGraph;state="stopped";playbackRate=1;useRealtimeAudio=!0;currentFrame=null;frameRenderTimes=[];droppedFrames=0;scrubDebounceTimer=null;isScrubbing=!1;isRenderingFrame=!1;eventListeners=new Map;displayCanvas=null;displayCtx=null;constructor(e={}){this.config={...JH,...e},this.masterClock=WH({frameRate:this.config.frameRate}),this.realtimeAudioGraph=qH(this.masterClock)}async initialize(e,t){this.videoEngine=e,this.audioEngine=t,this.setupClockSubscription()}getRealtimeAudioGraph(){return this.realtimeAudioGraph}setupClockSubscription(){this.clockUnsubscribe&&this.clockUnsubscribe();const e={onTimeUpdate:t=>{this.handleClockTimeUpdate(t)},onStateChange:t=>{this.handleClockStateChange(t)}};this.clockUnsubscribe=this.masterClock.subscribe(e)}handleClockTimeUpdate(e){if(!(this.state!=="playing"||this.isRenderingFrame)){if(this.masterClock.shouldSkipFrame()){this.droppedFrames++;return}if(this.masterClock.shouldRepeatFrame()){this.emitEvent({type:"timeupdate",time:e,state:this.state});return}this.renderFrameAtTime(e),this.emitEvent({type:"timeupdate",time:e,state:this.state})}}handleClockStateChange(e){const t=this.state;e==="stopped"&&(this.state="stopped",this.stopAudioPlayback(),t!=="stopped"&&(this.emitEvent({type:"stop",time:0,state:this.state}),this.emitEvent({type:"statechange",time:0,state:this.state})))}getMasterClock(){return this.masterClock}setProject(e){this.project=e,this.state="stopped",this.masterClock.setDuration(e.timeline.duration),this.pruneAudioBuffers(e)}setDisplayCanvas(e){this.displayCanvas=e,this.displayCtx=e.getContext("2d")}getState(){return this.state}getCurrentTime(){return this.masterClock.currentTime}getCurrentFrame(){return this.currentFrame}isPlaying(){return this.state==="playing"}getIsScrubbing(){return this.isScrubbing}async play(){if(!this.project||!this.videoEngine)throw new Error("PlaybackController not properly initialized");if(this.state==="playing")return;const e=this.project.timeline.duration;this.masterClock.currentTime>=e&&this.masterClock.seek(0),this.state="playing",await this.preloadAudioBuffers(),await this.masterClock.play(),await this.startAudioPlayback();const t=this.masterClock.currentTime;this.emitEvent({type:"play",time:t,state:this.state}),this.emitEvent({type:"statechange",time:t,state:this.state})}pause(){if(this.state!=="playing")return;this.state="paused",this.masterClock.pause(),this.stopAudioPlayback();const e=this.masterClock.currentTime;this.emitEvent({type:"pause",time:e,state:this.state}),this.emitEvent({type:"statechange",time:e,state:this.state})}stop(){const e=this.state;this.state="stopped",this.masterClock.stop(),this.stopAudioPlayback(),this.emitEvent({type:"stop",time:0,state:this.state}),e!==this.state&&this.emitEvent({type:"statechange",time:0,state:this.state})}async togglePlayback(){this.state==="playing"?this.pause():await this.play()}async seek(e){if(!this.project)return;const t=this.state==="playing",i=this.project.timeline.duration,n=Math.max(0,Math.min(e,i));this.masterClock.seek(n),this.realtimeAudioGraph.seekTo(n),t&&(this.stopAudioPlayback(),await this.startAudioPlayback()),await this.renderFrameAtTime(n),this.emitEvent({type:"seek",time:n,state:this.state})}startScrubbing(){this.isScrubbing=!0,this.state==="playing"&&this.pause()}async scrubTo(e){if(!this.project||!this.videoEngine)return{frame:null,renderTime:0,fromCache:!1,timedOut:!1};const t=this.project.timeline.duration,i=Math.max(0,Math.min(e,t));return this.masterClock.seek(i),this.realtimeAudioGraph.seekTo(i),this.emitEvent({type:"timeupdate",time:i,state:this.state}),this.renderFrameWithTimeout(i)}endScrubbing(){this.isScrubbing=!1,this.scrubDebounceTimer&&(clearTimeout(this.scrubDebounceTimer),this.scrubDebounceTimer=null)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Math.min(4,e)),this.masterClock.setPlaybackRate(this.playbackRate)}getPlaybackRate(){return this.playbackRate}getStats(){const e=this.frameRenderTimes.length>0?this.frameRenderTimes.reduce((t,i)=>t+i,0)/this.frameRenderTimes.length:0;return{currentTime:this.masterClock.currentTime,duration:this.project?.timeline.duration??0,state:this.state,fps:this.calculateFPS(),droppedFrames:this.droppedFrames,audioBufferHealth:this.calculateAudioBufferHealth(),videoBufferHealth:1,avgFrameRenderTime:e}}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){this.eventListeners.get(e)?.delete(t)}dispose(){this.stop(),this.clockUnsubscribe&&(this.clockUnsubscribe(),this.clockUnsubscribe=null),this.masterClock.dispose(),this.realtimeAudioGraph.dispose(),this.clearAudioBuffer(),this.eventListeners.clear(),this.currentFrame?.image.close(),this.currentFrame=null,this.displayCanvas=null,this.displayCtx=null,this.videoEngine=null,this.audioEngine=null,this.project=null}async renderFrameAtTime(e){if(!this.project||!this.videoEngine||this.isRenderingFrame)return;this.isRenderingFrame=!0;const t=performance.now();try{const i=await this.videoEngine.renderFrame(this.project,e),n=performance.now()-t;this.trackFrameRenderTime(n),this.masterClock.reportVideoTime(e),this.currentFrame&&this.currentFrame!==i&&this.currentFrame.image.close(),this.currentFrame=i,this.drawFrameToCanvas(i),this.emitEvent({type:"framerendered",time:e,state:this.state,frame:i})}catch(i){console.error("Frame render error:",i),this.droppedFrames++}finally{this.isRenderingFrame=!1}}async renderFrameWithTimeout(e){if(!this.project||!this.videoEngine)return{frame:null,renderTime:0,fromCache:!1,timedOut:!1};if(this.isRenderingFrame)return{frame:null,renderTime:0,fromCache:!1,timedOut:!1};this.isRenderingFrame=!0;const t=performance.now();let i=null;const n=this.videoEngine.renderFrame(this.project,e);try{const r=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error("Frame render timeout"))},this.config.frameRenderTimeout)}),a=await Promise.race([n,r]),o=performance.now()-t;return this.trackFrameRenderTime(o),this.currentFrame&&this.currentFrame!==a&&this.currentFrame.image.close(),this.currentFrame=a,this.drawFrameToCanvas(a),{frame:a,renderTime:o,fromCache:!1,timedOut:!1}}catch(r){const a=performance.now()-t;return r instanceof Error&&r.message==="Frame render timeout"?(n.then(o=>{o&&o!==this.currentFrame&&o.image.close()}).catch(()=>{}),{frame:null,renderTime:a,fromCache:!1,timedOut:!0}):(console.error("Frame render error:",r),{frame:null,renderTime:a,fromCache:!1,timedOut:!1})}finally{i!==null&&clearTimeout(i),this.isRenderingFrame=!1}}drawFrameToCanvas(e){!this.displayCanvas||!this.displayCtx||((this.displayCanvas.width!==e.width||this.displayCanvas.height!==e.height)&&(this.displayCanvas.width=e.width,this.displayCanvas.height=e.height),this.displayCtx.drawImage(e.image,0,0))}async startAudioPlayback(){!this.config.enableAudio||!this.project||this.useRealtimeAudio&&(await this.realtimeAudioGraph.resume(),this.setupTracksInAudioGraph(),this.realtimeAudioGraph.startScheduler(e=>this.getAudioClipsAtTime(e)))}setupTracksInAudioGraph(){if(!this.project)return;const e=this.project.timeline.tracks.some(t=>t.solo);for(const t of this.project.timeline.tracks)t.type!=="audio"&&t.type!=="video"||(this.realtimeAudioGraph.createTrack({trackId:t.id,volume:1,pan:0,muted:t.muted,solo:t.solo,effects:[]}),e&&this.realtimeAudioGraph.setTrackSolo(t.id,t.solo))}getAudioClipsAtTime(e){if(!this.project||!this.audioEngine)return[];const t=[],{timeline:i,mediaLibrary:n}=this.project;for(const r of i.tracks)if(!(r.type!=="audio"&&r.type!=="video"))for(const a of r.clips){const o=a.startTime+a.duration;if(o<=e||a.startTime>e+1)continue;const c=n.items.find(u=>u.id===a.mediaId);if(!c?.blob)continue;const l=this.getOrDecodeAudioBuffer(c);l&&t.push({clipId:a.id,trackId:r.id,audioBuffer:l,startTime:a.startTime,endTime:o,mediaOffset:a.inPoint,volume:a.volume,volumeAutomation:a.automation?.volume??[],pan:KI(a.audioEffects||[]),effects:TH(a.audioEffects||[]),speed:a.speed??1})}return t}audioBufferCache=new Map;audioDecodePromises=new Map;async preloadAudioBuffers(){if(!this.project)return;const{timeline:e,mediaLibrary:t}=this.project,i=new Set;for(const r of e.tracks)if(!(r.type!=="audio"&&r.type!=="video"))for(const a of r.clips){const o=t.items.find(c=>c.id===a.mediaId);o?.blob&&!this.audioBufferCache.has(o.id)&&i.add(o.id)}const n=[];for(const r of i){const a=t.items.find(o=>o.id===r);a?.blob&&n.push(this.decodeAudioBuffer(a))}await Promise.all(n)}async decodeAudioBuffer(e){if(this.audioBufferCache.has(e.id))return this.audioBufferCache.get(e.id)||null;if(this.audioDecodePromises.has(e.id))return this.audioDecodePromises.get(e.id)||null;if(!e.blob)return null;const t=this.masterClock.getAudioContext(),i=e.blob.arrayBuffer().then(n=>t.decodeAudioData(n)).then(n=>(this.audioBufferCache.set(e.id,n),this.audioDecodePromises.delete(e.id),n)).catch(()=>(this.audioDecodePromises.delete(e.id),null));return this.audioDecodePromises.set(e.id,i),i}getOrDecodeAudioBuffer(e){const t=this.audioBufferCache.get(e.id);return t||(e.blob&&this.decodeAudioBuffer(e),null)}stopAudioPlayback(){this.useRealtimeAudio&&this.realtimeAudioGraph.stopScheduler()}clearAudioBuffer(){this.stopAudioPlayback(),this.audioBufferCache.clear(),this.audioDecodePromises.clear()}pruneAudioBuffers(e){const t=new Set;for(const i of e.timeline.tracks)if(!(i.type!=="audio"&&i.type!=="video"))for(const n of i.clips)t.add(n.mediaId);for(const i of[...this.audioBufferCache.keys()])t.has(i)||this.audioBufferCache.delete(i);for(const i of[...this.audioDecodePromises.keys()])t.has(i)||this.audioDecodePromises.delete(i);this.stopAudioPlayback()}trackFrameRenderTime(e){this.frameRenderTimes.push(e),this.frameRenderTimes.length>60&&this.frameRenderTimes.shift()}calculateFPS(){if(this.frameRenderTimes.length<2)return 0;const e=this.frameRenderTimes.reduce((t,i)=>t+i,0)/this.frameRenderTimes.length;return e>0?1e3/e:0}calculateAudioBufferHealth(){return 1}emitEvent(e){const t=this.eventListeners.get(e.type);if(t)for(const n of t)try{n(e)}catch(r){console.error("Event listener error:",r)}const i=this.eventListeners.get("all");if(i)for(const n of i)try{n(e)}catch(r){console.error("Event listener error:",r)}}}let om=null;function eY(){return om||(om=new ZH),om}const Bv={fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.75)",position:"bottom"},cm={default:Bv,classic:{fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.75)",position:"bottom"},modern:{fontFamily:"Helvetica Neue",fontSize:28,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.5)",position:"bottom"},cinematic:{fontFamily:"Georgia",fontSize:26,color:"#f0f0f0",backgroundColor:"transparent",position:"bottom"},bold:{fontFamily:"Impact",fontSize:32,color:"#ffff00",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"bottom"},minimal:{fontFamily:"Roboto",fontSize:22,color:"#ffffff",backgroundColor:"transparent",position:"bottom"},topCenter:{fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.75)",position:"top"},centered:{fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.75)",position:"center"}};function M0(){return`subtitle-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function OT(s){const e=s.trim().match(/^(\d{1,2}):(\d{2}):(\d{2})[,.](\d{3})$/);if(!e)return null;const t=parseInt(e[1],10),i=parseInt(e[2],10),n=parseInt(e[3],10),r=parseInt(e[4],10);return i>=60||n>=60?null:t*3600+i*60+n+r/1e3}function BT(s){(s<0||!isFinite(s))&&(s=0);const e=Math.round(s*1e3),t=Math.floor(e/36e5),i=Math.floor(e%36e5/6e4),n=Math.floor(e%6e4/1e3),r=e%1e3;return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")},${r.toString().padStart(3,"0")}`}function tY(s){const e=[],t=[],n=s.replace(/\r\n/g,` +`).replace(/\r/g,` +`).split(/\n\n+/).filter(a=>a.trim());let r=1;for(let a=0;a\s*(.+?)(?:\s+.*)?$/);if(!h){t.push({line:r+1,message:`Invalid timestamp format: "${d}"`,segment:a+1}),r+=o.split(` +`).length+1;continue}const f=OT(h[1]),p=OT(h[2]);if(f===null){t.push({line:r+1,message:`Invalid start timestamp: "${h[1]}"`,segment:a+1}),r+=o.split(` +`).length+1;continue}if(p===null){t.push({line:r+1,message:`Invalid end timestamp: "${h[2]}"`,segment:a+1}),r+=o.split(` +`).length+1;continue}if(p<=f){t.push({line:r+1,message:"End time must be greater than start time",segment:a+1}),r+=o.split(` +`).length+1;continue}const m=c.slice(2).join(` +`).trim();if(!m){t.push({line:r+2,message:"Empty subtitle text",segment:a+1}),r+=o.split(` +`).length+1;continue}e.push({id:M0(),text:m,startTime:f,endTime:p,style:Bv}),r+=o.split(` +`).length+1}return{success:t.length===0,subtitles:e,errors:t}}function iY(s){const e=[...s].sort((i,n)=>i.startTime-n.startTime),t=[];for(let i=0;i ${o} +${n.text}`)}return t.join(` + +`)}class sY{importSRT(e,t){const i=tY(t);return{timeline:{...e,subtitles:[...e.subtitles,...i.subtitles]},result:i}}exportSRT(e){return iY(e.subtitles)}addSubtitle(e,t,i,n,r){if(n<=i)return{error:"End time must be greater than start time"};if(i<0)return{error:"Start time cannot be negative"};const a={id:M0(),text:t,startTime:i,endTime:n,style:r||Bv};return{timeline:{...e,subtitles:[...e.subtitles,a]},subtitle:a}}updateSubtitle(e,t,i){const n=e.subtitles.findIndex(d=>d.id===t);if(n===-1)return{error:"Subtitle not found"};const r=e.subtitles[n],a=i.startTime??r.startTime,o=i.endTime??r.endTime;if(o<=a)return{error:"End time must be greater than start time"};if(a<0)return{error:"Start time cannot be negative"};const c={...r,text:i.text??r.text,startTime:a,endTime:o},l=[...e.subtitles];return l[n]=c,{timeline:{...e,subtitles:l},subtitle:c}}removeSubtitle(e,t){return e.subtitles.findIndex(r=>r.id===t)===-1?{error:"Subtitle not found"}:{timeline:{...e,subtitles:e.subtitles.filter(r=>r.id!==t)}}}setGlobalStyle(e,t){return{...e,subtitles:e.subtitles.map(i=>({...i,style:t}))}}setSubtitleStyle(e,t,i){const n=e.subtitles.findIndex(a=>a.id===t);if(n===-1)return{error:"Subtitle not found"};const r=[...e.subtitles];return r[n]={...r[n],style:i},{timeline:{...e,subtitles:r}}}getSubtitleAtTime(e,t){return e.subtitles.find(i=>t>=i.startTime&&tn.endTime>t&&n.startTimet.startTime-i.startTime)}shiftAllSubtitles(e,t){return{...e,subtitles:e.subtitles.map(i=>({...i,startTime:Math.max(0,i.startTime+t),endTime:Math.max(.001,i.endTime+t)}))}}applyStylePreset(e,t){const i=cm[t];return i?{timeline:this.setGlobalStyle(e,i)}:{error:`Unknown style preset: ${t}`}}mergeAdjacentSubtitles(e,t=.1){const i=this.getSortedSubtitles(e);if(i.length<=1)return e;const n=[];let r={...i[0]};for(let a=1;ac.id===t);if(!n)return{error:"Subtitle not found"};if(i<=n.startTime||i>=n.endTime)return{error:"Split time must be within subtitle duration"};const r={...n,endTime:i},a={...n,id:M0(),startTime:i},o=e.subtitles.filter(c=>c.id!==t);return o.push(r,a),{timeline:{...e,subtitles:o},subtitles:[r,a]}}clearAllSubtitles(e){return{...e,subtitles:[]}}getStylePresets(){return Object.keys(cm)}getStylePreset(e){return cm[e]}}const nY=[{code:"en-US",name:"English (US)"},{code:"en-GB",name:"English (UK)"},{code:"es-ES",name:"Spanish (Spain)"},{code:"es-MX",name:"Spanish (Mexico)"},{code:"fr-FR",name:"French"},{code:"de-DE",name:"German"},{code:"it-IT",name:"Italian"},{code:"pt-BR",name:"Portuguese (Brazil)"},{code:"pt-PT",name:"Portuguese (Portugal)"},{code:"ja-JP",name:"Japanese"},{code:"ko-KR",name:"Korean"},{code:"zh-CN",name:"Chinese (Simplified)"},{code:"zh-TW",name:"Chinese (Traditional)"},{code:"ru-RU",name:"Russian"},{code:"ar-SA",name:"Arabic"},{code:"hi-IN",name:"Hindi"},{code:"nl-NL",name:"Dutch"},{code:"pl-PL",name:"Polish"},{code:"sv-SE",name:"Swedish"},{code:"da-DK",name:"Danish"},{code:"fi-FI",name:"Finnish"},{code:"no-NO",name:"Norwegian"},{code:"tr-TR",name:"Turkish"},{code:"th-TH",name:"Thai"},{code:"vi-VN",name:"Vietnamese"},{code:"id-ID",name:"Indonesian"},{code:"ms-MY",name:"Malay"},{code:"el-GR",name:"Greek"},{code:"cs-CZ",name:"Czech"},{code:"ro-RO",name:"Romanian"},{code:"hu-HU",name:"Hungarian"},{code:"uk-UA",name:"Ukrainian"},{code:"he-IL",name:"Hebrew"}],rY={language:"en-US",continuous:!0,interimResults:!1,maxAlternatives:1},aY={fontFamily:"Arial",fontSize:24,color:"#ffffff",backgroundColor:"rgba(0, 0, 0, 0.7)",position:"bottom"};class $v{recognition=null;audioContext=null;mediaSource=null;segments=[];isTranscribing=!1;currentOptions=rY;progressCallback=null;segmentCallback=null;startTime=0;segmentStartTime=0;static isSupported(){return typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)}static getSupportedLanguages(){return[...nY]}constructor(){this.initRecognition()}initRecognition(){if(!$v.isSupported())return;const e=window.SpeechRecognition||window.webkitSpeechRecognition;e&&(this.recognition=new e,this.setupRecognitionHandlers())}setupRecognitionHandlers(){this.recognition&&(this.recognition.onresult=e=>{const t=e.results[e.results.length-1];if(!t.isFinal)return;const i=t[0].transcript.trim();if(!i)return;const n=this.getCurrentTime(),r={text:i,startTime:this.segmentStartTime,endTime:n,confidence:t[0].confidence};this.segments.push(r),this.segmentStartTime=n,this.segmentCallback&&this.segmentCallback(r),this.reportProgress("transcribing")},this.recognition.onerror=e=>{e.error==="no-speech"||e.error==="aborted"||console.error("Speech recognition error:",e.error)},this.recognition.onend=()=>{if(this.isTranscribing&&this.recognition)try{this.recognition.start()}catch{this.isTranscribing=!1,this.reportProgress("completed")}})}getCurrentTime(){return(performance.now()-this.startTime)/1e3}reportProgress(e){this.progressCallback&&this.progressCallback({status:e,progress:e==="completed"?100:50,currentTime:this.getCurrentTime(),totalDuration:0,segmentsFound:this.segments.length})}setOptions(e){this.currentOptions={...this.currentOptions,...e},this.applyOptions()}applyOptions(){this.recognition&&(this.recognition.lang=this.currentOptions.language,this.recognition.continuous=this.currentOptions.continuous,this.recognition.interimResults=this.currentOptions.interimResults,this.recognition.maxAlternatives=this.currentOptions.maxAlternatives)}onProgress(e){this.progressCallback=e}onSegment(e){this.segmentCallback=e}async startLiveTranscription(){if(!this.recognition)throw new Error("Speech recognition not supported in this browser");if(!this.isTranscribing){this.segments=[],this.isTranscribing=!0,this.startTime=performance.now(),this.segmentStartTime=0,this.applyOptions(),this.reportProgress("transcribing");try{this.recognition.start()}catch(e){throw this.isTranscribing=!1,e}}}stopTranscription(){if(!this.isTranscribing)return{success:!0,segments:this.segments,language:this.currentOptions.language};if(this.isTranscribing=!1,this.recognition)try{this.recognition.stop()}catch{}return this.reportProgress("completed"),{success:!0,segments:[...this.segments],language:this.currentOptions.language}}async transcribeAudioElement(e,t=0,i){return this.recognition?new Promise(n=>{this.segments=[],this.isTranscribing=!0,this.startTime=performance.now(),this.segmentStartTime=t;const r=()=>{o(),n(this.stopTranscription())},a=()=>{i&&e.currentTime>=t+i&&r()},o=()=>{e.removeEventListener("ended",r),e.removeEventListener("timeupdate",a)};if(e.addEventListener("ended",r),e.addEventListener("timeupdate",a),this.applyOptions(),this.reportProgress("transcribing"),e.currentTime=t,e.play().catch(()=>{o(),n({success:!1,segments:[],error:"Failed to play audio for transcription"})}),!this.recognition){o(),n({success:!1,segments:[],error:"Speech recognition not available"});return}try{this.recognition.start()}catch{o(),n({success:!1,segments:[],error:"Failed to start speech recognition"})}}):{success:!1,segments:[],error:"Speech recognition not supported. Try Chrome or Edge browser."}}segmentsToSubtitles(e,t){const i={...aY,...t};return e.map((n,r)=>({id:`auto-caption-${Date.now()}-${r}`,text:n.text,startTime:n.startTime,endTime:n.endTime,style:i}))}getSegments(){return[...this.segments]}clearSegments(){this.segments=[]}isActive(){return this.isTranscribing}dispose(){this.stopTranscription(),this.mediaSource&&(this.mediaSource.disconnect(),this.mediaSource=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.recognition=null,this.progressCallback=null,this.segmentCallback=null}}const _r=s=>!s||s==="linear"?t=>t:s==="ease-in"?Ss.easeInQuad:s==="ease-out"?Ss.easeOutQuad:s==="ease-in-out"?Ss.easeInOutQuad:s==="bezier"?Ss.easeInOutCubic:Ss[s]||(t=>t),Yt={opacity:1,scale:{x:1,y:1},rotation:0,offsetX:0,offsetY:0,blur:0},oY=s=>{const{unit:e,progress:t,isIn:i}=s,n=s.animation.stagger||.05,r=e.index*n,a=s.animation.inDuration-(e.totalUnits-1)*n;let o;return i?o=Math.max(0,Math.min(1,(t*s.animation.inDuration-r)/a)):o=1-Math.max(0,Math.min(1,(t*s.animation.outDuration-r)/a)),{...Yt,opacity:o>=.5?1:0}},cY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.03,o=_r(r.easing||"easeOutQuad"),c=e.index*a,l=i?n.inDuration:n.outDuration,u=Math.max(.1,l-(e.totalUnits-1)*a);let d=Math.max(0,Math.min(1,(t*l-c)/u));i||(d=1-d);const h=o(d),f=r.fadeOpacity?.start??0,p=r.fadeOpacity?.end??1,m=f+(p-f)*h;return{...Yt,opacity:m}},Ju=s=>e=>{const{unit:t,progress:i,isIn:n,animation:r}=e,a=r.params,o=r.stagger||.03,c=_r(a.easing||"easeOutCubic"),l=a.slideDistance||50,u=t.index*o,d=n?r.inDuration:r.outDuration,h=Math.max(.1,d-(t.totalUnits-1)*o);let f=Math.max(0,Math.min(1,(i*d-u)/h));n||(f=1-f);const p=c(f);let m=0,g=0;const v=l*(1-p);switch(s){case"left":m=-v;break;case"right":m=v;break;case"up":g=-v;break;case"down":g=v;break}return{...Yt,opacity:p,offsetX:m,offsetY:g}},lY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.03,o=_r(r.easing||"easeOutBack"),c=r.scaleFrom??0,l=r.scaleTo??1,u=e.index*a,d=i?n.inDuration:n.outDuration,h=Math.max(.1,d-(e.totalUnits-1)*a);let f=Math.max(0,Math.min(1,(t*d-u)/h));i||(f=1-f);const p=o(f),m=c+(l-c)*p;return{...Yt,opacity:p,scale:{x:m,y:m}}},uY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.03,o=_r(r.easing||"easeOutQuad"),c=r.blurAmount??10,l=e.index*a,u=i?n.inDuration:n.outDuration,d=Math.max(.1,u-(e.totalUnits-1)*a);let h=Math.max(0,Math.min(1,(t*u-l)/d));i||(h=1-h);const f=o(h),p=c*(1-f);return{...Yt,opacity:f,blur:p}},dY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.05,o=r.bounceHeight??30,c=e.index*a,l=i?n.inDuration:n.outDuration,u=Math.max(.1,l-(e.totalUnits-1)*a);let d=Math.max(0,Math.min(1,(t*l-c)/u));i||(d=1-d);const h=Ss.easeOutBounce(d),f=-o*(1-h);return{...Yt,opacity:d>0?1:0,offsetY:f}},hY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.03,o=_r(r.easing||"easeOutBack"),c=r.rotateAngle??180,l=e.index*a,u=i?n.inDuration:n.outDuration,d=Math.max(.1,u-(e.totalUnits-1)*a);let h=Math.max(0,Math.min(1,(t*u-l)/d));i||(h=1-h);const f=o(h),p=c*(1-f);return{...Yt,opacity:f,rotation:p,scale:{x:f,y:f}}},fY=s=>{const{unit:e,progress:t,animation:i}=s,n=i.params,r=n.waveAmplitude??10,a=n.waveFrequency??2,o=e.index/e.totalUnits*Math.PI*2,c=Math.sin(t*Math.PI*2*a+o)*r;return{...Yt,offsetY:c}},pY=s=>{const{progress:e,animation:t}=s,i=t.params,n=i.shakeIntensity??5,r=i.shakeSpeed??20,a=Math.sin(e*Math.PI*2*r)*n,o=Math.cos(e*Math.PI*2*r*1.3)*n*.5;return{...Yt,offsetX:a,offsetY:o}},mY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.05,o=r.popOvershoot??1.2,c=e.index*a,l=i?n.inDuration:n.outDuration,u=Math.max(.1,l-(e.totalUnits-1)*a);let d=Math.max(0,Math.min(1,(t*l-c)/u));i||(d=1-d);const h=Ss.easeOutBack(d),f=d>0?h*(d<.5?o:1):0;return{...Yt,opacity:d>0?1:0,scale:{x:Math.max(0,f),y:Math.max(0,f)}}},gY=s=>{const{unit:e,progress:t,animation:i}=s,n=i.params,r=n.glitchIntensity??10,a=n.glitchSpeed??10,o=t*a,c=Math.floor(o)+e.index*.3,l=Math.sin(c*12.9898)*43758.5453,u=l-Math.floor(l),d=u>.7,h=d?(u-.5)*r*2:0,f=d?(u-.5)*5:0;return{...Yt,offsetX:h,skewX:f,color:d&&u>.85?`hsl(${u*360}, 100%, 50%)`:void 0}},yY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.03,o=_r(r.easing||"easeOutCubic"),c=r.splitDirection||"horizontal",l=e.index*a,u=i?n.inDuration:n.outDuration,d=Math.max(.1,u-(e.totalUnits-1)*a);let h=Math.max(0,Math.min(1,(t*u-l)/d));i||(h=1-h);const f=o(h),p=(e.totalUnits-1)/2,v=100*(e.index-p)*(1-f)/p;return{...Yt,opacity:f,offsetX:c==="horizontal"?v:0,offsetY:c==="vertical"?v:0}},vY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=n.stagger||.05,o=_r(r.easing||"easeOutBack"),c=r.flipAxis||"y",l=e.index*a,u=i?n.inDuration:n.outDuration,d=Math.max(.1,u-(e.totalUnits-1)*a);let h=Math.max(0,Math.min(1,(t*u-l)/d));i||(h=1-h);const f=o(h),p=90*(1-f),m=Math.cos(p*Math.PI/180);return{...Yt,opacity:f>.1?1:0,scale:c==="x"?{x:m,y:1}:{x:1,y:m},rotation:0}},bY=s=>{const{unit:e,progress:t,isIn:i,animation:n}=s,r=n.params,a=r.wordDelay??.2,o=_r(r.easing||"easeOutQuad"),c=e.index*a,l=i?n.inDuration:n.outDuration;let d=Math.max(0,Math.min(1,(t*l-c)/.3));i||(d=1-d);const h=o(d);return{...Yt,opacity:h,offsetY:20*(1-h),scale:{x:.8+.2*h,y:.8+.2*h}}},xY=s=>{const{unit:e,progress:t,animation:i}=s,r=i.params.rainbowSpeed??1,a=(e.index/e.totalUnits*360+t*360*r)%360;return{...Yt,color:`hsl(${a}, 80%, 60%)`}},wY={none:()=>Yt,typewriter:oY,fade:cY,"slide-left":Ju("left"),"slide-right":Ju("right"),"slide-up":Ju("up"),"slide-down":Ju("down"),scale:lY,blur:uY,bounce:dY,rotate:hY,wave:fY,shake:pY,pop:mY,glitch:gY,split:yY,flip:vY,"word-by-word":bY,rainbow:xY};function lm(s){const e=wY[s.animation.preset];return e?e(s):Yt}class _Y{measureCtx=null;constructor(){if(typeof OffscreenCanvas<"u"){const e=new OffscreenCanvas(1,1);this.measureCtx=e.getContext("2d")}else if(typeof document<"u"){const e=document.createElement("canvas");this.measureCtx=e.getContext("2d")}}measureText(e,t,i,n,r,a){if(!this.measureCtx)return this.createFallbackLayout(e,i,a);const o=this.measureCtx;o.font=`${n} ${i}px ${t}`;const c=e.split(` +`),l=[],u=[],d=[];let h=0,f=0,p=0;const m=i*a;for(let w=0;w0){const T=R-_-r,S={word:$,chars:y,x:_,y:p,width:T,height:i,lineIndex:w,wordIndexInLine:D,globalIndex:f};k.push(S),d.push(S),f++,D++}}const B={text:b,words:k,x:0,y:p,width:M,height:m,lineIndex:w};l.push(B),p+=m}const g=Math.max(...l.map(w=>w.width),0);return{characters:u,words:d,lines:l,totalWidth:g,totalHeight:p}}createFallbackLayout(e,t,i){const n=t*.6,r=e.split(` +`),a=[],o=[],c=[];let l=0,u=0,d=0;const h=t*i;for(let f=0;f0){const R=g-M,I={word:b,chars:A,x:M,y:d,width:R,height:t,lineIndex:f,wordIndexInLine:m.length,globalIndex:u};m.push(I),c.push(I),u++}}const w={text:p,words:m,x:0,y:d,width:g,height:h,lineIndex:f};a.push(w),d+=h}return{characters:o,words:c,lines:a,totalWidth:Math.max(...a.map(f=>f.width),0),totalHeight:d}}calculateAnimatedLayout(e,t){const i=e.animation;if(!i||i.preset==="none")return this.createStaticLayout(e);const n=this.measureText(e.text,e.style.fontFamily,e.style.fontSize,String(e.style.fontWeight),e.style.letterSpacing,e.style.lineHeight),r=t-e.startTime,a=e.duration,o=r<=i.inDuration,c=r>=a-i.outDuration,l=!o&&!c;let u,d;if(o)u=i.inDuration>0?r/i.inDuration:1,d=!0;else if(c){const p=a-i.outDuration;u=i.outDuration>0?(r-p)/i.outDuration:0,d=!1}else u=1,d=!0;const h=i.unit||"character",f=[];for(const p of n.lines){const m=[];for(const b of p.words){const k=[];for(const I of b.chars){let D,B;h==="character"?(D={text:I.char,index:I.globalIndex,totalUnits:n.characters.length,x:I.x,y:I.y,width:I.width,height:I.height},B=n.characters.length):h==="word"?(D={text:b.word,index:b.globalIndex,totalUnits:n.words.length,x:b.x,y:b.y,width:b.width,height:b.height},B=n.words.length):(D={text:p.text,index:p.lineIndex,totalUnits:n.lines.length,x:p.x,y:p.y,width:p.width,height:p.height},B=n.lines.length);const $={unit:{...D,totalUnits:B},progress:l?1:u,isIn:d,animation:i,totalDuration:a},V=lm($);k.push({...I,state:V})}const M={unit:{text:b.word,index:b.globalIndex,totalUnits:n.words.length,x:b.x,y:b.y,width:b.width,height:b.height},progress:l?1:u,isIn:d,animation:i,totalDuration:a},R=h==="word"||h==="line"?lm(M):{opacity:1,scale:{x:1,y:1},rotation:0,offsetX:0,offsetY:0,blur:0};m.push({...b,state:R,animatedChars:k})}const v={unit:{text:p.text,index:p.lineIndex,totalUnits:n.lines.length,x:p.x,y:p.y,width:p.width,height:p.height},progress:l?1:u,isIn:d,animation:i,totalDuration:a},w=h==="line"?lm(v):{opacity:1,scale:{x:1,y:1},rotation:0,offsetX:0,offsetY:0,blur:0};f.push({...p,state:w,animatedWords:m})}return{lines:f,totalWidth:n.totalWidth,totalHeight:n.totalHeight}}createStaticLayout(e){const t=this.measureText(e.text,e.style.fontFamily,e.style.fontSize,String(e.style.fontWeight),e.style.letterSpacing,e.style.lineHeight),i={opacity:1,scale:{x:1,y:1},rotation:0,offsetX:0,offsetY:0,blur:0};return{lines:t.lines.map(r=>({...r,state:i,animatedWords:r.words.map(a=>({...a,state:i,animatedChars:a.chars.map(o=>({...o,state:i}))}))})),totalWidth:t.totalWidth,totalHeight:t.totalHeight}}}new _Y;const TY=[{id:"smileys",name:"Smileys & Emotion",emojis:[{id:"grinning",emoji:"😀",name:"Grinning Face",category:"smileys"},{id:"joy",emoji:"😂",name:"Face with Tears of Joy",category:"smileys"},{id:"heart_eyes",emoji:"😍",name:"Smiling Face with Heart-Eyes",category:"smileys"},{id:"thinking",emoji:"🤔",name:"Thinking Face",category:"smileys"},{id:"sunglasses",emoji:"😎",name:"Smiling Face with Sunglasses",category:"smileys"},{id:"wink",emoji:"😉",name:"Winking Face",category:"smileys"},{id:"thumbsup",emoji:"👍",name:"Thumbs Up",category:"smileys"},{id:"clap",emoji:"👏",name:"Clapping Hands",category:"smileys"},{id:"fire",emoji:"🔥",name:"Fire",category:"smileys"},{id:"heart",emoji:"❤️",name:"Red Heart",category:"smileys"},{id:"star",emoji:"⭐",name:"Star",category:"smileys"},{id:"sparkles",emoji:"✨",name:"Sparkles",category:"smileys"}]},{id:"gestures",name:"Gestures",emojis:[{id:"wave",emoji:"👋",name:"Waving Hand",category:"gestures"},{id:"ok_hand",emoji:"👌",name:"OK Hand",category:"gestures"},{id:"point_up",emoji:"☝️",name:"Index Pointing Up",category:"gestures"},{id:"point_right",emoji:"👉",name:"Backhand Index Pointing Right",category:"gestures"},{id:"raised_hands",emoji:"🙌",name:"Raising Hands",category:"gestures"},{id:"pray",emoji:"🙏",name:"Folded Hands",category:"gestures"},{id:"muscle",emoji:"💪",name:"Flexed Biceps",category:"gestures"},{id:"v",emoji:"✌️",name:"Victory Hand",category:"gestures"}]},{id:"objects",name:"Objects",emojis:[{id:"camera",emoji:"📷",name:"Camera",category:"objects"},{id:"video_camera",emoji:"📹",name:"Video Camera",category:"objects"},{id:"microphone",emoji:"🎤",name:"Microphone",category:"objects"},{id:"headphones",emoji:"🎧",name:"Headphones",category:"objects"},{id:"movie_camera",emoji:"🎥",name:"Movie Camera",category:"objects"},{id:"clapper",emoji:"🎬",name:"Clapper Board",category:"objects"},{id:"trophy",emoji:"🏆",name:"Trophy",category:"objects"},{id:"medal",emoji:"🏅",name:"Sports Medal",category:"objects"},{id:"bell",emoji:"🔔",name:"Bell",category:"objects"},{id:"megaphone",emoji:"📣",name:"Megaphone",category:"objects"}]},{id:"symbols",name:"Symbols",emojis:[{id:"check",emoji:"✅",name:"Check Mark",category:"symbols"},{id:"x",emoji:"❌",name:"Cross Mark",category:"symbols"},{id:"question",emoji:"❓",name:"Question Mark",category:"symbols"},{id:"exclamation",emoji:"❗",name:"Exclamation Mark",category:"symbols"},{id:"100",emoji:"💯",name:"Hundred Points",category:"symbols"},{id:"arrow_right",emoji:"➡️",name:"Right Arrow",category:"symbols"},{id:"arrow_left",emoji:"⬅️",name:"Left Arrow",category:"symbols"},{id:"arrow_up",emoji:"⬆️",name:"Up Arrow",category:"symbols"},{id:"arrow_down",emoji:"⬇️",name:"Down Arrow",category:"symbols"},{id:"new",emoji:"🆕",name:"New",category:"symbols"},{id:"free",emoji:"🆓",name:"Free",category:"symbols"}]},{id:"nature",name:"Nature",emojis:[{id:"sun",emoji:"☀️",name:"Sun",category:"nature"},{id:"moon",emoji:"🌙",name:"Crescent Moon",category:"nature"},{id:"cloud",emoji:"☁️",name:"Cloud",category:"nature"},{id:"rainbow",emoji:"🌈",name:"Rainbow",category:"nature"},{id:"snowflake",emoji:"❄️",name:"Snowflake",category:"nature"},{id:"lightning",emoji:"⚡",name:"Lightning",category:"nature"},{id:"flower",emoji:"🌸",name:"Cherry Blossom",category:"nature"},{id:"tree",emoji:"🌳",name:"Deciduous Tree",category:"nature"}]}];class kY{stickers=new Map;categories=new Map;emojiCategories=TY;constructor(){this.initializeDefaultCategories()}initializeDefaultCategories(){const e=[{id:"arrows",name:"Arrows",icon:"➡️"},{id:"badges",name:"Badges",icon:"🏷️"},{id:"banners",name:"Banners",icon:"🎗️"},{id:"callouts",name:"Callouts",icon:"💬"},{id:"social",name:"Social Media",icon:"📱"},{id:"custom",name:"Custom",icon:"✨"}];for(const t of e)this.categories.set(t.id,t)}addSticker(e){this.stickers.set(e.id,e)}removeSticker(e){return this.stickers.delete(e)}getSticker(e){return this.stickers.get(e)}getAllStickers(){return Array.from(this.stickers.values())}getStickersByCategory(e){return Array.from(this.stickers.values()).filter(t=>t.category===e)}searchStickers(e){const t=e.toLowerCase();return Array.from(this.stickers.values()).filter(i=>i.name.toLowerCase().includes(t)||i.tags?.some(n=>n.toLowerCase().includes(t)))}addCategory(e){this.categories.set(e.id,e)}getCategories(){return Array.from(this.categories.values())}getCategory(e){return this.categories.get(e)}getEmojiCategories(){return this.emojiCategories}getEmojisByCategory(e){return this.emojiCategories.find(i=>i.id===e)?.emojis||[]}getAllEmojis(){return this.emojiCategories.flatMap(e=>e.emojis)}searchEmojis(e){const t=e.toLowerCase();return this.getAllEmojis().filter(i=>i.name.toLowerCase().includes(t))}getEmoji(e){return this.getAllEmojis().find(t=>t.id===e)}createStickerClip(e,t,i,n){return{id:`sticker_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,trackId:t,startTime:i,duration:n,type:"sticker",imageUrl:e.imageUrl,category:e.category,name:e.name,transform:{...oh},keyframes:[]}}createEmojiClip(e,t,i,n){const r=this.emojiToDataUrl(e.emoji);return{id:`emoji_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,trackId:t,startTime:i,duration:n,type:"emoji",imageUrl:r,category:e.category,name:e.name,transform:{...oh},keyframes:[]}}emojiToDataUrl(e,t=128){if(typeof document>"u")return`data:text/plain;base64,${btoa(e)}`;const i=document.createElement("canvas");i.width=t,i.height=t;const n=i.getContext("2d");return n?(n.font=`${t*.8}px "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif`,n.textAlign="center",n.textBaseline="middle",n.fillText(e,t/2,t/2),i.toDataURL("image/png")):`data:text/plain;base64,${btoa(e)}`}async importSticker(e,t,i="custom",n){const r=await this.fileToDataUrl(e),a={id:`custom_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,name:t,category:i,imageUrl:r,tags:n};return this.addSticker(a),a}fileToDataUrl(e){return new Promise((t,i)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>i(new Error("Failed to read file")),n.readAsDataURL(e)})}clearCustomStickers(){for(const[e,t]of this.stickers)t.category==="custom"&&this.stickers.delete(e)}}const Pee=new kY,AY={x:0,y:0,scale:1,rotation:0,anchorX:.5,anchorY:.5},SY="normal",CY=1;class EY{defaultWidth;defaultHeight;canvas=null;ctx=null;constructor(e={}){this.defaultWidth=e.width??1920,this.defaultHeight=e.height??1080}createProject(e=this.defaultWidth,t=this.defaultHeight,i="Untitled"){return{id:Ap(),name:i,width:e,height:t,layers:[],selectedLayerIndex:-1,backgroundColor:"#ffffff"}}importPhoto(e,t,i="Background"){const n=this.createLayer({name:i,type:"image",content:t});return{...e,width:t.width,height:t.height,layers:[n],selectedLayerIndex:0}}createLayer(e={}){return{id:Ap(),name:e.name??"Layer",type:e.type??"image",content:e.content??null,opacity:e.opacity??CY,blendMode:e.blendMode??SY,visible:!0,locked:!1,mask:null,adjustments:[],transform:{...AY}}}addLayer(e,t={}){const i=this.createLayer(t),n=[...e.layers],r=t.insertAt??e.selectedLayerIndex+1,a=Math.max(0,Math.min(r,n.length));return n.splice(a,0,i),{...e,layers:n,selectedLayerIndex:a}}removeLayer(e,t){const i=e.layers.findIndex(a=>a.id===t);if(i===-1)return e;const n=e.layers.filter(a=>a.id!==t);let r=e.selectedLayerIndex;return r>=n.length?r=Math.max(0,n.length-1):r>i&&r--,{...e,layers:n,selectedLayerIndex:n.length>0?r:-1}}reorderLayers(e,t,i){if(t<0||t>=e.layers.length||i<0||i>=e.layers.length)return{success:!1,layers:e.layers,error:"Invalid layer index"};if(t===i)return{success:!0,layers:e.layers};const n=[...e.layers],[r]=n.splice(t,1);return n.splice(i,0,r),{success:!0,layers:n}}setLayerOpacity(e,t,i){const n=Math.max(0,Math.min(1,i));return{...e,layers:e.layers.map(r=>r.id===t?{...r,opacity:n}:r)}}setLayerVisibility(e,t,i){return{...e,layers:e.layers.map(n=>n.id===t?{...n,visible:i??!n.visible}:n)}}setLayerBlendMode(e,t,i){return{...e,layers:e.layers.map(n=>n.id===t?{...n,blendMode:i}:n)}}setLayerTransform(e,t,i){return{...e,layers:e.layers.map(n=>n.id===t?{...n,transform:{...n.transform,...i}}:n)}}setLayerLocked(e,t,i){return{...e,layers:e.layers.map(n=>n.id===t?{...n,locked:i}:n)}}renameLayer(e,t,i){return{...e,layers:e.layers.map(n=>n.id===t?{...n,name:i}:n)}}duplicateLayer(e,t){const i=e.layers.find(o=>o.id===t);if(!i)return e;const n=e.layers.findIndex(o=>o.id===t),r={...i,id:Ap(),name:`${i.name} Copy`},a=[...e.layers];return a.splice(n+1,0,r),{...e,layers:a,selectedLayerIndex:n+1}}selectLayer(e,t){const i=e.layers.findIndex(n=>n.id===t);return i===-1?e:{...e,selectedLayerIndex:i}}getSelectedLayer(e){return e.selectedLayerIndex<0||e.selectedLayerIndex>=e.layers.length?null:e.layers[e.selectedLayerIndex]}getLayer(e,t){return e.layers.find(i=>i.id===t)??null}async renderComposite(e,t={}){const i=t.width??e.width,n=t.height??e.height,r=t.includeHidden??!1,a=t.backgroundColor??e.backgroundColor;(!this.canvas||this.canvas.width!==i||this.canvas.height!==n)&&(this.canvas=new OffscreenCanvas(i,n),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}));const o=this.ctx;o.fillStyle=a,o.fillRect(0,0,i,n);for(const c of e.layers)!c.visible&&!r||!c.content&&c.type==="image"||(o.globalAlpha=c.opacity,o.globalCompositeOperation=this.getCanvasBlendMode(c.blendMode),c.content&&(o.save(),this.applyLayerTransform(o,c,i,n),o.drawImage(c.content,0,0),o.restore()));return o.globalAlpha=1,o.globalCompositeOperation="source-over",createImageBitmap(this.canvas)}applyLayerTransform(e,t,i,n){const{transform:r,content:a}=t;if(!a)return;const o=a.width,c=a.height,l=o*r.anchorX,u=c*r.anchorY;e.translate(r.x+l,r.y+u),e.rotate(r.rotation*Math.PI/180),e.scale(r.scale,r.scale),e.translate(-l,-u)}getCanvasBlendMode(e){return{normal:"source-over",multiply:"multiply",screen:"screen",overlay:"overlay",softLight:"soft-light",hardLight:"hard-light",colorDodge:"color-dodge",colorBurn:"color-burn",difference:"difference",exclusion:"exclusion",hue:"hue",saturation:"saturation",color:"color",luminosity:"luminosity"}[e]??"source-over"}async flattenLayers(e){if(e.layers.length===0)return e;const t=await this.renderComposite(e),i=this.createLayer({name:"Flattened",type:"image",content:t});return{...e,layers:[i],selectedLayerIndex:0}}async mergeLayerDown(e,t){const i=e.layers.findIndex(u=>u.id===t);if(i<=0)return e;const n=e.layers[i],r=e.layers[i-1],a={...e,layers:[r,n],backgroundColor:"transparent"},o=await this.renderComposite(a),c={...r,content:o,name:r.name},l=[...e.layers];return l.splice(i-1,2,c),{...e,layers:l,selectedLayerIndex:Math.min(e.selectedLayerIndex,l.length-1)}}canModifyLayer(e,t){const i=this.getLayer(e,t);return i!==null&&!i.locked}getVisibleLayers(e){return e.layers.filter(t=>t.visible)}getLayerCount(e){return e.layers.length}dispose(){this.canvas=null,this.ctx=null}}let um=null;function MY(){return um||(um=new EY),um}const ge="full",Ri=s=>({controlId:s}),se=(s,e,t=1,i=1,n=0,r=.5,a=.5)=>({position:{x:s,y:e},scale:{x:t,y:i},rotation:n,anchor:{x:r,y:a},opacity:1}),Ve=s=>s,be=s=>s,lP=[{id:"cinema-letterbox",name:"Cinematic Letterbox",description:"Wide-screen bars with grain and vignette.",category:"cinema",thumbnailUrl:null,previewUrl:null,tags:["cinema","letterbox","grain"],supportedTargets:["video","image"],controls:[{id:"grainAmount",label:"Grain",type:"number",defaultValue:.3,min:0,max:1,step:.05},{id:"barOpacity",label:"Bar Opacity",type:"number",defaultValue:1,min:0,max:1,step:.05}],recipe:{effects:[{type:"film-grain",params:{intensity:Ri("grainAmount"),size:1.5}},{type:"vignette",params:{intensity:.4,radius:.8}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.05),content:{shapeType:"rectangle",width:1920,height:120,style:{fill:{type:"solid",color:"#000000",opacity:Ri("barOpacity")},stroke:{color:"#000000",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.95),content:{shapeType:"rectangle",width:1920,height:120,style:{fill:{type:"solid",color:"#000000",opacity:Ri("barOpacity")},stroke:{color:"#000000",width:0,opacity:0}}}})],audioEffects:[]}},{id:"cinema-light-frame",name:"Light Frame",description:"A subtle warm edge frame for cinematic shots.",category:"cinema",thumbnailUrl:null,previewUrl:null,tags:["cinema","frame","warm"],supportedTargets:["video","image"],controls:[{id:"frameOpacity",label:"Frame Opacity",type:"number",defaultValue:.22,min:0,max:.8,step:.02}],recipe:{effects:[{type:"contrast",params:{value:.08}},{type:"brightness",params:{value:.03}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),blendOpacity:Ri("frameOpacity"),content:{shapeType:"rectangle",width:1820,height:980,style:{fill:{type:"none",opacity:0},stroke:{color:"#f8c89a",width:8,opacity:1}}}})],audioEffects:[]}},{id:"cinema-warm-fade",name:"Warm Fade",description:"Soft warm grade for lifestyle and travel cuts.",category:"cinema",thumbnailUrl:null,previewUrl:null,tags:["cinema","warm","travel"],supportedTargets:["video","image"],controls:[{id:"warmth",label:"Warmth",type:"number",defaultValue:.14,min:0,max:.4,step:.01}],recipe:{effects:[{type:"brightness",params:{value:.02}},{type:"contrast",params:{value:.1}},{type:"saturation",params:{value:Ri("warmth")}}],overlays:[],audioEffects:[]}},{id:"glitch-digital",name:"Digital Glitch",description:"RGB drift with moving scanline accents.",category:"glitch",thumbnailUrl:null,previewUrl:null,tags:["glitch","rgb","scanline"],supportedTargets:["video","image"],controls:[{id:"glitchAmount",label:"Glitch",type:"number",defaultValue:.18,min:0,max:.6,step:.02}],recipe:{effects:[{type:"chromatic-aberration",params:{intensity:4}},{type:"film-grain",params:{intensity:Ri("glitchAmount"),size:2}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.2),keyframes:[{time:0,property:"position.y",value:.18},{time:.4,property:"position.y",value:.74},{time:.8,property:"position.y",value:.32},{time:1,property:"position.y",value:.86}],content:{shapeType:"rectangle",width:1920,height:32,style:{fill:{type:"solid",color:"rgba(0,255,255,0.12)",opacity:1},stroke:{color:"rgba(0,255,255,0.12)",width:0,opacity:0}}}})],audioEffects:[]}},{id:"glitch-rgb-scan",name:"RGB Scan",description:"Thin scanlines and channel separation.",category:"glitch",thumbnailUrl:null,previewUrl:null,tags:["glitch","scan","rgb"],supportedTargets:["video","image"],recipe:{effects:[{type:"chromatic-aberration",params:{intensity:6}},{type:"contrast",params:{value:.08}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1920,height:1020,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,0,128,0.25)",width:2,opacity:1}}}})],audioEffects:[]}},{id:"glitch-static-frame",name:"Static Frame",description:"Noisy border treatment with light distortion.",category:"glitch",thumbnailUrl:null,previewUrl:null,tags:["glitch","static","noise"],supportedTargets:["video","image"],recipe:{effects:[{type:"film-grain",params:{intensity:.45,size:2.3}},{type:"contrast",params:{value:.15}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1860,height:1020,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.18)",width:12,opacity:1}}}})],audioEffects:[]}},{id:"retro-vhs",name:"VHS Tape",description:"Classic tape softness with transport text.",category:"retro",thumbnailUrl:null,previewUrl:null,tags:["retro","vhs","tape"],supportedTargets:["video","image"],recipe:{effects:[{type:"chromatic-aberration",params:{intensity:3}},{type:"film-grain",params:{intensity:.6,size:2.5}},{type:"blur",params:{radius:.5}},{type:"vignette",params:{intensity:.45,radius:.7}}],overlays:[Ve({type:"text",trackType:"text",timing:ge,transform:se(.08,.9,1,1,0,0,.5),content:{text:"PLAY >",style:{fontFamily:"JetBrains Mono",fontSize:28,color:"rgba(255,255,255,0.85)",fontWeight:600,textAlign:"left",verticalAlign:"middle",lineHeight:1.1,letterSpacing:1}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.92,.9,1,1,0,1,.5),content:{text:"SP",style:{fontFamily:"JetBrains Mono",fontSize:22,color:"rgba(255,255,255,0.65)",fontWeight:600,textAlign:"right",verticalAlign:"middle",lineHeight:1.1,letterSpacing:1}}})],audioEffects:[]}},{id:"retro-crt-monitor",name:"CRT Monitor",description:"Soft corner frame and green terminal vibe.",category:"retro",thumbnailUrl:null,previewUrl:null,tags:["retro","crt","monitor"],supportedTargets:["video","image"],recipe:{effects:[{type:"contrast",params:{value:.12}},{type:"brightness",params:{value:-.04}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1840,height:1e3,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(105,255,173,0.25)",width:6,opacity:1},cornerRadius:18}}})],audioEffects:[]}},{id:"retro-old-film",name:"Old Film",description:"High grain monochrome with gate marker text.",category:"retro",thumbnailUrl:null,previewUrl:null,tags:["retro","film","mono"],supportedTargets:["video","image"],recipe:{effects:[{type:"film-grain",params:{intensity:.75,size:2.8}},{type:"contrast",params:{value:.22}},{type:"brightness",params:{value:-.08}}],overlays:[Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:1.2},transform:se(.08,.08,1,1,0,0,.5),content:{text:"ROLL 04",style:{fontFamily:"JetBrains Mono",fontSize:22,color:"rgba(255,255,255,0.8)",fontWeight:600,textAlign:"left",verticalAlign:"middle",lineHeight:1.1,letterSpacing:1}}})],audioEffects:[]}},{id:"retro-sepia-drift",name:"Sepia Drift",description:"Subtle vintage warmth with a soft border.",category:"retro",thumbnailUrl:null,previewUrl:null,tags:["retro","sepia","vintage"],supportedTargets:["video","image"],recipe:{effects:[{type:"brightness",params:{value:.04}},{type:"contrast",params:{value:.06}},{type:"saturation",params:{value:-.08}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),blendOpacity:.3,content:{shapeType:"rectangle",width:1860,height:1020,style:{fill:{type:"none",opacity:0},stroke:{color:"#7d5b39",width:10,opacity:1}}}})],audioEffects:[]}},{id:"social-recording",name:"Recording Camera",description:"Classic REC indicator, timer, and frame border.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","rec","recording"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.045,.055),emphasisAnimation:{type:"pulse",speed:1,intensity:.55,loop:!0},content:{shapeType:"circle",width:14,height:14,style:{fill:{type:"solid",color:"#ff4d4d",opacity:1},stroke:{color:"#ff4d4d",width:0,opacity:0}}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.075,.055,1,1,0,0,.5),content:{text:"REC",style:{fontFamily:"Inter",fontSize:18,color:"#ff4d4d",fontWeight:700,textAlign:"left",verticalAlign:"middle",lineHeight:1.1,letterSpacing:2}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.94,.06,1,1,0,1,.5),content:{text:"00:00:00",style:{fontFamily:"JetBrains Mono",fontSize:18,color:"rgba(255,255,255,0.85)",fontWeight:600,textAlign:"right",verticalAlign:"middle",lineHeight:1.1,letterSpacing:1}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1760,height:920,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.32)",width:4,opacity:1}}}})],audioEffects:[]}},{id:"social-facecam-frame",name:"Facecam Frame",description:"Corner frame for reaction and gameplay clips.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","facecam","reaction"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.78,.76),content:{shapeType:"rectangle",width:560,height:320,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.9)",width:6,opacity:1},cornerRadius:22}}})],audioEffects:[]}},{id:"social-countdown-lead",name:"Countdown Lead",description:"Short intro count-in for tutorials and hooks.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","countdown","hook"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:2},transform:se(.5,.18),keyframes:[{time:0,property:"opacity",value:0},{time:.2,property:"opacity",value:1},{time:.8,property:"opacity",value:1},{time:1,property:"opacity",value:0}],content:{text:"3 2 1",style:{fontFamily:"Inter",fontSize:82,color:"#ffffff",fontWeight:800,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:8}}})],audioEffects:[]}},{id:"social-comment-pop",name:"Comment Pop",description:"Pinned comment bubble for social callouts.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","comment","bubble"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:{kind:"intro",duration:3},transform:se(.5,.15),content:{shapeType:"rectangle",width:1080,height:140,style:{fill:{type:"solid",color:"rgba(255,255,255,0.92)",opacity:1},stroke:{color:"rgba(0,0,0,0.08)",width:2,opacity:1},cornerRadius:999}}}),Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:3},transform:se(.5,.15),content:{text:"Pinned: Drop your best take below",style:{fontFamily:"Inter",fontSize:30,color:"#111111",fontWeight:700,textAlign:"center",verticalAlign:"middle",lineHeight:1.1,letterSpacing:0}}})],audioEffects:[]}},{id:"branding-watermark-drift",name:"Watermark Drift",description:"Soft moving corner watermark for brand protection.",category:"branding",thumbnailUrl:null,previewUrl:null,tags:["branding","watermark","corner"],supportedTargets:["video","image"],controls:[{id:"watermarkText",label:"Watermark",type:"text",defaultValue:"@openreel"},{id:"watermarkOpacity",label:"Opacity",type:"number",defaultValue:.45,min:.1,max:1,step:.05}],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:ge,transform:se(.88,.92,1,1,0,1,.5),keyframes:[{time:0,property:"position.x",value:.88},{time:.5,property:"position.x",value:.84},{time:1,property:"position.x",value:.88}],blendOpacity:Ri("watermarkOpacity"),content:{text:"{control.watermarkText}",style:{fontFamily:"Inter",fontSize:22,color:"rgba(255,255,255,0.92)",fontWeight:600,textAlign:"right",verticalAlign:"middle",lineHeight:1.1,letterSpacing:.5}}})],audioEffects:[]}},{id:"branding-copyright",name:"Moving Copyright",description:"Full-width copyright crawl for delivered cuts.",category:"branding",thumbnailUrl:null,previewUrl:null,tags:["branding","copyright","crawl"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:ge,transform:se(.5,.95),keyframes:[{time:0,property:"position.x",value:1.2},{time:.1,property:"position.x",value:.5},{time:.9,property:"position.x",value:.5},{time:1,property:"position.x",value:-.2}],content:{text:"Copyright {year} All Rights Reserved",style:{fontFamily:"Inter",fontSize:18,color:"rgba(255,255,255,0.7)",fontWeight:500,textAlign:"center",verticalAlign:"middle",lineHeight:1.1,letterSpacing:.5}}})],audioEffects:[]}},{id:"branding-lower-third",name:"Lower Third",description:"Simple branded name tag.",category:"branding",thumbnailUrl:null,previewUrl:null,tags:["branding","lower third","name"],supportedTargets:["video","image"],controls:[{id:"name",label:"Name",type:"text",defaultValue:"Open Reel"},{id:"role",label:"Role",type:"text",defaultValue:"Creator"},{id:"accent",label:"Accent",type:"color",defaultValue:"#7bf1a8"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:{kind:"intro",duration:4},transform:se(.18,.88,1,1,0,0,.5),content:{shapeType:"rectangle",width:520,height:124,style:{fill:{type:"solid",color:"rgba(7,7,10,0.76)",opacity:1},stroke:{color:Ri("accent"),width:4,opacity:1},cornerRadius:18}}}),Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:4},transform:se(.11,.865,1,1,0,0,.5),content:{text:"{control.name}",style:{fontFamily:"Inter",fontSize:34,color:"#ffffff",fontWeight:800,textAlign:"left",verticalAlign:"middle",lineHeight:1.1,letterSpacing:0}}}),Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:4},transform:se(.11,.905,1,1,0,0,.5),content:{text:"{control.role}",style:{fontFamily:"Inter",fontSize:22,color:"rgba(255,255,255,0.72)",fontWeight:500,textAlign:"left",verticalAlign:"middle",lineHeight:1.1,letterSpacing:0}}})],audioEffects:[]}},{id:"branding-subscribe-tag",name:"Subscribe Tag",description:"End-card subscribe banner.",category:"branding",thumbnailUrl:null,previewUrl:null,tags:["branding","subscribe","end card"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:{kind:"outro",duration:3.5},transform:se(.5,.88),content:{shapeType:"rectangle",width:760,height:110,style:{fill:{type:"solid",color:"#ff3b30",opacity:1},stroke:{color:"#ff3b30",width:0,opacity:0},cornerRadius:999}}}),Ve({type:"text",trackType:"text",timing:{kind:"outro",duration:3.5},transform:se(.5,.88),content:{text:"Subscribe for the next drop",style:{fontFamily:"Inter",fontSize:28,color:"#ffffff",fontWeight:800,textAlign:"center",verticalAlign:"middle",lineHeight:1.1,letterSpacing:.5}}})],audioEffects:[]}},{id:"color-warm-pop",name:"Warm Pop",description:"Golden warmth with gentle contrast.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","warm","pop"],supportedTargets:["video","image"],recipe:{effects:[{type:"brightness",params:{value:.05}},{type:"contrast",params:{value:.12}},{type:"saturation",params:{value:.14}}],overlays:[],audioEffects:[]}},{id:"color-cool-bloom",name:"Cool Bloom",description:"Softer cooler palette for night and tech footage.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","cool","tech"],supportedTargets:["video","image"],recipe:{effects:[{type:"brightness",params:{value:-.02}},{type:"contrast",params:{value:.08}},{type:"saturation",params:{value:-.08}}],overlays:[],audioEffects:[]}},{id:"color-dramatic-noir",name:"Dramatic Noir",description:"High-contrast moody look.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","dramatic","noir"],supportedTargets:["video","image"],recipe:{effects:[{type:"contrast",params:{value:.2}},{type:"brightness",params:{value:-.08}},{type:"vignette",params:{intensity:.55,radius:.72}}],overlays:[],audioEffects:[]}},{id:"color-vintage-wash",name:"Vintage Wash",description:"Low-contrast faded stock feel.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","vintage","fade"],supportedTargets:["video","image"],recipe:{effects:[{type:"brightness",params:{value:.08}},{type:"contrast",params:{value:-.05}},{type:"saturation",params:{value:-.12}}],overlays:[],audioEffects:[]}},{id:"overlay-focus-frame",name:"Focus Frame",description:"Center guide frame with crosshair accents.",category:"overlay",thumbnailUrl:null,previewUrl:null,tags:["overlay","focus","frame"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1360,height:760,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.4)",width:4,opacity:1}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"line",width:120,height:6,style:{fill:{type:"solid",color:"rgba(255,255,255,0.55)",opacity:1},stroke:{color:"rgba(255,255,255,0.55)",width:0,opacity:0}}}})],audioEffects:[]}},{id:"overlay-soft-border",name:"Soft Border",description:"Thin elegant border for editorial framing.",category:"overlay",thumbnailUrl:null,previewUrl:null,tags:["overlay","border","editorial"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1840,height:1e3,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.24)",width:5,opacity:1}}}})],audioEffects:[]}},{id:"overlay-spotlight-title",name:"Spotlight Title",description:"Headline treatment for hero moments.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","headline","hero"],supportedTargets:["video","image"],controls:[{id:"headline",label:"Headline",type:"text",defaultValue:"Headline"}],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:4},transform:se(.5,.18),content:{text:"{control.headline}",style:{fontFamily:"Inter",fontSize:88,color:"#ffffff",fontWeight:800,textAlign:"center",verticalAlign:"middle",lineHeight:.95,letterSpacing:-1},animation:{preset:"slide-up",inDuration:.45,outDuration:.35,params:{easing:"easeOutCubic"}}}})],audioEffects:[]}},{id:"text-kinetic-punch",name:"Kinetic Punch",description:"Bold text punch-in for transitions and hooks.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","kinetic","hook"],supportedTargets:["video","image"],controls:[{id:"caption",label:"Caption",type:"text",defaultValue:"Watch this"},{id:"accent",label:"Accent",type:"color",defaultValue:"#ffb100"}],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:3},transform:se(.5,.82),emphasisAnimation:{type:"bounce",speed:1,intensity:.5,loop:!0},content:{text:"{control.caption}",style:{fontFamily:"Inter",fontSize:56,color:Ri("accent"),fontWeight:900,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:0},animation:{preset:"pop",inDuration:.3,outDuration:.25,params:{easing:"easeOutBack"}}}})],audioEffects:[]}},{id:"text-stamp-upper",name:"Stamp Upper",description:"Upper-third stamp for chapter labels.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","stamp","chapter"],supportedTargets:["video","image"],controls:[{id:"label",label:"Label",type:"text",defaultValue:"Chapter One"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:{kind:"intro",duration:3.5},transform:se(.5,.12),content:{shapeType:"rectangle",width:720,height:92,style:{fill:{type:"solid",color:"rgba(255,255,255,0.08)",opacity:1},stroke:{color:"rgba(255,255,255,0.42)",width:2,opacity:1},cornerRadius:999}}}),Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:3.5},transform:se(.5,.12),content:{text:"{control.label}",style:{fontFamily:"Inter",fontSize:32,color:"#ffffff",fontWeight:700,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:2}}})],audioEffects:[]}},{id:"text-neon-tag",name:"Neon Tag",description:"Bright tag for music and nightlife content.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","neon","music"],supportedTargets:["video","image"],controls:[{id:"tag",label:"Tag",type:"text",defaultValue:"LIVE SET"}],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:ge,transform:se(.13,.14,1,1,0,0,.5),emphasisAnimation:{type:"glow",speed:1,intensity:.6,loop:!0},content:{text:"{control.tag}",style:{fontFamily:"Inter",fontSize:34,color:"#66f7ff",fontWeight:800,textAlign:"left",verticalAlign:"middle",lineHeight:1,letterSpacing:1}}})],audioEffects:[]}},{id:"social-live-badge",name:"Live Badge",description:"Pulsing LIVE indicator for stream-style overlays.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","live","stream"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.92,.06),emphasisAnimation:{type:"pulse",speed:.8,intensity:.4,loop:!0},content:{shapeType:"rectangle",width:120,height:40,style:{fill:{type:"solid",color:"#ff0000",opacity:1},stroke:{color:"#ff0000",width:0,opacity:0},cornerRadius:8}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.92,.06),content:{text:"LIVE",style:{fontFamily:"Inter",fontSize:16,color:"#ffffff",fontWeight:800,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:2}}})],audioEffects:[]}},{id:"social-hashtag-strip",name:"Hashtag Strip",description:"Bottom hashtag bar for social video posts.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","hashtag","bar"],supportedTargets:["video","image"],controls:[{id:"tags",label:"Hashtags",type:"text",defaultValue:"#openreel #editing #creative"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.94),content:{shapeType:"rectangle",width:1920,height:56,style:{fill:{type:"solid",color:"rgba(0,0,0,0.6)",opacity:1},stroke:{color:"rgba(0,0,0,0)",width:0,opacity:0}}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.5,.94),content:{text:"{control.tags}",style:{fontFamily:"Inter",fontSize:18,color:"rgba(255,255,255,0.9)",fontWeight:600,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:.5}}})],audioEffects:[]}},{id:"cinema-anamorphic-flare",name:"Anamorphic Flare",description:"Top and bottom bars with blue lens flare accents.",category:"cinema",thumbnailUrl:null,previewUrl:null,tags:["cinema","anamorphic","flare"],supportedTargets:["video","image"],recipe:{effects:[{type:"contrast",params:{value:.06}},{type:"vignette",params:{intensity:.3,radius:.85}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.035),content:{shapeType:"rectangle",width:1920,height:80,style:{fill:{type:"solid",color:"#000000",opacity:1},stroke:{color:"#000000",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.965),content:{shapeType:"rectangle",width:1920,height:80,style:{fill:{type:"solid",color:"#000000",opacity:1},stroke:{color:"#000000",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.3,.5),keyframes:[{time:0,property:"position.x",value:.1},{time:.5,property:"position.x",value:.7},{time:1,property:"position.x",value:.1}],content:{shapeType:"rectangle",width:320,height:4,style:{fill:{type:"solid",color:"rgba(100,180,255,0.15)",opacity:1},stroke:{color:"rgba(100,180,255,0)",width:0,opacity:0}}}})],audioEffects:[]}},{id:"cinema-noir-bars",name:"Noir Bars",description:"Heavy letterbox with deep contrast for dramatic scenes.",category:"cinema",thumbnailUrl:null,previewUrl:null,tags:["cinema","noir","dramatic"],supportedTargets:["video","image"],recipe:{effects:[{type:"contrast",params:{value:.18}},{type:"brightness",params:{value:-.06}},{type:"vignette",params:{intensity:.6,radius:.65}},{type:"saturation",params:{value:-.15}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.06),content:{shapeType:"rectangle",width:1920,height:140,style:{fill:{type:"solid",color:"#000000",opacity:1},stroke:{color:"#000000",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.94),content:{shapeType:"rectangle",width:1920,height:140,style:{fill:{type:"solid",color:"#000000",opacity:1},stroke:{color:"#000000",width:0,opacity:0}}}})],audioEffects:[]}},{id:"overlay-grid-guide",name:"Grid Guide",description:"Rule of thirds grid for composition reference.",category:"overlay",thumbnailUrl:null,previewUrl:null,tags:["overlay","grid","composition"],supportedTargets:["video","image"],controls:[{id:"gridOpacity",label:"Grid Opacity",type:"number",defaultValue:.2,min:.05,max:.6,step:.05}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.333,.5),content:{shapeType:"rectangle",width:2,height:1080,style:{fill:{type:"solid",color:"rgba(255,255,255,0.2)",opacity:Ri("gridOpacity")},stroke:{color:"rgba(255,255,255,0)",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.666,.5),content:{shapeType:"rectangle",width:2,height:1080,style:{fill:{type:"solid",color:"rgba(255,255,255,0.2)",opacity:Ri("gridOpacity")},stroke:{color:"rgba(255,255,255,0)",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.333),content:{shapeType:"rectangle",width:1920,height:2,style:{fill:{type:"solid",color:"rgba(255,255,255,0.2)",opacity:Ri("gridOpacity")},stroke:{color:"rgba(255,255,255,0)",width:0,opacity:0}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.666),content:{shapeType:"rectangle",width:1920,height:2,style:{fill:{type:"solid",color:"rgba(255,255,255,0.2)",opacity:Ri("gridOpacity")},stroke:{color:"rgba(255,255,255,0)",width:0,opacity:0}}}})],audioEffects:[]}},{id:"overlay-corner-brackets",name:"Corner Brackets",description:"Elegant corner frame markers for cinematic focus.",category:"overlay",thumbnailUrl:null,previewUrl:null,tags:["overlay","brackets","frame"],supportedTargets:["video","image"],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.08,.1,1,1,0,0,0),content:{shapeType:"rectangle",width:80,height:80,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.6)",width:3,opacity:1}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.92,.1,1,1,0,1,0),content:{shapeType:"rectangle",width:80,height:80,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.6)",width:3,opacity:1}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.08,.9,1,1,0,0,1),content:{shapeType:"rectangle",width:80,height:80,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.6)",width:3,opacity:1}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.92,.9,1,1,0,1,1),content:{shapeType:"rectangle",width:80,height:80,style:{fill:{type:"none",opacity:0},stroke:{color:"rgba(255,255,255,0.6)",width:3,opacity:1}}}})],audioEffects:[]}},{id:"text-subtitle-bar",name:"Subtitle Bar",description:"Bottom subtitle with dark backing for readability.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","subtitle","caption"],supportedTargets:["video","image"],controls:[{id:"subtitle",label:"Subtitle",type:"text",defaultValue:"Your subtitle text here"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.88),content:{shapeType:"rectangle",width:1400,height:64,style:{fill:{type:"solid",color:"rgba(0,0,0,0.7)",opacity:1},stroke:{color:"rgba(0,0,0,0)",width:0,opacity:0},cornerRadius:12}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.5,.88),content:{text:"{control.subtitle}",style:{fontFamily:"Inter",fontSize:28,color:"#ffffff",fontWeight:600,textAlign:"center",verticalAlign:"middle",lineHeight:1.1,letterSpacing:0}}})],audioEffects:[]}},{id:"text-quote-block",name:"Quote Block",description:"Centered quote with decorative marks.",category:"text-effects",thumbnailUrl:null,previewUrl:null,tags:["text","quote","editorial"],supportedTargets:["video","image"],controls:[{id:"quote",label:"Quote",type:"text",defaultValue:"Create something worth sharing."}],recipe:{effects:[],overlays:[Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:5},transform:se(.5,.42),content:{text:"“",style:{fontFamily:"Inter",fontSize:120,color:"rgba(255,255,255,0.2)",fontWeight:900,textAlign:"center",verticalAlign:"middle",lineHeight:.6,letterSpacing:0}}}),Ve({type:"text",trackType:"text",timing:{kind:"intro",duration:5},transform:se(.5,.5),content:{text:"{control.quote}",style:{fontFamily:"Inter",fontSize:36,color:"#ffffff",fontWeight:500,textAlign:"center",verticalAlign:"middle",lineHeight:1.4,letterSpacing:0},animation:{preset:"fade",inDuration:.6,outDuration:.4,params:{easing:"easeOutCubic"}}}})],audioEffects:[]}},{id:"color-teal-orange",name:"Teal & Orange",description:"Hollywood color grading — cool shadows, warm highlights.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","teal","orange","hollywood"],supportedTargets:["video","image"],recipe:{effects:[{type:"contrast",params:{value:.1}},{type:"saturation",params:{value:.12}},{type:"brightness",params:{value:.02}}],overlays:[],audioEffects:[]}},{id:"color-monochrome",name:"Monochrome",description:"Clean black and white with lifted blacks.",category:"color",thumbnailUrl:null,previewUrl:null,tags:["color","monochrome","black","white"],supportedTargets:["video","image"],recipe:{effects:[{type:"saturation",params:{value:-1}},{type:"contrast",params:{value:.15}},{type:"brightness",params:{value:.04}}],overlays:[],audioEffects:[]}},{id:"glitch-datamosh",name:"Datamosh",description:"Heavy grain and color separation for chaotic energy.",category:"glitch",thumbnailUrl:null,previewUrl:null,tags:["glitch","datamosh","chaos"],supportedTargets:["video","image"],recipe:{effects:[{type:"chromatic-aberration",params:{intensity:8}},{type:"film-grain",params:{intensity:.55,size:3}},{type:"contrast",params:{value:.2}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.4),keyframes:[{time:0,property:"position.y",value:.12},{time:.15,property:"position.y",value:.88},{time:.3,property:"position.y",value:.25},{time:.5,property:"position.y",value:.72},{time:.7,property:"position.y",value:.4},{time:.85,property:"position.y",value:.92},{time:1,property:"position.y",value:.15}],content:{shapeType:"rectangle",width:1920,height:16,style:{fill:{type:"solid",color:"rgba(255,0,100,0.08)",opacity:1},stroke:{color:"rgba(255,0,100,0)",width:0,opacity:0}}}})],audioEffects:[]}},{id:"branding-end-card",name:"End Card",description:"Full outro card with name and call to action.",category:"branding",thumbnailUrl:null,previewUrl:null,tags:["branding","end card","outro"],supportedTargets:["video","image"],controls:[{id:"channel",label:"Channel Name",type:"text",defaultValue:"Your Channel"},{id:"cta",label:"Call to Action",type:"text",defaultValue:"Subscribe for more"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:{kind:"outro",duration:5},transform:se(.5,.5),content:{shapeType:"rectangle",width:1920,height:1080,style:{fill:{type:"solid",color:"rgba(0,0,0,0.85)",opacity:1},stroke:{color:"rgba(0,0,0,0)",width:0,opacity:0}}}}),Ve({type:"text",trackType:"text",timing:{kind:"outro",duration:5},transform:se(.5,.42),content:{text:"{control.channel}",style:{fontFamily:"Inter",fontSize:56,color:"#ffffff",fontWeight:800,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:-1},animation:{preset:"fade",inDuration:.5,outDuration:.3,params:{easing:"easeOutCubic"}}}}),Ve({type:"text",trackType:"text",timing:{kind:"outro",duration:5},transform:se(.5,.55),content:{text:"{control.cta}",style:{fontFamily:"Inter",fontSize:24,color:"rgba(255,255,255,0.7)",fontWeight:500,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:.5},animation:{preset:"fade",inDuration:.7,outDuration:.3,params:{easing:"easeOutCubic"}}}})],audioEffects:[]}},{id:"social-viewer-count",name:"Viewer Count",description:"Animated viewer/like counter badge.",category:"social",thumbnailUrl:null,previewUrl:null,tags:["social","viewers","counter"],supportedTargets:["video","image"],controls:[{id:"count",label:"Count",type:"text",defaultValue:"1.2K watching"}],recipe:{effects:[],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.92,.94),content:{shapeType:"rectangle",width:180,height:36,style:{fill:{type:"solid",color:"rgba(0,0,0,0.65)",opacity:1},stroke:{color:"rgba(255,255,255,0.15)",width:1,opacity:1},cornerRadius:18}}}),Ve({type:"text",trackType:"text",timing:ge,transform:se(.92,.94),content:{text:"{control.count}",style:{fontFamily:"Inter",fontSize:13,color:"rgba(255,255,255,0.9)",fontWeight:600,textAlign:"center",verticalAlign:"middle",lineHeight:1,letterSpacing:.3}}})],audioEffects:[]}},{id:"retro-polaroid",name:"Polaroid",description:"White border frame with warm vintage tones.",category:"retro",thumbnailUrl:null,previewUrl:null,tags:["retro","polaroid","frame"],supportedTargets:["video","image"],recipe:{effects:[{type:"brightness",params:{value:.03}},{type:"saturation",params:{value:-.06}},{type:"contrast",params:{value:.05}}],overlays:[be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.5),content:{shapeType:"rectangle",width:1700,height:900,style:{fill:{type:"none",opacity:0},stroke:{color:"#f5f0e8",width:40,opacity:1}}}}),be({type:"shape",trackType:"graphics",timing:ge,transform:se(.5,.94),content:{shapeType:"rectangle",width:1700,height:80,style:{fill:{type:"solid",color:"#f5f0e8",opacity:1},stroke:{color:"#f5f0e8",width:0,opacity:0}}}})],audioEffects:[]}}],IY=new Map(lP.map(s=>[s.id,s]));function PY(){return lP}function $T(s){return IY.get(s)}const Un={position:{x:.5,y:.5},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},RY=/\{([^}]+)\}/g;function DY(s){return typeof s=="object"&&s!==null&&"controlId"in s}function FY(s){return(s.controls||[]).reduce((e,t)=>(e[t.id]=t.defaultValue,e),{})}function LY(s,e={}){return{...FY(s),...e}}function OY(s,e,t={}){const i=LY(s,t);return{template:s,controlValues:i,effects:s.recipe.effects.map((n,r)=>jT(n,e,i,r)),audioEffects:s.recipe.audioEffects.map((n,r)=>jT(n,e,i,r)),overlays:s.recipe.overlays.map((n,r)=>jY(n,e,i,r))}}function I0(s,e,t){const i=e.now??new Date,n={year:`${i.getFullYear()}`,date:i.toISOString().slice(0,10),datetime:i.toISOString(),duration:`${e.clip.duration}`,"clip.id":e.clip.id,"clip.name":e.clip.name??"Clip"};return s.replace(RY,(r,a)=>{if(a.startsWith("control.")){const o=a.slice(8);return`${t[o]??""}`}return n[a]??`{${a}}`})}function BY(s,e){if(s==="full")return{startTime:e.clip.startTime,duration:e.clip.duration};if(s.kind==="intro"){const t=Math.max(0,Math.min(s.duration,e.clip.duration));return{startTime:e.clip.startTime,duration:t}}if(s.kind==="outro"){const t=Math.max(0,Math.min(s.duration,e.clip.duration));return{startTime:e.clip.startTime+Math.max(0,e.clip.duration-t),duration:t}}return $Y(s,e)}function $Y(s,e){const t=s.unit==="fraction"?s.start*e.clip.duration:s.start,i=s.unit==="fraction"?s.end*e.clip.duration:s.end,n=gh(t,0,e.clip.duration),r=gh(i,n,e.clip.duration);return{startTime:e.clip.startTime+n,duration:r-n}}function jT(s,e,t,i){return{id:s.id||`${s.type}-${i+1}`,type:s.type,enabled:s.enabled??!0,params:P0(s.params,e,t),keyframes:NY(s.keyframes||[],e,t)}}function jY(s,e,t,i){const n=BY(s.timing,e),r=UY(s.transform,e,t),a=s.blendOpacity===void 0?void 0:Et(Gt(s.blendOpacity,e,t),1),o=zY(s.emphasisAnimation,e,t),c=VY(s.keyframes||[],n.duration,e,t),l=s.id||`${s.type}-${i+1}`;return s.type==="text"?{id:l,type:"text",trackType:"text",timing:n,transform:r,blendMode:s.blendMode,blendOpacity:a,emphasisAnimation:o,keyframes:c,content:{text:I0(s.content.text,e,t),style:P0(s.content.style||{},e,t),animation:s.content.animation}}:s.type==="shape"?{id:l,type:"shape",trackType:"graphics",timing:n,transform:r,blendMode:s.blendMode,blendOpacity:a,emphasisAnimation:o,keyframes:c,content:{shapeType:s.content.shapeType,width:Et(Gt(s.content.width,e,t),0),height:Et(Gt(s.content.height,e,t),0),style:P0(s.content.style||{},e,t)}}:{id:l,type:"image",trackType:"graphics",timing:n,transform:r,blendMode:s.blendMode,blendOpacity:a,emphasisAnimation:o,keyframes:c,content:{assetId:s.content.assetId,imageUrl:s.content.imageUrl?I0(s.content.imageUrl,e,t):s.content.assetId?e.assetUrls?.[s.content.assetId]:void 0,name:s.content.name}}}function NY(s,e,t){return s.map(i=>({time:gh(i.time,0,1)*e.clip.duration,property:i.property.startsWith("effect.")?i.property:`effect.${i.property}`,value:Gt(i.value,e,t),easing:i.easing||"linear"}))}function VY(s,e,t,i){return s.map(n=>({time:gh(n.time,0,1)*e,property:n.property,value:Gt(n.value,t,i),easing:n.easing||"linear"}))}function UY(s,e,t){return{position:{x:Et(zn(s?.position?.x,e,t),Un.position.x),y:Et(zn(s?.position?.y,e,t),Un.position.y)},scale:{x:Et(zn(s?.scale?.x,e,t),Un.scale.x),y:Et(zn(s?.scale?.y,e,t),Un.scale.y)},rotation:Et(zn(s?.rotation,e,t),Un.rotation),anchor:{x:Et(zn(s?.anchor?.x,e,t),Un.anchor.x),y:Et(zn(s?.anchor?.y,e,t),Un.anchor.y)},opacity:Et(zn(s?.opacity,e,t),Un.opacity)}}function zY(s,e,t){if(s)return{type:s.type,speed:Et(Gt(s.speed,e,t),1),intensity:Et(Gt(s.intensity,e,t),1),loop:s.loop,focusPoint:s.focusPoint?{x:Et(Gt(s.focusPoint.x,e,t),.5),y:Et(Gt(s.focusPoint.y,e,t),.5)}:void 0,zoomScale:s.zoomScale===void 0?void 0:Et(Gt(s.zoomScale,e,t),1),holdDuration:s.holdDuration===void 0?void 0:Et(Gt(s.holdDuration,e,t),0),startTime:s.startTime===void 0?void 0:Et(Gt(s.startTime,e,t),0),animationDuration:s.animationDuration===void 0?void 0:Et(Gt(s.animationDuration,e,t),0)}}function P0(s,e,t){return Object.entries(s).reduce((i,[n,r])=>(i[n]=Gt(r,e,t),i),{})}function zn(s,e,t){if(s!==void 0)return Gt(s,e,t)}function Gt(s,e,t){return typeof s=="string"?I0(s,e,t):typeof s=="number"||typeof s=="boolean"?s:Array.isArray(s)?s.map(i=>Gt(i,e,t)):DY(s)?t[s.controlId]:Object.entries(s).reduce((i,[n,r])=>(i[n]=Gt(r,e,t),i),{})}function Et(s,e){return typeof s=="number"?s:e}function gh(s,e,t){return Math.min(Math.max(s,e),t)}const GY="openreel-templates",Os="templates",WY=1,nt={position:{x:.5,y:.5},scale:{x:1,y:1},rotation:0,anchor:{x:.5,y:.5},opacity:1},dm=[{id:"builtin-youtube-intro",name:"YouTube Intro",description:"10-second animated intro with logo and channel name",category:"youtube",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1920,height:1080,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-video-1",type:"video",name:"Background",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-1",type:"text",name:"Channel Name",clips:[{id:"clip-channel-name",mediaId:"text-channel",trackId:"track-text-1",startTime:1,duration:8,inPoint:0,outPoint:8,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.5}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"channel-name"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:10,markers:[]},placeholders:[{id:"channel-name",type:"text",label:"Channel Name",required:!0,defaultValue:"Your Channel"}],tags:["youtube","intro","animated"],version:"1.0.0"},{id:"builtin-tiktok-promo",name:"TikTok Promo",description:"Vertical 15-second promo with call-to-action text",category:"tiktok",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1920,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-video-1",type:"video",name:"Main Video",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-1",type:"text",name:"CTA Text",clips:[{id:"clip-cta",mediaId:"text-cta",trackId:"track-text-1",startTime:10,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.85}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"cta-text"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:15,markers:[]},placeholders:[{id:"cta-text",type:"text",label:"Call to Action",required:!0,defaultValue:"Swipe Up!"}],tags:["tiktok","vertical","promo"],version:"1.0.0"},{id:"builtin-lower-third",name:"Lower Third",description:"Professional name & title overlay for interviews",category:"lower-third",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1920,height:1080,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-video-1",type:"video",name:"Background Video",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-name",type:"text",name:"Name",clips:[{id:"clip-name",mediaId:"text-name",trackId:"track-text-name",startTime:.5,duration:4,inPoint:0,outPoint:4,effects:[],audioEffects:[],transform:{...nt,position:{x:.15,y:.82}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"name"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-title",type:"text",name:"Title",clips:[{id:"clip-title",mediaId:"text-title",trackId:"track-text-title",startTime:.7,duration:3.8,inPoint:0,outPoint:3.8,effects:[],audioEffects:[],transform:{...nt,position:{x:.15,y:.88}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"title"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:5,markers:[]},placeholders:[{id:"name",type:"text",label:"Name",required:!0,defaultValue:"John Smith"},{id:"title",type:"text",label:"Title/Position",required:!1,defaultValue:"CEO, Company Inc."}],tags:["lower-third","name","title","interview"],version:"1.0.0"},{id:"builtin-slideshow",name:"Photo Slideshow",description:"30-second slideshow with 5 image slots",category:"slideshow",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1920,height:1080,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-images",type:"image",name:"Photos",clips:[{id:"clip-image-1",mediaId:"placeholder-image-1",trackId:"track-images",startTime:0,duration:6,inPoint:0,outPoint:6,effects:[],audioEffects:[],transform:nt,volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"image-1"},{id:"clip-image-2",mediaId:"placeholder-image-2",trackId:"track-images",startTime:6,duration:6,inPoint:0,outPoint:6,effects:[],audioEffects:[],transform:nt,volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"image-2"},{id:"clip-image-3",mediaId:"placeholder-image-3",trackId:"track-images",startTime:12,duration:6,inPoint:0,outPoint:6,effects:[],audioEffects:[],transform:nt,volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"image-3"},{id:"clip-image-4",mediaId:"placeholder-image-4",trackId:"track-images",startTime:18,duration:6,inPoint:0,outPoint:6,effects:[],audioEffects:[],transform:nt,volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"image-4"},{id:"clip-image-5",mediaId:"placeholder-image-5",trackId:"track-images",startTime:24,duration:6,inPoint:0,outPoint:6,effects:[],audioEffects:[],transform:nt,volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"image-5"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-caption",type:"text",name:"Caption",clips:[{id:"clip-caption",mediaId:"text-caption",trackId:"track-text-caption",startTime:2,duration:26,inPoint:0,outPoint:26,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.9}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"caption"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:30,markers:[]},placeholders:[{id:"image-1",type:"media",label:"Photo 1",required:!0},{id:"image-2",type:"media",label:"Photo 2",required:!0},{id:"image-3",type:"media",label:"Photo 3",required:!0},{id:"image-4",type:"media",label:"Photo 4",required:!1},{id:"image-5",type:"media",label:"Photo 5",required:!1},{id:"caption",type:"text",label:"Caption",required:!1,defaultValue:"My Photo Album"}],tags:["slideshow","photos","memories"],version:"1.0.0"},{id:"builtin-instagram-reel",name:"Instagram Reel",description:"30-second vertical reel with animated hook text",category:"instagram",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1920,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-video-1",type:"video",name:"Main Video",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-hook",type:"text",name:"Hook Text",clips:[{id:"clip-hook",mediaId:"text-hook",trackId:"track-text-hook",startTime:.5,duration:4,inPoint:0,outPoint:4,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.15}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"hook-text"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-cta",type:"text",name:"CTA",clips:[{id:"clip-cta-reel",mediaId:"text-cta-reel",trackId:"track-text-cta",startTime:25,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.85}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"cta-text"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:30,markers:[]},placeholders:[{id:"hook-text",type:"text",label:"Hook Text",required:!0,defaultValue:"Wait for it..."},{id:"cta-text",type:"text",label:"Call to Action",required:!1,defaultValue:"Follow for more!"}],tags:["instagram","reel","vertical","hook"],version:"1.0.0"},{id:"builtin-youtube-shorts",name:"YouTube Short",description:"60-second vertical short with title and subscribe CTA",category:"youtube",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1920,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-video-1",type:"video",name:"Main Video",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-title",type:"text",name:"Title",clips:[{id:"clip-title-short",mediaId:"text-title-short",trackId:"track-text-title",startTime:0,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.1}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"title"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-subscribe",type:"text",name:"Subscribe CTA",clips:[{id:"clip-subscribe",mediaId:"text-subscribe",trackId:"track-text-subscribe",startTime:50,duration:10,inPoint:0,outPoint:10,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.9}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"subscribe-cta"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:60,markers:[]},placeholders:[{id:"title",type:"text",label:"Video Title",required:!0,defaultValue:"Did You Know?"},{id:"subscribe-cta",type:"text",label:"Subscribe CTA",required:!1,defaultValue:"Subscribe for more!"}],tags:["youtube","shorts","vertical","subscribe"],version:"1.0.0"},{id:"builtin-quote-card",name:"Quote Card",description:"Animated quote card with author attribution",category:"instagram",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1080,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-bg",type:"graphics",name:"Background",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-quote",type:"text",name:"Quote",clips:[{id:"clip-quote",mediaId:"text-quote",trackId:"track-text-quote",startTime:.5,duration:9,inPoint:0,outPoint:9,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.45}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"quote"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-author",type:"text",name:"Author",clips:[{id:"clip-author",mediaId:"text-author",trackId:"track-text-author",startTime:1.5,duration:8,inPoint:0,outPoint:8,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.7}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"author"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:10,markers:[]},placeholders:[{id:"quote",type:"text",label:"Quote",required:!0,defaultValue:"The only way to do great work is to love what you do."},{id:"author",type:"text",label:"Author",required:!0,defaultValue:"- Steve Jobs"}],tags:["instagram","quote","inspiration","square"],version:"1.0.0"},{id:"builtin-product-promo",name:"Product Promo",description:"15-second TikTok-style product showcase",category:"tiktok",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1920,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-product",type:"video",name:"Product Video",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-headline",type:"text",name:"Headline",clips:[{id:"clip-headline",mediaId:"text-headline",trackId:"track-text-headline",startTime:0,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.12}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"headline"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-price",type:"text",name:"Price",clips:[{id:"clip-price",mediaId:"text-price",trackId:"track-text-price",startTime:5,duration:10,inPoint:0,outPoint:10,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.75}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"price"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-cta-promo",type:"text",name:"CTA",clips:[{id:"clip-cta-promo",mediaId:"text-cta-promo",trackId:"track-text-cta-promo",startTime:10,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.88}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"cta"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:15,markers:[]},placeholders:[{id:"headline",type:"text",label:"Headline",required:!0,defaultValue:"NEW ARRIVAL"},{id:"price",type:"text",label:"Price",required:!0,defaultValue:"$29.99"},{id:"cta",type:"text",label:"Call to Action",required:!0,defaultValue:"Shop Now - Link in Bio!"}],tags:["tiktok","product","promo","ecommerce"],version:"1.0.0"},{id:"builtin-countdown",name:"Countdown Timer",description:"Event countdown with date and title",category:"instagram",thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:{width:1080,height:1920,frameRate:30,sampleRate:48e3,channels:2},timeline:{tracks:[{id:"track-bg-countdown",type:"graphics",name:"Background",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-event",type:"text",name:"Event Name",clips:[{id:"clip-event",mediaId:"text-event",trackId:"track-text-event",startTime:0,duration:10,inPoint:0,outPoint:10,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.25}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"event-name"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-date",type:"text",name:"Date",clips:[{id:"clip-date",mediaId:"text-date",trackId:"track-text-date",startTime:1,duration:9,inPoint:0,outPoint:9,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.6}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"event-date"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1},{id:"track-text-swipe",type:"text",name:"Swipe Up",clips:[{id:"clip-swipe",mediaId:"text-swipe",trackId:"track-text-swipe",startTime:5,duration:5,inPoint:0,outPoint:5,effects:[],audioEffects:[],transform:{...nt,position:{x:.5,y:.9}},volume:1,keyframes:[],isPlaceholder:!0,placeholderId:"swipe-cta"}],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}],subtitles:[],duration:10,markers:[]},placeholders:[{id:"event-name",type:"text",label:"Event Name",required:!0,defaultValue:"LAUNCH DAY"},{id:"event-date",type:"text",label:"Date",required:!0,defaultValue:"January 20th"},{id:"swipe-cta",type:"text",label:"Swipe CTA",required:!1,defaultValue:"Swipe Up for Details"}],tags:["instagram","stories","countdown","event"],version:"1.0.0"}];class qY{db=null;templates=new Map;async initialize(){if(!this.db)return new Promise((e,t)=>{const i=indexedDB.open(GY,WY);i.onerror=()=>t(i.error),i.onsuccess=()=>{this.db=i.result,this.loadBuiltinTemplates(),e()},i.onupgradeneeded=n=>{const r=n.target.result;r.objectStoreNames.contains(Os)||r.createObjectStore(Os,{keyPath:"id"})}})}loadBuiltinTemplates(){for(const e of dm)this.templates.set(e.id,e)}createFromProject(e,t){const i=`template-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,n=this.convertToTemplateTimeline(e.timeline,t.placeholders);return{id:i,name:t.name,description:t.description,category:t.category,thumbnailUrl:null,previewUrl:null,createdAt:Date.now(),modifiedAt:Date.now(),settings:e.settings,timeline:n,placeholders:t.placeholders,tags:t.tags||[],version:"1.0.0"}}convertToTemplateTimeline(e,t){const i=new Set(t.map(a=>a.id)),n=e.tracks.map(a=>({...a,clips:a.clips.map(o=>this.convertToTemplateClip(o,i))})),r=e.subtitles.map(a=>({...a,isPlaceholder:!1}));return{...e,tracks:n,subtitles:r}}convertToTemplateClip(e,t){return{...e,isPlaceholder:t.has(e.mediaId),placeholderId:t.has(e.mediaId)?e.mediaId:void 0}}applyTemplate(e,t){const i=[],n=[],r={...t};for(const u of e.placeholders)!r[u.id]&&u.defaultValue&&(r[u.id]={type:u.type,value:u.defaultValue}),u.required&&!r[u.id]&&i.push(u.label);const a=`project-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,o=this.createMediaFromReplacements(r,e.placeholders),c=e.timeline.tracks.map(u=>{const d=u.clips.map(h=>{const f=this.resolveClipPlaceholder(h,r);if(h.isPlaceholder&&h.placeholderId){const p=e.placeholders.find(m=>m.id===h.placeholderId);if(p?.type==="text"){const m=r[h.placeholderId]?.value||p.defaultValue||"Text";n.push({id:h.id,text:m,placeholderId:h.placeholderId})}}return f});return{...u,clips:d}});return{project:{id:a,name:`${e.name} - Copy`,createdAt:Date.now(),modifiedAt:Date.now(),settings:e.settings,mediaLibrary:{items:o},timeline:{...e.timeline,tracks:c,subtitles:e.timeline.subtitles.map(u=>this.resolveSubtitlePlaceholder(u,r))}},missingPlaceholders:i,textClips:n}}createMediaFromReplacements(e,t){const i=[];for(const n of t){const r=e[n.id];r&&r.type==="media"&&r.mediaBlob&&i.push({id:n.id,name:r.value,type:"image",fileHandle:null,blob:r.mediaBlob,metadata:{duration:0,width:1920,height:1080,frameRate:30,codec:"",sampleRate:0,channels:0,fileSize:r.mediaBlob.size},thumbnailUrl:null,waveformData:null})}return i}resolveClipPlaceholder(e,t){if(!e.isPlaceholder||!e.placeholderId){const{isPlaceholder:c,placeholderId:l,...u}=e;return u}if(!t[e.placeholderId]){const{isPlaceholder:c,placeholderId:l,...u}=e;return u}const{isPlaceholder:n,placeholderId:r,...a}=e,o=e.mediaId.startsWith("text-")||e.mediaId.startsWith("shape-")||e.mediaId.startsWith("svg-");return{...a,mediaId:o?e.mediaId:e.placeholderId}}resolveSubtitlePlaceholder(e,t){if(!e.isPlaceholder||!e.placeholderId){const{isPlaceholder:o,placeholderId:c,...l}=e;return l}const i=t[e.placeholderId];if(!i||i.type!=="text"){const{isPlaceholder:o,placeholderId:c,...l}=e;return l}const{isPlaceholder:n,placeholderId:r,...a}=e;return{...a,text:i.value}}resolvePropertyPath(e,t){const i=t.split(".");let n=e;for(let o=0;o=h.length)return null;n=h[f]}else{if(n[c]===void 0||n[c]===null||typeof n[c]!="object")return null;n=n[c]}}const r=i[i.length-1],a=r.match(/^(\w+)\[(\d+)\]$/);if(a){const[,o,c]=a,l=n[o];if(!Array.isArray(l))return null;const u=parseInt(c,10);return{parent:n,key:o,value:l[u]}}return{parent:n,key:r,value:n[r]}}setPropertyByPath(e,t,i){const n=this.resolvePropertyPath(e,t);if(!n)return!1;const{parent:r,key:a}=n,c=(t.split(".").pop()||"").match(/^(\w+)\[(\d+)\]$/);if(c){const[,l,u]=c,d=r[l];if(!Array.isArray(d))return!1;const h=parseInt(u,10);d[h]=i}else r[a]=i;return!0}validatePlaceholderValue(e,t){if(e.required&&(t==null||t===""))return{placeholderId:e.id,message:`${e.label} is required`,type:"missing"};if(t==null)return null;const i=e.constraints;switch(e.type){case"text":case"subtitle":if(typeof t!="string")return{placeholderId:e.id,message:`${e.label} must be a string`,type:"invalid"};if(i?.maxLength&&t.length>i.maxLength)return{placeholderId:e.id,message:`${e.label} exceeds maximum length of ${i.maxLength}`,type:"constraint"};if(i?.pattern&&!new RegExp(i.pattern).test(t))return{placeholderId:e.id,message:`${e.label} does not match required pattern`,type:"constraint"};break;case"number":if(typeof t!="number")return{placeholderId:e.id,message:`${e.label} must be a number`,type:"invalid"};if(i?.min!==void 0&&ti.max)return{placeholderId:e.id,message:`${e.label} must be at most ${i.max}`,type:"constraint"};break;case"boolean":if(typeof t!="boolean")return{placeholderId:e.id,message:`${e.label} must be a boolean`,type:"invalid"};break;case"color":if(typeof t!="string"||!/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(t))return{placeholderId:e.id,message:`${e.label} must be a valid hex color`,type:"invalid"};break}return i?.allowedValues&&!i.allowedValues.includes(String(t))?{placeholderId:e.id,message:`${e.label} must be one of: ${i.allowedValues.join(", ")}`,type:"constraint"}:null}applyScriptableTemplate(e,t){const i=[],n=[],r=[],a={...t};for(const d of e.placeholders){!a[d.id]&&d.defaultValue!==void 0&&(a[d.id]={type:d.type,value:d.defaultValue});const h=this.validatePlaceholderValue(d,a[d.id]?.value);h&&i.push(h)}const o=`project-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,c=JSON.parse(JSON.stringify(e.timeline));for(const d of e.placeholders){const h=a[d.id];if(h){for(const f of d.targets)this.applyPlaceholderToTarget(c,f,h.value,d,n);if(d.type==="text"){let f=!1;for(const p of d.targets)if(p.clipId)for(const m of c.tracks){const g=m.clips.find(v=>v.id===p.clipId);if(g){r.push({id:g.id,text:String(h.value??d.defaultValue??""),placeholderId:d.id,trackId:m.id,startTime:g.startTime,duration:g.duration,transform:g.transform}),f=!0;break}}if(!f)for(const p of c.tracks){for(const m of p.clips){const g=m;if(g.isPlaceholder&&g.placeholderId===d.id){r.push({id:m.id,text:String(h.value??d.defaultValue??""),placeholderId:d.id,trackId:p.id,startTime:m.startTime,duration:m.duration,transform:m.transform}),f=!0;break}}if(f)break}}}}const l=this.createMediaFromScriptableReplacements(a,e.placeholders);return{project:{id:o,name:`${e.name} - Copy`,createdAt:Date.now(),modifiedAt:Date.now(),settings:e.settings,mediaLibrary:{items:l},timeline:c},result:{success:i.length===0,errors:i,warnings:n},textClips:r}}applyPlaceholderToTarget(e,t,i,n,r){if(t.clipId){for(const a of e.tracks){const o=a.clips.find(c=>c.id===t.clipId);if(o){const c=o;this.setPropertyByPath(c,t.property,i)||r.push(`Failed to set ${t.property} on clip ${t.clipId}`);return}}r.push(`Clip ${t.clipId} not found for placeholder ${n.id}`)}else if(t.trackId){const a=e.tracks.find(o=>o.id===t.trackId);if(a){const o=a;this.setPropertyByPath(o,t.property,i)||r.push(`Failed to set ${t.property} on track ${t.trackId}`)}else r.push(`Track ${t.trackId} not found for placeholder ${n.id}`)}else if(t.effectId){for(const a of e.tracks)for(const o of a.clips){const c=o.effects.find(l=>l.id===t.effectId);if(c){const l=c;this.setPropertyByPath(l,t.property,i)||r.push(`Failed to set ${t.property} on effect ${t.effectId}`);return}}r.push(`Effect ${t.effectId} not found for placeholder ${n.id}`)}}createMediaFromScriptableReplacements(e,t){const i=[];for(const n of t){const r=e[n.id];if(r&&r.type==="media"&&r.mediaBlob){const a=r.mediaBlob,o=r.value;i.push({id:n.id,name:typeof o=="string"?o:n.label,type:"image",fileHandle:null,blob:a,metadata:{duration:0,width:1920,height:1080,frameRate:30,codec:"",sampleRate:0,channels:0,fileSize:a.size},thumbnailUrl:null,waveformData:null})}}return i}async saveTemplate(e){return this.db||await this.initialize(),new Promise((t,i)=>{const a=this.db.transaction([Os],"readwrite").objectStore(Os).put(e);a.onerror=()=>i(a.error),a.onsuccess=()=>{this.templates.set(e.id,e),t()}})}async loadTemplate(e){return this.templates.has(e)?this.templates.get(e)||null:(this.db||await this.initialize(),new Promise((t,i)=>{const a=this.db.transaction([Os],"readonly").objectStore(Os).get(e);a.onerror=()=>i(a.error),a.onsuccess=()=>{const o=a.result;o&&this.templates.set(o.id,o),t(o||null)}}))}async deleteTemplate(e){if(e.startsWith("builtin-"))throw new Error("Cannot delete built-in templates");return this.db||await this.initialize(),new Promise((t,i)=>{const a=this.db.transaction([Os],"readwrite").objectStore(Os).delete(e);a.onerror=()=>i(a.error),a.onsuccess=()=>{this.templates.delete(e),t()}})}async listTemplates(){return this.db||await this.initialize(),new Promise((e,t)=>{const r=this.db.transaction([Os],"readonly").objectStore(Os).getAll();r.onerror=()=>t(r.error),r.onsuccess=()=>{const a=r.result.map(this.toSummary),o=dm.map(this.toSummary);e([...o,...a])}})}getTemplatesByCategory(e){const t=[];for(const i of this.templates.values())i.category===e&&t.push(i);return t}searchTemplates(e){const t=e.toLowerCase(),i=[];for(const n of this.templates.values()){const r=n.name.toLowerCase().includes(t),a=n.description.toLowerCase().includes(t),o=n.tags.some(c=>c.toLowerCase().includes(t));(r||a||o)&&i.push(n)}return i}toSummary(e){return{id:e.id,name:e.name,category:e.category,thumbnailUrl:e.thumbnailUrl,placeholderCount:e.placeholders.length,duration:e.timeline.duration}}getBuiltinTemplates(){return[...dm]}getAllTemplates(){return Array.from(this.templates.values())}}function pn(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function uP(s,e){s.prototype=Object.create(e.prototype),s.prototype.constructor=s,s.__proto__=e}/*! + * GSAP 3.14.2 + * https://gsap.com + * + * @license Copyright 2008-2025, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license + * @author: Jack Doyle, jack@greensock.com +*/var Vi={autoSleep:120,force3D:"auto",nullTargetWarn:1,units:{lineHeight:""}},Fo={duration:.5,overwrite:!1,delay:0},jv,Ht,ze,us=1e8,De=1/us,R0=Math.PI*2,HY=R0/4,YY=0,dP=Math.sqrt,XY=Math.cos,KY=Math.sin,$t=function(e){return typeof e=="string"},ct=function(e){return typeof e=="function"},Fn=function(e){return typeof e=="number"},Nv=function(e){return typeof e>"u"},Zs=function(e){return typeof e=="object"},xi=function(e){return e!==!1},Vv=function(){return typeof window<"u"},Zu=function(e){return ct(e)||$t(e)},hP=typeof ArrayBuffer=="function"&&ArrayBuffer.isView||function(){},ti=Array.isArray,QY=/random\([^)]+\)/g,JY=/,\s*/g,NT=/(?:-?\.?\d|\.)+/gi,fP=/[-+=.]*\d+[.e\-+]*\d*[e\-+]*\d*/g,Ja=/[-+=.]*\d+[.e-]*\d*[a-z%]*/g,hm=/[-+=.]*\d+\.?\d*(?:e-|e\+)?\d*/gi,pP=/[+-]=-?[.\d]+/,ZY=/[^,'"\[\]\s]+/gi,eX=/^[+\-=e\s\d]*\d+[.\d]*([a-z]*|%)\s*$/i,Ke,$s,D0,Uv,Wi={},yh={},mP,gP=function(e){return(yh=Lo(e,Wi))&&ki},zv=function(e,t){return console.warn("Invalid property",e,"set to",t,"Missing plugin? gsap.registerPlugin()")},jl=function(e,t){return!t&&console.warn(e)},yP=function(e,t){return e&&(Wi[e]=t)&&yh&&(yh[e]=t)||Wi},Nl=function(){return 0},tX={suppressEvents:!0,isStart:!0,kill:!1},_d={suppressEvents:!0,kill:!1},iX={suppressEvents:!0},Gv={},or=[],F0={},vP,Di={},fm={},VT=30,Td=[],Wv="",qv=function(e){var t=e[0],i,n;if(Zs(t)||ct(t)||(e=[e]),!(i=(t._gsap||{}).harness)){for(n=Td.length;n--&&!Td[n].targetTest(t););i=Td[n]}for(n=e.length;n--;)e[n]&&(e[n]._gsap||(e[n]._gsap=new UP(e[n],i)))||e.splice(n,1);return e},ua=function(e){return e._gsap||qv(ds(e))[0]._gsap},bP=function(e,t,i){return(i=e[t])&&ct(i)?e[t]():Nv(i)&&e.getAttribute&&e.getAttribute(t)||i},wi=function(e,t){return(e=e.split(",")).forEach(t)||e},mt=function(e){return Math.round(e*1e5)/1e5||0},Ye=function(e){return Math.round(e*1e7)/1e7||0},lo=function(e,t){var i=t.charAt(0),n=parseFloat(t.substr(2));return e=parseFloat(e),i==="+"?e+n:i==="-"?e-n:i==="*"?e*n:e/n},sX=function(e,t){for(var i=t.length,n=0;e.indexOf(t[n])<0&&++no;)a=a._prev;return a?(t._next=a._next,a._next=t):(t._next=e[i],e[i]=t),t._next?t._next._prev=t:e[n]=t,t._prev=a,t.parent=t._dp=e,t},gf=function(e,t,i,n){i===void 0&&(i="_first"),n===void 0&&(n="_last");var r=t._prev,a=t._next;r?r._next=a:e[i]===t&&(e[i]=a),a?a._prev=r:e[n]===t&&(e[n]=r),t._next=t._prev=t.parent=null},gr=function(e,t){e.parent&&(!t||e.parent.autoRemoveChildren)&&e.parent.remove&&e.parent.remove(e),e._act=0},da=function(e,t){if(e&&(!t||t._end>e._dur||t._start<0))for(var i=e;i;)i._dirty=1,i=i.parent;return e},aX=function(e){for(var t=e.parent;t&&t.parent;)t._dirty=1,t.totalDuration(),t=t.parent;return e},L0=function(e,t,i,n){return e._startAt&&(Ht?e._startAt.revert(_d):e.vars.immediateRender&&!e.vars.autoRevert||e._startAt.render(t,!0,n))},oX=function s(e){return!e||e._ts&&s(e.parent)},zT=function(e){return e._repeat?Oo(e._tTime,e=e.duration()+e._rDelay)*e:0},Oo=function(e,t){var i=Math.floor(e=Ye(e/t));return e&&i===e?i-1:i},xh=function(e,t){return(e-t._start)*t._ts+(t._ts>=0?0:t._dirty?t.totalDuration():t._tDur)},yf=function(e){return e._end=Ye(e._start+(e._tDur/Math.abs(e._ts||e._rts||De)||0))},vf=function(e,t){var i=e._dp;return i&&i.smoothChildTiming&&e._ts&&(e._start=Ye(i._time-(e._ts>0?t/e._ts:((e._dirty?e.totalDuration():e._tDur)-t)/-e._ts)),yf(e),i._dirty||da(i,e)),e},kP=function(e,t){var i;if((t._time||!t._dur&&t._initted||t._startDe)&&t.render(i,!0)),da(e,t)._dp&&e._initted&&e._time>=e._dur&&e._ts){if(e._dur=0&&i.totalTime(i._tTime),i=i._dp;e._zTime=-De}},Vs=function(e,t,i,n){return t.parent&&gr(t),t._start=Ye((Fn(i)?i:i||e!==Ke?ns(e,i,t):e._time)+t._delay),t._end=Ye(t._start+(t.totalDuration()/Math.abs(t.timeScale())||0)),TP(e,t,"_first","_last",e._sort?"_start":0),O0(t)||(e._recent=t),n||kP(e,t),e._ts<0&&vf(e,e._tTime),e},AP=function(e,t){return(Wi.ScrollTrigger||zv("scrollTrigger",t))&&Wi.ScrollTrigger.create(t,e)},SP=function(e,t,i,n,r){if(Xv(e,t,r),!e._initted)return 1;if(!i&&e._pt&&!Ht&&(e._dur&&e.vars.lazy!==!1||!e._dur&&e.vars.lazy)&&vP!==Fi.frame)return or.push(e),e._lazy=[r,n],1},cX=function s(e){var t=e.parent;return t&&t._ts&&t._initted&&!t._lock&&(t.rawTime()<0||s(t))},O0=function(e){var t=e.data;return t==="isFromStart"||t==="isStart"},lX=function(e,t,i,n){var r=e.ratio,a=t<0||!t&&(!e._start&&cX(e)&&!(!e._initted&&O0(e))||(e._ts<0||e._dp._ts<0)&&!O0(e))?0:1,o=e._rDelay,c=0,l,u,d;if(o&&e._repeat&&(c=vu(0,e._tDur,t),u=Oo(c,o),e._yoyo&&u&1&&(a=1-a),u!==Oo(e._tTime,o)&&(r=1-a,e.vars.repeatRefresh&&e._initted&&e.invalidate())),a!==r||Ht||n||e._zTime===De||!t&&e._zTime){if(!e._initted&&SP(e,t,n,i,c))return;for(d=e._zTime,e._zTime=t||(i?De:0),i||(i=t&&!d),e.ratio=a,e._from&&(a=1-a),e._time=0,e._tTime=c,l=e._pt;l;)l.r(a,l.d),l=l._next;t<0&&L0(e,t,i,!0),e._onUpdate&&!i&&Oi(e,"onUpdate"),c&&e._repeat&&!i&&e.parent&&Oi(e,"onRepeat"),(t>=e._tDur||t<0)&&e.ratio===a&&(a&&gr(e,1),!i&&!Ht&&(Oi(e,a?"onComplete":"onReverseComplete",!0),e._prom&&e._prom()))}else e._zTime||(e._zTime=t)},uX=function(e,t,i){var n;if(i>t)for(n=e._first;n&&n._start<=i;){if(n.data==="isPause"&&n._start>t)return n;n=n._next}else for(n=e._last;n&&n._start>=i;){if(n.data==="isPause"&&n._start0&&!n&&vf(e,e._tTime=e._tDur*o),e.parent&&yf(e),i||da(e.parent,e),e},GT=function(e){return e instanceof ci?da(e):Bo(e,e._dur)},dX={_start:0,endTime:Nl,totalDuration:Nl},ns=function s(e,t,i){var n=e.labels,r=e._recent||dX,a=e.duration()>=us?r.endTime(!1):e._dur,o,c,l;return $t(t)&&(isNaN(t)||t in n)?(c=t.charAt(0),l=t.substr(-1)==="%",o=t.indexOf("="),c==="<"||c===">"?(o>=0&&(t=t.replace(/=/,"")),(c==="<"?r._start:r.endTime(r._repeat>=0))+(parseFloat(t.substr(1))||0)*(l?(o<0?r:i).totalDuration()/100:1)):o<0?(t in n||(n[t]=a),n[t]):(c=parseFloat(t.charAt(o-1)+t.substr(o+1)),l&&i&&(c=c/100*(ti(i)?i[0]:i).totalDuration()),o>1?s(e,t.substr(0,o-1),i)+c:a+c)):t==null?a:+t},fl=function(e,t,i){var n=Fn(t[1]),r=(n?2:1)+(e<2?0:1),a=t[r],o,c;if(n&&(a.duration=t[1]),a.parent=i,e){for(o=a,c=i;c&&!("immediateRender"in o);)o=c.vars.defaults||{},c=xi(c.vars.inherit)&&c.parent;a.immediateRender=xi(o.immediateRender),e<2?a.runBackwards=1:a.startAt=t[r-1]}return new xt(t[0],a,t[r+1])},Tr=function(e,t){return e||e===0?t(e):t},vu=function(e,t,i){return it?t:i},Qt=function(e,t){return!$t(e)||!(t=eX.exec(e))?"":t[1]},hX=function(e,t,i){return Tr(i,function(n){return vu(e,t,n)})},B0=[].slice,CP=function(e,t){return e&&Zs(e)&&"length"in e&&(!t&&!e.length||e.length-1 in e&&Zs(e[0]))&&!e.nodeType&&e!==$s},fX=function(e,t,i){return i===void 0&&(i=[]),e.forEach(function(n){var r;return $t(n)&&!t||CP(n,1)?(r=i).push.apply(r,ds(n)):i.push(n)})||i},ds=function(e,t,i){return ze&&!t&&ze.selector?ze.selector(e):$t(e)&&!i&&(D0||!$o())?B0.call((t||Uv).querySelectorAll(e),0):ti(e)?fX(e,i):CP(e)?B0.call(e,0):e?[e]:[]},$0=function(e){return e=ds(e)[0]||jl("Invalid scope")||{},function(t){var i=e.current||e.nativeElement||e;return ds(t,i.querySelectorAll?i:i===e?jl("Invalid scope")||Uv.createElement("div"):e)}},EP=function(e){return e.sort(function(){return .5-Math.random()})},MP=function(e){if(ct(e))return e;var t=Zs(e)?e:{each:e},i=ha(t.ease),n=t.from||0,r=parseFloat(t.base)||0,a={},o=n>0&&n<1,c=isNaN(n)||o,l=t.axis,u=n,d=n;return $t(n)?u=d={center:.5,edges:.5,end:1}[n]||0:!o&&c&&(u=n[0],d=n[1]),function(h,f,p){var m=(p||t).length,g=a[m],v,w,b,k,A,M,R,I,D;if(!g){if(D=t.grid==="auto"?0:(t.grid||[1,us])[1],!D){for(R=-us;R<(R=p[D++].getBoundingClientRect().left)&&DR&&(R=A),Am?m-1:l?l==="y"?m/D:D:Math.max(D,m/D))||0)*(n==="edges"?-1:1),g.b=m<0?r-m:r,g.u=Qt(t.amount||t.each)||0,i=i&&m<0?jP(i):i}return m=(g[h]-g.min)/g.max||0,Ye(g.b+(i?i(m):m)*g.v)+g.u}},j0=function(e){var t=Math.pow(10,((e+"").split(".")[1]||"").length);return function(i){var n=Ye(Math.round(parseFloat(i)/e)*e*t);return(n-n%1)/t+(Fn(i)?0:Qt(i))}},IP=function(e,t){var i=ti(e),n,r;return!i&&Zs(e)&&(n=i=e.radius||us,e.values?(e=ds(e.values),(r=!Fn(e[0]))&&(n*=n)):e=j0(e.increment)),Tr(t,i?ct(e)?function(a){return r=e(a),Math.abs(r-a)<=n?r:a}:function(a){for(var o=parseFloat(r?a.x:a),c=parseFloat(r?a.y:0),l=us,u=0,d=e.length,h,f;d--;)r?(h=e[d].x-o,f=e[d].y-c,h=h*h+f*f):h=Math.abs(e[d]-o),hn?r-a:a)})},Vl=function(e){return e.replace(QY,function(t){var i=t.indexOf("[")+1,n=t.substring(i||7,i?t.indexOf("]"):t.length-1).split(JY);return PP(i?n:+n[0],i?0:+n[1],+n[2]||1e-5)})},DP=function(e,t,i,n,r){var a=t-e,o=n-i;return Tr(r,function(c){return i+((c-e)/a*o||0)})},bX=function s(e,t,i,n){var r=isNaN(e+t)?0:function(f){return(1-f)*e+f*t};if(!r){var a=$t(e),o={},c,l,u,d,h;if(i===!0&&(n=1)&&(i=null),a)e={p:e},t={p:t};else if(ti(e)&&!ti(t)){for(u=[],d=e.length,h=d-2,l=1;l(o=Math.abs(o))&&(c=a,r=o);return c},Oi=function(e,t,i){var n=e.vars,r=n[t],a=ze,o=e._ctx,c,l,u;if(r)return c=n[t+"Params"],l=n.callbackScope||e,i&&or.length&&vh(),o&&(ze=o),u=c?r.apply(l,c):r.call(l),ze=a,u},qc=function(e){return gr(e),e.scrollTrigger&&e.scrollTrigger.kill(!!Ht),e.progress()<1&&Oi(e,"onInterrupt"),e},Za,FP=[],LP=function(e){if(e)if(e=!e.name&&e.default||e,Vv()||e.headless){var t=e.name,i=ct(e),n=t&&!i&&e.init?function(){this._props=[]}:e,r={init:Nl,render:Jv,add:Yv,kill:LX,modifier:FX,rawVars:0},a={targetTest:0,get:0,getSetter:Qv,aliases:{},register:0};if($o(),e!==n){if(Di[t])return;qi(n,qi(bh(e,r),a)),Lo(n.prototype,Lo(r,bh(e,a))),Di[n.prop=t]=n,e.targetTest&&(Td.push(n),Gv[t]=1),t=(t==="css"?"CSS":t.charAt(0).toUpperCase()+t.substr(1))+"Plugin"}yP(t,n),e.register&&e.register(ki,n,_i)}else FP.push(e)},Re=255,Hc={aqua:[0,Re,Re],lime:[0,Re,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,Re],navy:[0,0,128],white:[Re,Re,Re],olive:[128,128,0],yellow:[Re,Re,0],orange:[Re,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[Re,0,0],pink:[Re,192,203],cyan:[0,Re,Re],transparent:[Re,Re,Re,0]},pm=function(e,t,i){return e+=e<0?1:e>1?-1:0,(e*6<1?t+(i-t)*e*6:e<.5?i:e*3<2?t+(i-t)*(2/3-e)*6:t)*Re+.5|0},OP=function(e,t,i){var n=e?Fn(e)?[e>>16,e>>8&Re,e&Re]:0:Hc.black,r,a,o,c,l,u,d,h,f,p;if(!n){if(e.substr(-1)===","&&(e=e.substr(0,e.length-1)),Hc[e])n=Hc[e];else if(e.charAt(0)==="#"){if(e.length<6&&(r=e.charAt(1),a=e.charAt(2),o=e.charAt(3),e="#"+r+r+a+a+o+o+(e.length===5?e.charAt(4)+e.charAt(4):"")),e.length===9)return n=parseInt(e.substr(1,6),16),[n>>16,n>>8&Re,n&Re,parseInt(e.substr(7),16)/255];e=parseInt(e.substr(1),16),n=[e>>16,e>>8&Re,e&Re]}else if(e.substr(0,3)==="hsl"){if(n=p=e.match(NT),!t)c=+n[0]%360/360,l=+n[1]/100,u=+n[2]/100,a=u<=.5?u*(l+1):u+l-u*l,r=u*2-a,n.length>3&&(n[3]*=1),n[0]=pm(c+1/3,r,a),n[1]=pm(c,r,a),n[2]=pm(c-1/3,r,a);else if(~e.indexOf("="))return n=e.match(fP),i&&n.length<4&&(n[3]=1),n}else n=e.match(NT)||Hc.transparent;n=n.map(Number)}return t&&!p&&(r=n[0]/Re,a=n[1]/Re,o=n[2]/Re,d=Math.max(r,a,o),h=Math.min(r,a,o),u=(d+h)/2,d===h?c=l=0:(f=d-h,l=u>.5?f/(2-d-h):f/(d+h),c=d===r?(a-o)/f+(ae||v<0)&&(i+=v-t),n+=v,A=n-i,b=A-a,(b>0||w)&&(M=++d.frame,h=A-d.time*1e3,d.time=A=A/1e3,a+=b+(b>=r?4:r-b),k=1),w||(c=l(m)),k)for(f=0;f=v&&f--},_listeners:o},d}(),$o=function(){return!Ul&&Fi.wake()},_e={},wX=/^[\d.\-M][\d.\-,\s]/,_X=/["']/g,TX=function(e){for(var t={},i=e.substr(1,e.length-3).split(":"),n=i[0],r=1,a=i.length,o,c,l;r1&&i.config?i.config.apply(null,~e.indexOf("{")?[TX(t[1])]:kX(e).split(",").map(wP)):_e._CE&&wX.test(e)?_e._CE("",e):i},jP=function(e){return function(t){return 1-e(1-t)}},NP=function s(e,t){for(var i=e._first,n;i;)i instanceof ci?s(i,t):i.vars.yoyoEase&&(!i._yoyo||!i._repeat)&&i._yoyo!==t&&(i.timeline?s(i.timeline,t):(n=i._ease,i._ease=i._yEase,i._yEase=n,i._yoyo=t)),i=i._next},ha=function(e,t){return e&&(ct(e)?e:_e[e]||AX(e))||t},Aa=function(e,t,i,n){i===void 0&&(i=function(c){return 1-t(1-c)}),n===void 0&&(n=function(c){return c<.5?t(c*2)/2:1-t((1-c)*2)/2});var r={easeIn:t,easeOut:i,easeInOut:n},a;return wi(e,function(o){_e[o]=Wi[o]=r,_e[a=o.toLowerCase()]=i;for(var c in r)_e[a+(c==="easeIn"?".in":c==="easeOut"?".out":".inOut")]=_e[o+"."+c]=r[c]}),r},VP=function(e){return function(t){return t<.5?(1-e(1-t*2))/2:.5+e((t-.5)*2)/2}},mm=function s(e,t,i){var n=t>=1?t:1,r=(i||(e?.3:.45))/(t<1?t:1),a=r/R0*(Math.asin(1/n)||0),o=function(u){return u===1?1:n*Math.pow(2,-10*u)*KY((u-a)*r)+1},c=e==="out"?o:e==="in"?function(l){return 1-o(1-l)}:VP(o);return r=R0/r,c.config=function(l,u){return s(e,l,u)},c},gm=function s(e,t){t===void 0&&(t=1.70158);var i=function(a){return a?--a*a*((t+1)*a+t)+1:0},n=e==="out"?i:e==="in"?function(r){return 1-i(1-r)}:VP(i);return n.config=function(r){return s(e,r)},n};wi("Linear,Quad,Cubic,Quart,Quint,Strong",function(s,e){var t=e<5?e+1:e;Aa(s+",Power"+(t-1),e?function(i){return Math.pow(i,t)}:function(i){return i},function(i){return 1-Math.pow(1-i,t)},function(i){return i<.5?Math.pow(i*2,t)/2:1-Math.pow((1-i)*2,t)/2})});_e.Linear.easeNone=_e.none=_e.Linear.easeIn;Aa("Elastic",mm("in"),mm("out"),mm());(function(s,e){var t=1/e,i=2*t,n=2.5*t,r=function(o){return o0?i+(i+this._rDelay)*this._repeat:i):this.totalDuration()&&this._dur},e.totalDuration=function(i){return arguments.length?(this._dirty=0,Bo(this,this._repeat<0?i:(i-this._repeat*this._rDelay)/(this._repeat+1))):this._tDur},e.totalTime=function(i,n){if($o(),!arguments.length)return this._tTime;var r=this._dp;if(r&&r.smoothChildTiming&&this._ts){for(vf(this,i),!r._dp||r.parent||kP(r,this);r&&r.parent;)r.parent._time!==r._start+(r._ts>=0?r._tTime/r._ts:(r.totalDuration()-r._tTime)/-r._ts)&&r.totalTime(r._tTime,!0),r=r.parent;!this.parent&&this._dp.autoRemoveChildren&&(this._ts>0&&i0||!this._tDur&&!i)&&Vs(this._dp,this,this._start-this._delay)}return(this._tTime!==i||!this._dur&&!n||this._initted&&Math.abs(this._zTime)===De||!this._initted&&this._dur&&i||!i&&!this._initted&&(this.add||this._ptLookup))&&(this._ts||(this._pTime=i),xP(this,i,n)),this},e.time=function(i,n){return arguments.length?this.totalTime(Math.min(this.totalDuration(),i+zT(this))%(this._dur+this._rDelay)||(i?this._dur:0),n):this._time},e.totalProgress=function(i,n){return arguments.length?this.totalTime(this.totalDuration()*i,n):this.totalDuration()?Math.min(1,this._tTime/this._tDur):this.rawTime()>=0&&this._initted?1:0},e.progress=function(i,n){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&!(this.iteration()&1)?1-i:i)+zT(this),n):this.duration()?Math.min(1,this._time/this._dur):this.rawTime()>0?1:0},e.iteration=function(i,n){var r=this.duration()+this._rDelay;return arguments.length?this.totalTime(this._time+(i-1)*r,n):this._repeat?Oo(this._tTime,r)+1:1},e.timeScale=function(i,n){if(!arguments.length)return this._rts===-De?0:this._rts;if(this._rts===i)return this;var r=this.parent&&this._ts?xh(this.parent._time,this):this._tTime;return this._rts=+i||0,this._ts=this._ps||i===-De?0:this._rts,this.totalTime(vu(-Math.abs(this._delay),this.totalDuration(),r),n!==!1),yf(this),aX(this)},e.paused=function(i){return arguments.length?(this._ps!==i&&(this._ps=i,i?(this._pTime=this._tTime||Math.max(-this._delay,this.rawTime()),this._ts=this._act=0):($o(),this._ts=this._rts,this.totalTime(this.parent&&!this.parent.smoothChildTiming?this.rawTime():this._tTime||this._pTime,this.progress()===1&&Math.abs(this._zTime)!==De&&(this._tTime-=De)))),this):this._ps},e.startTime=function(i){if(arguments.length){this._start=Ye(i);var n=this.parent||this._dp;return n&&(n._sort||!this.parent)&&Vs(n,this,this._start-this._delay),this}return this._start},e.endTime=function(i){return this._start+(xi(i)?this.totalDuration():this.duration())/Math.abs(this._ts||1)},e.rawTime=function(i){var n=this.parent||this._dp;return n?i&&(!this._ts||this._repeat&&this._time&&this.totalProgress()<1)?this._tTime%(this._dur+this._rDelay):this._ts?xh(n.rawTime(i),this):this._tTime:this._tTime},e.revert=function(i){i===void 0&&(i=iX);var n=Ht;return Ht=i,Hv(this)&&(this.timeline&&this.timeline.revert(i),this.totalTime(-.01,i.suppressEvents)),this.data!=="nested"&&i.kill!==!1&&this.kill(),Ht=n,this},e.globalTime=function(i){for(var n=this,r=arguments.length?i:n.rawTime();n;)r=n._start+r/(Math.abs(n._ts)||1),n=n._dp;return!this.parent&&this._sat?this._sat.globalTime(i):r},e.repeat=function(i){return arguments.length?(this._repeat=i===1/0?-2:i,GT(this)):this._repeat===-2?1/0:this._repeat},e.repeatDelay=function(i){if(arguments.length){var n=this._time;return this._rDelay=i,GT(this),n?this.time(n):this}return this._rDelay},e.yoyo=function(i){return arguments.length?(this._yoyo=i,this):this._yoyo},e.seek=function(i,n){return this.totalTime(ns(this,i),xi(n))},e.restart=function(i,n){return this.play().totalTime(i?-this._delay:0,xi(n)),this._dur||(this._zTime=-De),this},e.play=function(i,n){return i!=null&&this.seek(i,n),this.reversed(!1).paused(!1)},e.reverse=function(i,n){return i!=null&&this.seek(i||this.totalDuration(),n),this.reversed(!0).paused(!1)},e.pause=function(i,n){return i!=null&&this.seek(i,n),this.paused(!0)},e.resume=function(){return this.paused(!1)},e.reversed=function(i){return arguments.length?(!!i!==this.reversed()&&this.timeScale(-this._rts||(i?-De:0)),this):this._rts<0},e.invalidate=function(){return this._initted=this._act=0,this._zTime=-De,this},e.isActive=function(){var i=this.parent||this._dp,n=this._start,r;return!!(!i||this._ts&&this._initted&&i.isActive()&&(r=i.rawTime(!0))>=n&&r1?(n?(a[i]=n,r&&(a[i+"Params"]=r),i==="onUpdate"&&(this._onUpdate=n)):delete a[i],this):a[i]},e.then=function(i){var n=this,r=n._prom;return new Promise(function(a){var o=ct(i)?i:_P,c=function(){var u=n.then;n.then=null,r&&r(),ct(o)&&(o=o(n))&&(o.then||o===n)&&(n.then=u),a(o),n.then=u};n._initted&&n.totalProgress()===1&&n._ts>=0||!n._tTime&&n._ts<0?c():n._prom=c})},e.kill=function(){qc(this)},s}();qi(zl.prototype,{_time:0,_start:0,_end:0,_tTime:0,_tDur:0,_dirty:0,_repeat:0,_yoyo:!1,parent:null,_initted:!1,_rDelay:0,_ts:1,_dp:0,ratio:0,_zTime:-De,_prom:0,_ps:!1,_rts:1});var ci=function(s){uP(e,s);function e(i,n){var r;return i===void 0&&(i={}),r=s.call(this,i)||this,r.labels={},r.smoothChildTiming=!!i.smoothChildTiming,r.autoRemoveChildren=!!i.autoRemoveChildren,r._sort=xi(i.sortChildren),Ke&&Vs(i.parent||Ke,pn(r),n),i.reversed&&r.reverse(),i.paused&&r.paused(!0),i.scrollTrigger&&AP(pn(r),i.scrollTrigger),r}var t=e.prototype;return t.to=function(n,r,a){return fl(0,arguments,this),this},t.from=function(n,r,a){return fl(1,arguments,this),this},t.fromTo=function(n,r,a,o){return fl(2,arguments,this),this},t.set=function(n,r,a){return r.duration=0,r.parent=this,hl(r).repeatDelay||(r.repeat=0),r.immediateRender=!!r.immediateRender,new xt(n,r,ns(this,a),1),this},t.call=function(n,r,a){return Vs(this,xt.delayedCall(0,n,r),a)},t.staggerTo=function(n,r,a,o,c,l,u){return a.duration=r,a.stagger=a.stagger||o,a.onComplete=l,a.onCompleteParams=u,a.parent=this,new xt(n,a,ns(this,c)),this},t.staggerFrom=function(n,r,a,o,c,l,u){return a.runBackwards=1,hl(a).immediateRender=xi(a.immediateRender),this.staggerTo(n,r,a,o,c,l,u)},t.staggerFromTo=function(n,r,a,o,c,l,u,d){return o.startAt=a,hl(o).immediateRender=xi(o.immediateRender),this.staggerTo(n,r,o,c,l,u,d)},t.render=function(n,r,a){var o=this._time,c=this._dirty?this.totalDuration():this._tDur,l=this._dur,u=n<=0?0:Ye(n),d=this._zTime<0!=n<0&&(this._initted||!l),h,f,p,m,g,v,w,b,k,A,M,R;if(this!==Ke&&u>c&&n>=0&&(u=c),u!==this._tTime||a||d){if(o!==this._time&&l&&(u+=this._time-o,n+=this._time-o),h=u,k=this._start,b=this._ts,v=!b,d&&(l||(o=this._zTime),(n||!r)&&(this._zTime=n)),this._repeat){if(M=this._yoyo,g=l+this._rDelay,this._repeat<-1&&n<0)return this.totalTime(g*100+n,r,a);if(h=Ye(u%g),u===c?(m=this._repeat,h=l):(A=Ye(u/g),m=~~A,m&&m===A&&(h=l,m--),h>l&&(h=l)),A=Oo(this._tTime,g),!o&&this._tTime&&A!==m&&this._tTime-A*g-this._dur<=0&&(A=m),M&&m&1&&(h=l-h,R=1),m!==A&&!this._lock){var I=M&&A&1,D=I===(M&&m&1);if(m=o&&n>=0)for(f=this._first;f;){if(p=f._next,(f._act||h>=f._start)&&f._ts&&w!==f){if(f.parent!==this)return this.render(n,r,a);if(f.render(f._ts>0?(h-f._start)*f._ts:(f._dirty?f.totalDuration():f._tDur)+(h-f._start)*f._ts,r,a),h!==this._time||!this._ts&&!v){w=0,p&&(u+=this._zTime=-De);break}}f=p}else{f=this._last;for(var B=n<0?n:h;f;){if(p=f._prev,(f._act||B<=f._end)&&f._ts&&w!==f){if(f.parent!==this)return this.render(n,r,a);if(f.render(f._ts>0?(B-f._start)*f._ts:(f._dirty?f.totalDuration():f._tDur)+(B-f._start)*f._ts,r,a||Ht&&Hv(f)),h!==this._time||!this._ts&&!v){w=0,p&&(u+=this._zTime=B?-De:De);break}}f=p}}if(w&&!r&&(this.pause(),w.render(h>=o?0:-De)._zTime=h>=o?1:-1,this._ts))return this._start=k,yf(this),this.render(n,r,a);this._onUpdate&&!r&&Oi(this,"onUpdate",!0),(u===c&&this._tTime>=this.totalDuration()||!u&&o)&&(k===this._start||Math.abs(b)!==Math.abs(this._ts))&&(this._lock||((n||!l)&&(u===c&&this._ts>0||!u&&this._ts<0)&&gr(this,1),!r&&!(n<0&&!o)&&(u||o||!c)&&(Oi(this,u===c&&n>=0?"onComplete":"onReverseComplete",!0),this._prom&&!(u0)&&this._prom())))}return this},t.add=function(n,r){var a=this;if(Fn(r)||(r=ns(this,r,n)),!(n instanceof zl)){if(ti(n))return n.forEach(function(o){return a.add(o,r)}),this;if($t(n))return this.addLabel(n,r);if(ct(n))n=xt.delayedCall(0,n);else return this}return this!==n?Vs(this,n,r):this},t.getChildren=function(n,r,a,o){n===void 0&&(n=!0),r===void 0&&(r=!0),a===void 0&&(a=!0),o===void 0&&(o=-us);for(var c=[],l=this._first;l;)l._start>=o&&(l instanceof xt?r&&c.push(l):(a&&c.push(l),n&&c.push.apply(c,l.getChildren(!0,r,a)))),l=l._next;return c},t.getById=function(n){for(var r=this.getChildren(1,1,1),a=r.length;a--;)if(r[a].vars.id===n)return r[a]},t.remove=function(n){return $t(n)?this.removeLabel(n):ct(n)?this.killTweensOf(n):(n.parent===this&&gf(this,n),n===this._recent&&(this._recent=this._last),da(this))},t.totalTime=function(n,r){return arguments.length?(this._forcing=1,!this._dp&&this._ts&&(this._start=Ye(Fi.time-(this._ts>0?n/this._ts:(this.totalDuration()-n)/-this._ts))),s.prototype.totalTime.call(this,n,r),this._forcing=0,this):this._tTime},t.addLabel=function(n,r){return this.labels[n]=ns(this,r),this},t.removeLabel=function(n){return delete this.labels[n],this},t.addPause=function(n,r,a){var o=xt.delayedCall(0,r||Nl,a);return o.data="isPause",this._hasPause=1,Vs(this,o,ns(this,n))},t.removePause=function(n){var r=this._first;for(n=ns(this,n);r;)r._start===n&&r.data==="isPause"&&gr(r),r=r._next},t.killTweensOf=function(n,r,a){for(var o=this.getTweensOf(n,a),c=o.length;c--;)Zn!==o[c]&&o[c].kill(n,r);return this},t.getTweensOf=function(n,r){for(var a=[],o=ds(n),c=this._first,l=Fn(r),u;c;)c instanceof xt?sX(c._targets,o)&&(l?(!Zn||c._initted&&c._ts)&&c.globalTime(0)<=r&&c.globalTime(c.totalDuration())>r:!r||c.isActive())&&a.push(c):(u=c.getTweensOf(o,r)).length&&a.push.apply(a,u),c=c._next;return a},t.tweenTo=function(n,r){r=r||{};var a=this,o=ns(a,n),c=r,l=c.startAt,u=c.onStart,d=c.onStartParams,h=c.immediateRender,f,p=xt.to(a,qi({ease:r.ease||"none",lazy:!1,immediateRender:!1,time:o,overwrite:"auto",duration:r.duration||Math.abs((o-(l&&"time"in l?l.time:a._time))/a.timeScale())||De,onStart:function(){if(a.pause(),!f){var g=r.duration||Math.abs((o-(l&&"time"in l?l.time:a._time))/a.timeScale());p._dur!==g&&Bo(p,g,0,1).render(p._time,!0,!0),f=1}u&&u.apply(p,d||[])}},r));return h?p.render(0):p},t.tweenFromTo=function(n,r,a){return this.tweenTo(r,qi({startAt:{time:ns(this,n)}},a))},t.recent=function(){return this._recent},t.nextLabel=function(n){return n===void 0&&(n=this._time),WT(this,ns(this,n))},t.previousLabel=function(n){return n===void 0&&(n=this._time),WT(this,ns(this,n),1)},t.currentLabel=function(n){return arguments.length?this.seek(n,!0):this.previousLabel(this._time+De)},t.shiftChildren=function(n,r,a){a===void 0&&(a=0);var o=this._first,c=this.labels,l;for(n=Ye(n);o;)o._start>=a&&(o._start+=n,o._end+=n),o=o._next;if(r)for(l in c)c[l]>=a&&(c[l]+=n);return da(this)},t.invalidate=function(n){var r=this._first;for(this._lock=0;r;)r.invalidate(n),r=r._next;return s.prototype.invalidate.call(this,n)},t.clear=function(n){n===void 0&&(n=!0);for(var r=this._first,a;r;)a=r._next,this.remove(r),r=a;return this._dp&&(this._time=this._tTime=this._pTime=0),n&&(this.labels={}),da(this)},t.totalDuration=function(n){var r=0,a=this,o=a._last,c=us,l,u,d;if(arguments.length)return a.timeScale((a._repeat<0?a.duration():a.totalDuration())/(a.reversed()?-n:n));if(a._dirty){for(d=a.parent;o;)l=o._prev,o._dirty&&o.totalDuration(),u=o._start,u>c&&a._sort&&o._ts&&!a._lock?(a._lock=1,Vs(a,o,u-o._delay,1)._lock=0):c=u,u<0&&o._ts&&(r-=u,(!d&&!a._dp||d&&d.smoothChildTiming)&&(a._start+=Ye(u/a._ts),a._time-=u,a._tTime-=u),a.shiftChildren(-u,!1,-1/0),c=0),o._end>r&&o._ts&&(r=o._end),o=l;Bo(a,a===Ke&&a._time>r?a._time:r,1,1),a._dirty=0}return a._tDur},e.updateRoot=function(n){if(Ke._ts&&(xP(Ke,xh(n,Ke)),vP=Fi.frame),Fi.frame>=VT){VT+=Vi.autoSleep||120;var r=Ke._first;if((!r||!r._ts)&&Vi.autoSleep&&Fi._listeners.length<2){for(;r&&!r._ts;)r=r._next;r||Fi.sleep()}}},e}(zl);qi(ci.prototype,{_lock:0,_hasPause:0,_forcing:0});var SX=function(e,t,i,n,r,a,o){var c=new _i(this._pt,e,t,0,1,YP,null,r),l=0,u=0,d,h,f,p,m,g,v,w;for(c.b=i,c.e=n,i+="",n+="",(v=~n.indexOf("random("))&&(n=Vl(n)),a&&(w=[i,n],a(w,e,t),i=w[0],n=w[1]),h=i.match(hm)||[];d=hm.exec(n);)p=d[0],m=n.substring(l,d.index),f?f=(f+1)%5:m.substr(-5)==="rgba("&&(f=1),p!==h[u++]&&(g=parseFloat(h[u-1])||0,c._pt={_next:c._pt,p:m||u===1?m:",",s:g,c:p.charAt(1)==="="?lo(g,p)-g:parseFloat(p)-g,m:f&&f<4?Math.round:0},l=hm.lastIndex);return c.c=l")}),k.duration();else{M={};for(I in p)I==="ease"||I==="easeEach"||IX(I,p[I],M,p.easeEach);for(I in M)for(y=M[I].sort(function(S,C){return S.t-C.t}),V=0,A=0;Ac-De&&!u?c:nl&&(h=l)),v=this._yoyo&&p&1,v&&(k=this._yEase,h=l-h),g=Oo(this._tTime,m),h===o&&!a&&this._initted&&p===g)return this._tTime=d,this;p!==g&&(b&&this._yEase&&NP(b,v),this.vars.repeatRefresh&&!v&&!this._lock&&h!==m&&this._initted&&(this._lock=a=1,this.render(Ye(m*p),!0).invalidate()._lock=0))}if(!this._initted){if(SP(this,u?n:h,a,r,d))return this._tTime=0,this;if(o!==this._time&&!(a&&this.vars.repeatRefresh&&p!==g))return this;if(l!==this._dur)return this.render(n,r,a)}if(this._tTime=d,this._time=h,!this._act&&this._ts&&(this._act=1,this._lazy=0),this.ratio=w=(k||this._ease)(h/l),this._from&&(this.ratio=w=1-w),!o&&d&&!r&&!g&&(Oi(this,"onStart"),this._tTime!==d))return this;for(f=this._pt;f;)f.r(w,f.d),f=f._next;b&&b.render(n<0?n:b._dur*b._ease(h/this._dur),r,a)||this._startAt&&(this._zTime=n),this._onUpdate&&!r&&(u&&L0(this,n,r,a),Oi(this,"onUpdate")),this._repeat&&p!==g&&this.vars.onRepeat&&!r&&this.parent&&Oi(this,"onRepeat"),(d===this._tDur||!d)&&this._tTime===d&&(u&&!this._onUpdate&&L0(this,n,!0,!0),(n||!l)&&(d===this._tDur&&this._ts>0||!d&&this._ts<0)&&gr(this,1),!r&&!(u&&!o)&&(d||o||v)&&(Oi(this,d===c?"onComplete":"onReverseComplete",!0),this._prom&&!(d0)&&this._prom()))}return this},t.targets=function(){return this._targets},t.invalidate=function(n){return(!n||!this.vars.runBackwards)&&(this._startAt=0),this._pt=this._op=this._onUpdate=this._lazy=this.ratio=0,this._ptLookup=[],this.timeline&&this.timeline.invalidate(n),s.prototype.invalidate.call(this,n)},t.resetTo=function(n,r,a,o,c){Ul||Fi.wake(),this._ts||this.play();var l=Math.min(this._dur,(this._dp._time-this._start)*this._ts),u;return this._initted||Xv(this,l),u=this._ease(l/this._dur),EX(this,n,r,a,o,u,l,c)?this.resetTo(n,r,a,o,1):(vf(this,0),this.parent||TP(this._dp,this,"_first","_last",this._dp._sort?"_start":0),this.render(0))},t.kill=function(n,r){if(r===void 0&&(r="all"),!n&&(!r||r==="all"))return this._lazy=this._pt=0,this.parent?qc(this):this.scrollTrigger&&this.scrollTrigger.kill(!!Ht),this;if(this.timeline){var a=this.timeline.totalDuration();return this.timeline.killTweensOf(n,r,Zn&&Zn.vars.overwrite!==!0)._first||qc(this),this.parent&&a!==this.timeline.totalDuration()&&Bo(this,this._dur*this.timeline._tDur/a,0,1),this}var o=this._targets,c=n?ds(n):o,l=this._ptLookup,u=this._pt,d,h,f,p,m,g,v;if((!r||r==="all")&&rX(o,c))return r==="all"&&(this._pt=0),qc(this);for(d=this._op=this._op||[],r!=="all"&&($t(r)&&(m={},wi(r,function(w){return m[w]=1}),r=m),r=MX(o,r)),v=o.length;v--;)if(~c.indexOf(o[v])){h=l[v],r==="all"?(d[v]=r,p=h,f={}):(f=d[v]=d[v]||{},p=r);for(m in p)g=h&&h[m],g&&((!("kill"in g.d)||g.d.kill(m)===!0)&&gf(this,g,"_pt"),delete h[m]),f!=="all"&&(f[m]=1)}return this._initted&&!this._pt&&u&&qc(this),this},e.to=function(n,r){return new e(n,r,arguments[2])},e.from=function(n,r){return fl(1,arguments)},e.delayedCall=function(n,r,a,o){return new e(r,0,{immediateRender:!1,lazy:!1,overwrite:!1,delay:n,onComplete:r,onReverseComplete:r,onCompleteParams:a,onReverseCompleteParams:a,callbackScope:o})},e.fromTo=function(n,r,a){return fl(2,arguments)},e.set=function(n,r){return r.duration=0,r.repeatDelay||(r.repeat=0),new e(n,r)},e.killTweensOf=function(n,r,a){return Ke.killTweensOf(n,r,a)},e}(zl);qi(xt.prototype,{_targets:[],_lazy:0,_startAt:0,_op:0,_onInit:0});wi("staggerTo,staggerFrom,staggerFromTo",function(s){xt[s]=function(){var e=new ci,t=B0.call(arguments,0);return t.splice(s==="staggerFromTo"?5:4,0,0),e[s].apply(e,t)}});var Kv=function(e,t,i){return e[t]=i},qP=function(e,t,i){return e[t](i)},PX=function(e,t,i,n){return e[t](n.fp,i)},RX=function(e,t,i){return e.setAttribute(t,i)},Qv=function(e,t){return ct(e[t])?qP:Nv(e[t])&&e.setAttribute?RX:Kv},HP=function(e,t){return t.set(t.t,t.p,Math.round((t.s+t.c*e)*1e6)/1e6,t)},DX=function(e,t){return t.set(t.t,t.p,!!(t.s+t.c*e),t)},YP=function(e,t){var i=t._pt,n="";if(!e&&t.b)n=t.b;else if(e===1&&t.e)n=t.e;else{for(;i;)n=i.p+(i.m?i.m(i.s+i.c*e):Math.round((i.s+i.c*e)*1e4)/1e4)+n,i=i._next;n+=t.c}t.set(t.t,t.p,n,t)},Jv=function(e,t){for(var i=t._pt;i;)i.r(e,i.d),i=i._next},FX=function(e,t,i,n){for(var r=this._pt,a;r;)a=r._next,r.p===n&&r.modifier(e,t,i),r=a},LX=function(e){for(var t=this._pt,i,n;t;)n=t._next,t.p===e&&!t.op||t.op===e?gf(this,t,"_pt"):t.dep||(i=1),t=n;return!i},OX=function(e,t,i,n){n.mSet(e,t,n.m.call(n.tween,i,n.mt),n)},XP=function(e){for(var t=e._pt,i,n,r,a;t;){for(i=t._next,n=r;n&&n.pr>t.pr;)n=n._next;(t._prev=n?n._prev:a)?t._prev._next=t:r=t,(t._next=n)?n._prev=t:a=t,t=i}e._pt=r},_i=function(){function s(t,i,n,r,a,o,c,l,u){this.t=i,this.s=r,this.c=a,this.p=n,this.r=o||HP,this.d=c||this,this.set=l||Kv,this.pr=u||0,this._next=t,t&&(t._prev=this)}var e=s.prototype;return e.modifier=function(i,n,r){this.mSet=this.mSet||this.set,this.set=OX,this.m=i,this.mt=r,this.tween=n},s}();wi(Wv+"parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert,scrollTrigger",function(s){return Gv[s]=1});Wi.TweenMax=Wi.TweenLite=xt;Wi.TimelineLite=Wi.TimelineMax=ci;Ke=new ci({sortChildren:!1,defaults:Fo,autoRemoveChildren:!0,id:"root",smoothChildTiming:!0});Vi.stringFilter=$P;var fa=[],kd={},BX=[],HT=0,$X=0,ym=function(e){return(kd[e]||BX).map(function(t){return t()})},V0=function(){var e=Date.now(),t=[];e-HT>2&&(ym("matchMediaInit"),fa.forEach(function(i){var n=i.queries,r=i.conditions,a,o,c,l;for(o in n)a=$s.matchMedia(n[o]).matches,a&&(c=1),a!==r[o]&&(r[o]=a,l=1);l&&(i.revert(),c&&t.push(i))}),ym("matchMediaRevert"),t.forEach(function(i){return i.onMatch(i,function(n){return i.add(null,n)})}),HT=e,ym("matchMedia"))},KP=function(){function s(t,i){this.selector=i&&$0(i),this.data=[],this._r=[],this.isReverted=!1,this.id=$X++,t&&this.add(t)}var e=s.prototype;return e.add=function(i,n,r){ct(i)&&(r=n,n=i,i=ct);var a=this,o=function(){var l=ze,u=a.selector,d;return l&&l!==a&&l.data.push(a),r&&(a.selector=$0(r)),ze=a,d=n.apply(a,arguments),ct(d)&&a._r.push(d),ze=l,a.selector=u,a.isReverted=!1,d};return a.last=o,i===ct?o(a,function(c){return a.add(null,c)}):i?a[i]=o:o},e.ignore=function(i){var n=ze;ze=null,i(this),ze=n},e.getTweens=function(){var i=[];return this.data.forEach(function(n){return n instanceof s?i.push.apply(i,n.getTweens()):n instanceof xt&&!(n.parent&&n.parent.data==="nested")&&i.push(n)}),i},e.clear=function(){this._r.length=this.data.length=0},e.kill=function(i,n){var r=this;if(i?function(){for(var o=r.getTweens(),c=r.data.length,l;c--;)l=r.data[c],l.data==="isFlip"&&(l.revert(),l.getChildren(!0,!0,!1).forEach(function(u){return o.splice(o.indexOf(u),1)}));for(o.map(function(u){return{g:u._dur||u._delay||u._sat&&!u._sat.vars.immediateRender?u.globalTime(0):-1/0,t:u}}).sort(function(u,d){return d.g-u.g||-1/0}).forEach(function(u){return u.t.revert(i)}),c=r.data.length;c--;)l=r.data[c],l instanceof ci?l.data!=="nested"&&(l.scrollTrigger&&l.scrollTrigger.revert(),l.kill()):!(l instanceof xt)&&l.revert&&l.revert(i);r._r.forEach(function(u){return u(i,r)}),r.isReverted=!0}():this.data.forEach(function(o){return o.kill&&o.kill()}),this.clear(),n)for(var a=fa.length;a--;)fa[a].id===this.id&&fa.splice(a,1)},e.revert=function(i){this.kill(i||{})},s}(),jX=function(){function s(t){this.contexts=[],this.scope=t,ze&&ze.data.push(this)}var e=s.prototype;return e.add=function(i,n,r){Zs(i)||(i={matches:i});var a=new KP(0,r||this.scope),o=a.conditions={},c,l,u;ze&&!a.selector&&(a.selector=ze.selector),this.contexts.push(a),n=a.add("onMatch",n),a.queries=i;for(l in i)l==="all"?u=1:(c=$s.matchMedia(i[l]),c&&(fa.indexOf(a)<0&&fa.push(a),(o[l]=c.matches)&&(u=1),c.addListener?c.addListener(V0):c.addEventListener("change",V0)));return u&&n(a,function(d){return a.add(null,d)}),this},e.revert=function(i){this.kill(i||{})},e.kill=function(i){this.contexts.forEach(function(n){return n.kill(i,!0)})},s}(),wh={registerPlugin:function(){for(var e=arguments.length,t=new Array(e),i=0;i1){var n=e.map(function(u){return ki.quickSetter(u,t,i)}),r=n.length;return function(u){for(var d=r;d--;)n[d](u)}}e=e[0]||{};var a=Di[t],o=ua(e),c=o.harness&&(o.harness.aliases||{})[t]||t,l=a?function(u){var d=new a;Za._pt=0,d.init(e,i?u+i:u,Za,0,[e]),d.render(1,d),Za._pt&&Jv(1,Za)}:o.set(e,c);return a?l:function(u){return l(e,c,i?u+i:u,o,1)}},quickTo:function(e,t,i){var n,r=ki.to(e,qi((n={},n[t]="+=0.1",n.paused=!0,n.stagger=0,n),i||{})),a=function(c,l,u){return r.resetTo(t,c,l,u)};return a.tween=r,a},isTweening:function(e){return Ke.getTweensOf(e,!0).length>0},defaults:function(e){return e&&e.ease&&(e.ease=ha(e.ease,Fo.ease)),UT(Fo,e||{})},config:function(e){return UT(Vi,e||{})},registerEffect:function(e){var t=e.name,i=e.effect,n=e.plugins,r=e.defaults,a=e.extendTimeline;(n||"").split(",").forEach(function(o){return o&&!Di[o]&&!Wi[o]&&jl(t+" effect requires "+o+" plugin.")}),fm[t]=function(o,c,l){return i(ds(o),qi(c||{},r),l)},a&&(ci.prototype[t]=function(o,c,l){return this.add(fm[t](o,Zs(c)?c:(l=c)&&{},this),l)})},registerEase:function(e,t){_e[e]=ha(t)},parseEase:function(e,t){return arguments.length?ha(e,t):_e},getById:function(e){return Ke.getById(e)},exportRoot:function(e,t){e===void 0&&(e={});var i=new ci(e),n,r;for(i.smoothChildTiming=xi(e.smoothChildTiming),Ke.remove(i),i._dp=0,i._time=i._tTime=Ke._time,n=Ke._first;n;)r=n._next,(t||!(!n._dur&&n instanceof xt&&n.vars.onComplete===n._targets[0]))&&Vs(i,n,n._start-n._delay),n=r;return Vs(Ke,i,0),i},context:function(e,t){return e?new KP(e,t):ze},matchMedia:function(e){return new jX(e)},matchMediaRefresh:function(){return fa.forEach(function(e){var t=e.conditions,i,n;for(n in t)t[n]&&(t[n]=!1,i=1);i&&e.revert()})||V0()},addEventListener:function(e,t){var i=kd[e]||(kd[e]=[]);~i.indexOf(t)||i.push(t)},removeEventListener:function(e,t){var i=kd[e],n=i&&i.indexOf(t);n>=0&&i.splice(n,1)},utils:{wrap:yX,wrapYoyo:vX,distribute:MP,random:PP,snap:IP,normalize:gX,getUnit:Qt,clamp:hX,splitColor:OP,toArray:ds,selector:$0,mapRange:DP,pipe:pX,unitize:mX,interpolate:bX,shuffle:EP},install:gP,effects:fm,ticker:Fi,updateRoot:ci.updateRoot,plugins:Di,globalTimeline:Ke,core:{PropTween:_i,globals:yP,Tween:xt,Timeline:ci,Animation:zl,getCache:ua,_removeLinkedListItem:gf,reverting:function(){return Ht},context:function(e){return e&&ze&&(ze.data.push(e),e._ctx=ze),ze},suppressOverwrites:function(e){return jv=e}}};wi("to,from,fromTo,delayedCall,set,killTweensOf",function(s){return wh[s]=xt[s]});Fi.add(ci.updateRoot);Za=wh.to({},{duration:0});var NX=function(e,t){for(var i=e._pt;i&&i.p!==t&&i.op!==t&&i.fp!==t;)i=i._next;return i},VX=function(e,t){var i=e._targets,n,r,a;for(n in t)for(r=i.length;r--;)a=e._ptLookup[r][n],a&&(a=a.d)&&(a._pt&&(a=NX(a,n)),a&&a.modifier&&a.modifier(t[n],e,i[r],n))},vm=function(e,t){return{name:e,headless:1,rawVars:1,init:function(n,r,a){a._onInit=function(o){var c,l;if($t(r)&&(c={},wi(r,function(u){return c[u]=1}),r=c),t){c={};for(l in r)c[l]=t(r[l]);r=c}VX(o,r)}}}},ki=wh.registerPlugin({name:"attr",init:function(e,t,i,n,r){var a,o,c;this.tween=i;for(a in t)c=e.getAttribute(a)||"",o=this.add(e,"setAttribute",(c||0)+"",t[a],n,r,0,0,a),o.op=a,o.b=c,this._props.push(a)},render:function(e,t){for(var i=t._pt;i;)Ht?i.set(i.t,i.p,i.b,i):i.r(e,i.d),i=i._next}},{name:"endArray",headless:1,init:function(e,t){for(var i=t.length;i--;)this.add(e,i,e[i]||0,t[i],0,0,0,0,0,1)}},vm("roundProps",j0),vm("modifiers"),vm("snap",IP))||wh;xt.version=ci.version=ki.version="3.14.2";mP=1;Vv()&&$o();_e.Power0;_e.Power1;_e.Power2;_e.Power3;_e.Power4;_e.Linear;_e.Quad;_e.Cubic;_e.Quart;_e.Quint;_e.Strong;_e.Elastic;_e.Back;_e.SteppedEase;_e.Bounce;_e.Sine;_e.Expo;_e.Circ;/*! + * CSSPlugin 3.14.2 + * https://gsap.com + * + * Copyright 2008-2025, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license + * @author: Jack Doyle, jack@greensock.com +*/var YT,er,uo,Zv,Zr,XT,eb,UX=function(){return typeof window<"u"},Ln={},Vr=180/Math.PI,ho=Math.PI/180,Da=Math.atan2,KT=1e8,tb=/([A-Z])/g,zX=/(left|right|width|margin|padding|x)/i,GX=/[\s,\(]\S/,Ws={autoAlpha:"opacity,visibility",scale:"scaleX,scaleY",alpha:"opacity"},U0=function(e,t){return t.set(t.t,t.p,Math.round((t.s+t.c*e)*1e4)/1e4+t.u,t)},WX=function(e,t){return t.set(t.t,t.p,e===1?t.e:Math.round((t.s+t.c*e)*1e4)/1e4+t.u,t)},qX=function(e,t){return t.set(t.t,t.p,e?Math.round((t.s+t.c*e)*1e4)/1e4+t.u:t.b,t)},HX=function(e,t){return t.set(t.t,t.p,e===1?t.e:e?Math.round((t.s+t.c*e)*1e4)/1e4+t.u:t.b,t)},YX=function(e,t){var i=t.s+t.c*e;t.set(t.t,t.p,~~(i+(i<0?-.5:.5))+t.u,t)},QP=function(e,t){return t.set(t.t,t.p,e?t.e:t.b,t)},JP=function(e,t){return t.set(t.t,t.p,e!==1?t.b:t.e,t)},XX=function(e,t,i){return e.style[t]=i},KX=function(e,t,i){return e.style.setProperty(t,i)},QX=function(e,t,i){return e._gsap[t]=i},JX=function(e,t,i){return e._gsap.scaleX=e._gsap.scaleY=i},ZX=function(e,t,i,n,r){var a=e._gsap;a.scaleX=a.scaleY=i,a.renderTransform(r,a)},eK=function(e,t,i,n,r){var a=e._gsap;a[t]=i,a.renderTransform(r,a)},Ze="transform",Ti=Ze+"Origin",tK=function s(e,t){var i=this,n=this.target,r=n.style,a=n._gsap;if(e in Ln&&r){if(this.tfm=this.tfm||{},e!=="transform")e=Ws[e]||e,~e.indexOf(",")?e.split(",").forEach(function(o){return i.tfm[o]=mn(n,o)}):this.tfm[e]=a.x?a[e]:mn(n,e),e===Ti&&(this.tfm.zOrigin=a.zOrigin);else return Ws.transform.split(",").forEach(function(o){return s.call(i,o,t)});if(this.props.indexOf(Ze)>=0)return;a.svg&&(this.svgo=n.getAttribute("data-svg-origin"),this.props.push(Ti,t,"")),e=Ze}(r||t)&&this.props.push(e,t,r[e])},ZP=function(e){e.translate&&(e.removeProperty("translate"),e.removeProperty("scale"),e.removeProperty("rotate"))},iK=function(){var e=this.props,t=this.target,i=t.style,n=t._gsap,r,a;for(r=0;r=0?QT[a]:"")+e},G0=function(){UX()&&window.document&&(YT=window,er=YT.document,uo=er.documentElement,Zr=z0("div")||{style:{}},z0("div"),Ze=jo(Ze),Ti=Ze+"Origin",Zr.style.cssText="border-width:0;line-height:0;position:absolute;padding:0",t5=!!jo("perspective"),eb=ki.core.reverting,Zv=1)},JT=function(e){var t=e.ownerSVGElement,i=z0("svg",t&&t.getAttribute("xmlns")||"http://www.w3.org/2000/svg"),n=e.cloneNode(!0),r;n.style.display="block",i.appendChild(n),uo.appendChild(i);try{r=n.getBBox()}catch{}return i.removeChild(n),uo.removeChild(i),r},ZT=function(e,t){for(var i=t.length;i--;)if(e.hasAttribute(t[i]))return e.getAttribute(t[i])},i5=function(e){var t,i;try{t=e.getBBox()}catch{t=JT(e),i=1}return t&&(t.width||t.height)||i||(t=JT(e)),t&&!t.width&&!t.x&&!t.y?{x:+ZT(e,["x","cx","x1"])||0,y:+ZT(e,["y","cy","y1"])||0,width:0,height:0}:t},s5=function(e){return!!(e.getCTM&&(!e.parentNode||e.ownerSVGElement)&&i5(e))},yr=function(e,t){if(t){var i=e.style,n;t in Ln&&t!==Ti&&(t=Ze),i.removeProperty?(n=t.substr(0,2),(n==="ms"||t.substr(0,6)==="webkit")&&(t="-"+t),i.removeProperty(n==="--"?t:t.replace(tb,"-$1").toLowerCase())):i.removeAttribute(t)}},tr=function(e,t,i,n,r,a){var o=new _i(e._pt,t,i,0,1,a?JP:QP);return e._pt=o,o.b=n,o.e=r,e._props.push(i),o},ek={deg:1,rad:1,turn:1},sK={grid:1,flex:1},vr=function s(e,t,i,n){var r=parseFloat(i)||0,a=(i+"").trim().substr((r+"").length)||"px",o=Zr.style,c=zX.test(t),l=e.tagName.toLowerCase()==="svg",u=(l?"client":"offset")+(c?"Width":"Height"),d=100,h=n==="px",f=n==="%",p,m,g,v;if(n===a||!r||ek[n]||ek[a])return r;if(a!=="px"&&!h&&(r=s(e,t,i,"px")),v=e.getCTM&&s5(e),(f||a==="%")&&(Ln[t]||~t.indexOf("adius")))return p=v?e.getBBox()[c?"width":"height"]:e[u],mt(f?r/p*d:r/100*p);if(o[c?"width":"height"]=d+(h?a:n),m=n!=="rem"&&~t.indexOf("adius")||n==="em"&&e.appendChild&&!l?e:e.parentNode,v&&(m=(e.ownerSVGElement||{}).parentNode),(!m||m===er||!m.appendChild)&&(m=er.body),g=m._gsap,g&&f&&g.width&&c&&g.time===Fi.time&&!g.uncache)return mt(r/g.width*d);if(f&&(t==="height"||t==="width")){var w=e.style[t];e.style[t]=d+n,p=e[u],w?e.style[t]=w:yr(e,t)}else(f||a==="%")&&!sK[Bi(m,"display")]&&(o.position=Bi(e,"position")),m===e&&(o.position="static"),m.appendChild(Zr),p=Zr[u],m.removeChild(Zr),o.position="absolute";return c&&f&&(g=ua(m),g.time=Fi.time,g.width=m[u]),mt(h?p*r/d:p&&r?d/p*r:0)},mn=function(e,t,i,n){var r;return Zv||G0(),t in Ws&&t!=="transform"&&(t=Ws[t],~t.indexOf(",")&&(t=t.split(",")[0])),Ln[t]&&t!=="transform"?(r=Wl(e,n),r=t!=="transformOrigin"?r[t]:r.svg?r.origin:Th(Bi(e,Ti))+" "+r.zOrigin+"px"):(r=e.style[t],(!r||r==="auto"||n||~(r+"").indexOf("calc("))&&(r=_h[t]&&_h[t](e,t,i)||Bi(e,t)||bP(e,t)||(t==="opacity"?1:0))),i&&!~(r+"").trim().indexOf(" ")?vr(e,t,r,i)+i:r},nK=function(e,t,i,n){if(!i||i==="none"){var r=jo(t,e,1),a=r&&Bi(e,r,1);a&&a!==i?(t=r,i=a):t==="borderColor"&&(i=Bi(e,"borderTopColor"))}var o=new _i(this._pt,e.style,t,0,1,YP),c=0,l=0,u,d,h,f,p,m,g,v,w,b,k,A;if(o.b=i,o.e=n,i+="",n+="",n.substring(0,6)==="var(--"&&(n=Bi(e,n.substring(4,n.indexOf(")")))),n==="auto"&&(m=e.style[t],e.style[t]=n,n=Bi(e,t)||n,m?e.style[t]=m:yr(e,t)),u=[i,n],$P(u),i=u[0],n=u[1],h=i.match(Ja)||[],A=n.match(Ja)||[],A.length){for(;d=Ja.exec(n);)g=d[0],w=n.substring(c,d.index),p?p=(p+1)%5:(w.substr(-5)==="rgba("||w.substr(-5)==="hsla(")&&(p=1),g!==(m=h[l++]||"")&&(f=parseFloat(m)||0,k=m.substr((f+"").length),g.charAt(1)==="="&&(g=lo(f,g)+k),v=parseFloat(g),b=g.substr((v+"").length),c=Ja.lastIndex-b.length,b||(b=b||Vi.units[t]||k,c===n.length&&(n+=b,o.e+=b)),k!==b&&(f=vr(e,t,m,b)||0),o._pt={_next:o._pt,p:w||l===1?w:",",s:f,c:v-f,m:p&&p<4||t==="zIndex"?Math.round:0});o.c=c-1;)o=r[l],Ln[o]&&(c=1,o=o==="transformOrigin"?Ti:Ze),yr(i,o);c&&(yr(i,Ze),a&&(a.svg&&i.removeAttribute("transform"),n.scale=n.rotate=n.translate="none",Wl(i,1),a.uncache=1,ZP(n)))}},_h={clearProps:function(e,t,i,n,r){if(r.data!=="isFromStart"){var a=e._pt=new _i(e._pt,t,i,0,0,aK);return a.u=n,a.pr=-10,a.tween=r,e._props.push(i),1}}},Gl=[1,0,0,1,0,0],n5={},r5=function(e){return e==="matrix(1, 0, 0, 1, 0, 0)"||e==="none"||!e},ik=function(e){var t=Bi(e,Ze);return r5(t)?Gl:t.substr(7).match(fP).map(mt)},ib=function(e,t){var i=e._gsap||ua(e),n=e.style,r=ik(e),a,o,c,l;return i.svg&&e.getAttribute("transform")?(c=e.transform.baseVal.consolidate().matrix,r=[c.a,c.b,c.c,c.d,c.e,c.f],r.join(",")==="1,0,0,1,0,0"?Gl:r):(r===Gl&&!e.offsetParent&&e!==uo&&!i.svg&&(c=n.display,n.display="block",a=e.parentNode,(!a||!e.offsetParent&&!e.getBoundingClientRect().width)&&(l=1,o=e.nextElementSibling,uo.appendChild(e)),r=ik(e),c?n.display=c:yr(e,"display"),l&&(o?a.insertBefore(e,o):a?a.appendChild(e):uo.removeChild(e))),t&&r.length>6?[r[0],r[1],r[4],r[5],r[12],r[13]]:r)},W0=function(e,t,i,n,r,a){var o=e._gsap,c=r||ib(e,!0),l=o.xOrigin||0,u=o.yOrigin||0,d=o.xOffset||0,h=o.yOffset||0,f=c[0],p=c[1],m=c[2],g=c[3],v=c[4],w=c[5],b=t.split(" "),k=parseFloat(b[0])||0,A=parseFloat(b[1])||0,M,R,I,D;i?c!==Gl&&(R=f*g-p*m)&&(I=k*(g/R)+A*(-m/R)+(m*w-g*v)/R,D=k*(-p/R)+A*(f/R)-(f*w-p*v)/R,k=I,A=D):(M=i5(e),k=M.x+(~b[0].indexOf("%")?k/100*M.width:k),A=M.y+(~(b[1]||b[0]).indexOf("%")?A/100*M.height:A)),n||n!==!1&&o.smooth?(v=k-l,w=A-u,o.xOffset=d+(v*f+w*m)-v,o.yOffset=h+(v*p+w*g)-w):o.xOffset=o.yOffset=0,o.xOrigin=k,o.yOrigin=A,o.smooth=!!n,o.origin=t,o.originIsAbsolute=!!i,e.style[Ti]="0px 0px",a&&(tr(a,o,"xOrigin",l,k),tr(a,o,"yOrigin",u,A),tr(a,o,"xOffset",d,o.xOffset),tr(a,o,"yOffset",h,o.yOffset)),e.setAttribute("data-svg-origin",k+" "+A)},Wl=function(e,t){var i=e._gsap||new UP(e);if("x"in i&&!t&&!i.uncache)return i;var n=e.style,r=i.scaleX<0,a="px",o="deg",c=getComputedStyle(e),l=Bi(e,Ti)||"0",u,d,h,f,p,m,g,v,w,b,k,A,M,R,I,D,B,$,V,y,_,T,S,C,E,P,L,O,U,j,N,z;return u=d=h=m=g=v=w=b=k=0,f=p=1,i.svg=!!(e.getCTM&&s5(e)),c.translate&&((c.translate!=="none"||c.scale!=="none"||c.rotate!=="none")&&(n[Ze]=(c.translate!=="none"?"translate3d("+(c.translate+" 0 0").split(" ").slice(0,3).join(", ")+") ":"")+(c.rotate!=="none"?"rotate("+c.rotate+") ":"")+(c.scale!=="none"?"scale("+c.scale.split(" ").join(",")+") ":"")+(c[Ze]!=="none"?c[Ze]:"")),n.scale=n.rotate=n.translate="none"),R=ib(e,i.svg),i.svg&&(i.uncache?(E=e.getBBox(),l=i.xOrigin-E.x+"px "+(i.yOrigin-E.y)+"px",C=""):C=!t&&e.getAttribute("data-svg-origin"),W0(e,C||l,!!C||i.originIsAbsolute,i.smooth!==!1,R)),A=i.xOrigin||0,M=i.yOrigin||0,R!==Gl&&($=R[0],V=R[1],y=R[2],_=R[3],u=T=R[4],d=S=R[5],R.length===6?(f=Math.sqrt($*$+V*V),p=Math.sqrt(_*_+y*y),m=$||V?Da(V,$)*Vr:0,w=y||_?Da(y,_)*Vr+m:0,w&&(p*=Math.abs(Math.cos(w*ho))),i.svg&&(u-=A-(A*$+M*y),d-=M-(A*V+M*_))):(z=R[6],j=R[7],L=R[8],O=R[9],U=R[10],N=R[11],u=R[12],d=R[13],h=R[14],I=Da(z,U),g=I*Vr,I&&(D=Math.cos(-I),B=Math.sin(-I),C=T*D+L*B,E=S*D+O*B,P=z*D+U*B,L=T*-B+L*D,O=S*-B+O*D,U=z*-B+U*D,N=j*-B+N*D,T=C,S=E,z=P),I=Da(-y,U),v=I*Vr,I&&(D=Math.cos(-I),B=Math.sin(-I),C=$*D-L*B,E=V*D-O*B,P=y*D-U*B,N=_*B+N*D,$=C,V=E,y=P),I=Da(V,$),m=I*Vr,I&&(D=Math.cos(I),B=Math.sin(I),C=$*D+V*B,E=T*D+S*B,V=V*D-$*B,S=S*D-T*B,$=C,T=E),g&&Math.abs(g)+Math.abs(m)>359.9&&(g=m=0,v=180-v),f=mt(Math.sqrt($*$+V*V+y*y)),p=mt(Math.sqrt(S*S+z*z)),I=Da(T,S),w=Math.abs(I)>2e-4?I*Vr:0,k=N?1/(N<0?-N:N):0),i.svg&&(C=e.getAttribute("transform"),i.forceCSS=e.setAttribute("transform","")||!r5(Bi(e,Ze)),C&&e.setAttribute("transform",C))),Math.abs(w)>90&&Math.abs(w)<270&&(r?(f*=-1,w+=m<=0?180:-180,m+=m<=0?180:-180):(p*=-1,w+=w<=0?180:-180)),t=t||i.uncache,i.x=u-((i.xPercent=u&&(!t&&i.xPercent||(Math.round(e.offsetWidth/2)===Math.round(-u)?-50:0)))?e.offsetWidth*i.xPercent/100:0)+a,i.y=d-((i.yPercent=d&&(!t&&i.yPercent||(Math.round(e.offsetHeight/2)===Math.round(-d)?-50:0)))?e.offsetHeight*i.yPercent/100:0)+a,i.z=h+a,i.scaleX=mt(f),i.scaleY=mt(p),i.rotation=mt(m)+o,i.rotationX=mt(g)+o,i.rotationY=mt(v)+o,i.skewX=w+o,i.skewY=b+o,i.transformPerspective=k+a,(i.zOrigin=parseFloat(l.split(" ")[2])||!t&&i.zOrigin||0)&&(n[Ti]=Th(l)),i.xOffset=i.yOffset=0,i.force3D=Vi.force3D,i.renderTransform=i.svg?cK:t5?a5:oK,i.uncache=0,i},Th=function(e){return(e=e.split(" "))[0]+" "+e[1]},bm=function(e,t,i){var n=Qt(t);return mt(parseFloat(t)+parseFloat(vr(e,"x",i+"px",n)))+n},oK=function(e,t){t.z="0px",t.rotationY=t.rotationX="0deg",t.force3D=0,a5(e,t)},Or="0deg",Cc="0px",Br=") ",a5=function(e,t){var i=t||this,n=i.xPercent,r=i.yPercent,a=i.x,o=i.y,c=i.z,l=i.rotation,u=i.rotationY,d=i.rotationX,h=i.skewX,f=i.skewY,p=i.scaleX,m=i.scaleY,g=i.transformPerspective,v=i.force3D,w=i.target,b=i.zOrigin,k="",A=v==="auto"&&e&&e!==1||v===!0;if(b&&(d!==Or||u!==Or)){var M=parseFloat(u)*ho,R=Math.sin(M),I=Math.cos(M),D;M=parseFloat(d)*ho,D=Math.cos(M),a=bm(w,a,R*D*-b),o=bm(w,o,-Math.sin(M)*-b),c=bm(w,c,I*D*-b+b)}g!==Cc&&(k+="perspective("+g+Br),(n||r)&&(k+="translate("+n+"%, "+r+"%) "),(A||a!==Cc||o!==Cc||c!==Cc)&&(k+=c!==Cc||A?"translate3d("+a+", "+o+", "+c+") ":"translate("+a+", "+o+Br),l!==Or&&(k+="rotate("+l+Br),u!==Or&&(k+="rotateY("+u+Br),d!==Or&&(k+="rotateX("+d+Br),(h!==Or||f!==Or)&&(k+="skew("+h+", "+f+Br),(p!==1||m!==1)&&(k+="scale("+p+", "+m+Br),w.style[Ze]=k||"translate(0, 0)"},cK=function(e,t){var i=t||this,n=i.xPercent,r=i.yPercent,a=i.x,o=i.y,c=i.rotation,l=i.skewX,u=i.skewY,d=i.scaleX,h=i.scaleY,f=i.target,p=i.xOrigin,m=i.yOrigin,g=i.xOffset,v=i.yOffset,w=i.forceCSS,b=parseFloat(a),k=parseFloat(o),A,M,R,I,D;c=parseFloat(c),l=parseFloat(l),u=parseFloat(u),u&&(u=parseFloat(u),l+=u,c+=u),c||l?(c*=ho,l*=ho,A=Math.cos(c)*d,M=Math.sin(c)*d,R=Math.sin(c-l)*-h,I=Math.cos(c-l)*h,l&&(u*=ho,D=Math.tan(l-u),D=Math.sqrt(1+D*D),R*=D,I*=D,u&&(D=Math.tan(u),D=Math.sqrt(1+D*D),A*=D,M*=D)),A=mt(A),M=mt(M),R=mt(R),I=mt(I)):(A=d,I=h,M=R=0),(b&&!~(a+"").indexOf("px")||k&&!~(o+"").indexOf("px"))&&(b=vr(f,"x",a,"px"),k=vr(f,"y",o,"px")),(p||m||g||v)&&(b=mt(b+p-(p*A+m*R)+g),k=mt(k+m-(p*M+m*I)+v)),(n||r)&&(D=f.getBBox(),b=mt(b+n/100*D.width),k=mt(k+r/100*D.height)),D="matrix("+A+","+M+","+R+","+I+","+b+","+k+")",f.setAttribute("transform",D),w&&(f.style[Ze]=D)},lK=function(e,t,i,n,r){var a=360,o=$t(r),c=parseFloat(r)*(o&&~r.indexOf("rad")?Vr:1),l=c-n,u=n+l+"deg",d,h;return o&&(d=r.split("_")[1],d==="short"&&(l%=a,l!==l%(a/2)&&(l+=l<0?a:-a)),d==="cw"&&l<0?l=(l+a*KT)%a-~~(l/a)*a:d==="ccw"&&l>0&&(l=(l-a*KT)%a-~~(l/a)*a)),e._pt=h=new _i(e._pt,t,i,n,l,WX),h.e=u,h.u="deg",e._props.push(i),h},sk=function(e,t){for(var i in t)e[i]=t[i];return e},uK=function(e,t,i){var n=sk({},i._gsap),r="perspective,force3D,transformOrigin,svgOrigin",a=i.style,o,c,l,u,d,h,f,p;n.svg?(l=i.getAttribute("transform"),i.setAttribute("transform",""),a[Ze]=t,o=Wl(i,1),yr(i,Ze),i.setAttribute("transform",l)):(l=getComputedStyle(i)[Ze],a[Ze]=t,o=Wl(i,1),a[Ze]=l);for(c in Ln)l=n[c],u=o[c],l!==u&&r.indexOf(c)<0&&(f=Qt(l),p=Qt(u),d=f!==p?vr(i,c,l,p):parseFloat(l),h=parseFloat(u),e._pt=new _i(e._pt,o,c,d,h-d,U0),e._pt.u=p||0,e._props.push(c));sk(o,n)};wi("padding,margin,Width,Radius",function(s,e){var t="Top",i="Right",n="Bottom",r="Left",a=(e<3?[t,i,n,r]:[t+r,t+i,n+i,n+r]).map(function(o){return e<2?s+o:"border"+o+s});_h[e>1?"border"+s:s]=function(o,c,l,u,d){var h,f;if(arguments.length<4)return h=a.map(function(p){return mn(o,p,l)}),f=h.join(" "),f.split(h[0]).length===5?h[0]:f;h=(u+"").split(" "),f={},a.forEach(function(p,m){return f[p]=h[m]=h[m]||h[(m-1)/2|0]}),o.init(c,f,d)}});var o5={name:"css",register:G0,targetTest:function(e){return e.style&&e.nodeType},init:function(e,t,i,n,r){var a=this._props,o=e.style,c=i.vars.startAt,l,u,d,h,f,p,m,g,v,w,b,k,A,M,R,I,D;Zv||G0(),this.styles=this.styles||e5(e),I=this.styles.props,this.tween=i;for(m in t)if(m!=="autoRound"&&(u=t[m],!(Di[m]&&zP(m,t,i,n,e,r)))){if(f=typeof u,p=_h[m],f==="function"&&(u=u.call(i,n,e,r),f=typeof u),f==="string"&&~u.indexOf("random(")&&(u=Vl(u)),p)p(this,e,m,u,i)&&(R=1);else if(m.substr(0,2)==="--")l=(getComputedStyle(e).getPropertyValue(m)+"").trim(),u+="",cr.lastIndex=0,cr.test(l)||(g=Qt(l),v=Qt(u),v?g!==v&&(l=vr(e,m,l,v)+v):g&&(u+=g)),this.add(o,"setProperty",l,u,n,r,0,0,m),a.push(m),I.push(m,0,o[m]);else if(f!=="undefined"){if(c&&m in c?(l=typeof c[m]=="function"?c[m].call(i,n,e,r):c[m],$t(l)&&~l.indexOf("random(")&&(l=Vl(l)),Qt(l+"")||l==="auto"||(l+=Vi.units[m]||Qt(mn(e,m))||""),(l+"").charAt(1)==="="&&(l=mn(e,m))):l=mn(e,m),h=parseFloat(l),w=f==="string"&&u.charAt(1)==="="&&u.substr(0,2),w&&(u=u.substr(2)),d=parseFloat(u),m in Ws&&(m==="autoAlpha"&&(h===1&&mn(e,"visibility")==="hidden"&&d&&(h=0),I.push("visibility",0,o.visibility),tr(this,o,"visibility",h?"inherit":"hidden",d?"inherit":"hidden",!d)),m!=="scale"&&m!=="transform"&&(m=Ws[m],~m.indexOf(",")&&(m=m.split(",")[0]))),b=m in Ln,b){if(this.styles.save(m),D=u,f==="string"&&u.substring(0,6)==="var(--"){if(u=Bi(e,u.substring(4,u.indexOf(")"))),u.substring(0,5)==="calc("){var B=e.style.perspective;e.style.perspective=u,u=Bi(e,"perspective"),B?e.style.perspective=B:yr(e,"perspective")}d=parseFloat(u)}if(k||(A=e._gsap,A.renderTransform&&!t.parseTransform||Wl(e,t.parseTransform),M=t.smoothOrigin!==!1&&A.smooth,k=this._pt=new _i(this._pt,o,Ze,0,1,A.renderTransform,A,0,-1),k.dep=1),m==="scale")this._pt=new _i(this._pt,A,"scaleY",A.scaleY,(w?lo(A.scaleY,w+d):d)-A.scaleY||0,U0),this._pt.u=0,a.push("scaleY",m),m+="X";else if(m==="transformOrigin"){I.push(Ti,0,o[Ti]),u=rK(u),A.svg?W0(e,u,0,M,0,this):(v=parseFloat(u.split(" ")[2])||0,v!==A.zOrigin&&tr(this,A,"zOrigin",A.zOrigin,v),tr(this,o,m,Th(l),Th(u)));continue}else if(m==="svgOrigin"){W0(e,u,1,M,0,this);continue}else if(m in n5){lK(this,A,m,h,w?lo(h,w+u):u);continue}else if(m==="smoothOrigin"){tr(this,A,"smooth",A.smooth,u);continue}else if(m==="force3D"){A[m]=u;continue}else if(m==="transform"){uK(this,u,e);continue}}else m in o||(m=jo(m)||m);if(b||(d||d===0)&&(h||h===0)&&!GX.test(u)&&m in o)g=(l+"").substr((h+"").length),d||(d=0),v=Qt(u)||(m in Vi.units?Vi.units[m]:g),g!==v&&(h=vr(e,m,l,v)),this._pt=new _i(this._pt,b?A:o,m,h,(w?lo(h,w+d):d)-h,!b&&(v==="px"||m==="zIndex")&&t.autoRound!==!1?YX:U0),this._pt.u=v||0,b&&D!==u?(this._pt.b=l,this._pt.e=D,this._pt.r=HX):g!==v&&v!=="%"&&(this._pt.b=l,this._pt.r=qX);else if(m in o)nK.call(this,e,m,l,w?w+u:u);else if(m in e)this.add(e,m,l||e[m],w?w+u:u,n,r);else if(m!=="parseTransform"){zv(m,u);continue}b||(m in o?I.push(m,0,o[m]):typeof e[m]=="function"?I.push(m,2,e[m]()):I.push(m,1,l||e[m])),a.push(m)}}R&&XP(this)},render:function(e,t){if(t.tween._time||!eb())for(var i=t._pt;i;)i.r(e,i.d),i=i._next;else t.styles.revert()},get:mn,aliases:Ws,getSetter:function(e,t,i){var n=Ws[t];return n&&n.indexOf(",")<0&&(t=n),t in Ln&&t!==Ti&&(e._gsap.x||mn(e,"x"))?i&&XT===i?t==="scale"?JX:QX:(XT=i||{})&&(t==="scale"?ZX:eK):e.style&&!Nv(e.style[t])?XX:~t.indexOf("-")?KX:Qv(e,t)},core:{_removeProperty:yr,_getMatrix:ib}};ki.utils.checkPrefix=jo;ki.core.getStyleSaver=e5;(function(s,e,t,i){var n=wi(s+","+e+","+t,function(r){Ln[r]=1});wi(e,function(r){Vi.units[r]="deg",n5[r]=1}),Ws[n[13]]=s+","+e,wi(i,function(r){var a=r.split(":");Ws[a[1]]=n[a[0]]})})("x,y,z,scale,scaleX,scaleY,xPercent,yPercent","rotation,rotationX,rotationY,skewX,skewY","transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective","0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY");wi("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective",function(s){Vi.units[s]="px"});ki.registerPlugin(o5);var sb=ki.registerPlugin(o5)||ki;sb.core.Tween;/*! + * paths 3.14.2 + * https://gsap.com + * + * Copyright 2008-2025, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license + * @author: Jack Doyle, jack@greensock.com +*/var dK=/[achlmqstvz]|(-?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,hK=/(?:(-)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,fK=/[\+\-]?\d*\.?\d+e[\+\-]?\d+/ig,pK=/(^[#\.][a-z]|[a-y][a-z])/i,mK=Math.PI/180,gK=180/Math.PI,ed=Math.sin,td=Math.cos,hs=Math.abs,bn=Math.sqrt,yK=Math.atan2,q0=1e8,nk=function(e){return typeof e=="string"},c5=function(e){return typeof e=="number"},vK=function(e){return typeof e>"u"},bK={},xK={},kh=1e5,l5=function(e){return Math.round((e+q0)%1*kh)/kh||(e<0?0:1)},Se=function(e){return Math.round(e*kh)/kh||0},rk=function(e){return Math.round(e*1e10)/1e10||0},ak=function(e){return e.closed=Math.abs(e[0]-e[e.length-2])<.001&&Math.abs(e[1]-e[e.length-1])<.001},ok=function(e,t,i,n){var r=e[t],a=n===1?6:H0(r,i,n);if((a||!n)&&a+i+2t){for(;--r&&e[r]>t;);r<0&&(r=0)}else for(;e[++r] element or an SVG path data string")}function TK(s){for(var e=[],t=0;t-1;)a=n[r].nodeName.toLowerCase(),t.indexOf(","+a+",")<0&&i.setAttributeNS(null,a,n[r].nodeValue);return i},SK={rect:"rx,ry,x,y,width,height",circle:"r,cx,cy",ellipse:"rx,ry,cx,cy",line:"x1,x2,y1,y2"},CK=function(e,t){for(var i=t?t.split(","):[],n={},r=i.length;--r>-1;)n[i[r]]=+e.getAttribute(i[r])||0;return n};function EK(s,e){var t=s.tagName.toLowerCase(),i=.552284749831,n,r,a,o,c,l,u,d,h,f,p,m,g,v,w,b,k,A,M,R,I,D;return t==="path"||!s.getBBox?s:(l=AK(s,"x,y,width,height,cx,cy,rx,ry,r,x1,x2,y1,y2,points"),D=CK(s,SK[t]),t==="rect"?(o=D.rx,c=D.ry||o,r=D.x,a=D.y,f=D.width-o*2,p=D.height-c*2,o||c?(m=r+o*(1-i),g=r+o,v=g+f,w=v+o*i,b=v+o,k=a+c*(1-i),A=a+c,M=A+p,R=M+c*i,I=M+c,n="M"+b+","+A+" V"+M+" C"+[b,R,w,I,v,I,v-(v-g)/3,I,g+(v-g)/3,I,g,I,m,I,r,R,r,M,r,M-(M-A)/3,r,A+(M-A)/3,r,A,r,k,m,a,g,a,g+(v-g)/3,a,v-(v-g)/3,a,v,a,w,a,b,k,b,A].join(",")+"z"):n="M"+(r+f)+","+a+" v"+p+" h"+-f+" v"+-p+" h"+f+"z"):t==="circle"||t==="ellipse"?(t==="circle"?(o=c=D.r,d=o*i):(o=D.rx,c=D.ry,d=c*i),r=D.cx,a=D.cy,u=o*i,n="M"+(r+o)+","+a+" C"+[r+o,a+d,r+u,a+c,r,a+c,r-u,a+c,r-o,a+d,r-o,a,r-o,a-d,r-u,a-c,r,a-c,r+u,a-c,r+o,a-d,r+o,a].join(",")+"z"):t==="line"?n="M"+D.x1+","+D.y1+" L"+D.x2+","+D.y2:(t==="polyline"||t==="polygon")&&(h=(s.getAttribute("points")+"").match(hK)||[],r=h.shift(),a=h.shift(),n="M"+r+","+a+" L"+h.join(","),t==="polygon"&&(n+=","+r+","+a+"z")),l.setAttribute("d",f5(l._gsRawPath=Ah(n))),e&&s.parentNode&&(s.parentNode.insertBefore(l,s),s.parentNode.removeChild(s)),l)}function d5(s,e,t){var i=s[e],n=s[e+2],r=s[e+4],a;return i+=(n-i)*t,n+=(r-n)*t,i+=(n-i)*t,a=n+(r+(s[e+6]-r)*t-n)*t-i,i=s[e+1],n=s[e+3],r=s[e+5],i+=(n-i)*t,n+=(r-n)*t,i+=(n-i)*t,Se(yK(n+(r+(s[e+7]-r)*t-n)*t-i,a)*gK)}function h5(s,e,t){t=vK(t)?1:rk(t)||0,e=rk(e)||0;var i=Math.max(0,~~(hs(t-e)-1e-8)),n=TK(s);if(e>t&&(e=1-e,t=1-t,wK(n),n.totalLength=0),e<0||t<0){var r=Math.abs(~~Math.min(e,t))+1;e+=r,t+=r}n.totalLength||pa(n);var a=t>1,o=lk(n,e,bK,!0),c=lk(n,t,xK),l=c.segment,u=o.segment,d=c.segIndex,h=o.segIndex,f=c.i,p=o.i,m=h===d,g=f===p&&m,v,w,b,k,A,M,R,I;if(a||i){for(v=dd)&&n.splice(k,1);else l.angle=d5(l,f+b,0),f+=b,o=l[f],c=l[f+1],l.length=l.totalLength=0,l.totalPoints=n.totalPoints=8,l.push(o,c,o,c,o,c,o,c);return n.totalLength=0,n}function MK(s,e,t){e=e||0,s.samples||(s.samples=[],s.lookup=[]);var i=~~s.resolution||12,n=1/i,r=s.length,a=s[e],o=s[e+1],c=e?e/6*i:0,l=s.samples,u=s.lookup,d=(e?s.minLength:q0)||q0,h=l[c+t*i-1],f=e?l[c-1]:0,p,m,g,v,w,b,k,A,M,R,I,D,B,$,V,y,_;for(l.length=u.length=0,m=e+2;m8&&(s.splice(m,6),m-=6,r-=6);else for(p=1;p<=i;p++)$=n*p,B=1-$,b=k-(k=($*$*g+3*B*($*v+B*w))*$),I=D-(D=($*$*A+3*B*($*M+B*R))*$),y=bn(I*I+b*b),y=1)return 0;var i=s[e],n=s[e+1],r=s[e+2],a=s[e+3],o=s[e+4],c=s[e+5],l=s[e+6],u=s[e+7],d=i+(r-i)*t,h=r+(o-r)*t,f=n+(a-n)*t,p=a+(c-a)*t,m=d+(h-d)*t,g=f+(p-f)*t,v=o+(l-o)*t,w=c+(u-c)*t;return h+=(v-h)*t,p+=(w-p)*t,s.splice(e+2,4,Se(d),Se(f),Se(m),Se(g),Se(m+(h-m)*t),Se(g+(p-g)*t),Se(h),Se(p),Se(v),Se(w)),s.samples&&s.samples.splice(e/6*s.resolution|0,0,0,0,0,0,0,0),6}function lk(s,e,t,i){t=t||{},s.totalLength||pa(s),(e<0||e>1)&&(e=l5(e));var n=0,r=s[0],a,o,c,l,u,d,h;if(!e)h=d=n=0,r=s[0];else if(e===1)h=1,n=s.length-1,r=s[n],d=r.length-8;else{if(s.length>1){for(c=s.totalLength*e,u=d=0;(u+=s[d++].totalLength)1)&&(e=l5(e)),n.lookup||pa(s),s.length>1){for(c=s.totalLength*e,u=d=0;(u+=s[d++].totalLength)=1?1-1e-9:h||1e-9):n.angle||0),r}function Yc(s,e,t,i,n,r,a){for(var o=s.length,c,l,u,d,h;--o>-1;)for(c=s[o],l=c.length,u=0;u1&&(t=bn(k)*t,i=bn(k)*i);var A=t*t,M=i*i,R=(A*M-A*b-M*w)/(A*b+M*w);R<0&&(R=0);var I=(r===a?-1:1)*bn(R),D=I*(t*v/i),B=I*-(i*g/t),$=(s+o)/2,V=(e+c)/2,y=$+(u*D-d*B),_=V+(d*D+u*B),T=(g-D)/t,S=(v-B)/i,C=(-g-D)/t,E=(-v-B)/i,P=T*T+S*S,L=(S<0?-1:1)*Math.acos(T/bn(P)),O=(T*E-S*C<0?-1:1)*Math.acos((T*C+S*E)/bn(P*(C*C+E*E)));isNaN(O)&&(O=h),!a&&O>0?O-=f:a&&O<0&&(O+=f),L%=f,O%=f;var U=Math.ceil(hs(O)/(f/4)),j=[],N=O/U,z=4/3*ed(N/2)/(1+td(N/2)),W=u*t,Q=d*t,fe=d*-i,ye=u*i,le;for(le=0;le-1e-4?0:B}).match(dK)||[],t=[],i=0,n=0,r=2/3,a=e.length,o=0,c="ERROR: malformed path: "+s,l,u,d,h,f,p,m,g,v,w,b,k,A,M,R,I=function(B,$,V,y){w=(V-B)/3,b=(y-$)/3,m.push(B+w,$+b,V-w,y-b,V,y)};if(!s||!isNaN(e[0])||isNaN(e[1]))return console.log(c),t;for(l=0;l.5||hs(n-h)>.5)&&(I(i,n,d,h),f==="L"&&(l+=2)),i=d,n=h;else if(f==="A"){if(M=e[l+4],R=e[l+5],w=e[l+6],b=e[l+7],u=7,M.length>1&&(M.length<3?(b=w,w=R,u--):(b=R,w=M.substr(2),u-=2),R=M.charAt(1),M=M.charAt(0)),k=IK(i,n,+e[l+1],+e[l+2],+e[l+3],+M,+R,(p?i:0)+w*1,(p?n:0)+b*1),l+=u,k)for(u=0;u1?OK(l):l.getItem(0).matrix:Sh,d=l.a*u.x+l.c*u.y,h=l.b*u.x+l.d*u.y):(l=new ql,d=h=0),t&&e.tagName.toLowerCase()==="g"&&(d=h=0),(n||!e.getBoundingClientRect().width?i:a).appendChild(c),c.setAttribute("transform","matrix("+l.a+","+l.b+","+l.c+","+l.d+","+(l.e+d)+","+(l.f+h)+")");else{if(d=h=0,p5)for(l=e.offsetParent,u=e;u&&(u=u.parentNode)&&u!==l&&u.parentNode;)(ma.getComputedStyle(u)[Cs]+"").length>4&&(d=u.offsetLeft,h=u.offsetTop,u=0);if(f=ma.getComputedStyle(e),f.position!=="absolute"&&f.position!=="fixed")for(l=e.offsetParent;a&&a!==l;)d+=a.scrollLeft||0,h+=a.scrollTop||0,a=a.parentNode;u=c.style,u.top=e.offsetTop-h+"px",u.left=e.offsetLeft-d+"px",u[Cs]=f[Cs],u[X0]=f[X0],u.position=f.position==="fixed"?"fixed":"absolute",o.appendChild(c)}return c},wm=function(e,t,i,n,r,a,o){return e.a=t,e.b=i,e.c=n,e.d=r,e.e=a,e.f=o,e},ql=function(){function s(t,i,n,r,a,o){t===void 0&&(t=1),i===void 0&&(i=0),n===void 0&&(n=0),r===void 0&&(r=1),a===void 0&&(a=0),o===void 0&&(o=0),wm(this,t,i,n,r,a,o)}var e=s.prototype;return e.inverse=function(){var i=this.a,n=this.b,r=this.c,a=this.d,o=this.e,c=this.f,l=i*a-n*r||1e-10;return wm(this,a/l,-n/l,-r/l,i/l,(r*c-a*o)/l,-(i*c-n*o)/l)},e.multiply=function(i){var n=this.a,r=this.b,a=this.c,o=this.d,c=this.e,l=this.f,u=i.a,d=i.c,h=i.b,f=i.d,p=i.e,m=i.f;return wm(this,u*n+h*a,u*r+h*o,d*n+f*a,d*r+f*o,c+p*n+m*a,l+p*r+m*o)},e.clone=function(){return new s(this.a,this.b,this.c,this.d,this.e,this.f)},e.equals=function(i){var n=this.a,r=this.b,a=this.c,o=this.d,c=this.e,l=this.f;return n===i.a&&r===i.b&&a===i.c&&o===i.d&&c===i.e&&l===i.f},e.apply=function(i,n){n===void 0&&(n={});var r=i.x,a=i.y,o=this.a,c=this.b,l=this.c,u=this.d,d=this.e,h=this.f;return n.x=r*o+a*l+d||0,n.y=r*c+a*u+h||0,n},s}();function fo(s,e,t,i){if(!s||!s.parentNode||(wn||m5(s)).documentElement===s)return new ql;var n=RK(s),r=rb(s),a=r?g5:y5,o=$K(s,t),c=a[0].getBoundingClientRect(),l=a[1].getBoundingClientRect(),u=a[2].getBoundingClientRect(),d=o.parentNode,h=!i&&LK(s),f=new ql((l.left-c.left)/100,(l.top-c.top)/100,(u.left-c.left)/100,(u.top-c.top)/100,c.left+(h?0:FK()),c.top+(h?0:DK()));if(d.removeChild(o),n)for(c=n.length;c--;)l=n[c],l.scaleX=l.scaleY=0,l.renderTransform(1,l);return e?f.inverse():f}/*! + * MotionPathPlugin 3.14.2 + * https://gsap.com + * + * @license Copyright 2008-2025, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license + * @author: Jack Doyle, jack@greensock.com +*/var jK="x,translateX,left,marginLeft,xPercent".split(","),NK="y,translateY,top,marginTop,yPercent".split(","),VK=Math.PI/180,as,v5,Ba,K0,_m,dk,UK=function(){return as||typeof window<"u"&&(as=window.gsap)&&as.registerPlugin&&as},Ec=function(e,t,i,n){for(var r=t.length,a=n===2?0:n,o=0;o1?e=1:e<0&&(e=0);n--;)uk(i[n],e,!n&&t.rotate,i[n]);for(;r;)r.set(r.t,r.p,r.path[r.pp]+r.u,r.d,e),r=r._next;t.rotate&&t.rSet(t.target,t.rProp,i[0].angle*(t.radians?VK:1)+t.rOffset+t.ru,t,e)}else t.styles.revert()},getLength:function(e){return pa(Ad(e)).totalLength},sliceRawPath:h5,getRawPath:Ad,pointsToSegment:Y0,stringToRawPath:Ah,rawPathToString:f5,transformRawPath:Yc,getGlobalMatrix:fo,getPositionOnPath:uk,cacheRawPathMeasurements:pa,convertToPath:function(e,t){return K0(e).map(function(i){return EK(i,t!==!1)})},convertCoordinates:function(e,t,i){var n=fo(t,!0,!0).multiply(fo(e));return i?n.apply(i):n},getAlignMatrix:Q0,getRelativePosition:function(e,t,i,n){var r=Q0(e,t,i,n);return{x:r.e,y:r.f}},arrayToRawPath:function(e,t){t=t||{};var i=Ec(Ec([],e,t.x||"x",0),e,t.y||"y",1);return t.relative&&b5(i),[t.type==="cubic"?i:Y0(i,t.curviness)]}};UK()&&as.registerPlugin(w5);sb.registerPlugin(w5);function pk(s,e){if(s.length===0)return null;if(s.length===1)return{x:s[0].x,y:s[0].y};const t=[...s].sort((c,l)=>c.time-l.time);if(e<=t[0].time)return{x:t[0].x,y:t[0].y};if(e>=t[t.length-1].time){const c=t[t.length-1];return{x:c.x,y:c.y}}let i=0;for(let c=0;c=t[c].time&&e<=t[c+1].time){i=c;break}const n=t[i],r=t[i+1],a=r.time-n.time,o=a>0?(e-n.time)/a:0;return n.controlPoints&&r.controlPoints?qK({x:n.x,y:n.y},n.controlPoints.cp2,r.controlPoints.cp1,{x:r.x,y:r.y},o):{x:n.x+(r.x-n.x)*o,y:n.y+(r.y-n.y)*o}}function qK(s,e,t,i,n){const r=1-n,a=r*r,o=a*r,c=n*n,l=c*n,u=o*s.x+3*a*n*e.x+3*r*c*t.x+l*i.x,d=o*s.y+3*a*n*e.y+3*r*c*t.y+l*i.y,f=Math.min(1,n+.001),p=1-f,m=Math.pow(p,3)*s.x+3*Math.pow(p,2)*f*e.x+3*p*Math.pow(f,2)*t.x+Math.pow(f,3)*i.x,g=Math.pow(p,3)*s.y+3*Math.pow(p,2)*f*e.y+3*p*Math.pow(f,2)*t.y+Math.pow(f,3)*i.y,v=Math.atan2(g-d,m-u)*(180/Math.PI);return{x:u,y:d,rotation:v}}function HK(s,e,t=.5){if(s.length<2)return s[0]||{x:0,y:0};const i=s.length-1,n=Math.min(Math.floor(e*i),i-1),r=e*i%1,a=s[Math.max(0,n-1)],o=s[n],c=s[Math.min(s.length-1,n+1)],l=s[Math.min(s.length-1,n+2)],u=r*r,d=u*r,h=t*(c.x-a.x),f=t*(c.y-a.y),p=t*(l.x-o.x),m=t*(l.y-o.y),g=2*d-3*u+1,v=d-2*u+r,w=-2*d+3*u,b=d-u;return{x:g*o.x+v*h+w*c.x+b*p,y:g*o.y+v*f+w*c.y+b*m}}function YK(s){if(s.length===0)return"";if(s.length===1)return`M ${s[0].x} ${s[0].y}`;const e=[...s].sort((i,n)=>i.time-n.time);let t=`M ${e[0].x} ${e[0].y}`;for(let i=0;it.time-i.time);return e.map((t,i)=>{if(t.controlPoints)return t;const n=e[i-1],r=e[i+1];let a=0,o=0;return n&&r?(a=(r.x-n.x)/4,o=(r.y-n.y)/4):r?(a=(r.x-t.x)/3,o=(r.y-t.y)/3):n&&(a=(t.x-n.x)/3,o=(t.y-n.y)/3),{...t,controlPoints:{cp1:{x:t.x-a,y:t.y-o},cp2:{x:t.x+a,y:t.y+o}}}})}class XK{timelines=new Map;motionPaths=new Map;createTimeline(e,t){this.timelines.has(e)&&this.timelines.get(e).kill();const i=sb.timeline({paused:!0,defaults:{duration:t?.duration||1,ease:t?.ease||"none"}});return this.timelines.set(e,i),i}getTimeline(e){return this.timelines.get(e)}removeTimeline(e){const t=this.timelines.get(e);t&&(t.kill(),this.timelines.delete(e))}setMotionPath(e,t){this.motionPaths.set(e,{...t,clipId:e})}getMotionPath(e){return this.motionPaths.get(e)}removeMotionPath(e){this.motionPaths.delete(e)}updateGSAPMotionPathPoint(e,t,i){const n=this.motionPaths.get(e);!n||t<0||t>=n.points.length||(n.points[t]={...n.points[t],...i},this.motionPaths.set(e,n))}addGSAPMotionPathPoint(e,t){const i=this.motionPaths.get(e);i&&(i.points.push(t),i.points.sort((n,r)=>n.time-r.time),i.points=mk(i.points),this.motionPaths.set(e,i))}removeGSAPMotionPathPoint(e,t){const i=this.motionPaths.get(e);!i||t<0||t>=i.points.length||i.points.length<=2||(i.points.splice(t,1),i.points=mk(i.points),this.motionPaths.set(e,i))}samplePositionAtTime(e,t,i){const n=this.motionPaths.get(e);if(!n||!n.enabled||n.points.length===0)return null;const r=i>0?t/i:0,a=Math.max(0,Math.min(1,r));return n.pathType==="catmull-rom"?HK(n.points,a):pk(n.points,a)}getSVGPath(e){const t=this.motionPaths.get(e);return t?YK(t.points):""}sampleFrameTransforms(e,t,i,n){const r=this.motionPaths.get(e);if(!r||!r.enabled)return[];const a=[],o=i-t,c=Math.ceil(o*n);for(let l=0;l<=c;l++){const u=t+l/n,d=o>0?(u-t)/o:0,h=pk(r.points,d);h&&a.push({time:u,...h})}return a}dispose(){for(const e of this.timelines.values())e.kill();this.timelines.clear(),this.motionPaths.clear()}}let Tm=null;function Ree(){return Tm||(Tm=new XK),Tm}const pi={format:"mp4",codec:"h264",width:1920,height:1080,frameRate:30,bitrate:5e3,bitrateMode:"cbr",quality:80,keyframeInterval:60,audioSettings:{format:"aac",sampleRate:48e3,bitDepth:16,bitrate:192,channels:2}},km={format:"mp3",sampleRate:48e3,bitDepth:16,bitrate:320,channels:2},gk={format:"jpg",quality:90,width:1920,height:1080},Gn={"4k-high":{width:3840,height:2160,bitrate:8e4,frameRate:30,quality:95},"4k":{width:3840,height:2160,bitrate:5e4,frameRate:30,quality:90},"4k-60":{width:3840,height:2160,bitrate:65e3,frameRate:60,quality:90},"1080p-high":{width:1920,height:1080,bitrate:25e3,frameRate:30,quality:95},"1080p":{width:1920,height:1080,bitrate:15e3,frameRate:30,quality:85},"720p":{width:1280,height:720,bitrate:8e3,frameRate:30,quality:80}};let rs=null,Am=null;async function KK(){if(typeof WebAssembly>"u")return null;try{const s=new URL("data:application/wasm;base64,AGFzbQEAAAABKwdgBH9/f38AYAF/AX9gA39/fwBgBX9/f39/AGACf38Bf2ADf39/AX9gAAACDQEDZW52BWFib3J0AAADCgkCAAADBAUBAQYFAwEAAQYGAX8BQQALB3AHD2VuY29kZVdhdjE2TW9ubwABEWVuY29kZVdhdjE2U3RlcmVvAAIRZW5jb2RlV2F2MjRTdGVyZW8AAw53cml0ZVdhdkhlYWRlcgAECmFsbG9jYXRlVTgABwthbGxvY2F0ZUYzMgAIBm1lbW9yeQIACAEJDAEICs8LCYEBAgR/AX0gACgCCEECdiEEA0AgAyAESARAIAIgA0EBdGoiBSABKAIEakMAAIC/QwAAgD8gACgCBCADQQJ0aioCACIHIAdDAACAP14bIAdDAACAv10bQwD+/0aU/AAiBjoAACABKAIEIAVBAWpqIAbBQQh1OgAAIANBAWohAwwBCwsL1wECAX0FfyAAKAIIQQJ2IQgDQCAFIAhIBEBDAACAv0MAAIA/IAVBAnQiCSABKAIEaioCACIEIARDAACAP14bIARDAACAv10bQwD+/0aU/AAhByADIAlqIgYgAigCBGpDAACAv0MAAIA/IAkgACgCBGoqAgAiBCAEQwAAgD9eGyAEQwAAgL9dG0MA/v9GlPwAIgk6AAAgAigCBCAGQQFqaiAJwUEIdToAACACKAIEIAZBAmpqIAc6AAAgAigCBCAGQQNqaiAHwUEIdToAACAFQQFqIQUMAQsLC/4BAgF9BX8gACgCCEECdiEIA0AgBiAISARAQwAAgL9DAACAPyAGQQJ0IgkgASgCBGoqAgAiBCAEQwAAgD9eGyAEQwAAgL9dG0P+//9KlPwAIQcgAyAGQQZsaiIFIAIoAgRqQwAAgL9DAACAPyAJIAAoAgRqKgIAIgQgBEMAAIA/XhsgBEMAAIC/XRtD/v//SpT8ACIJOgAAIAIoAgQgBUEBamogCUEIdToAACACKAIEIAVBAmpqIAlBEHU6AAAgAigCBCAFQQNqaiAHOgAAIAIoAgQgBUEEamogB0EIdToAACACKAIEIAVBBWpqIAdBEHU6AAAgBkEBaiEGDAELCwuRBAEDfyABIANBA3VsIgYgAmwhBSAAKAIEQdIAOgAAIAAoAgRByQA6AAEgACgCBEHGADoAAiAAKAIEQcYAOgADIAAoAgQgBCAGbCIEQSRqIgc6AAQgACgCBCAHQQh1OgAFIAAoAgQgB0EQdToABiAAKAIEIAdBGHU6AAcgACgCBEHXADoACCAAKAIEQcEAOgAJIAAoAgRB1gA6AAogACgCBEHFADoACyAAKAIEQeYAOgAMIAAoAgRB7QA6AA0gACgCBEH0ADoADiAAKAIEQSA6AA8gACgCBEEQOgAQIAAoAgRBADoAESAAKAIEQQA6ABIgACgCBEEAOgATIAAoAgRBAToAFCAAKAIEQQA6ABUgACgCBCABOgAWIAAoAgQgAUEIdToAFyAAKAIEIAI6ABggACgCBCACQQh1OgAZIAAoAgQgAkEQdToAGiAAKAIEIAJBGHU6ABsgACgCBCAFOgAcIAAoAgQgBUEIdToAHSAAKAIEIAVBEHU6AB4gACgCBCAFQRh1OgAfIAAoAgQgBjoAICAAKAIEIAZBCHU6ACEgACgCBCADOgAiIAAoAgQgA0EIdToAIyAAKAIEQeQAOgAkIAAoAgRB4QA6ACUgACgCBEH0ADoAJiAAKAIEQeEAOgAnIAAoAgQgBDoAKCAAKAIEIARBCHU6ACkgACgCBCAEQRB1OgAqIAAoAgQgBEEYdToAKwvKAQEGfyAAQez///8DSwRAQZAJQdAJQdYAQR4QAAALIABBEGoiBEH8////A0sEQEGQCUHQCUEhQR0QAAALIwAhAyMAQQRqIgIgBEETakFwcUEEayIEaiIFPwAiBkEQdEEPakFwcSIHSwRAIAYgBSAHa0H//wNqQYCAfHFBEHYiByAGIAdKG0AAQQBIBEAgB0AAQQBIBEAACwsLIAUkACADIAQ2AgAgAkEEayIDQQA2AgQgA0EANgIIIAMgATYCDCADIAA2AhAgAkEQagtsACAARQRAQQxBAxAFIQALIABBADYCACAAQQA2AgQgAEEANgIIIAFB/P///wMgAnZLBEBBoAhB0AhBE0E5EAAACyABIAJ0IgFBARAFIgJBACAB/AsAIAAgAjYCACAAIAI2AgQgACABNgIIIAALDgBBDEEFEAUgAEEAEAYLDgBBDEEEEAUgAEECEAYLBwBB/AkkAAsL2QEIAEGMCAsBLABBmAgLIwIAAAAcAAAASQBuAHYAYQBsAGkAZAAgAGwAZQBuAGcAdABoAEG8CAsBPABByAgLLQIAAAAmAAAAfgBsAGkAYgAvAGEAcgByAGEAeQBiAHUAZgBmAGUAcgAuAHQAcwBB/AgLATwAQYgJCy8CAAAAKAAAAEEAbABsAG8AYwBhAHQAaQBvAG4AIAB0AG8AbwAgAGwAYQByAGcAZQBBvAkLATwAQcgJCyUCAAAAHgAAAH4AbABpAGIALwByAHQALwBzAHQAdQBiAC4AdABz",import.meta.url),e=await fetch(s);if(!e.ok)return null;const t=await e.arrayBuffer(),{instance:i}=await WebAssembly.instantiate(t,{env:{abort:()=>{throw new Error("WASM abort")}}});return i.exports}catch{return null}}async function QK(){return rs?!0:(Am||(Am=KK()),rs=await Am,rs!==null)}function JK(s,e,t){for(let i=0;i>8&255}}function ZK(s,e,t,i){for(let n=0;n>8&255,t[l+2]=c&255,t[l+3]=c>>8&255}}function eQ(s,e,t,i){for(let r=0;r>8&255,t[u+2]=c>>16&255,t[u+3]=l&255,t[u+4]=l>>8&255,t[u+5]=l>>16&255}}function tQ(s,e,t,i,n){const r=i>>3,a=e*r,o=t*a,c=n*a,l=36+c;s[0]=82,s[1]=73,s[2]=70,s[3]=70,s[4]=l&255,s[5]=l>>8&255,s[6]=l>>16&255,s[7]=l>>24&255,s[8]=87,s[9]=65,s[10]=86,s[11]=69,s[12]=102,s[13]=109,s[14]=116,s[15]=32,s[16]=16,s[17]=0,s[18]=0,s[19]=0,s[20]=1,s[21]=0,s[22]=e&255,s[23]=e>>8&255,s[24]=t&255,s[25]=t>>8&255,s[26]=t>>16&255,s[27]=t>>24&255,s[28]=o&255,s[29]=o>>8&255,s[30]=o>>16&255,s[31]=o>>24&255,s[32]=a&255,s[33]=a>>8&255,s[34]=i&255,s[35]=i>>8&255,s[36]=100,s[37]=97,s[38]=116,s[39]=97,s[40]=c&255,s[41]=c>>8&255,s[42]=c>>16&255,s[43]=c>>24&255}class iQ{useWasm;constructor(){this.useWasm=rs!==null}async ensureWasm(){return this.useWasm?!0:(await QK()&&(this.useWasm=!0),this.useWasm)}encodeWav16Mono(e,t,i){this.useWasm&&rs?rs.encodeWav16Mono(e,t,i):JK(e,t,i)}encodeWav16Stereo(e,t,i,n){this.useWasm&&rs?rs.encodeWav16Stereo(e,t,i,n):ZK(e,t,i,n)}encodeWav24Stereo(e,t,i,n){this.useWasm&&rs?rs.encodeWav24Stereo(e,t,i,n):eQ(e,t,i,n)}writeWavHeader(e,t,i,n,r){this.useWasm&&rs?rs.writeWavHeader(e,t,i,n,r):tQ(e,t,i,n,r)}encodeFullWav(e,t,i=16){const n=e.length,r=e[0].length,a=i>>3,o=r*n*a,c=new Uint8Array(44+o);return this.writeWavHeader(c,n,t,i,r),n===1&&i===16?this.encodeWav16Mono(e[0],c,44):n===1&&i===24?this.encodeWav24Mono(e[0],c,44):i===16?this.encodeWav16Stereo(e[0],e[1],c,44):this.encodeWav24Stereo(e[0],e[1],c,44),c}encodeWav24Mono(e,t,i){for(let r=0;r>8&255,t[c+2]=o>>16&255}}}let Sm=null;function sQ(){return Sm||(Sm=new iQ),Sm}class ab{static AUDIO_EXPORT_CHUNK_DURATION_SECONDS=15;mediabunny=null;initialized=!1;videoEngine=null;audioEngine=null;upscalingEngine=null;abortController=null;currentExport=null;exportWorker=null;async initialize(){if(!this.initialized){try{this.mediabunny=await ii(()=>import("./index-DjtrfS0G.js"),[])}catch(e){console.warn("[ExportEngine] MediaBunny not available:",e),this.mediabunny=null}try{this.videoEngine=YI(),this.audioEngine=aP(),this.videoEngine.isInitialized()||await this.videoEngine.initialize(),this.audioEngine.isInitialized()||await this.audioEngine.initialize(),this.initialized=!0}catch(e){throw new Error(`ExportEngine initialization failed: ${e instanceof Error?e.message:"Unknown error"}`)}}}async initializeGPUForExport(e,t){(!this.initialized||!this.videoEngine)&&await this.initialize();try{await this.videoEngine.initializeGPUCompositor(e,t);const i=this.videoEngine.getGPUCompositor();if(i){const n=i.getDevice();return n&&(this.upscalingEngine=gH(),await this.upscalingEngine.initialize({device:n})),!0}return!1}catch(i){throw new Error(`ExportEngine initialization failed: ${i instanceof Error?i.message:"Unknown error"}`)}}isMediaBunnyAvailable(){return this.mediabunny!==null}isWebCodecsSupported(){return typeof VideoEncoder<"u"&&typeof AudioEncoder<"u"}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.mediabunny)throw new Error("ExportEngine not initialized. Call initialize() first.")}async findSupportedAudioCodec(e,t,i){const n=e.getSupportedAudioCodecs(),a=[t.bitrate*1e3,192e3,128e3,96e3].filter((c,l,u)=>u.indexOf(c)===l);for(const c of a){const l=await i(n);if(l&&await this.isAudioConfigSupported(l,c,t.channels,t.sampleRate))return{codec:l,bitrate:c}}for(const c of["aac","mp3","opus"])if(n.some(l=>String(l).toLowerCase().includes(c)||c==="aac"&&String(l).toLowerCase().includes("mp4a"))){for(const l of a)if(await this.isAudioConfigSupported(c,l,t.channels,t.sampleRate))return{codec:c,bitrate:l}}return{codec:await i(n)||"aac",bitrate:128e3}}async isAudioConfigSupported(e,t,i,n){if(typeof AudioEncoder>"u")return!0;try{let r;e==="aac"||e.includes("mp4a")?r="mp4a.40.2":e==="opus"?r="opus":e==="mp3"?r="mp3":r=e;const a={codec:r,sampleRate:n,numberOfChannels:i,bitrate:t};return(await AudioEncoder.isConfigSupported(a)).supported===!0}catch{return!1}}async*exportVideo(e,t={},i){if(this.ensureInitialized(),!this.mediabunny){const f=this.isWebCodecsSupported()?"MediaBunny library failed to load. Please refresh the page and try again.":"Video export requires WebCodecs API which is not supported in your browser. Please use Chrome, Edge, or another WebCodecs-compatible browser.";return{success:!1,error:this.createError("UNSUPPORTED_CODEC",f,"preparing")}}const n={...pi,...t,audioSettings:{...pi.audioSettings,...t.audioSettings}};n.codec==="prores"&&(n.codec="h264",n.format="mp4",n.bitrate=25e3,n.quality=95);const{timeline:r}=e,a=this.calculateTimelineDuration(r),o=n.codec==="vp9"||n.codec==="av1"||n.codec==="h265",c=a>120;let l=o?1920:3840,u=o?1080:2160;if(c&&(l=Math.min(l,1920),u=Math.min(u,1080)),n.width>l||n.height>u){const f=Math.min(l/n.width,u/n.height,1);n.width=Math.round(n.width*f/2)*2,n.height=Math.round(n.height*f/2)*2}if(c&&n.frameRate>30&&(n.frameRate=30),this.abortController=new AbortController,this.currentExport={startTime:Date.now(),framesRendered:0},await this.initializeGPUForExport(n.width,n.height),this.videoEngine?.resetExportState(),this.videoEngine&&(this.videoEngine.exportMode=!0),a<=0)return{success:!1,error:this.createError("MUXER_ERROR","Timeline is empty. Add clips before exporting.","preparing")};if(!i)return{success:!1,error:this.createError("MUXER_ERROR","No writable stream provided. Export requires a file destination.","preparing")};const d=Math.ceil(a*n.frameRate);let h=0;try{yield this.createProgress("preparing",0,d,0,0);const{Output:f,StreamTarget:p,Mp4OutputFormat:m,WebMOutputFormat:g,MovOutputFormat:v,VideoSampleSource:w,AudioBufferSource:b,VideoSample:k,getFirstEncodableVideoCodec:A,getFirstEncodableAudioCodec:M,QUALITY_MEDIUM:R}=this.mediabunny,I=i,D=new WritableStream({async write(P){const L=P.data.buffer.slice(P.data.byteOffset,P.data.byteOffset+P.data.byteLength);await I.seek(P.position),await I.write(L),h+=P.data.byteLength}});let B;switch(n.format){case"webm":B=new g;break;case"mov":B=new v;break;case"mp4":default:B=new m({fastStart:!1});break}const $=new p(D,{chunked:!0,chunkSize:4*1024*1024}),V=new f({format:B,target:$}),y=await A(B.getSupportedVideoCodecs(),{width:n.width,height:n.height});if(!y)throw this.createError("UNSUPPORTED_CODEC","No supported video codec found","preparing");const _=await this.findSupportedAudioCodec(B,n.audioSettings,M),T=new w({codec:y,bitrate:n.bitrate?n.bitrate*1e3:R,keyFrameInterval:n.keyframeInterval/n.frameRate,hardwareAcceleration:"prefer-software"}),S=new b({codec:_.codec,bitrate:_.bitrate});V.addVideoTrack(T),V.addAudioTrack(S),V.setMetadataTags({title:e.name,date:new Date}),await V.start();try{await this.encodeTimelineAudioToSource(e,S)}finally{this.audioEngine?.clearCache()}S.close();const C=sa(),E=[];for(const P of e.timeline.tracks)if(P.type==="video")for(const L of P.clips){const O=e.mediaLibrary.items.find(U=>U.id===L.mediaId);if(O?.blob&&!E.includes(O.id)){E.push(O.id);try{await C.createExportDecoder(O.id,O.blob,n.width)}catch{}}}for(let P=0;PsetTimeout(z,2))}yield this.createProgress("rendering",(P+1)/d,d,P+1,h)}return T.close(),C.disposeAllExportDecoders(),C.clearFrameCache(),this.videoEngine?.clearVideoElementCache(),this.videoEngine?.clearCache(),this.videoEngine&&(this.videoEngine.exportMode=!1),yield this.createProgress("muxing",.98,d,d,h),await V.finalize(),await i.close(),yield this.createProgress("complete",1,d,d,h),{success:!0,stats:this.calculateStats(d,h)}}catch(f){try{await i.abort()}catch{}return f&&typeof f=="object"&&"code"in f?{success:!1,error:f}:{success:!1,error:this.createError("FRAME_ENCODE_FAILED",f instanceof Error?f.message:"Unknown error","rendering")}}finally{this.abortController=null,this.currentExport=null,this.audioEngine?.clearCache(),this.videoEngine?.clearVideoElementCache(),this.videoEngine?.clearCache(),this.videoEngine&&(this.videoEngine.exportMode=!1);try{sa().disposeAllExportDecoders(),sa().clearFrameCache()}catch{}}}terminateWorker(){this.exportWorker&&(this.exportWorker.terminate(),this.exportWorker=null)}async*exportAudio(e,t={}){this.ensureInitialized();const i={...km,...t};if(!this.mediabunny&&i.format!=="wav")return{success:!1,error:this.createError("UNSUPPORTED_CODEC",`Audio export to ${i.format} format requires MediaBunny. WAV format is available as a fallback.`,"preparing")};this.abortController=new AbortController,this.currentExport={startTime:Date.now(),framesRendered:0};const{timeline:n}=e,r=this.calculateTimelineDuration(n);if(r<=0)return{success:!1,error:this.createError("AUDIO_ENCODE_FAILED","Timeline is empty. Add clips before exporting.","preparing")};try{yield this.createProgress("preparing",0,1,0,0);const a=await this.renderTimelineAudio(e);if(!a)throw this.createError("AUDIO_ENCODE_FAILED","No audio to export","rendering");yield this.createProgress("encoding",.5,1,0,0);let o;return i.format==="wav"?o=this.encodeWav(a,i):o=await this.encodeAudioWithMediaBunny(a,i),yield this.createProgress("complete",1,1,1,o.size),{success:!0,blob:o,stats:{duration:Date.now()-this.currentExport.startTime,framesRendered:1,averageSpeed:1,fileSize:o.size,averageBitrate:o.size*8/r}}}catch(a){return a&&typeof a=="object"&&"code"in a?{success:!1,error:a}:{success:!1,error:this.createError("AUDIO_ENCODE_FAILED",a instanceof Error?a.message:"Unknown error","encoding")}}finally{this.abortController=null,this.currentExport=null}}async exportFrame(e,t,i={}){this.ensureInitialized();const n={...gk,width:e.settings.width,height:e.settings.height,...i};try{const r=await this.videoEngine.renderFrame(e,t,n.width,n.height);let a;if(n.width!==r.width||n.height!==r.height){a=new OffscreenCanvas(n.width,n.height);const l=a.getContext("2d");l&&l.drawImage(r.image,0,0,n.width,n.height),r.image.close()}else{a=new OffscreenCanvas(r.width,r.height);const l=a.getContext("2d");l&&l.drawImage(r.image,0,0),r.image.close()}const o=this.getImageMimeType(n.format),c=await a.convertToBlob({type:o,quality:n.quality/100});return{success:!0,blob:c,stats:{duration:0,framesRendered:1,averageSpeed:0,fileSize:c.size,averageBitrate:0}}}catch(r){return{success:!1,error:this.createError("FRAME_ENCODE_FAILED",r instanceof Error?r.message:"Unknown error","rendering")}}}async exportImage(e,t={}){return this.exportFrame(e,0,t)}async*exportImageSequence(e,t={}){this.ensureInitialized();const{timeline:i}=e,n=e.settings.frameRate,r=Math.ceil(i.duration*n),a={...gk,width:e.settings.width,height:e.settings.height,startFrame:0,endFrame:r-1,namingPattern:"frame_{0000}",...t};this.abortController=new AbortController,this.currentExport={startTime:Date.now(),framesRendered:0};const o=a.endFrame-a.startFrame+1,c=[];try{yield this.createProgress("preparing",0,o,0,0);for(let u=0;up+m.size,0))}yield this.createProgress("complete",1,o,o,0);const l=c.reduce((u,d)=>u+d.size,0);return{success:!0,blob:c[0],stats:this.calculateStats(o,l)}}catch(l){return l&&typeof l=="object"&&"code"in l?{success:!1,error:l}:{success:!1,error:this.createError("FRAME_ENCODE_FAILED",l instanceof Error?l.message:"Unknown error","rendering")}}finally{this.abortController=null,this.currentExport=null}}cancel(){this.abortController&&this.abortController.abort()}getPresets(){return[{id:"4k-master",name:"4K Master Quality",description:"Maximum quality 4K for professional delivery",category:"broadcast",settings:{...pi,...Gn["4k-high"],codec:"h265",quality:95}},{id:"4k-prores-hq",name:"4K ProRes HQ",description:"Professional 4K ProRes for editing/mastering",category:"broadcast",settings:{...pi,width:3840,height:2160,frameRate:30,format:"mov",codec:"prores",proresProfile:"hq",bitrate:88e4,quality:100}},{id:"4k-prores-4444",name:"4K ProRes 4444",description:"Highest quality ProRes with alpha channel support",category:"broadcast",settings:{...pi,width:3840,height:2160,frameRate:30,format:"mov",codec:"prores",proresProfile:"4444",bitrate:132e4,quality:100}},{id:"youtube-4k",name:"YouTube 4K",description:"4K UHD optimized for YouTube",category:"social",settings:{...pi,...Gn["4k"],codec:"h264"}},{id:"youtube-4k-60",name:"YouTube 4K 60fps",description:"4K 60fps for YouTube gaming/motion",category:"social",settings:{...pi,...Gn["4k-60"],codec:"h264"}},{id:"youtube-1080p-high",name:"YouTube 1080p High",description:"High bitrate 1080p for YouTube",category:"social",settings:{...pi,...Gn["1080p-high"],codec:"h264"}},{id:"youtube-1080p",name:"YouTube 1080p",description:"Standard 1080p for YouTube",category:"social",settings:{...pi,...Gn["1080p"],codec:"h264"}},{id:"tiktok-1080p",name:"TikTok/Reels",description:"Vertical 1080x1920 for TikTok/Reels",category:"social",settings:{...pi,width:1080,height:1920,bitrate:15e3,frameRate:30,codec:"h264"}},{id:"twitter",name:"Twitter/X",description:"Optimized for Twitter",category:"social",settings:{...pi,...Gn["720p"],codec:"h264"}},{id:"web-vp9",name:"Web (VP9)",description:"WebM VP9 for web embedding (720p for stability)",category:"web",settings:{...pi,format:"webm",codec:"vp9",...Gn["720p"]}},{id:"archive-4k",name:"Archive 4K",description:"High quality 4K for archival",category:"archive",settings:{...pi,...Gn["4k-high"],codec:"h265"}},{id:"archive-prores",name:"Archive ProRes",description:"Lossless quality ProRes for archival",category:"archive",settings:{...pi,width:1920,height:1080,format:"mov",codec:"prores",proresProfile:"hq",bitrate:22e4,quality:100}},{id:"audio-mp3",name:"MP3 Audio",description:"MP3 320kbps",category:"custom",settings:km},{id:"audio-wav",name:"WAV Audio",description:"Uncompressed WAV 24-bit",category:"archive",settings:{...km,format:"wav",bitDepth:24,sampleRate:48e3}}]}createPreset(e,t){return{id:`custom-${Date.now()}`,name:e,description:"Custom preset",settings:t,category:"custom"}}estimateFileSize(e,t){const i=e.timeline.duration;if("codec"in t){const n=t.bitrate*1e3,r=t.audioSettings.bitrate*1e3;return Math.ceil((n+r)*i/8)}else return t.format==="wav"?Math.ceil(i*t.sampleRate*t.channels*(t.bitDepth/8)):Math.ceil(t.bitrate*1e3*i/8)}estimateExportTime(e,t){const i=e.timeline.duration;if("codec"in t){const r=t.width*t.height/(1920*1080),a=t.codec==="h265"||t.codec==="av1"?2:1;return i*r*a*.5}else return i*.1}async renderTimelineAudio(e,t=0,i){const{timeline:n}=e;if(!n.tracks.some(l=>(l.type==="audio"||l.type==="video")&&!l.muted&&l.clips.length>0))return null;const a=this.calculateTimelineDuration(n);if(a<=0)return null;const o=Math.max(0,Math.min(i??a,a-t));return o<=0?null:(await this.audioEngine.renderAudio(e,t,o)).buffer}async encodeTimelineAudioToSource(e,t){const i=this.calculateTimelineDuration(e.timeline);if(i<=0)return;const n=ab.AUDIO_EXPORT_CHUNK_DURATION_SECONDS;for(let r=0;rsetTimeout(c,0)))}}async encodeAudioWithMediaBunny(e,t){const{Output:i,BufferTarget:n,Mp3OutputFormat:r,AudioSampleSource:a,AudioSample:o,getFirstEncodableAudioCodec:c}=this.mediabunny;let l;switch(t.format){case"mp3":l=new r;break;case"aac":case"flac":case"ogg":default:return this.encodeWav(e,t)}const u=new n,d=new i({format:l,target:u}),h=await c(l.getSupportedAudioCodecs()),f=new a({codec:h||"mp3",bitrate:t.bitrate*1e3});d.addAudioTrack(f),await d.start();const p=o.fromAudioBuffer(e,0);for(const g of p)await f.add(g),g.close();f.close(),await d.finalize();const m=u.buffer;if(!m)throw new Error("Audio encoding failed");return new Blob([m],{type:this.getAudioMimeType(t.format)})}encodeWav(e,t){const i=Math.min(e.numberOfChannels,t.channels),n=t.sampleRate,r=t.bitDepth;if(r===32)return this.encodeWav32Float(e,i,n);const a=sQ(),o=[];for(let l=0;l0?n/a:0,c=i-n,l=o>0?c/o:0;return{phase:e,progress:t,estimatedTimeRemaining:l,currentFrame:n,totalFrames:i,bytesWritten:r,currentBitrate:a>0?r*8/a:0}}createError(e,t,i){return{code:e,message:t,phase:i,recoverable:e==="CANCELLED"}}calculateStats(e,t){const i=this.currentExport?Date.now()-this.currentExport.startTime:0,n=this.currentExport?.framesRendered||e;return{duration:i,framesRendered:n,averageSpeed:i>0?n/i*1e3:0,fileSize:t,averageBitrate:i>0?t*8e3/i:0}}calculateTimelineDuration(e){let t=0;for(const o of e.tracks)for(const c of o.clips){const l=c.startTime+c.duration;l>t&&(t=l)}const i=na.getAllTextClips();for(const o of i){const c=o.startTime+o.duration;c>t&&(t=c)}const n=As.getAllShapeClips();for(const o of n){const c=o.startTime+o.duration;c>t&&(t=c)}const r=As.getAllSVGClips();for(const o of r){const c=o.startTime+o.duration;c>t&&(t=c)}const a=As.getAllStickerClips();for(const o of a){const c=o.startTime+o.duration;c>t&&(t=c)}if(e.subtitles)for(const o of e.subtitles)o.endTime>t&&(t=o.endTime);return t}shouldApplyUpscaling(e,t){if(!t.upscaling?.enabled)return!1;const i=e.settings.width,n=e.settings.height,r=t.width,a=t.height;return r>i||a>n}dispose(){this.cancel(),this.terminateWorker(),this.mediabunny=null,this.videoEngine=null,this.audioEngine=null,this.upscalingEngine&&(this.upscalingEngine.clearTexturePool(),this.upscalingEngine=null),this.initialized=!1}}let Cm=null;function nQ(){return Cm||(Cm=new ab),Cm}class _5{videoEffectsEngine=null;colorGradingEngine=null;initialized=!1;clipEffects=new Map;clipColorGrading=new Map;renderer=null;effectsChangeCallbacks=[];pendingReRenders=new Map;async initialize(e=1920,t=1080){if(!this.initialized)try{this.videoEffectsEngine=new lu({width:e,height:t,useGPU:!0,preferWebGPU:Fl()}),await this.videoEffectsEngine.initialize(),this.colorGradingEngine=new Jq(e,t),this.colorGradingEngine.initialize(),this.initialized=!0}catch(i){const n=i instanceof Error?i.message:"Unknown initialization error";throw new Error(`EffectsBridge initialization failed: ${n}`)}}isInitialized(){return this.initialized}applyVideoEffect(e,t,i={}){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const n=this.clipEffects.get(e)||[],r={id:ve(),type:t,enabled:!0,params:{...this.getDefaultParams(t),...i},order:n.length};return n.push(r),this.clipEffects.set(e,n),{success:!0,effectId:r.id}}removeVideoEffect(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipEffects.get(e);if(!i)return{success:!1,error:"No effects found for clip"};const n=i.findIndex(r=>r.id===t);return n===-1?{success:!1,error:"Effect not found"}:(i.splice(n,1),i.forEach((r,a)=>{r.order=a}),this.clipEffects.set(e,i),{success:!0})}updateVideoEffect(e,t,i){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const n=this.clipEffects.get(e);if(!n)return{success:!1,error:"No effects found for clip"};const r=n.find(a=>a.id===t);return r?(r.params={...r.params,...i},this.notifyEffectsChanged(e),{success:!0,effectId:t}):{success:!1,error:"Effect not found"}}reorderEffects(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipEffects.get(e);if(!i)return{success:!1,error:"No effects found for clip"};const n=new Map(i.map(a=>[a.id,a]));for(const a of t)if(!n.has(a))return{success:!1,error:`Effect ${a} not found`};const r=[];return t.forEach((a,o)=>{const c=n.get(a);c.order=o,r.push(c)}),this.clipEffects.set(e,r),{success:!0}}getEffects(e){return[...this.clipEffects.get(e)||[]].sort((i,n)=>i.order-n.order)}getEffect(e,t){return this.clipEffects.get(e)?.find(n=>n.id===t)}toggleEffect(e,t,i){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const n=this.clipEffects.get(e);if(!n)return{success:!1,error:"No effects found for clip"};const r=n.find(a=>a.id===t);return r?(r.enabled=i,{success:!0,effectId:t}):{success:!1,error:"Effect not found"}}resetEffect(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipEffects.get(e);if(!i)return{success:!1,error:"No effects found for clip"};const n=i.find(r=>r.id===t);return n?(n.params=this.getDefaultParams(n.type),{success:!0,effectId:t}):{success:!1,error:"Effect not found"}}async processEffects(e,t){if(!this.initialized||!this.videoEffectsEngine)return{image:t,processingTime:0};const i=this.getEffects(e);if(i.length===0)return{image:t,processingTime:0};const n=i.filter(r=>r.enabled);if(n.length===0)return{image:t,processingTime:0};try{const r=n.map(o=>({id:o.id,type:o.type,enabled:o.enabled,params:o.params})),a=await this.videoEffectsEngine.applyEffects(t,r);return!a.image||a.image.width===0||a.image.height===0?(console.warn("[EffectsBridge] Effects processing returned invalid image"),{image:t,processingTime:a.processingTime}):{image:a.image,processingTime:a.processingTime}}catch(r){return console.error("[EffectsBridge] Effects processing failed:",r),{image:t,processingTime:0}}}getDefaultParams(e){switch(e){case"brightness":return{value:0};case"contrast":return{value:1};case"saturation":return{value:1};case"hue":return{rotation:0};case"blur":return{radius:0,type:"gaussian"};case"sharpen":return{amount:0,radius:1,threshold:0};case"vignette":return{amount:0,midpoint:.5,roundness:.5,feather:.3};case"grain":return{amount:0,size:1,roughness:.5,colored:!1};case"temperature":return{value:0};case"tint":return{value:0};case"tonal":return{shadows:0,midtones:0,highlights:0};case"chromaKey":return{keyColor:{r:0,g:1,b:0},tolerance:.3,edgeSoftness:.1,spillSuppression:.5};case"shadow":return{offsetX:5,offsetY:5,blur:10,opacity:.8,color:"#000000"};case"glow":return{radius:10,intensity:1,color:"#ffffff"};case"motion-blur":return{angle:0,distance:20};case"radial-blur":return{amount:20,centerX:50,centerY:50};case"chromatic-aberration":return{amount:5,angle:0};default:return{}}}applyColorWheels(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipColorGrading.get(e)||{};return i.colorWheels=t,this.clipColorGrading.set(e,i),{success:!0}}applyCurves(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipColorGrading.get(e)||{};return i.curves=t,this.clipColorGrading.set(e,i),{success:!0}}applyLUT(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipColorGrading.get(e)||{};return i.lut=t,this.clipColorGrading.set(e,i),{success:!0}}applyHSL(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipColorGrading.get(e)||{};return i.hsl=t,this.clipColorGrading.set(e,i),{success:!0}}applyWhiteBalance(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=this.clipColorGrading.get(e)||{};return t.temperature!==void 0&&(i.temperature=t.temperature),t.tint!==void 0&&(i.tint=t.tint),this.clipColorGrading.set(e,i),{success:!0}}getColorGrading(e){return this.clipColorGrading.get(e)||{}}resetColorGrading(e){return this.initialized?(this.clipColorGrading.set(e,{colorWheels:{...Wq},curves:{...qq},hsl:{...Hq},temperature:0,tint:0}),{success:!0}):{success:!1,error:"EffectsBridge not initialized"}}async processColorGrading(e,t){if(!this.initialized||!this.colorGradingEngine)return{image:t,processingTime:0};const i=this.getColorGrading(e);let n=t,r=0;if(i.colorWheels){const o=await this.colorGradingEngine.applyColorWheels(n,i.colorWheels);n=o.image,r+=o.processingTime}if(i.curves){const o=await this.colorGradingEngine.applyCurves(n,i.curves);n=o.image,r+=o.processingTime}if(i.lut){const o=await this.colorGradingEngine.applyLUT(n,i.lut);n=o.image,r+=o.processingTime}if(i.hsl){const o=await this.colorGradingEngine.applyHSL(n,i.hsl);n=o.image,r+=o.processingTime}const a=[];if(this.videoEffectsEngine&&i.temperature!==void 0&&i.temperature!==0&&a.push({id:"wb-temperature",type:"temperature",enabled:!0,params:{value:i.temperature}}),this.videoEffectsEngine&&i.tint!==void 0&&i.tint!==0&&a.push({id:"wb-tint",type:"tint",enabled:!0,params:{value:i.tint}}),a.length>0&&this.videoEffectsEngine)try{const o=await this.videoEffectsEngine.applyEffects(n,a);o.image&&o.image.width>0&&o.image.height>0&&(n=o.image,r+=o.processingTime)}catch(o){console.warn("[EffectsBridge] White balance processing failed:",o)}return{image:n,processingTime:r}}async generateWaveform(e){return!this.initialized||!this.colorGradingEngine?null:this.colorGradingEngine.generateWaveform(e)}async generateVectorscope(e,t=256){return!this.initialized||!this.colorGradingEngine?null:this.colorGradingEngine.generateVectorscope(e,t)}async generateHistogram(e){return!this.initialized||!this.colorGradingEngine?null:this.colorGradingEngine.generateHistogram(e)}serializeEffects(e){const t=this.getEffects(e),i=this.getColorGrading(e),n=t.map(a=>({id:a.id,type:a.type,enabled:a.enabled,params:a.params,order:a.order})),r={};return i.colorWheels&&(r.colorWheels=i.colorWheels),i.curves&&(r.curves=i.curves),i.lut&&(r.lut={data:Array.from(i.lut.data),size:i.lut.size,intensity:i.lut.intensity}),i.hsl&&(r.hsl=i.hsl),i.temperature!==void 0&&(r.temperature=i.temperature),i.tint!==void 0&&(r.tint=i.tint),{effects:n,colorGrading:r}}deserializeEffects(e,t){if(!this.initialized)return{success:!1,error:"EffectsBridge not initialized"};const i=t.effects.map(r=>({id:r.id,type:r.type,enabled:r.enabled,params:r.params,order:r.order}));this.clipEffects.set(e,i);const n={};return t.colorGrading.colorWheels&&(n.colorWheels=t.colorGrading.colorWheels),t.colorGrading.curves&&(n.curves=t.colorGrading.curves),t.colorGrading.lut&&(n.lut={data:new Uint8Array(t.colorGrading.lut.data),size:t.colorGrading.lut.size,intensity:t.colorGrading.lut.intensity}),t.colorGrading.hsl&&(n.hsl=t.colorGrading.hsl),t.colorGrading.temperature!==void 0&&(n.temperature=t.colorGrading.temperature),t.colorGrading.tint!==void 0&&(n.tint=t.colorGrading.tint),this.clipColorGrading.set(e,n),{success:!0}}clearEffects(e){this.clipEffects.delete(e),this.clipColorGrading.delete(e)}onEffectsChange(e){this.effectsChangeCallbacks.push(e)}offEffectsChange(e){const t=this.effectsChangeCallbacks.indexOf(e);t!==-1&&this.effectsChangeCallbacks.splice(t,1)}notifyEffectsChanged(e){const t=this.pendingReRenders.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{this.pendingReRenders.delete(e);const r=this.getEffects(e).map(a=>({id:a.id,type:a.type,enabled:a.enabled,params:a.params}));for(const a of this.effectsChangeCallbacks)a(e,r)},16);this.pendingReRenders.set(e,i)}getRendererType(){return this.videoEffectsEngine&&typeof this.videoEffectsEngine.getRendererType=="function"?this.videoEffectsEngine.getRendererType():"none"}isUsingWebGPU(){return this.videoEffectsEngine&&typeof this.videoEffectsEngine.isUsingWebGPU=="function"?this.videoEffectsEngine.isUsingWebGPU():!1}dispose(){for(const e of this.pendingReRenders.values())clearTimeout(e);this.pendingReRenders.clear(),this.effectsChangeCallbacks=[],this.renderer&&(this.renderer.destroy(),this.renderer=null),this.colorGradingEngine&&this.colorGradingEngine.dispose(),this.clipEffects.clear(),this.clipColorGrading.clear(),this.videoEffectsEngine=null,this.colorGradingEngine=null,this.initialized=!1}}let yi=null,id=null,T5=1920,k5=1080;function Bs(){return yi||(yi=new _5),yi.isInitialized()||yi.initialize(T5,k5).catch(s=>{console.error("[EffectsBridge] Background initialization failed:",s)}),yi}async function rQ(s=1920,e=1080){return yi?.isInitialized()?yi:id||(id=(async()=>(yi||(yi=new _5),await yi.initialize(s,e),T5=s,k5=e,yi))(),id)}async function Dee(s=1920,e=1080){return rQ(s,e)}function Fee(){yi&&(yi.dispose(),yi=null)}class aQ{transitionEngine=null;initialized=!1;trackTransitions=new Map;initialize(e=1920,t=1080){if(!this.initialized)try{this.transitionEngine=TG(e,t),this.initialized=!0}catch(i){const n=i instanceof Error?i.message:"Unknown initialization error";throw new Error(`TransitionBridge initialization failed: ${n}`)}}isInitialized(){return this.initialized}getEngine(){return this.transitionEngine}createTransition(e,t,i,n,r){if(!this.initialized||!this.transitionEngine)return{success:!1,error:"TransitionBridge not initialized"};const a=this.transitionEngine.validateTransition(e,t,n);if(!a.valid&&!a.warning)return{success:!1,error:a.error};const o=this.transitionEngine.createTransition(e,t,i,n,r);if(!o)return{success:!1,error:"Failed to create transition"};const c=e.trackId,u=(this.trackTransitions.get(c)||[]).filter(d=>!(d.clipAId===e.id&&d.clipBId===t.id));return u.push(o),this.trackTransitions.set(c,u),{success:!0,transitionId:o.id,warning:a.warning,maxDuration:a.maxDuration}}updateTransition(e,t){if(!this.initialized||!this.transitionEngine)return{success:!1,error:"TransitionBridge not initialized"};let i=null,n=null;for(const[c,l]of this.trackTransitions.entries()){const u=l.find(d=>d.id===e);if(u){i=u,n=c;break}}if(!i||!n)return{success:!1,error:"Transition not found"};const r={...i,type:t.type??i.type,duration:t.duration??i.duration,params:t.params?{...i.params,...t.params}:i.params},a=this.trackTransitions.get(n)||[],o=a.findIndex(c=>c.id===e);return o!==-1&&(a[o]=r,this.trackTransitions.set(n,a)),{success:!0,transitionId:e}}removeTransition(e){if(!this.initialized)return{success:!1,error:"TransitionBridge not initialized"};for(const[t,i]of this.trackTransitions.entries()){const n=i.findIndex(r=>r.id===e);if(n!==-1)return i.splice(n,1),this.trackTransitions.set(t,i),{success:!0,transitionId:e}}return{success:!1,error:"Transition not found"}}getTransition(e){for(const t of this.trackTransitions.values()){const i=t.find(n=>n.id===e);if(i)return i}}getTransitionsForTrack(e){return this.trackTransitions.get(e)||[]}setTransitionsForTrack(e,t){this.trackTransitions.set(e,t.map(i=>({...i,params:{...i.params}})))}getTransitionBetweenClips(e,t){for(const i of this.trackTransitions.values()){const n=i.find(r=>r.clipAId===e&&r.clipBId===t);if(n)return n}}validateTransition(e,t,i){return!this.initialized||!this.transitionEngine?{valid:!1,error:"TransitionBridge not initialized"}:this.transitionEngine.validateTransition(e,t,i)}areClipsAdjacent(e,t){return!this.initialized||!this.transitionEngine?!1:this.transitionEngine.areClipsAdjacent(e,t)}findAdjacentClipPairs(e){return!this.initialized||!this.transitionEngine?[]:this.transitionEngine.findAdjacentClipPairs(e)}getAvailableTransitionTypes(){return[{type:"crossfade",name:"Crossfade",description:"Smooth blend between clips",hasDirection:!1,hasCustomParams:!1},{type:"dipToBlack",name:"Dip to Black",description:"Fade through black",hasDirection:!1,hasCustomParams:!0},{type:"dipToWhite",name:"Dip to White",description:"Fade through white",hasDirection:!1,hasCustomParams:!0},{type:"wipe",name:"Wipe",description:"Wipe from one clip to another",hasDirection:!0,hasCustomParams:!0},{type:"slide",name:"Slide",description:"Slide incoming clip over outgoing",hasDirection:!0,hasCustomParams:!0},{type:"zoom",name:"Zoom",description:"Zoom transition between clips",hasDirection:!1,hasCustomParams:!0},{type:"push",name:"Push",description:"Push outgoing clip with incoming",hasDirection:!0,hasCustomParams:!1}]}getDefaultParams(e){return!this.initialized||!this.transitionEngine?{}:this.transitionEngine.getDefaultParams(e)}calculateProgress(e,t,i){return!this.initialized||!this.transitionEngine?0:this.transitionEngine.calculateTransitionProgress(e,t,i)}isTimeInTransition(e,t,i){return!this.initialized||!this.transitionEngine?!1:this.transitionEngine.isTimeInTransition(e,t,i)}async renderTransition(e,t,i,n){if(!this.initialized||!this.transitionEngine)return null;try{const r=await this.transitionEngine.renderTransition(e,t,i,n);return{frame:r.frame,processingTime:r.processingTime}}catch(r){return console.error("[TransitionBridge] Render error:",r),null}}async renderTransitionToCanvas(e,t,i,n){if(!this.initialized||!this.transitionEngine)return null;try{return await this.transitionEngine.renderTransitionToCanvas(e,t,i,n)}catch(r){return console.error("[TransitionBridge] Render error:",r),null}}clearTransitionsForTrack(e){this.trackTransitions.delete(e)}clearAllTransitions(){this.trackTransitions.clear()}resize(e,t){this.transitionEngine&&this.transitionEngine.resize(e,t)}dispose(){this.transitionEngine&&this.transitionEngine.dispose(),this.trackTransitions.clear(),this.transitionEngine=null,this.initialized=!1}}let po=null;function J0(){return po||(po=new aQ),po}function Lee(s=1920,e=1080){const t=J0();return t.initialize(s,e),t}function Oee(){po&&(po.dispose(),po=null)}const oQ={interval:3e4,maxSlots:3,enabled:!0,debounceTime:2e3},cQ="openreel-autosave",lQ=1,Zi="autosaves";class uQ{config;db=null;intervalId=null;debounceTimeoutId=null;lastSavedHash="";currentSlot=0;listeners=new Map;pendingProject=null;isDirty=!1;constructor(e={}){this.config={...oQ,...e}}async initialize(){try{this.db=await this.openDatabase()}catch(e){console.error("[AutoSave] Failed to initialize:",e),this.emit("error",{error:e,message:"Failed to initialize auto-save"})}}openDatabase(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(new Error("IndexedDB not supported"));return}const i=indexedDB.open(cQ,lQ);i.onerror=()=>{t(new Error(`Failed to open auto-save database: ${i.error?.message}`))},i.onsuccess=()=>{e(i.result)},i.onupgradeneeded=n=>{const r=n.target.result;if(!r.objectStoreNames.contains(Zi)){const a=r.createObjectStore(Zi,{keyPath:"id"});a.createIndex("projectId","projectId",{unique:!1}),a.createIndex("timestamp","timestamp",{unique:!1}),a.createIndex("slot","slot",{unique:!1})}}})}start(e){this.config.enabled&&(this.stop(),this.pendingProject=e(),this.saveIfDirty(),this.intervalId=setInterval(()=>{this.pendingProject=e(),this.saveIfDirty()},this.config.interval))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.debounceTimeoutId&&(clearTimeout(this.debounceTimeoutId),this.debounceTimeoutId=null)}markDirty(){this.isDirty=!0,this.debounceTimeoutId&&clearTimeout(this.debounceTimeoutId),this.debounceTimeoutId=setTimeout(()=>{this.saveIfDirty()},this.config.debounceTime)}async saveIfDirty(){if(!this.pendingProject||!this.isDirty)return;const e=this.pendingProject,t=this.computeHash(e);if(t!==this.lastSavedHash)try{await this.save(e),this.lastSavedHash=t,this.isDirty=!1}catch(i){console.error("[AutoSave] Save failed:",i),this.emit("error",{error:i,message:"Auto-save failed"})}}async save(e){if(!this.db)throw new Error("Auto-save database not initialized");const t={id:`${e.id}-slot-${this.currentSlot}`,projectId:e.id,projectName:e.name,timestamp:Date.now(),slot:this.currentSlot,data:JSON.stringify(e)};await this.saveRecord(t),this.currentSlot=(this.currentSlot+1)%this.config.maxSlots,await this.cleanupOldSaves(e.id),this.emit("saved",{projectId:e.id,timestamp:t.timestamp,slot:t.slot})}saveRecord(e){return new Promise((t,i)=>{if(!this.db){i(new Error("Database not initialized"));return}const a=this.db.transaction(Zi,"readwrite").objectStore(Zi).put(e);a.onsuccess=()=>t(),a.onerror=()=>i(new Error(`Failed to save: ${a.error?.message}`))})}async cleanupOldSaves(e){if(!this.db)return;const i=(await this.getAllSaves()).filter(n=>n.projectId===e);if(i.length>this.config.maxSlots){const n=i.sort((r,a)=>a.timestamp-r.timestamp).slice(this.config.maxSlots);for(const r of n)await this.deleteRecord(r.id)}}deleteRecord(e){return new Promise((t,i)=>{if(!this.db){i(new Error("Database not initialized"));return}const a=this.db.transaction(Zi,"readwrite").objectStore(Zi).delete(e);a.onsuccess=()=>t(),a.onerror=()=>i(new Error(`Failed to delete: ${a.error?.message}`))})}getAllSaves(){return new Promise((e,t)=>{if(!this.db){t(new Error("Database not initialized"));return}const r=this.db.transaction(Zi,"readonly").objectStore(Zi).getAll();r.onsuccess=()=>e(r.result),r.onerror=()=>t(new Error(`Failed to get saves: ${r.error?.message}`))})}async checkForRecovery(e){this.db||await this.initialize();try{const t=await this.getAllSaves();let i=t;e&&(i=t.filter(r=>r.projectId===e));const n=i.sort((r,a)=>a.timestamp-r.timestamp).map(r=>({id:r.id,projectId:r.projectId,projectName:r.projectName,timestamp:r.timestamp,slot:r.slot,isRecovery:!0}));return n.length>0&&this.emit("recoveryAvailable",{saves:n}),n}catch(t){return console.error("[AutoSave] Failed to check for recovery:",t),[]}}async recover(e){this.db||await this.initialize();try{const t=await this.getRecord(e);if(!t)return console.warn(`[AutoSave] No save found with id: ${e}`),null;const i=JSON.parse(t.data);return this.emit("restored",{project:i,timestamp:t.timestamp}),i}catch(t){return console.error("[AutoSave] Recovery failed:",t),this.emit("error",{error:t,message:"Failed to recover project"}),null}}getRecord(e){return new Promise((t,i)=>{if(!this.db){i(new Error("Database not initialized"));return}const a=this.db.transaction(Zi,"readonly").objectStore(Zi).get(e);a.onsuccess=()=>t(a.result||null),a.onerror=()=>i(new Error(`Failed to get record: ${a.error?.message}`))})}async getMostRecentSave(e){const t=await this.checkForRecovery(e);return t.length>0?t[0]:null}async clearProjectSaves(e){if(!this.db)return;const i=(await this.getAllSaves()).filter(n=>n.projectId===e);for(const n of i)await this.deleteRecord(n.id)}async clearAllSaves(){if(this.db)return new Promise((e,t)=>{const r=this.db.transaction(Zi,"readwrite").objectStore(Zi).clear();r.onsuccess=()=>{e()},r.onerror=()=>t(new Error(`Failed to clear: ${r.error?.message}`))})}computeHash(e){const t=JSON.stringify({id:e.id,modifiedAt:e.modifiedAt,trackCount:e.timeline.tracks.length,clipCount:e.timeline.tracks.reduce((n,r)=>n+r.clips.length,0),mediaCount:e.mediaLibrary.items.length});let i=0;for(let n=0;n{try{i(t)}catch(n){console.error("[AutoSave] Event callback error:",n)}})}async forceSave(e){this.pendingProject=e,this.isDirty=!0,await this.saveIfDirty()}destroy(){this.stop(),this.db&&(this.db.close(),this.db=null),this.listeners.clear()}}const Us=new uQ;async function dQ(){await Us.initialize()}async function hQ(s){return Us.checkForRecovery(s)}const Cd=new Map;async function un(s,e){return Cd.has(s)||Cd.set(s,Promise.resolve(e())),Cd.get(s)}const yk={WARNING_LINEAR:Math.pow(10,-6/20),CLIPPING_LINEAR:1};function vk(s){return{isWarning:s>yk.WARNING_LINEAR,isClipping:s>=yk.CLIPPING_LINEAR}}const sd={peaks:new Map,rms:new Map,masterPeak:0,masterRms:0,isClipping:!1,isWarning:!1},bk={currentTime:0,duration:0,state:"stopped",fps:0,droppedFrames:0,audioBufferHealth:1,videoBufferHealth:1,avgFrameRenderTime:0};na.initialize(1920,1080);const q=Yl()(ty((s,e)=>({initialized:!1,initializing:!1,initError:null,videoEngine:null,audioEngine:null,playbackController:null,titleEngine:na,subtitleEngine:null,graphicsEngine:As,photoEngine:null,exportEngine:null,speechToTextEngine:null,templateEngine:null,soundLibraryEngine:null,chromaKeyEngine:null,multiCamEngine:null,maskEngine:null,nestedSequenceEngine:null,adjustmentLayerEngine:null,currentFrame:null,playbackStats:bk,audioLevels:sd,initialize:async()=>{const t=e();if(!(t.initialized||t.initializing)){s({initializing:!0,initError:null});try{const i=YI(),n=aP(),r=eY(),a=MY(),o=nQ();na.initialize(1920,1080),await i.initialize(),await n.initialize(),await r.initialize(i,n),await o.initialize(),s({initialized:!0,initializing:!1,initError:null,videoEngine:i,audioEngine:n,playbackController:r,titleEngine:na,graphicsEngine:As,photoEngine:a,exportEngine:o})}catch(i){const n=i instanceof Error?i.message:"Unknown initialization error";throw s({initialized:!1,initializing:!1,initError:n}),i}}},dispose:()=>{const t=e();t.videoEngine?.dispose(),t.audioEngine?.dispose(),t.playbackController?.dispose(),t.photoEngine?.dispose(),t.exportEngine?.dispose(),t.graphicsEngine?.clearCache(),t.currentFrame&&t.currentFrame.image.close(),Cd.clear(),s({initialized:!1,initializing:!1,initError:null,videoEngine:null,audioEngine:null,playbackController:null,titleEngine:null,subtitleEngine:null,graphicsEngine:null,photoEngine:null,exportEngine:null,speechToTextEngine:null,soundLibraryEngine:null,chromaKeyEngine:null,multiCamEngine:null,maskEngine:null,nestedSequenceEngine:null,adjustmentLayerEngine:null,currentFrame:null,playbackStats:bk,audioLevels:sd})},renderFrame:async t=>{const{videoEngine:i,initialized:n}=e();return null},getAudioLevels:()=>{const{audioLevels:t}=e();return t||sd},updateAudioLevels:t=>{const i=new Map,n=new Map;let r=0,a=0,o=!1,c=!1;for(const[u,d]of t){i.set(u,d.peak),n.set(u,d.rms),r=Math.max(r,d.peak),a=Math.max(a,d.rms);const h=vk(d.peak);h.isClipping&&(o=!0),h.isWarning&&(c=!0)}const l=vk(r);l.isClipping&&(o=!0),l.isWarning&&(c=!0),s({audioLevels:{peaks:i,rms:n,masterPeak:r,masterRms:a,isClipping:o,isWarning:c}})},resetAudioLevels:()=>{s({audioLevels:sd})},getVideoEngine:()=>e().videoEngine,getAudioEngine:()=>e().audioEngine,getPlaybackController:()=>e().playbackController,getTitleEngine:()=>e().titleEngine,getSubtitleEngine:()=>un("subtitle",()=>new sY),getGraphicsEngine:()=>e().graphicsEngine,getPhotoEngine:()=>e().photoEngine,getExportEngine:()=>e().exportEngine,getSpeechToTextEngine:()=>un("speechToText",()=>new $v),getTemplateEngine:()=>un("template",()=>new qY),getSoundLibraryEngine:()=>un("soundLibrary",()=>new QH),getChromaKeyEngine:()=>un("chromaKey",()=>new rH({width:1920,height:1080})),getMultiCamEngine:()=>un("multiCam",()=>new aH),getMaskEngine:()=>un("mask",()=>new sH({width:1920,height:1080})),getNestedSequenceEngine:()=>un("nestedSequence",()=>new W7),getAdjustmentLayerEngine:()=>un("adjustmentLayer",()=>new cH)})));class fQ{mediaImportService=null;waveformGenerator=null;initialized=!1;async generateVideoElementThumbnails(e,t=10,i=160){if(typeof document>"u")return[];const n=URL.createObjectURL(e),r=document.createElement("video");r.src=n,r.muted=!0,r.playsInline=!0,r.preload="metadata";const a=()=>{r.removeAttribute("src"),r.load(),URL.revokeObjectURL(n)},o=(c,l=2500)=>new Promise((u,d)=>{let h;const f=g=>{h!==void 0&&window.clearTimeout(h),r.removeEventListener(c,p),r.removeEventListener("error",m),g?d(g):u()},p=()=>f(),m=()=>f(new Error("Video thumbnail decode failed"));h=window.setTimeout(()=>f(new Error("Video thumbnail decode timed out")),l),r.addEventListener(c,p,{once:!0}),r.addEventListener("error",m,{once:!0})});try{await o("loadedmetadata");const c=r.videoWidth||i,l=r.videoHeight||Math.round(i*9/16),u=Math.max(1,Math.round(i*(l/Math.max(1,c)))),d=Number.isFinite(r.duration)&&r.duration>0?r.duration:0,h=Math.max(0,d-.05),f=d>0?Array.from({length:Math.max(1,t)},(v,w)=>{const b=t<=1?.1:(w+.5)/Math.max(1,t);return Math.min(h,Math.max(0,d*b))}):[0],p=document.createElement("canvas");p.width=i,p.height=u;const m=p.getContext("2d");if(!m)return[];const g=[];for(const v of f)Math.abs(r.currentTime-v)>.01&&(r.currentTime=v,await o("seeked")),m.fillStyle="#000",m.fillRect(0,0,i,u),m.drawImage(r,0,0,i,u),g.push({timestamp:v,dataUrl:p.toDataURL("image/jpeg",.72)});return g}catch{return[]}finally{a()}}async initialize(){if(!this.initialized)try{this.mediaImportService=await NM(),this.waveformGenerator=UM(),this.initialized=!0}catch(e){const t=e instanceof Error?e.message:"Unknown initialization error";throw new Error(`MediaBridge initialization failed: ${t}`)}}isInitialized(){return this.initialized}async importFile(e,t=!0,i=!1){if(!this.initialized||!this.mediaImportService)return{success:!1,error:"MediaBridge not initialized",hasWaveform:!1};const n=this.captureProjectState();try{const r=await this.mediaImportService.importMedia(e,{generateThumbnails:!i,thumbnailCount:10,thumbnailWidth:160,generateWaveform:t&&!i,waveformSamplesPerSecond:100,useFallback:!0,quickMode:i});if(!r.success||!r.media)return{success:!1,error:r.error||"Import failed",warnings:r.warnings,hasWaveform:!1};const a=r.media.metadata;return this.validateMetadata(a)?{success:!0,media:r.media,warnings:r.warnings,hasWaveform:r.media.waveformData!==null}:{success:!1,error:"Failed to extract valid metadata from media file",hasWaveform:!1}}catch(r){return this.restoreProjectState(n),{success:!1,error:r instanceof Error?r.message:"Unknown import error",hasWaveform:!1}}}async generateThumbnailsForMedia(e,t){if(!this.initialized||!this.mediaImportService)return[];try{const n=(await this.mediaImportService.generateThumbnailsForMedia(e,t,{count:10,width:160})).map(r=>({timestamp:r.timestamp,dataUrl:r.dataUrl||""})).filter(r=>r.dataUrl);return n.length>0||t!=="video"?n:await this.generateVideoElementThumbnails(e,10,160)}catch{return t==="video"?await this.generateVideoElementThumbnails(e,10,160):[]}}async importFiles(e,t){if(!this.initialized||!this.mediaImportService)return e.map(()=>({success:!1,error:"MediaBridge not initialized",hasWaveform:!1}));const i=[];for(let n=0;n0&&e.height>0;return e.duration===null||e.duration===void 0||!t&&e.duration<=0?!1:t?!(e.width===null||e.width===void 0||e.width<=0||e.height===null||e.height===void 0||e.height<=0):!(e.hasVideo&&(e.width===null||e.width===void 0||e.width<=0||e.height===null||e.height===void 0||e.height<=0))}validateWaveformData(e){if(!e.peaks||e.peaks.length===0||e.duration<=0)return!1;const t=Math.ceil(e.duration*e.samplesPerSecond),i=e.peaks.length,n=Math.max(t*.1,10);return!(Math.abs(i-t)>n)}getSupportedFormats(){return this.mediaImportService?this.mediaImportService.getSupportedFormats():{video:[],audio:[],image:[]}}async isFormatSupported(e){return this.mediaImportService?(await this.mediaImportService.validateFormat(e)).supported:!1}captureProjectState(){const t=ys.getState().project;return{mediaLibraryIds:t.mediaLibrary.items.map(i=>i.id),timelineClipIds:t.timeline.tracks.flatMap(i=>i.clips.map(n=>n.id))}}restoreProjectState(e){}dispose(){this.mediaImportService=null,this.waveformGenerator=null,this.initialized=!1}}let mo=null;function Z0(){return mo||(mo=new fQ),mo}async function xk(){const s=Z0();return await s.initialize(),s}function Bee(){mo&&(mo.dispose(),mo=null)}const wk=["Tokyo","Paris","London","Sydney","Berlin","Milan","Seoul","Dubai","Oslo","Vienna","Kyoto","Prague","Lisbon","Boston","Austin","Denver","Portland","Seattle","Montreal","Toronto","Barcelona","Amsterdam","Stockholm","Helsinki","Dublin","Cairo","Mumbai","Bangkok","Singapore","Zurich","Geneva","Florence","Venice","Naples","Athens","Lagos","Nairobi","Marrakech","Cape Town","Havana","Lima","Rio","Santiago","Phoenix","Chicago","Brooklyn","Manhattan","Queens","Osaka","Taipei"],_k=["Morning","Evening","Midnight","Golden","Silver","Crystal","Velvet","Neon","Cosmic","Electric","Vintage","Modern","Classic","Urban","Serene","Bold","Swift","Vivid","Radiant","Mystic"];function pQ(){const s=_k[Math.floor(Math.random()*_k.length)],e=wk[Math.floor(Math.random()*wk.length)];return`${s} ${e}`}const mQ={width:1920,height:1080,frameRate:30,sampleRate:48e3,channels:2};function gQ(){return{tracks:[],subtitles:[],duration:0,markers:[]}}function Tk(s,e){const t=Date.now(),i=s||pQ();return{id:ve(),name:i,createdAt:t,modifiedAt:t,settings:{...mQ,...e},mediaLibrary:{items:[]},timeline:gQ()}}function kk(s){let e=0;for(const t of s.timeline.tracks)for(const i of t.clips){const n=i.startTime+i.duration;n>e&&(e=n)}return e}const On=new OM;async function Ak(s,e,t,i){const n={id:e,projectId:s,blob:t,metadata:i};await On.saveMedia(n)}async function $ee(s){return(await On.loadMedia(s))?.blob||null}async function yQ(s){return On.getMediaByProject(s)}async function vQ(s){await On.deleteMedia(s)}async function jee(s,e,t){await On.saveFileHandle(s,e,t)}async function bQ(s,e){return On.loadFileHandle(s,e)}async function Nee(s,e){await On.saveDirectoryHandle(s,e)}async function xQ(s){return On.loadDirectoryHandle(s)}async function wQ(){await On.clearAllData();const s=["openreel-autosave","openreel-projects","openreel-templates"];await Promise.allSettled(s.map(e=>new Promise((t,i)=>{const n=indexedDB.deleteDatabase(e);n.onsuccess=()=>t(),n.onerror=()=>i(n.error),n.onblocked=()=>t()})))}async function _Q(s,e){return e==="audio"?null:e==="image"?URL.createObjectURL(s):new Promise(t=>{const i=document.createElement("video");i.muted=!0,i.playsInline=!0,i.preload="metadata";const n=()=>{URL.revokeObjectURL(i.src),i.remove()};i.onloadeddata=()=>{i.currentTime=.1},i.onseeked=()=>{try{const r=document.createElement("canvas");r.width=Math.min(i.videoWidth,320),r.height=Math.min(i.videoHeight,320/i.videoWidth*i.videoHeight);const a=r.getContext("2d");a?(a.drawImage(i,0,0,r.width,r.height),r.toBlob(o=>{n(),t(o?URL.createObjectURL(o):null)},"image/jpeg",.7)):(n(),t(null))}catch{n(),t(null)}},i.onerror=()=>{n(),t(null)},setTimeout(()=>{n(),t(null)},5e3),i.src=URL.createObjectURL(s)})}async function TQ(s,e){const t=e||s.blob;if(!t)return s;let i=s.thumbnailUrl;return(!i||i.startsWith("blob:"))&&(i=await _Q(t,s.type)),{...s,blob:t,thumbnailUrl:i,filmstripThumbnails:void 0}}const kQ="openreel-projects",AQ=1,nd="projects",es="recent",Em=10,Mc=[{id:"blank",name:"Blank Project",description:"Start from scratch with no pre-configured tracks",category:"General",settings:{width:1920,height:1080,frameRate:30}},{id:"youtube-landscape",name:"YouTube Landscape",description:"1920x1080 at 30fps - Standard YouTube format",category:"Social Media",settings:{width:1920,height:1080,frameRate:30},tracks:[{type:"video",name:"Main Video"},{type:"audio",name:"Background Music"},{type:"audio",name:"Voiceover"}]},{id:"youtube-short",name:"YouTube Shorts",description:"1080x1920 at 60fps - Vertical short-form content",category:"Social Media",settings:{width:1080,height:1920,frameRate:60},tracks:[{type:"video",name:"Main Video"},{type:"audio",name:"Audio"},{type:"text",name:"Captions"}]},{id:"tiktok",name:"TikTok",description:"1080x1920 at 60fps - Optimized for TikTok",category:"Social Media",settings:{width:1080,height:1920,frameRate:60},tracks:[{type:"video",name:"Main"},{type:"audio",name:"Sound"}]},{id:"instagram-reel",name:"Instagram Reel",description:"1080x1920 at 30fps - Instagram Reels format",category:"Social Media",settings:{width:1080,height:1920,frameRate:30},tracks:[{type:"video",name:"Video"},{type:"audio",name:"Audio"}]},{id:"instagram-post",name:"Instagram Post",description:"1080x1080 at 30fps - Square format for posts",category:"Social Media",settings:{width:1080,height:1080,frameRate:30},tracks:[{type:"video",name:"Video"}]},{id:"cinematic-4k",name:"Cinematic 4K",description:"3840x2160 at 24fps - Film-like quality",category:"Professional",settings:{width:3840,height:2160,frameRate:24},tracks:[{type:"video",name:"A-Roll"},{type:"video",name:"B-Roll"},{type:"audio",name:"Dialogue"},{type:"audio",name:"Music"},{type:"audio",name:"SFX"}]},{id:"podcast",name:"Podcast Video",description:"1920x1080 at 30fps - Audio-focused with waveform visualizer",category:"Audio",settings:{width:1920,height:1080,frameRate:30},tracks:[{type:"video",name:"Background"},{type:"audio",name:"Host"},{type:"audio",name:"Guest"},{type:"graphics",name:"Waveform"}]},{id:"tutorial",name:"Screen Recording",description:"1920x1080 at 60fps - Perfect for tutorials",category:"Educational",settings:{width:1920,height:1080,frameRate:60},tracks:[{type:"video",name:"Screen"},{type:"video",name:"Webcam"},{type:"audio",name:"Narration"},{type:"text",name:"Annotations"}]}];class SQ{db=null;listeners=new Map;currentFileHandle=null;async initialize(){this.db=await this.openDatabase()}openDatabase(){return new Promise((e,t)=>{if(typeof indexedDB>"u"){t(new Error("IndexedDB not supported"));return}const i=indexedDB.open(kQ,AQ);i.onerror=()=>{t(new Error(`Failed to open database: ${i.error?.message}`))},i.onsuccess=()=>e(i.result),i.onupgradeneeded=n=>{const r=n.target.result;r.objectStoreNames.contains(nd)||r.createObjectStore(nd,{keyPath:"id"}),r.objectStoreNames.contains(es)||r.createObjectStore(es,{keyPath:"id"}).createIndex("lastOpened","lastOpened",{unique:!1})}})}async createProject(e={}){const t=e.templateId&&Mc.find(a=>a.id===e.templateId)||Mc[0],i={width:1920,height:1080,frameRate:30,sampleRate:48e3,channels:2,...t.settings,...e.settings},n=t.tracks?.map((a,o)=>({id:`track-${Date.now()}-${o}`,type:a.type,name:a.name,clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}))||[],r={id:ve(),name:e.name||"Untitled Project",createdAt:Date.now(),modifiedAt:Date.now(),settings:i,timeline:{duration:0,tracks:n,markers:[],subtitles:[]},mediaLibrary:{items:[]}};return this.currentFileHandle=null,this.emit("projectOpened",{project:r}),r}async saveProject(e){return this.currentFileHandle?this.saveToFileHandle(e,this.currentFileHandle):this.saveProjectAs(e)}async saveProjectAs(e){if(!("showSaveFilePicker"in window))return this.downloadProject(e);try{const i=await window.showSaveFilePicker({suggestedName:`${e.name}.oreel`,types:[{description:"OpenReel Project",accept:{"application/json":[".oreel",".json"]}}]}),n=await this.saveToFileHandle(e,i);return n&&(this.currentFileHandle=i,await this.addToRecent(e,i)),n}catch(t){return t.name==="AbortError"||console.error("[ProjectManager] Save failed:",t),!1}}async saveToFileHandle(e,t){try{const i=await t.createWritable(),n=JSON.stringify(e,null,2);return await i.write(n),await i.close(),this.emit("projectSaved",{project:e}),!0}catch(i){return console.error("[ProjectManager] Save to file failed:",i),!1}}downloadProject(e){try{const t=JSON.stringify(e,null,2),i=new Blob([t],{type:"application/json"}),n=URL.createObjectURL(i),r=document.createElement("a");return r.href=n,r.download=`${e.name}.oreel`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),this.emit("projectSaved",{project:e}),!0}catch(t){return console.error("[ProjectManager] Download failed:",t),!1}}async openProject(){if("showOpenFilePicker"in window)try{const e=window,[t]=await e.showOpenFilePicker({types:[{description:"OpenReel Project",accept:{"application/json":[".oreel",".json"]}}],multiple:!1}),n=await(await t.getFile()).text(),r=JSON.parse(n);return this.currentFileHandle=t,await this.addToRecent(r,t),this.emit("projectOpened",{project:r}),r}catch(e){return e.name==="AbortError"||console.error("[ProjectManager] Open failed:",e),null}return this.openProjectViaInput()}openProjectViaInput(){return new Promise(e=>{const t=document.createElement("input");t.type="file",t.accept=".oreel,.json",t.onchange=async()=>{const i=t.files?.[0];if(!i){e(null);return}try{const n=await i.text(),r=JSON.parse(n);await this.addToRecent(r),this.emit("projectOpened",{project:r}),e(r)}catch(n){console.error("[ProjectManager] Parse failed:",n),e(null)}},t.click()})}async openRecentProject(e){if(e.fileHandle)try{const t=e.fileHandle;if(await t.queryPermission?.({mode:"read"})!=="granted"&&await t.requestPermission?.({mode:"read"})!=="granted")return null;const r=await(await e.fileHandle.getFile()).text(),a=JSON.parse(r);return this.currentFileHandle=e.fileHandle,await this.updateRecentTimestamp(e.id),this.emit("projectOpened",{project:a}),a}catch(t){return console.error("[ProjectManager] Open recent failed:",t),await this.removeFromRecent(e.id),null}return this.loadProjectFromDb(e.id)}async loadProjectFromDb(e){return this.db?new Promise(t=>{const r=this.db.transaction(nd,"readonly").objectStore(nd).get(e);r.onsuccess=()=>{const a=r.result;a&&this.emit("projectOpened",{project:a}),t(a||null)},r.onerror=()=>t(null)}):null}async getRecentProjects(){return this.db||await this.initialize(),new Promise(e=>{if(!this.db){e([]);return}const r=this.db.transaction(es,"readonly").objectStore(es).index("lastOpened").getAll();r.onsuccess=()=>{const a=r.result.sort((o,c)=>c.lastOpened-o.lastOpened).slice(0,Em);e(a)},r.onerror=()=>e([])})}async addToRecent(e,t){if(!this.db)return;const i={id:e.id,name:e.name,lastOpened:Date.now(),fileHandle:t,duration:e.timeline.duration,trackCount:e.timeline.tracks.length};return new Promise(n=>{const r=this.db.transaction(es,"readwrite");r.objectStore(es).put(i),r.oncomplete=()=>{this.emit("recentUpdated"),this.cleanupOldRecent(),n()},r.onerror=()=>n()})}async updateRecentTimestamp(e){if(this.db)return new Promise(t=>{const n=this.db.transaction(es,"readwrite").objectStore(es),r=n.get(e);r.onsuccess=()=>{const a=r.result;a&&(a.lastOpened=Date.now(),n.put(a)),t()},r.onerror=()=>t()})}async removeFromRecent(e){if(this.db)return new Promise(t=>{const i=this.db.transaction(es,"readwrite");i.objectStore(es).delete(e),i.oncomplete=()=>{this.emit("recentUpdated"),t()},i.onerror=()=>t()})}async cleanupOldRecent(){const e=await this.getRecentProjects();if(e.length>Em){const t=e.slice(Em);for(const i of t)await this.removeFromRecent(i.id)}}async clearRecentProjects(){if(this.db)return new Promise(e=>{const t=this.db.transaction(es,"readwrite");t.objectStore(es).clear(),t.oncomplete=()=>{this.emit("recentUpdated"),e()},t.onerror=()=>e()})}getTemplates(){return[...Mc]}getTemplatesByCategory(){const e=new Map;for(const t of Mc){const i=e.get(t.category)||[];i.push(t),e.set(t.category,i)}return e}getCurrentFileHandle(){return this.currentFileHandle}hasUnsavedChanges(e){const t=e;return!this.currentFileHandle||e.modifiedAt>(t.lastSavedAt??0)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(i=>{try{i(t)}catch(n){console.error("[ProjectManager] Event callback error:",n)}})}}const CQ=new SQ,ys=Yl()(ty((s,e)=>{const t=new zc,i=new Ou(t),n=y=>y.timeline.tracks.flatMap(_=>_.clips.map(T=>T.id)),r=y=>y.map((_,T)=>({id:_.id,type:_.type,enabled:_.enabled,params:_.params,order:T})),a=(y,_,T)=>{let S=!1;const C=y.timeline.tracks.map(E=>{let P=!1;const L=E.clips.map(O=>O.id!==_?O:(S=!0,P=!0,T(O)));return P?{...E,clips:L}:E});return S?{...y,timeline:{...y.timeline,tracks:C},modifiedAt:Date.now()}:null},o=y=>{const _=Bs();if(!_.isInitialized())return{};const T=_.getColorGrading(y);return{...T.colorWheels?{colorWheels:T.colorWheels}:{},...T.curves?{curves:T.curves}:{},...T.lut?{lut:{data:Array.from(T.lut.data),size:T.lut.size,intensity:T.lut.intensity}}:{},...T.hsl?{hsl:T.hsl}:{}}},c=(y,_)=>{const T=Bs();if(!T.isInitialized())return;const S=y.timeline.tracks.flatMap(E=>E.clips).find(E=>E.id===_);if(!S){T.clearEffects(_);return}const C=r(S.effects);T.deserializeEffects(_,{effects:C.map(E=>({id:E.id,type:E.type,enabled:E.enabled,params:E.params,order:E.order})),colorGrading:o(_)})},l=(y,_)=>{const T=Bs();if(!T.isInitialized())return;const S=new Set(n(y));for(const C of _?n(_):[])S.has(C)||T.clearEffects(C);for(const C of S)c(y,C)},u=(y,_)=>{const T=J0();if(!T.isInitialized())return;const S=y.timeline.tracks.find(C=>C.id===_);if(!S){T.clearTransitionsForTrack(_);return}T.setTransitionsForTrack(_,S.transitions)},d=(y,_)=>{const T=J0();if(!T.isInitialized())return;const S=new Set(y.timeline.tracks.map(C=>C.id));for(const C of _?_.timeline.tracks.map(E=>E.id):[])S.has(C)||T.clearTransitionsForTrack(C);for(const C of y.timeline.tracks)u(y,C.id)},h=y=>({id:`track-${ve()}`,type:y,name:y==="text"?"Recipe Text":"Recipe Graphics",clips:[],transitions:[],locked:!1,hidden:!1,muted:!1,solo:!1}),f=(y,_)=>{if(y.timeline.tracks.some(C=>C.id===_.track.id))return y;const T=[...y.timeline.tracks],S=Math.max(0,Math.min(_.position,T.length));return T.splice(S,0,_.track),{...y,timeline:{...y.timeline,tracks:T},modifiedAt:Date.now()}},p=(y,_)=>{const T=y.timeline.tracks.filter(S=>S.id!==_);return T.length===y.timeline.tracks.length?y:{...y,timeline:{...y.timeline,tracks:T},modifiedAt:Date.now()}},m=(y,_)=>{const T=y.timeline.tracks.find(S=>S.id===_);if(!T)return!1;if(T.clips.length>0)return!0;if(T.type==="text")return q.getState().getTitleEngine()?.getAllTextClips().some(C=>C.trackId===_)??!1;if(T.type==="graphics"){const S=q.getState().getGraphicsEngine();return S?[...S.getAllShapeClips(),...S.getAllSVGClips(),...S.getAllStickerClips()].some(C=>C.trackId===_):!1}return!1},g=(y,_)=>_.map((T,S)=>({id:`${y}-keyframe-${S+1}`,time:T.time,property:T.property,value:T.value,easing:T.easing})),v=(y,_,T,S,C)=>({templateId:y,applicationId:_,ownerClipId:T,ownerTrackId:S,controlValues:C}),w=(y,_,T=Date.now())=>({templateId:y.template.id,applicationId:_,name:y.template.name,category:y.template.category,appliedAt:T,controlValues:y.controlValues}),b=y=>({ownerClipId:y.ownerClipId,templateId:y.templateId,applicationId:y.applicationId,appliedTemplate:y.appliedTemplate,addedEffects:y.addedEffects,addedAudioEffects:y.addedAudioEffects,addedKeyframes:y.addedKeyframes,overlays:y.overlays,trackSnapshots:y.trackSnapshots}),k=y=>y.overlays.reduce((_,T)=>(_[T.overlay.trackType]=T.trackId,_),{}),A=(y,_)=>{const{templateUndoStack:T,templateRedoStack:S}=e();return[...T,...S].reverse().find(C=>C.ownerClipId===y&&C.applicationId===_)},M=(y,_,T,S={},C={})=>{const E=$T(_);if(!E)return null;const P=y.timeline.tracks.find(de=>de.clips.some(qe=>qe.id===T)),L=P?.clips.find(de=>de.id===T);if(!P||!L)return null;const O=P.type==="image"?"image":P.type==="video"?"video":null;if(!O||E.supportedTargets&&!E.supportedTargets.includes(O))return null;const U=q.getState().getTitleEngine(),j=q.getState().getGraphicsEngine(),N=E.recipe.overlays.some(de=>de.trackType==="text"),z=E.recipe.overlays.some(de=>de.trackType==="graphics");if(N&&!U||z&&!j)return null;const W=y.mediaLibrary.items.find(de=>de.id===L.mediaId),Q=y.mediaLibrary.items.reduce((de,qe)=>{const Sr=qe.originalUrl??qe.thumbnailUrl??void 0;return Sr&&(de[qe.id]=Sr),de},{}),fe=OY(E,{clip:{id:L.id,startTime:L.startTime,duration:L.duration,name:W?.name},assetUrls:Q},S),ye=C.applicationId||`editing-template-${ve()}`,le=w(fe,ye,C.appliedAt),Le=v(E.id,ye,L.id,L.trackId,le.controlValues),Oe=fe.effects.map((de,qe)=>({id:`template-effect-${ye}-${qe+1}-${de.id}`,type:de.type,params:de.params,enabled:de.enabled,metadata:{templateSource:Le}})),jt=fe.audioEffects.map((de,qe)=>({id:`template-audio-effect-${ye}-${qe+1}-${de.id}`,type:de.type,params:de.params,enabled:de.enabled,metadata:{templateSource:Le}})),dt=[...fe.effects.flatMap((de,qe)=>g(`template-keyframe-${ye}-video-${qe+1}`,de.keyframes)),...fe.audioEffects.flatMap((de,qe)=>g(`template-keyframe-${ye}-audio-${qe+1}`,de.keyframes))];let ht=y;const Si=[...(C.preservedTrackSnapshots||[]).filter(de=>ht.timeline.tracks.some(qe=>qe.id===de.track.id))],Lt={};for(const de of Si)(de.track.type==="text"||de.track.type==="graphics")&&(Lt[de.track.type]=de.track.id);const Ar=de=>{const qe=Lt[de];if(qe&&ht.timeline.tracks.some(uc=>uc.id===qe))return qe;const Sr=C.preferredTrackIds?.[de];if(Sr&&ht.timeline.tracks.some(uc=>uc.id===Sr))return Lt[de]=Sr,Sr;const xf=ht.timeline.tracks.find(uc=>uc.type===de);if(xf)return Lt[de]=xf.id,xf.id;const xu={track:h(de),position:0};return Si.push(xu),ht=f(ht,xu),Lt[de]=xu.track.id,xu.track.id},pb=fe.overlays.map((de,qe)=>({trackId:Ar(de.trackType),overlay:{...de,id:`template-overlay-${ye}-${qe+1}-${de.id}`}})),mb=a(ht,T,de=>({...de,effects:[...de.effects,...Oe],audioEffects:[...de.audioEffects,...jt],keyframes:[...de.keyframes,...dt],metadata:{...de.metadata||{},appliedTemplates:[...de.metadata?.appliedTemplates||[],le]}}));if(!mb)return null;ht=mb;for(const de of pb)if(!I(de,Le))return B(ht,T,ye,Si.map(qe=>qe.track.id)),null;return c(ht,T),{project:{...ht,modifiedAt:Date.now()},applicationState:{ownerClipId:T,templateId:E.id,applicationId:ye,appliedTemplate:le,addedEffects:Oe,addedAudioEffects:jt,addedKeyframes:dt,overlays:pb,trackSnapshots:Si}}},R=y=>{const _=q.getState().getTitleEngine(),T=q.getState().getGraphicsEngine();for(const S of y)if(S.overlay.type==="text"&&!_||S.overlay.type!=="text"&&!T||S.overlay.type==="image"&&!S.overlay.content.imageUrl)return!1;return!0},I=(y,_)=>{const T={templateSource:_,templateManaged:!0,templateTrackType:y.overlay.trackType};if(y.overlay.type==="text"){const C=q.getState().getTitleEngine();return C?C.getTextClip(y.overlay.id)?!0:(C.createTextClip({id:y.overlay.id,trackId:y.trackId,startTime:y.overlay.timing.startTime,duration:y.overlay.timing.duration,text:y.overlay.content.text,style:y.overlay.content.style,transform:y.overlay.transform,animation:y.overlay.content.animation?{preset:y.overlay.content.animation.preset,params:y.overlay.content.animation.params||{},inDuration:y.overlay.content.animation.inDuration,outDuration:y.overlay.content.animation.outDuration,stagger:y.overlay.content.animation.stagger,unit:y.overlay.content.animation.unit}:void 0,metadata:T}),!!C.updateTextClip(y.overlay.id,{keyframes:g(y.overlay.id,y.overlay.keyframes),blendMode:y.overlay.blendMode,blendOpacity:y.overlay.blendOpacity,emphasisAnimation:y.overlay.emphasisAnimation,metadata:T})):!1}const S=q.getState().getGraphicsEngine();return S?y.overlay.type==="shape"?S.getShapeClip(y.overlay.id)?!0:(S.createShape({id:y.overlay.id,shapeType:y.overlay.content.shapeType,width:y.overlay.content.width,height:y.overlay.content.height,style:y.overlay.content.style,metadata:T},y.trackId,y.overlay.timing.startTime,y.overlay.timing.duration),!!S.updateShapeClip(y.overlay.id,{transform:y.overlay.transform,keyframes:g(y.overlay.id,y.overlay.keyframes),blendMode:y.overlay.blendMode,blendOpacity:y.overlay.blendOpacity,emphasisAnimation:y.overlay.emphasisAnimation})):S.getStickerClip(y.overlay.id)?!0:y.overlay.content.imageUrl?(S.addStickerClip({id:y.overlay.id,trackId:y.trackId,startTime:y.overlay.timing.startTime,duration:y.overlay.timing.duration,type:"sticker",imageUrl:y.overlay.content.imageUrl,name:y.overlay.content.name,transform:y.overlay.transform,keyframes:g(y.overlay.id,y.overlay.keyframes),blendMode:y.overlay.blendMode,blendOpacity:y.overlay.blendOpacity,emphasisAnimation:y.overlay.emphasisAnimation,metadata:T}),!0):!1:!1},D=(y,_,T)=>{const S=y.timeline.tracks.flatMap(P=>P.clips).find(P=>P.id===_);if(S&&((S.metadata?.appliedTemplates||[]).some(P=>P.applicationId===T)||S.effects.some(P=>P.metadata?.templateSource?.applicationId===T)||S.audioEffects.some(P=>P.metadata?.templateSource?.applicationId===T)||S.keyframes.some(P=>P.id.startsWith(`template-keyframe-${T}-`)))||q.getState().getTitleEngine()?.getAllTextClips().some(P=>P.metadata?.templateSource?.applicationId===T))return!0;const E=q.getState().getGraphicsEngine();return E?[...E.getAllShapeClips(),...E.getAllSVGClips(),...E.getAllStickerClips()].some(P=>P.metadata?.templateSource?.applicationId===T):!1},B=(y,_,T,S=[])=>{let C=y;if(y.timeline.tracks.flatMap(O=>O.clips).find(O=>O.id===_)){const O=a(y,_,U=>{const j=(U.metadata?.appliedTemplates||[]).filter(z=>z.applicationId!==T),N={...U.metadata||{}};return j.length>0?N.appliedTemplates=j:delete N.appliedTemplates,{...U,effects:U.effects.filter(z=>z.metadata?.templateSource?.applicationId!==T),audioEffects:U.audioEffects.filter(z=>z.metadata?.templateSource?.applicationId!==T),keyframes:U.keyframes.filter(z=>!z.id.startsWith(`template-keyframe-${T}-`)),metadata:Object.keys(N).length>0?N:void 0}});O&&(C=O)}const P=q.getState().getTitleEngine();for(const O of P?.getAllTextClips()||[])O.metadata?.templateSource?.applicationId===T&&P?.deleteTextClip(O.id);const L=q.getState().getGraphicsEngine();if(L){for(const O of L.getAllShapeClips())O.metadata?.templateSource?.applicationId===T&&L.deleteShapeClip(O.id);for(const O of L.getAllSVGClips())O.metadata?.templateSource?.applicationId===T&&L.deleteSVGClip(O.id);for(const O of L.getAllStickerClips())O.metadata?.templateSource?.applicationId===T&&L.deleteStickerClip(O.id)}for(const O of S)m(C,O)||(C=p(C,O));return c(C,_),{...C,modifiedAt:Date.now()}},$=(y,_,T=!0)=>B(y,_.ownerClipId,_.applicationId,T?_.trackSnapshots.map(S=>S.track.id):[]),V=(y,_)=>{if(!R(_.overlays))return null;let T=y;for(const P of _.trackSnapshots)T=f(T,P);const S=T.timeline.tracks.flatMap(P=>P.clips).find(P=>P.id===_.ownerClipId);if(!S)return null;const C=v(_.templateId,_.applicationId,_.ownerClipId,S.trackId,_.appliedTemplate.controlValues),E=a(T,_.ownerClipId,P=>{const L=new Set(P.effects.map(z=>z.id)),O=new Set(P.audioEffects.map(z=>z.id)),U=new Set(P.keyframes.map(z=>z.id)),j=P.metadata?.appliedTemplates||[],N=j.some(z=>z.applicationId===_.applicationId);return{...P,effects:[...P.effects,..._.addedEffects.filter(z=>!L.has(z.id))],audioEffects:[...P.audioEffects,..._.addedAudioEffects.filter(z=>!O.has(z.id))],keyframes:[...P.keyframes,..._.addedKeyframes.filter(z=>!U.has(z.id))],metadata:{...P.metadata||{},appliedTemplates:N?j:[...j,_.appliedTemplate]}}});if(!E)return null;T=E;for(const P of _.overlays)if(!I(P,C))return null;return c(T,_.ownerClipId),{...T,modifiedAt:Date.now()}};return{project:Tk(),photoProjects:new Map,actionExecutor:i,actionHistory:t,clipUndoStack:[],clipRedoStack:[],templateUndoStack:[],templateRedoStack:[],isLoading:!1,error:null,clipboard:[],copiedEffects:[],createNewProject:(y,_)=>{const T=new zc,S=new Ou(T),C=e().project,E=Tk(y,_);l(E,C),d(E,C),s({project:E,actionHistory:T,actionExecutor:S,clipUndoStack:[],clipRedoStack:[],templateUndoStack:[],templateRedoStack:[],error:null})},loadProject:y=>{const _=e().project,T=q.getState().getTitleEngine(),S=q.getState().getGraphicsEngine();T&&y.textClips&&T.loadTextClips(y.textClips),S&&(y.shapeClips&&S.loadShapeClips(y.shapeClips),y.svgClips&&S.loadSVGClips(y.svgClips),y.stickerClips&&S.loadStickerClips(y.stickerClips));const C=new zc,E=new Ou(C),P=y.timeline.tracks.reduce((U,j)=>j.clips.reduce((N,z)=>Math.max(N,z.startTime+z.duration),U),0),L=P>0&&y.timeline.duration===0?{...y,timeline:{...y.timeline,duration:P}}:y;l(L,_),d(L,_),s({project:L,actionHistory:C,actionExecutor:E,clipUndoStack:[],clipRedoStack:[],templateUndoStack:[],templateRedoStack:[],error:null});const O=L.mediaLibrary.items.filter(U=>U.isPlaceholder&&U.sourceFile);O.length>0&&"FileSystemFileHandle"in window&&(async()=>{let U=0;const j=[];for(const N of O)if(N.sourceFile)try{const z=await bQ(N.sourceFile.name,N.sourceFile.size);if(!z){j.push(N);continue}const W=await z.getFile();await e().replaceMediaAsset(N.id,W,N.sourceFile.folder),U++}catch{j.push(N)}if(j.length>0)try{const N=await xQ(L.id);if(N){const z=new Map,W=N.handle.entries();for await(const[,Q]of W)if(Q.kind==="file"){const fe=await Q.getFile();z.set(`${fe.name.toLowerCase()}:${fe.size}`,{file:fe,folder:N.folderName})}for(const Q of j){if(!Q.sourceFile)continue;const fe=z.get(`${Q.sourceFile.name.toLowerCase()}:${Q.sourceFile.size}`);if(fe)try{await e().replaceMediaAsset(Q.id,fe.file,fe.folder),U++}catch{}}}}catch{}U>0&&console.info(`[ProjectStore] Auto-restored ${U} asset(s) from file handles`)})()},renameProject:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"project/rename",id:ve(),timestamp:Date.now(),params:{name:y}},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},updateSettings:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"project/updateSettings",id:ve(),timestamp:Date.now(),params:y},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},importMedia:async y=>{const{project:_}=e();try{const T=Z0();T.isInitialized()||await xk();const S=y.size>50*1024*1024,C=await T.importFile(y,!0,S);if(!C.success||!C.media)return{success:!1,error:{code:"DECODE_ERROR",message:C.error||"Failed to import media"}};const E=C.media;let P=null;const L=[];if(E.thumbnails&&E.thumbnails.length>0){for(const N of E.thumbnails){let z=null;if(N.dataUrl)z=N.dataUrl;else if(N.canvas)try{if(N.canvas instanceof OffscreenCanvas){const W=await N.canvas.convertToBlob({type:"image/jpeg",quality:.7});z=URL.createObjectURL(W)}else N.canvas instanceof HTMLCanvasElement&&(z=N.canvas.toDataURL("image/jpeg",.7))}catch(W){console.warn("Failed to convert thumbnail canvas to URL:",W)}z&&L.push({timestamp:N.timestamp,url:z})}L.length>0&&(P=L[0].url)}let O;if(y.type.startsWith("image/")?O="image":E.metadata.hasVideo?O="video":E.metadata.hasAudio?O="audio":O="image",O==="video"&&!P)try{const N=await T.generateThumbnailsForMedia(E.blob??y,O);N.length>0&&(P=N[0].dataUrl,L.push(...N.map(z=>({timestamp:z.timestamp,url:z.dataUrl}))))}catch{}const U={id:ve(),name:y.name,type:O,fileHandle:null,blob:y,metadata:{duration:E.metadata.duration||0,width:E.metadata.width||0,height:E.metadata.height||0,frameRate:E.metadata.frameRate||0,codec:E.metadata.codec||"",sampleRate:E.metadata.sampleRate||0,channels:E.metadata.channels||0,fileSize:y.size},thumbnailUrl:P,waveformData:E.waveformData?.peaks||null,filmstripThumbnails:L.length>0?L:void 0,sourceFile:{name:y.name,size:y.size,lastModified:y.lastModified}},j={..._,mediaLibrary:{..._.mediaLibrary,items:[..._.mediaLibrary.items,U]},modifiedAt:Date.now()};s({project:j});try{await Ak(j.id,U.id,y,U.metadata)}catch(N){console.error("[ProjectStore] Failed to persist media blob:",N)}return O==="video"&&!P&&setTimeout(async()=>{try{const N=await T.generateThumbnailsForMedia(U.blob??y,O);if(N.length>0){const z=e().project,W=z.mediaLibrary.items.findIndex(Q=>Q.id===U.id);if(W!==-1){const Q=[...z.mediaLibrary.items];Q[W]={...Q[W],thumbnailUrl:N[0].dataUrl,filmstripThumbnails:N.map(fe=>({timestamp:fe.timestamp,url:fe.dataUrl}))},s({project:{...z,mediaLibrary:{...z.mediaLibrary,items:Q},modifiedAt:Date.now()}})}}}catch{}},100),{success:!0,actionId:U.id}}catch(T){return{success:!1,error:{code:"DECODE_ERROR",message:T instanceof Error?T.message:"Unknown import error"}}}},deleteMedia:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"media/delete",id:ve(),timestamp:Date.now(),params:{mediaId:y}},C=await T.execute(S,_);return C.success&&(s({project:{..._}}),vQ(y).catch(E=>console.warn("[ProjectStore] Failed to delete media blob:",E))),C},replaceMediaAsset:async(y,_,T)=>{const{project:S}=e();try{const C=Z0();C.isInitialized()||await xk();const E=await C.importFile(_,!0);if(!E.success||!E.media)return{success:!1,error:{code:"DECODE_ERROR",message:E.error||"Failed to import media"}};const P=E.media;let L=null;const O=[];if(P.thumbnails&&P.thumbnails.length>0){for(const z of P.thumbnails){let W=null;if(z.dataUrl)W=z.dataUrl;else if(z.canvas)try{if(z.canvas instanceof OffscreenCanvas){const Q=await z.canvas.convertToBlob({type:"image/jpeg",quality:.7});W=URL.createObjectURL(Q)}else z.canvas instanceof HTMLCanvasElement&&(W=z.canvas.toDataURL("image/jpeg",.7))}catch(Q){console.warn("Failed to convert thumbnail canvas to URL:",Q)}W&&O.push({timestamp:z.timestamp,url:W})}O.length>0&&(L=O[0].url)}const U=P.metadata.hasVideo?"video":P.metadata.hasAudio?"audio":"image";if(U==="video"&&!L)try{const z=await C.generateThumbnailsForMedia(P.blob??_,U);z.length>0&&(L=z[0].dataUrl,O.push(...z.map(W=>({timestamp:W.timestamp,url:W.dataUrl}))))}catch{}const j={id:y,name:_.name,type:U,fileHandle:null,blob:_,metadata:{duration:P.metadata.duration||0,width:P.metadata.width||0,height:P.metadata.height||0,frameRate:P.metadata.frameRate||0,codec:P.metadata.codec||"",sampleRate:P.metadata.sampleRate||0,channels:P.metadata.channels||0,fileSize:_.size},thumbnailUrl:L,waveformData:P.waveformData?.peaks||null,filmstripThumbnails:O.length>0?O:void 0,isPlaceholder:!1,sourceFile:{name:_.name,size:_.size,lastModified:_.lastModified,folder:T}},N=S.mediaLibrary.items.map(z=>z.id===y?j:z);return s({project:{...S,mediaLibrary:{items:N},modifiedAt:Date.now()}}),j.type==="video"&&!j.thumbnailUrl&&setTimeout(async()=>{try{const z=await C.generateThumbnailsForMedia(j.blob??_,j.type);if(z.length>0){const W=e().project,Q=W.mediaLibrary.items.map(fe=>fe.id===y?{...fe,thumbnailUrl:z[0].dataUrl,filmstripThumbnails:z.map(ye=>({timestamp:ye.timestamp,url:ye.dataUrl}))}:fe);s({project:{...W,mediaLibrary:{items:Q},modifiedAt:Date.now()}})}}catch{}},100),{success:!0,actionId:ve()}}catch(C){return{success:!1,error:{code:"DECODE_ERROR",message:C instanceof Error?C.message:"Unknown import error"}}}},renameMedia:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"media/rename",id:ve(),timestamp:Date.now(),params:{mediaId:y,name:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},getMediaItem:y=>{const{project:_}=e();return _.mediaLibrary.items.find(T=>T.id===y)},addPlaceholderMedia:y=>{const{project:_}=e();s({project:{..._,mediaLibrary:{..._.mediaLibrary,items:[..._.mediaLibrary.items,y]},modifiedAt:Date.now()}})},setKieAIItemState:(y,_,T)=>{const{project:S}=e(),C=S.mediaLibrary.items.map(E=>E.id===y?{...E,isPending:_,kieaiError:T}:E);s({project:{...S,mediaLibrary:{...S.mediaLibrary,items:C},modifiedAt:Date.now()}})},replacePlaceholderMedia:async(y,_,T)=>{const{project:S}=e();let C=null,E=0,P=0;if(_.size>0&&_.type.startsWith("image/"))try{const j=await createImageBitmap(_);E=j.width,P=j.height;const N=320,z=Math.min(N/j.width,N/j.height,1),W=Math.round(j.width*z),Q=Math.round(j.height*z),fe=new OffscreenCanvas(W,Q);fe.getContext("2d").drawImage(j,0,0,W,Q),j.close();const le=await fe.convertToBlob({type:"image/jpeg",quality:.75});C=await new Promise((Le,Oe)=>{const jt=new FileReader;jt.onload=()=>Le(jt.result),jt.onerror=()=>Oe(jt.error),jt.readAsDataURL(le)})}catch(j){console.warn("[ProjectStore] KieAI thumbnail generation failed:",j)}const L=new File([_],T,{type:_.type||"image/png"}),O={id:y,name:T,type:"image",fileHandle:null,blob:L,metadata:{duration:0,width:E,height:P,frameRate:0,codec:"",sampleRate:0,channels:0,fileSize:L.size},thumbnailUrl:C,waveformData:null,isPlaceholder:!1,isPending:!1},U=S.mediaLibrary.items.map(j=>j.id===y?O:j);s({project:{...S,mediaLibrary:{...S.mediaLibrary,items:U},modifiedAt:Date.now()}});try{await Ak(S.id,y,L,O.metadata)}catch(j){console.error("[ProjectStore] Failed to persist KieAI result blob:",j)}},addTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C=structuredClone(T),E={type:"track/add",id:ve(),timestamp:Date.now(),params:{trackType:y,position:_}},P=await S.execute(E,C);if(P.success){const L={...C,modifiedAt:Date.now()};s({project:L})}return P},removeTrack:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"track/remove",id:ve(),timestamp:Date.now(),params:{trackId:y}},C=await T.execute(S,_);return C.success&&s({project:{..._,timeline:{..._.timeline},modifiedAt:Date.now()}}),C},renameTrack:(y,_)=>{const{project:T}=e(),S=_.trim();S&&s({project:{...T,timeline:{...T.timeline,tracks:T.timeline.tracks.map(C=>C.id===y?{...C,name:S}:C)},modifiedAt:Date.now()}})},reorderTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"track/reorder",id:ve(),timestamp:Date.now(),params:{trackId:y,newPosition:_}},E=await S.execute(C,T);return E.success&&s({project:{...T,modifiedAt:Date.now()}}),E},lockTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"track/lock",id:ve(),timestamp:Date.now(),params:{trackId:y,locked:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},hideTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"track/hide",id:ve(),timestamp:Date.now(),params:{trackId:y,hidden:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},muteTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"track/mute",id:ve(),timestamp:Date.now(),params:{trackId:y,muted:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},soloTrack:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"track/solo",id:ve(),timestamp:Date.now(),params:{trackId:y,solo:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},getTrack:y=>{const{project:_}=e();return _.timeline.tracks.find(T=>T.id===y)},addClip:async(y,_,T)=>{const{project:S,actionExecutor:C}=e(),E=structuredClone(S),P={type:"clip/add",id:ve(),timestamp:Date.now(),params:{trackId:y,mediaId:_,startTime:T}},L=await C.execute(P,E);if(L.success){const O={...E,modifiedAt:Date.now()};s({project:O})}return L},addClipToNewTrack:async(y,_)=>{const{project:T,addTrack:S,getMediaItem:C}=e(),E=C(y);if(!E)return{success:!1,error:{code:"MEDIA_NOT_FOUND",message:"Media item not found"}};let P;E.type==="video"?P="video":E.type==="audio"?P="audio":E.type==="image"?P="image":P="video";const L=_!==void 0?_:kk(T),O=await S(P);if(!O.success)return O;const{project:U,actionExecutor:j}=e(),N=U.timeline.tracks.find(fe=>fe.clips.length===0&&fe.type===P);if(!N)return{success:!1,error:{code:"TRACK_NOT_FOUND",message:"Could not find newly created track"}};const z=structuredClone(U),W={type:"clip/add",id:ve(),timestamp:Date.now(),params:{trackId:N.id,mediaId:y,startTime:L}},Q=await j.execute(W,z);if(Q.success){const fe={...z,modifiedAt:Date.now()};s({project:fe})}return Q},separateAudio:async y=>{const{project:_,actionExecutor:T}=e(),S=_.timeline.tracks.flatMap(j=>j.clips).find(j=>j.id===y);if(!S)return{success:!1,error:{code:"CLIP_NOT_FOUND",message:"Clip not found"}};const C=_.mediaLibrary.items.find(j=>j.id===S.mediaId);if(!C||C.type!=="video"||!C.metadata?.channels||C.metadata.channels===0)return{success:!1,error:{code:"MEDIA_NOT_FOUND",message:"Media has no audio to separate"}};let E=C.metadata.audioTrackCount??1;if(E<=1&&C.blob)try{const{getFFmpegFallback:j}=await ii(async()=>{const{getFFmpegFallback:W}=await Promise.resolve().then(()=>iG);return{getFFmpegFallback:W}},void 0),z=await j().probeAudioStreams(C.blob);z.audioStreamCount>1&&(E=z.audioStreamCount)}catch{}const P=structuredClone(_),L=P.timeline.tracks.filter(j=>j.type==="audio").length;for(let j=L;jj.type==="audio");if(O.length===0)return{success:!1,error:{code:"TRACK_NOT_FOUND",message:"Could not find or create audio track"}};let U={success:!0};for(let j=0;jW.id===y);if(z!==-1){N.clips[z].volume=0;break}}const j={...P,modifiedAt:Date.now()};s({project:j})}return U},removeClip:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"clip/remove",id:ve(),timestamp:Date.now(),params:{clipId:y}},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},moveClip:async(y,_,T)=>{const{project:S,actionExecutor:C}=e(),E={type:"clip/move",id:ve(),timestamp:Date.now(),params:{clipId:y,startTime:_,trackId:T}},P=await C.execute(E,S);return P.success&&s({project:{...S}}),P},beginHistoryGroup:y=>{const{actionExecutor:_}=e();_.getHistory().beginGroup(y)},endHistoryGroup:()=>{const{actionExecutor:y}=e();y.getHistory().endGroup()},closeGapBeforeClip:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"clip/closeGapBefore",id:ve(),timestamp:Date.now(),params:{clipId:y}},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},consolidateTrack:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"track/consolidate",id:ve(),timestamp:Date.now(),params:{trackId:y}},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},moveClips:async y=>{if(y.length===0)return{success:!0};if(y.length===1)return e().moveClip(y[0].clipId,y[0].startTime,y[0].trackId);const{actionExecutor:_}=e(),T=_.getHistory();T.beginGroup("Move clips");try{let S={success:!0};for(const C of y){const{project:E}=e(),P={type:"clip/move",id:ve(),timestamp:Date.now(),params:{clipId:C.clipId,startTime:C.startTime,trackId:C.trackId}};if(S=await _.execute(P,E),!S.success)break;s({project:{...E}})}return S}finally{T.endGroup()}},trimClip:async(y,_,T)=>{const{project:S,actionExecutor:C}=e(),E={type:"clip/trim",id:ve(),timestamp:Date.now(),params:{clipId:y,inPoint:_,outPoint:T}},P=await C.execute(E,S);return P.success&&s({project:{...S}}),P},splitClip:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"clip/split",id:ve(),timestamp:Date.now(),params:{clipId:y,time:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},rippleDeleteClip:async y=>{const{project:_,actionExecutor:T}=e(),S={type:"clip/rippleDelete",id:ve(),timestamp:Date.now(),params:{clipId:y}},C=await T.execute(S,_);return C.success&&s({project:{..._}}),C},slipClip:async(y,_)=>{const{project:T,actionExecutor:S}=e(),C={type:"clip/slip",id:ve(),timestamp:Date.now(),params:{clipId:y,delta:_}},E=await S.execute(C,T);return E.success&&s({project:{...T}}),E},slideClip:async(y,_)=>{const{project:T,actionExecutor:S,getClip:C}=e();if(!C(y))return{success:!1,error:{code:"INVALID_PARAMS",message:"Clip not found"}};const P=T.timeline.tracks.find(W=>W.clips.some(Q=>Q.id===y));if(!P)return{success:!1,error:{code:"INVALID_PARAMS",message:"Track not found"}};const L=[...P.clips].sort((W,Q)=>W.startTime-Q.startTime),O=L.findIndex(W=>W.id===y),U=O>0?L[O-1]:void 0,j=O{const{project:S,actionExecutor:C}=e(),E={type:"clip/roll",id:ve(),timestamp:Date.now(),params:{leftClipId:y,rightClipId:_,delta:T}},P=await C.execute(E,S);return P.success&&s({project:{...S}}),P},trimToPlayhead:async(y,_,T)=>{const{project:S,actionExecutor:C}=e(),E={type:"clip/trimToPlayhead",id:ve(),timestamp:Date.now(),params:{clipId:y,playheadTime:_,trimStart:T}},P=await C.execute(E,S);return P.success&&s({project:{...S}}),P},getClip:y=>{const{project:_}=e();for(const T of _.timeline.tracks){const S=T.clips.find(C=>C.id===y);if(S)return S}},addClipTransition:y=>{const{project:_}=e(),T=_.timeline.tracks.flatMap(P=>P.clips).find(P=>P.id===y.clipAId);if(!T)return null;const S=_.timeline.tracks.find(P=>P.id===T.trackId);if(!S)return null;const C={...S,transitions:[...S.transitions.filter(P=>P.id!==y.id&&!(P.clipAId===y.clipAId&&P.clipBId===y.clipBId)),y]},E={..._,timeline:{..._.timeline,tracks:_.timeline.tracks.map(P=>P.id===S.id?C:P)},modifiedAt:Date.now()};return u(E,S.id),s({project:E}),y},updateClipTransition:(y,_)=>{const{project:T}=e();let S=null,C=null;const E=T.timeline.tracks.map(L=>{let O=!1;const U=L.transitions.map(j=>j.id!==y?j:(O=!0,S=L.id,C={...j,..._.type!==void 0?{type:_.type}:{},..._.duration!==void 0?{duration:_.duration}:{},..._.params!==void 0?{params:{...j.params,..._.params}}:{}},C));return O?{...L,transitions:U}:L});if(!C||!S)return null;const P={...T,timeline:{...T.timeline,tracks:E},modifiedAt:Date.now()};return u(P,S),s({project:P}),C},removeClipTransition:y=>{const{project:_}=e();let T=null,S=!1;const C=_.timeline.tracks.map(P=>{const L=P.transitions.filter(O=>{const U=O.id!==y;return U||(T=P.id,S=!0),U});return L.length!==P.transitions.length?{...P,transitions:L}:P});if(!S||!T)return!1;const E={..._,timeline:{..._.timeline,tracks:C},modifiedAt:Date.now()};return u(E,T),s({project:E}),!0},getClipTransition:y=>{const{project:_}=e();for(const T of _.timeline.tracks){const S=T.transitions.find(C=>C.id===y);if(S)return S}},getClipTransitionBetweenClips:(y,_)=>{const{project:T}=e();for(const S of T.timeline.tracks){const C=S.transitions.find(E=>E.clipAId===y&&E.clipBId===_);if(C)return C}},copyClips:y=>{const{getClip:_}=e(),S=y.map(_).filter(C=>C!==void 0).map(C=>({...JSON.parse(JSON.stringify(C))}));s({clipboard:S})},pasteClips:async(y,_)=>{const{clipboard:T,project:S,actionExecutor:C}=e(),E=[];if(T.length===0)return[{success:!1,error:{code:"INVALID_PARAMS",message:"Clipboard is empty"}}];const P=Math.min(...T.map(L=>L.startTime));for(const L of T){const O=L.startTime-P,U=_+O,j={type:"clip/add",id:ve(),timestamp:Date.now(),params:{trackId:y,mediaId:L.mediaId,startTime:U,duration:L.duration,inPoint:L.inPoint,outPoint:L.outPoint,volume:L.volume,effects:L.effects}},N=await C.execute(j,S);E.push(N)}return s({project:{...S}}),E},duplicateClip:async y=>{const{getClip:_,project:T,actionExecutor:S}=e(),C=_(y);if(!C)return{success:!1,error:{code:"INVALID_PARAMS",message:"Clip not found"}};const E=T.timeline.tracks.find(z=>z.clips.some(W=>W.id===y));if(!E)return{success:!1,error:{code:"INVALID_PARAMS",message:"Track not found"}};const P=[...E.clips].sort((z,W)=>z.startTime-W.startTime);let L=C.startTime+C.duration;const O=1e-4;for(const z of P)if(z.id!==C.id&&!(z.startTime+z.duration<=L+O)){if(z.startTime>=L+C.duration-O)break;L=z.startTime+z.duration}const U=structuredClone(T),j={type:"clip/add",id:ve(),timestamp:Date.now(),params:{trackId:E.id,mediaId:C.mediaId,startTime:L,duration:C.duration,inPoint:C.inPoint,outPoint:C.outPoint,volume:C.volume,effects:structuredClone(C.effects),audioEffects:C.audioEffects?structuredClone(C.audioEffects):void 0,keyframes:C.keyframes?structuredClone(C.keyframes):void 0,transform:C.transform?structuredClone(C.transform):void 0,...C.fade?{fade:C.fade}:{},...C.speed!==void 0?{speed:C.speed}:{},...C.reversed!==void 0?{reversed:C.reversed}:{},...C.audioTrackIndex!==void 0?{audioTrackIndex:C.audioTrackIndex}:{}}},N=await S.execute(j,U);if(N.success){const z={...U,modifiedAt:Date.now()};s({project:z})}return N},copyEffects:y=>{const{getClip:_}=e(),T=_(y);if(T){const S=JSON.parse(JSON.stringify(T.effects));s({copiedEffects:S})}},pasteEffects:async y=>{const{copiedEffects:_,project:T,actionExecutor:S}=e();if(_.length===0)return{success:!1,error:{code:"INVALID_PARAMS",message:"No effects in clipboard"}};const C=[];for(const E of _){const P={type:"effect/add",id:ve(),timestamp:Date.now(),params:{clipId:y,effectType:E.type,params:E.params}},L=await S.execute(P,T);C.push(L)}return s({project:{...T}}),C[0]||{success:!1,error:{code:"UNKNOWN",message:"No results"}}},updateClipTransform:(y,_)=>{const{project:T}=e();let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(z=>z.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j={...U.transform,..._,position:{...U.transform.position,..._.position||{}},scale:{...U.transform.scale,..._.scale||{}},anchor:{...U.transform.anchor,..._.anchor||{}}},N=[...L.clips];return N[O]={...U,transform:j},{...L,clips:N}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E){const L=E.getTextClip(y);if(L){const O={...L.transform,..._,position:{...L.transform.position,..._.position||{}},scale:{...L.transform.scale,..._.scale||{}},anchor:{...L.transform.anchor,..._.anchor||{}}};return E.updateTextClip(y,{transform:O}),s({project:{...T,modifiedAt:Date.now()}}),!0}}const P=q.getState().getGraphicsEngine();if(P){const L=P.getShapeClip(y);if(L){const U={...L.transform,..._,position:{...L.transform.position,..._.position||{}},scale:{...L.transform.scale,..._.scale||{}},anchor:{...L.transform.anchor,..._.anchor||{}}};return P.updateShapeClip(y,{transform:U}),s({project:{...T,modifiedAt:Date.now()}}),!0}const O=P.getSVGClip(y);if(O){const U={...O.transform,..._,position:{...O.transform.position,..._.position||{}},scale:{...O.transform.scale,..._.scale||{}},anchor:{...O.transform.anchor,..._.anchor||{}}};return P.updateSVGClip(y,{transform:U}),s({project:{...T,modifiedAt:Date.now()}}),!0}}return!1},updateClipBlendMode:(y,_)=>{const{project:T}=e();let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,blendMode:_},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E&&E.getTextClip(y))return E.updateTextClip(y,{blendMode:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;const P=q.getState().getGraphicsEngine();if(P){if(P.getShapeClip(y))return P.updateShapeClip(y,{blendMode:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;if(P.getSVGClip(y))return P.updateSVGClip(y,{blendMode:_}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},updateClipBlendOpacity:(y,_)=>{const{project:T}=e();if(_<0||_>100)return console.error("Blend opacity must be between 0 and 100"),!1;let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,blendOpacity:_},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E&&E.getTextClip(y))return E.updateTextClip(y,{blendOpacity:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;const P=q.getState().getGraphicsEngine();if(P){if(P.getShapeClip(y))return P.updateShapeClip(y,{blendOpacity:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;if(P.getSVGClip(y))return P.updateSVGClip(y,{blendOpacity:_}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},updateClipEmphasisAnimation:(y,_)=>{const{project:T}=e();let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,emphasisAnimation:_},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E&&E.getTextClip(y))return E.updateTextClip(y,{emphasisAnimation:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;const P=q.getState().getGraphicsEngine();if(P){if(P.getShapeClip(y))return P.updateShapeClip(y,{emphasisAnimation:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;if(P.getSVGClip(y))return P.updateSVGClip(y,{emphasisAnimation:_}),s({project:{...T,modifiedAt:Date.now()}}),!0;if(P.getStickerClip(y))return P.updateStickerClip(y,{emphasisAnimation:_}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},updateClipRotate3D:(y,_)=>{const{project:T}=e();let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,transform:{...U.transform,rotate3d:_}},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E){const L=E.getTextClip(y);if(L)return E.updateTextClip(y,{transform:{...L.transform,rotate3d:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}const P=q.getState().getGraphicsEngine();if(P){const L=P.getShapeClip(y);if(L)return P.updateShapeClip(y,{transform:{...L.transform,rotate3d:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0;const O=P.getSVGClip(y);if(O)return P.updateSVGClip(y,{transform:{...O.transform,rotate3d:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},updateClipPerspective:(y,_)=>{const{project:T}=e();if(_<0)return console.error("Perspective must be non-negative"),!1;let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,transform:{...U.transform,perspective:_}},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E){const L=E.getTextClip(y);if(L)return E.updateTextClip(y,{transform:{...L.transform,perspective:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}const P=q.getState().getGraphicsEngine();if(P){const L=P.getShapeClip(y);if(L)return P.updateShapeClip(y,{transform:{...L.transform,perspective:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0;const O=P.getSVGClip(y);if(O)return P.updateSVGClip(y,{transform:{...O.transform,perspective:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},updateClipTransformStyle:(y,_)=>{const{project:T}=e();let S=!1;const C=T.timeline.tracks.map(L=>{const O=L.clips.findIndex(N=>N.id===y);if(O===-1)return L;S=!0;const U=L.clips[O],j=[...L.clips];return j[O]={...U,transform:{...U.transform,transformStyle:_}},{...L,clips:j}});if(S)return s({project:{...T,timeline:{...T.timeline,tracks:C},modifiedAt:Date.now()}}),!0;const E=q.getState().getTitleEngine();if(E){const L=E.getTextClip(y);if(L)return E.updateTextClip(y,{transform:{...L.transform,transformStyle:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}const P=q.getState().getGraphicsEngine();if(P){const L=P.getShapeClip(y);if(L)return P.updateShapeClip(y,{transform:{...L.transform,transformStyle:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0;const O=P.getSVGClip(y);if(O)return P.updateSVGClip(y,{transform:{...O.transform,transformStyle:_}}),s({project:{...T,modifiedAt:Date.now()}}),!0}return!1},undo:async()=>{const{project:y,actionExecutor:_,actionHistory:T,clipUndoStack:S,clipRedoStack:C,templateUndoStack:E,templateRedoStack:P}=e(),L=T.peekUndo()?.timestamp??-1,O=S.length>0?S[S.length-1].timestamp:-1,U=E.length>0?E[E.length-1].timestamp:-1;if(U>=0&&U>=O&&U>L){const N=E[E.length-1],z=$(y,b(N)),W=N.previousState?V(z,N.previousState):z;return W?(s({project:W,templateUndoStack:E.slice(0,-1),templateRedoStack:[...P,{...N,timestamp:Date.now()}]}),{success:!0}):{success:!1,error:{code:"INVALID_PARAMS",message:"Failed to undo editing template update"}}}if(O>=0&&O>L){const N=S[S.length-1];let z=!1;if(N.type==="shape"){const W=q.getState().getGraphicsEngine();W&&(z=W.deleteShapeClip(N.clipId))}else if(N.type==="text"){const W=q.getState().getTitleEngine();W&&(z=W.deleteTextClip(N.clipId))}else if(N.type==="svg"){const W=q.getState().getGraphicsEngine();W&&(z=W.deleteSVGClip(N.clipId))}else if(N.type==="sticker"){const W=q.getState().getGraphicsEngine();W&&(z=W.deleteStickerClip(N.clipId))}if(z){s({project:{...y,modifiedAt:Date.now()},clipUndoStack:S.slice(0,-1),clipRedoStack:[...C,{...N,timestamp:Date.now(),hadEmptyTrackUndo:!1}]});const W=N.trackId,fe=e().project.timeline.tracks.find(ye=>ye.id===W);if(fe){let ye=!1;if(fe.type==="text")ye=(q.getState().getTitleEngine()?.getAllTextClips()||[]).some(Oe=>Oe.trackId===W);else if(fe.type==="graphics"){const le=q.getState().getGraphicsEngine(),Le=le?.getAllShapeClips()||[],Oe=le?.getAllSVGClips()||[],jt=le?.getAllStickerClips()||[];ye=[...Le,...Oe,...jt].some(dt=>dt.trackId===W)}else(fe.type==="video"||fe.type==="audio"||fe.type==="image")&&(ye=fe.clips.length>0);if(!ye){const{actionHistory:le}=e(),Oe=le.peekUndo()?.action,dt={text:"text",shape:"graphics",svg:"graphics",sticker:"graphics"}[N.type]||fe.type,ht=Oe?.params?.trackType;if(Oe&&Oe.type==="track/add"&&ht===dt&&(await _.undo(e().project)).success){const Lt=e().clipRedoStack;if(Lt.length>0){const Ar=Lt[Lt.length-1];s({project:{...e().project},clipRedoStack:[...Lt.slice(0,-1),{...Ar,hadEmptyTrackUndo:!0,trackType:dt}]})}}}}return{success:!0}}}const j=await _.undo(y);return j.success&&s({project:{...y}}),j},redo:async()=>{const{project:y,actionExecutor:_,clipUndoStack:T,clipRedoStack:S,templateUndoStack:C,templateRedoStack:E}=e();if(E.length>0){const L=E[E.length-1],O=L.previousState?$(y,L.previousState):y,U=V(O,b(L));return U?(s({project:U,templateUndoStack:[...C,{...L,timestamp:Date.now()}],templateRedoStack:E.slice(0,-1)}),{success:!0}):{success:!1,error:{code:"INVALID_PARAMS",message:"Failed to restore editing template application"}}}if(S.length>0){const L=S[S.length-1];let O=!1,U;if(L.hadEmptyTrackUndo&&L.trackType){const N=await _.redo(e().project);if(!N.success)return N;const z=e().project,W=z.timeline.tracks.filter(Q=>Q.type===L.trackType);W.length>0&&(U=W[W.length-1].id),s({project:{...z}})}const j=U||L.trackId;if(L.type==="shape"){const N=q.getState().getGraphicsEngine();if(N){const z=L.clipData;N.createShape({shapeType:z.shapeType,width:200,height:200,style:z.style},j,z.startTime,z.duration),O=!0}}else if(L.type==="text"){const N=q.getState().getTitleEngine();if(N){const z=L.clipData;N.createTextClip({trackId:j,startTime:z.startTime,text:z.text,duration:z.duration,style:z.style}),O=!0}}else if(L.type==="svg"){const N=q.getState().getGraphicsEngine();if(N){const z=L.clipData;N.importSVG(z.svgContent,j,z.startTime,z.duration),O=!0}}else if(L.type==="sticker"){const N=q.getState().getGraphicsEngine();if(N){const z=L.clipData;N.addStickerClip({...z,trackId:j}),O=!0}}if(O){const N=U?{...L,trackId:U,clipData:{...L.clipData,trackId:U}}:L;return s({project:{...e().project,modifiedAt:Date.now()},clipUndoStack:[...T,{...N,timestamp:Date.now()}],clipRedoStack:S.slice(0,-1)}),{success:!0}}}const P=await _.redo(y);return P.success&&s({project:{...y}}),P},canUndo:()=>{const{actionHistory:y,clipUndoStack:_,templateUndoStack:T}=e();return T.length>0||_.length>0||y.canUndo()},canRedo:()=>{const{actionHistory:y,clipRedoStack:_,templateRedoStack:T}=e();return T.length>0||_.length>0||y.canRedo()},executeAction:async y=>{const{project:_,actionExecutor:T}=e(),S=await T.execute(y,_);return S.success&&s({project:{..._}}),S},getTimelineDuration:()=>{const{project:y}=e();return kk(y)},initializeAutoSave:async()=>{await dQ(),Us.start(()=>{const{project:y}=e(),_=q.getState().getTitleEngine(),T=q.getState().getGraphicsEngine();return{...y,textClips:_?.getAllTextClips()||[],shapeClips:T?.getAllShapeClips()||[],svgClips:T?.getAllSVGClips()||[],stickerClips:T?.getAllStickerClips()||[]}}),ys.subscribe(y=>y.project,()=>{Us.markDirty()})},checkForRecovery:async()=>{const{project:y}=e();return Us.checkForRecovery(y.id)},recoverFromAutoSave:async y=>{const _=await Us.recover(y);if(_){const T=await yQ(_.id),S=new Map(T.map(j=>[j.id,j.blob])),C=await Promise.all(_.mediaLibrary.items.map(j=>TQ(j,S.get(j.id)))),E={..._,mediaLibrary:{..._.mediaLibrary,items:C}},P=q.getState().getTitleEngine(),L=q.getState().getGraphicsEngine();P&&_.textClips&&P.loadTextClips(_.textClips),L&&(_.shapeClips&&L.loadShapeClips(_.shapeClips),_.svgClips&&L.loadSVGClips(_.svgClips),_.stickerClips&&L.loadStickerClips(_.stickerClips));const O=new zc,U=new Ou(O);return s({project:E,actionHistory:O,actionExecutor:U,clipUndoStack:[],clipRedoStack:[],templateUndoStack:[],templateRedoStack:[],error:null}),await CQ.addToRecent(E),!0}return!1},forceSave:async()=>{const{project:y}=e(),_=q.getState().getTitleEngine(),T=q.getState().getGraphicsEngine(),S={...y,textClips:_?.getAllTextClips()||[],shapeClips:T?.getAllShapeClips()||[],svgClips:T?.getAllSVGClips()||[],stickerClips:T?.getAllStickerClips()||[]};await Us.forceSave(S)},getFullProject:()=>{const{project:y}=e(),_=q.getState().getTitleEngine(),T=q.getState().getGraphicsEngine();return{...y,textClips:_?.getAllTextClips()||[],shapeClips:T?.getAllShapeClips()||[],svgClips:T?.getAllSVGClips()||[],stickerClips:T?.getAllStickerClips()||[]}},getEditingTemplates:()=>[...PY()],getEditingTemplate:y=>$T(y),applyEditingTemplate:(y,_,T={})=>{const{project:S,templateUndoStack:C}=e(),E=M(S,y,_,T);if(!E)return null;const P={type:"editing-template",mode:"apply",timestamp:Date.now(),description:`Apply ${E.applicationState.appliedTemplate.name}`,...E.applicationState};return s({project:E.project,templateUndoStack:[...C,P],templateRedoStack:[]}),E.applicationState.applicationId},updateEditingTemplateApplication:(y,_,T={})=>{const{project:S,templateUndoStack:C}=e(),E=A(y,_);if(!E)return!1;const P=b(E),L=$(S,P,!1),O=M(L,P.templateId,y,T,{applicationId:_,appliedAt:P.appliedTemplate.appliedAt,preferredTrackIds:k(P),preservedTrackSnapshots:P.trackSnapshots});if(!O){const j=V(L,P);return j&&s({project:j}),!1}const U={type:"editing-template",mode:"update",timestamp:Date.now(),description:`Update ${O.applicationState.appliedTemplate.name}`,previousState:P,...O.applicationState};return s({project:O.project,templateUndoStack:[...C,U],templateRedoStack:[]}),!0},removeEditingTemplateApplication:(y,_)=>{const{project:T,templateUndoStack:S,templateRedoStack:C}=e();if(!D(T,y,_))return!1;const E=A(y,_),P=B(T,y,_,E?.trackSnapshots.map(L=>L.track.id)||[]);return s({project:P,templateUndoStack:S.filter(L=>!(L.ownerClipId===y&&L.applicationId===_)),templateRedoStack:C.filter(L=>!(L.ownerClipId===y&&L.applicationId===_))}),!0},createTextClip:(y,_,T,S=5,C)=>{const E=q.getState().titleEngine;if(!E)return console.error("TitleEngine not available yet"),null;const{project:P}=e();if(!P.timeline.tracks.find(N=>N.id===y))return console.error(`Track ${y} not found`),null;const O=E.createTextClip({trackId:y,startTime:_,text:T,duration:S,style:C}),{clipUndoStack:U}=e(),j={type:"text",timestamp:Date.now(),clipId:O.id,trackId:y,clipData:{...O}};return s({project:{...P,modifiedAt:Date.now()},clipUndoStack:[...U,j],clipRedoStack:[]}),O},updateTextContent:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateText(y,_);return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},updateTextStyle:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateStyle(y,_);return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},updateTextAnimation:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateTextClip(y,{animation:_});return S&&s({project:{...e().project}}),S||null},updateTextTransform:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateTextClip(y,{transform:_});return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},updateTextBehindSubject:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateTextClip(y,{behindSubject:_});return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},updateText3D:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateTextClip(y,{text3d:_});return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},getTextClip:y=>{const _=q.getState().getTitleEngine();if(_)return _.getTextClip(y)},getAllTextClips:()=>{const y=q.getState().getTitleEngine();return y?y.getAllTextClips():[]},updateTextClipKeyframes:(y,_)=>{const T=q.getState().getTitleEngine();if(!T)return console.error("TitleEngine not initialized"),null;const S=T.updateTextClip(y,{keyframes:_});return S&&s({project:{...e().project,modifiedAt:Date.now()}}),S||null},applyTextAnimationPreset:(y,_,T=.5,S=.5,C)=>{const E=q.getState().getTitleEngine();if(!E)return null;const P=n0.createAnimationPreset(_,T,S,C),L=E.updateTextClip(y,{animation:P});if(L){const{project:O}=e();s({project:{...O,modifiedAt:Date.now()}})}return L||null},getAvailableAnimationPresets:()=>n0.getAvailablePresets(),addSubtitle:async y=>{const{project:_,addTrack:T,createTextClip:S}=e();let C=_.timeline.tracks.find(L=>L.type==="text"&&L.name==="Captions");if(!C){if(!(await T("text"))?.success)return;C=e().project.timeline.tracks.filter(j=>j.type==="text"&&!_.timeline.tracks.some(N=>N.id===j.id))[0],C&&(s(j=>({project:{...j.project,timeline:{...j.project.timeline,tracks:j.project.timeline.tracks.map(N=>N.id===C.id?{...N,name:"Captions"}:N)}}})),C={...C,name:"Captions"})}if(!C)return;const E=y.endTime-y.startTime,P=y.style;S(C.id,y.startTime,y.text,E,P?{fontFamily:P.fontFamily,fontSize:P.fontSize,color:P.color,backgroundColor:P.backgroundColor||void 0}:void 0)},removeSubtitle:y=>{s(_=>({project:{..._.project,timeline:{..._.project.timeline,subtitles:_.project.timeline.subtitles.filter(T=>T.id!==y)}}}))},updateSubtitle:(y,_)=>{s(T=>({project:{...T.project,timeline:{...T.project.timeline,subtitles:T.project.timeline.subtitles.map(S=>S.id===y?{...S,..._}:S)}}}))},getSubtitle:y=>e().project.timeline.subtitles.find(_=>_.id===y),importSRT:async y=>{const _=await q.getState().getSubtitleEngine(),{project:T,addSubtitle:S}=e(),{result:C}=_.importSRT(T.timeline,y),E=C.errors.map(P=>`Line ${P.line}: ${P.message}`);if(C.subtitles.length===0)return{success:!1,errors:E.length>0?E:["No valid subtitles were found in this SRT file."]};for(const P of C.subtitles)await S(P);return{success:!0,errors:E}},exportSRT:async()=>{const y=await q.getState().getSubtitleEngine(),{project:_}=e();return y.exportSRT(_.timeline)},applySubtitleStylePreset:async y=>{const _=await q.getState().getSubtitleEngine(),{project:T}=e(),S=_.applyStylePreset(T.timeline,y);return"error"in S?(console.error(S.error),!1):(s({project:{...T,timeline:S.timeline,modifiedAt:Date.now()}}),!0)},getSubtitleStylePresets:async()=>(await q.getState().getSubtitleEngine()).getStylePresets(),addMarker:(y,_="Marker",T="#3b82f6")=>{const S={id:`marker-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,time:y,label:_,color:T};s(C=>({project:{...C.project,timeline:{...C.project.timeline,markers:[...C.project.timeline.markers,S]}}}))},removeMarker:y=>{s(_=>({project:{..._.project,timeline:{..._.project.timeline,markers:_.project.timeline.markers.filter(T=>T.id!==y)}}}))},updateMarker:(y,_)=>{s(T=>({project:{...T.project,timeline:{...T.project.timeline,markers:T.project.timeline.markers.map(S=>S.id===y?{...S,..._}:S)}}}))},getMarker:y=>e().project.timeline.markers.find(T=>T.id===y),getMarkers:()=>e().project.timeline.markers,createShapeClip:(y,_,T,S=5,C)=>{const E=q.getState().getGraphicsEngine();if(!E)return console.error("GraphicsEngine not initialized"),null;const{project:P}=e();if(!P.timeline.tracks.find(N=>N.id===y))return console.error(`Track ${y} not found`),null;const O=E.createShape({shapeType:T,width:200,height:200,style:C},y,_,S),{clipUndoStack:U}=e(),j={type:"shape",timestamp:Date.now(),clipId:O.id,trackId:y,clipData:{...O}};return s({project:{...P,modifiedAt:Date.now()},clipUndoStack:[...U,j],clipRedoStack:[]}),O},updateShapeStyle:(y,_)=>{const T=q.getState().getGraphicsEngine();if(!T)return console.error("GraphicsEngine not initialized"),null;const S=T.getShapeClip(y);if(!S)return console.error(`Shape clip ${y} not found`),null;const C=T.updateShapeStyle(S,_),{project:E}=e();return s({project:{...E,modifiedAt:Date.now()}}),C},updateShapeTransform:(y,_)=>{const T=q.getState().getGraphicsEngine();if(!T)return console.error("GraphicsEngine not initialized"),null;if(T.getShapeClip(y)){const P=T.updateShapeClip(y,{transform:_}),{project:L}=e();return s({project:{...L,modifiedAt:Date.now()}}),P||null}if(T.getSVGClip(y)){const P=T.updateSVGClip(y,{transform:_}),{project:L}=e();return s({project:{...L,modifiedAt:Date.now()}}),P||null}if(T.getStickerClip(y)){const P=T.updateStickerClip(y,{transform:_}),{project:L}=e();return s({project:{...L,modifiedAt:Date.now()}}),P||null}return console.error(`Graphic clip ${y} not found`),null},importSVG:(y,_,T,S=5)=>{const C=q.getState().getGraphicsEngine();if(!C)return console.error("GraphicsEngine not initialized"),null;const{project:E}=e();if(!E.timeline.tracks.find(L=>L.id===_))return console.error(`Track ${_} not found`),null;try{const L=C.importSVG(y,_,T,S),{clipUndoStack:O}=e(),U={type:"svg",timestamp:Date.now(),clipId:L.id,trackId:_,clipData:{...L}};return s({project:{...E,modifiedAt:Date.now()},clipUndoStack:[...O,U],clipRedoStack:[]}),L}catch(L){return console.error("Failed to import SVG:",L),null}},getShapeClip:y=>{const _=q.getState().getGraphicsEngine();if(_)return _.getShapeClip(y)},getSVGClip:y=>{const _=q.getState().getGraphicsEngine();if(_)return _.getSVGClip(y)},getSVGClipById:y=>e().getSVGClip(y),updateSVGClip:(y,_)=>{const T=q.getState().getGraphicsEngine();if(!T)return console.error("[ProjectStore] GraphicsEngine not initialized"),null;const S=T.updateSVGClip(y,_);if(S){const{project:C}=e();s({project:{...C,modifiedAt:Date.now()}})}else console.error(`[ProjectStore] Failed to update SVG clip ${y}`);return S||null},createStickerClip:y=>{const _=q.getState().getGraphicsEngine();if(!_)return console.error("GraphicsEngine not initialized"),null;const{project:T}=e();return T.timeline.tracks.find(C=>C.id===y.trackId)?(_.addStickerClip(y),s({project:{...T,modifiedAt:Date.now()}}),y):(console.error(`Track ${y.trackId} not found`),null)},getStickerClip:y=>{const _=q.getState().getGraphicsEngine();if(_)return _.getStickerClip(y)},deleteShapeClip:y=>{const _=q.getState().getGraphicsEngine();if(!_)return!1;const T=_.deleteShapeClip(y);if(T){const{project:S}=e();s({project:{...S,modifiedAt:Date.now()}})}return T},deleteSVGClip:y=>{const _=q.getState().getGraphicsEngine();if(!_)return!1;const T=_.deleteSVGClip(y);if(T){const{project:S}=e();s({project:{...S,modifiedAt:Date.now()}})}return T},deleteStickerClip:y=>{const _=q.getState().getGraphicsEngine();if(!_)return!1;const T=_.deleteStickerClip(y);if(T){const{project:S}=e();s({project:{...S,modifiedAt:Date.now()}})}return T},deleteTextClip:y=>{const _=q.getState().getTitleEngine();if(!_)return!1;const T=_.deleteTextClip(y);if(T){const{project:S}=e();s({project:{...S,modifiedAt:Date.now()}})}return T},createPhotoProject:(y,_,T)=>{const S=q.getState().getPhotoEngine();if(!S)return console.error("PhotoEngine not initialized"),null;const C=S.createProject(y,_,T),{photoProjects:E}=e();return E.set(C.id,C),s({photoProjects:new Map(E)}),C},importPhotoForEditing:(y,_)=>{const T=q.getState().getPhotoEngine();if(!T)return console.error("PhotoEngine not initialized"),null;const S=T.createProject(y.width,y.height,_||"Photo Edit"),C=T.importPhoto(S,y,_),{photoProjects:E}=e();return E.set(C.id,C),s({photoProjects:new Map(E)}),C},addPhotoLayer:(y,_)=>{const T=q.getState().getPhotoEngine();if(!T)return console.error("PhotoEngine not initialized"),null;const{photoProjects:S}=e(),C=S.get(y);if(!C)return console.error(`Photo project ${y} not found`),null;const E=T.addLayer(C,_);return S.set(y,E),s({photoProjects:new Map(S)}),E},removePhotoLayer:(y,_)=>{const T=q.getState().getPhotoEngine();if(!T)return console.error("PhotoEngine not initialized"),null;const{photoProjects:S}=e(),C=S.get(y);if(!C)return console.error(`Photo project ${y} not found`),null;const E=T.removeLayer(C,_);return S.set(y,E),s({photoProjects:new Map(S)}),E},reorderPhotoLayers:(y,_,T)=>{const S=q.getState().getPhotoEngine();if(!S)return console.error("PhotoEngine not initialized"),null;const{photoProjects:C}=e(),E=C.get(y);if(!E)return console.error(`Photo project ${y} not found`),null;const P=S.reorderLayers(E,_,T);if(!P.success)return console.error(`Failed to reorder layers: ${P.error}`),null;const L={...E,layers:P.layers};return C.set(y,L),s({photoProjects:new Map(C)}),L},setPhotoLayerVisibility:(y,_,T)=>{const S=q.getState().getPhotoEngine();if(!S)return console.error("PhotoEngine not initialized"),null;const{photoProjects:C}=e(),E=C.get(y);if(!E)return console.error(`Photo project ${y} not found`),null;const P=S.setLayerVisibility(E,_,T);return C.set(y,P),s({photoProjects:new Map(C)}),P},setPhotoLayerOpacity:(y,_,T)=>{const S=q.getState().getPhotoEngine();if(!S)return console.error("PhotoEngine not initialized"),null;const{photoProjects:C}=e(),E=C.get(y);if(!E)return console.error(`Photo project ${y} not found`),null;const P=S.setLayerOpacity(E,_,T);return C.set(y,P),s({photoProjects:new Map(C)}),P},setPhotoLayerBlendMode:(y,_,T)=>{const S=q.getState().getPhotoEngine();if(!S)return console.error("PhotoEngine not initialized"),null;const{photoProjects:C}=e(),E=C.get(y);if(!E)return console.error(`Photo project ${y} not found`),null;const P=S.setLayerBlendMode(E,_,T);return C.set(y,P),s({photoProjects:new Map(C)}),P},getPhotoProject:y=>{const{photoProjects:_}=e();return _.get(y)||null},addVideoEffect:(y,_,T)=>{const{project:S}=e(),C=Bs();if(!C.isInitialized())return console.error("EffectsBridge not initialized"),null;const E=C.applyVideoEffect(y,_,T);if(!E.success||!E.effectId)return console.error("Failed to add video effect:",E.error),null;const P=C.getEffect(y,E.effectId);if(P){const L=a(S,y,O=>({...O,effects:[...O.effects,{id:P.id,type:P.type,enabled:P.enabled,params:P.params}]}));if(!L)return console.error("Failed to persist video effect: clip not found"),C.removeVideoEffect(y,P.id),null;c(L,y),s({project:L})}return P||null},updateVideoEffect:(y,_,T)=>{const{project:S}=e();let C=!1;const E=a(S,y,P=>({...P,effects:P.effects.map(L=>L.id!==_?L:(C=!0,{...L,params:{...L.params,...T}}))}));return!E||!C?(console.error("Failed to update video effect: effect not found"),null):(c(E,y),s({project:E}),Bs().getEffect(y,_)||null)},removeVideoEffect:(y,_)=>{const{project:T}=e();let S=!1;const C=a(T,y,E=>({...E,effects:E.effects.filter(P=>{const L=P.id!==_;return L||(S=!0),L})}));return!C||!S?(console.error("Failed to remove video effect: effect not found"),!1):(c(C,y),s({project:C}),!0)},reorderVideoEffects:(y,_)=>{const{project:T,getClip:S}=e(),C=S(y);if(!C)return console.error("Failed to reorder video effects: clip not found"),!1;const E=new Map(C.effects.map(O=>[O.id,O])),P=new Set(_);if(_.length!==C.effects.length||P.size!==C.effects.length||_.some(O=>!E.has(O)))return console.error("Failed to reorder video effects: invalid effect order"),!1;const L=a(T,y,O=>({...O,effects:_.map(U=>E.get(U))}));return L?(c(L,y),s({project:L}),!0):(console.error("Failed to reorder video effects: clip not found"),!1)},toggleVideoEffect:(y,_,T)=>{const{project:S}=e();let C=!1;const E=a(S,y,P=>({...P,effects:P.effects.map(L=>L.id!==_?L:(C=!0,{...L,enabled:T}))}));return!E||!C?(console.error("Failed to toggle video effect: effect not found"),null):(c(E,y),s({project:E}),Bs().getEffect(y,_)||null)},getVideoEffects:y=>{const{project:_}=e(),T=_.timeline.tracks.flatMap(P=>P.clips).find(P=>P.id===y),S=T?r(T.effects):[],C=Bs();if(!C.isInitialized())return S;const E=C.getEffects(y);return E.length===0&&S.length>0?(c(_,y),C.getEffects(y)):E.length>0?E:S},getVideoEffect:(y,_)=>e().getVideoEffects(y).find(T=>T.id===_),updateColorGrading:(y,_)=>{const T=Bs();if(!T.isInitialized())return console.error("EffectsBridge not initialized"),!1;if(_.colorWheels){const S=T.applyColorWheels(y,_.colorWheels);if(!S.success)return console.error("Failed to apply color wheels:",S.error),!1}if(_.curves){const S=T.applyCurves(y,_.curves);if(!S.success)return console.error("Failed to apply curves:",S.error),!1}if(_.lut){const S=T.applyLUT(y,_.lut);if(!S.success)return console.error("Failed to apply LUT:",S.error),!1}if(_.hsl){const S=T.applyHSL(y,_.hsl);if(!S.success)return console.error("Failed to apply HSL:",S.error),!1}if(_.temperature!==void 0||_.tint!==void 0){const S=T.applyWhiteBalance(y,{temperature:_.temperature,tint:_.tint});if(!S.success)return console.error("Failed to apply white balance:",S.error),!1}return s({project:{...e().project,modifiedAt:Date.now()}}),!0},getColorGrading:y=>{const _=Bs();return _.isInitialized()?_.getColorGrading(y):{}},resetColorGrading:y=>{const _=Bs();if(!_.isInitialized())return console.error("EffectsBridge not initialized"),!1;const T=_.resetColorGrading(y);return T.success?(s({project:{...e().project,modifiedAt:Date.now()}}),!0):(console.error("Failed to reset color grading:",T.error),!1)},addAudioEffect:(y,_)=>{const{project:T}=e();for(const S of T.timeline.tracks){const C=S.clips.findIndex(E=>E.id===y);if(C!==-1){const E=S.clips[C],L=[...E.audioEffects||[],_],O={...E,audioEffects:L},U=[...S.clips];U[C]=O;const j={...S,clips:U},N=T.timeline.tracks.map(W=>W.id===S.id?j:W),z={...T,timeline:{...T.timeline,tracks:N},modifiedAt:Date.now()};return s({project:z}),!0}}return!1},updateAudioEffect:(y,_,T)=>{const{project:S}=e();for(const C of S.timeline.tracks){const E=C.clips.findIndex(P=>P.id===y);if(E!==-1){const P=C.clips[E],L=P.audioEffects||[],O=L.findIndex(U=>U.id===_);if(O!==-1){const U=L[O],j={...U,params:{...U.params,...T}},N=[...L];N[O]=j;const z={...P,audioEffects:N},W=[...C.clips];W[E]=z;const Q={...C,clips:W},fe=S.timeline.tracks.map(le=>le.id===C.id?Q:le),ye={...S,timeline:{...S.timeline,tracks:fe},modifiedAt:Date.now()};return s({project:ye}),!0}}}return!1},removeAudioEffect:(y,_)=>{const{project:T}=e();for(const S of T.timeline.tracks){const C=S.clips.findIndex(E=>E.id===y);if(C!==-1){const E=S.clips[C],L=(E.audioEffects||[]).filter(W=>W.id!==_),O={...E,audioEffects:L},U=[...S.clips];U[C]=O;const j={...S,clips:U},N=T.timeline.tracks.map(W=>W.id===S.id?j:W),z={...T,timeline:{...T.timeline,tracks:N},modifiedAt:Date.now()};return s({project:z}),!0}}return!1},toggleAudioEffect:(y,_,T)=>{const{project:S}=e();for(const C of S.timeline.tracks){const E=C.clips.findIndex(P=>P.id===y);if(E!==-1){const P=C.clips[E],L=P.audioEffects||[],O=L.findIndex(U=>U.id===_);if(O!==-1){const j={...L[O],enabled:T},N=[...L];N[O]=j;const z={...P,audioEffects:N},W=[...C.clips];W[E]=z;const Q={...C,clips:W},fe=S.timeline.tracks.map(le=>le.id===C.id?Q:le),ye={...S,timeline:{...S.timeline,tracks:fe},modifiedAt:Date.now()};return s({project:ye}),!0}}}return!1},setAudioEffectPreviewBypass:(y,_,T)=>{const{project:S}=e();for(const C of S.timeline.tracks){const E=C.clips.findIndex(P=>P.id===y);if(E!==-1){const P=C.clips[E],L=P.audioEffects||[],O=L.findIndex(Le=>Le.id===_);if(O===-1)return!1;const U=L[O],j={...U.metadata??{}};T?j.previewBypass=!0:delete j.previewBypass;const N={...U,metadata:Object.keys(j).length>0?j:void 0},z=[...L];z[O]=N;const W={...P,audioEffects:z},Q=[...C.clips];Q[E]=W;const fe={...C,clips:Q},ye=S.timeline.tracks.map(Le=>Le.id===C.id?fe:Le),le={...S,timeline:{...S.timeline,tracks:ye},modifiedAt:Date.now()};return s({project:le}),!0}}return!1},getAudioEffects:y=>{const{project:_}=e();for(const T of _.timeline.tracks){const S=T.clips.find(C=>C.id===y);if(S)return S.audioEffects||[]}return[]},setClipAudioDucking:(y,_,T)=>{const{project:S}=e(),C=a(S,y,E=>({...E,automation:{...E.automation??{},volume:T.map(P=>({...P}))},metadata:{...E.metadata??{},audioDucking:{..._}}}));return C?(s({project:C}),!0):!1},clearClipAudioDucking:y=>{const{project:_}=e(),T=a(_,y,S=>{const C={...S.metadata??{}};delete C.audioDucking;const E={...S.automation??{}};return delete E.volume,{...S,automation:Object.keys(E).length>0?E:void 0,metadata:Object.keys(C).length>0?C:void 0}});return T?(s({project:T}),!0):!1},updateClipKeyframes:(y,_)=>{const{project:T}=e();for(const S of T.timeline.tracks){const C=S.clips.findIndex(E=>E.id===y);if(C!==-1){const P={...S.clips[C],keyframes:_},L=[...S.clips];L[C]=P;const O={...S,clips:L},U=T.timeline.tracks.map(N=>N.id===S.id?O:N),j={...T,timeline:{...T.timeline,tracks:U},modifiedAt:Date.now()};return s({project:j}),!0}}return!1}}}));Bk.registerLanguage("json",R5);const EQ=({isOpen:s,onClose:e})=>{const{project:t}=ys(),[i,n]=F.useState("export"),[r,a]=F.useState(""),[o,c]=F.useState(null),[l,u]=F.useState(!1),[d,h]=F.useState(!1),[f,p]=F.useState(!1),m=F.useRef(null),g=F.useMemo(()=>U7(),[]),v=F.useMemo(()=>G7(g),[g]),w=F.useMemo(()=>t?v.exportToJsonWithMetadata(t,`Exported from ${t.name}`):"",[t,v]),b=F.useCallback(async()=>{try{await navigator.clipboard.writeText(w),h(!0),setTimeout(()=>h(!1),2e3)}catch(y){console.error("Failed to copy:",y)}},[w]),k=F.useCallback(()=>{const y=new Blob([w],{type:"application/json"}),_=URL.createObjectURL(y),T=document.createElement("a");T.href=_;const S=t?.modifiedAt??Date.now(),C=new Date(S),E=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}_${String(C.getHours()).padStart(2,"0")}-${String(C.getMinutes()).padStart(2,"0")}`;T.download=`${t?.name||"project"}_${E}.json`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(_)},[w,t?.name,t?.modifiedAt]),A=F.useCallback(y=>{a(y),c(null);try{const _=v.validateProjectJson(y);c(_)}catch(_){c({valid:!1,errors:[`Validation error: ${_ instanceof Error?_.message:"Unknown error"}`],warnings:[]})}},[v]),M=F.useCallback(y=>{const _=new FileReader;_.onload=T=>{const S=T.target?.result;typeof S=="string"&&A(S)},_.readAsText(y)},[A]),R=F.useCallback(y=>{const _=y.target.files?.[0];_&&M(_),y.target.value=""},[M]),I=F.useCallback(y=>{y.preventDefault(),p(!0)},[]),D=F.useCallback(y=>{y.preventDefault(),p(!1)},[]),B=F.useCallback(y=>{y.preventDefault(),p(!1);const _=y.dataTransfer.files[0];_&&_.type==="application/json"?M(_):_&&c({valid:!1,errors:["Please upload a .json file"],warnings:[]})},[M]),$=F.useCallback(()=>{u(!0);try{const y=v.validateProjectJson(r);c(y)}catch(y){c({valid:!1,errors:[`Validation error: ${y instanceof Error?y.message:"Unknown error"}`],warnings:[]})}finally{u(!1)}},[r,v]),V=F.useCallback(()=>{if(o?.valid)try{const{project:y}=v.importFromJsonWithValidation(r);if(y){ys.getState().loadProject(y),e();const _=y.mediaLibrary.items.filter(T=>T.isPlaceholder).length;_>0&&Kj.warning(`${_} asset${_!==1?"s":""} need relinking`,'Go to Assets panel → click "Relink from Folder" to restore missing media.')}}catch(y){c({valid:!1,errors:[`Import error: ${y instanceof Error?y.message:"Unknown error"}`],warnings:[]})}},[r,o,v,e]);return s?x.jsx(Vh,{open:!0,onOpenChange:y=>!y&&e(),children:x.jsxs(cu,{className:"max-w-4xl p-0 gap-0 bg-background-secondary border-border overflow-hidden flex flex-col",style:{height:"70vh"},children:[x.jsx(Uh,{className:"p-4 border-b border-border space-y-0",children:x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx(ip,{size:20,className:"text-primary"}),x.jsxs("div",{children:[x.jsx(zh,{className:"text-lg font-semibold text-text-primary",children:"Project JSON"}),x.jsx(Gh,{className:"text-xs text-text-muted",children:"Export or import project as JSON"})]})]})}),x.jsxs("div",{className:"flex gap-1 p-2 border-b border-border",children:[x.jsx("button",{onClick:()=>n("export"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${i==="export"?"bg-background-tertiary text-text-primary":"text-text-secondary hover:text-text-primary hover:bg-background-elevated"}`,children:"Export JSON"}),x.jsx("button",{onClick:()=>n("import"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${i==="import"?"bg-background-tertiary text-text-primary":"text-text-secondary hover:text-text-primary hover:bg-background-elevated"}`,children:"Import"})]}),x.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[i==="export"&&x.jsx(x.Fragment,{children:w?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"flex gap-2 p-3 border-b border-border",children:[x.jsx(Kt,{variant:"outline",size:"sm",onClick:b,children:d?x.jsxs(x.Fragment,{children:[x.jsx(Sg,{size:16,className:"text-primary"}),"Copied!"]}):x.jsxs(x.Fragment,{children:[x.jsx(q$,{size:16}),"Copy"]})}),x.jsxs(Kt,{variant:"outline",size:"sm",onClick:k,children:[x.jsx(w3,{size:16}),"Download JSON"]})]}),x.jsx("div",{className:"flex-1 overflow-auto custom-scrollbar p-4",children:x.jsx("div",{className:"rounded-lg overflow-hidden border border-border",children:x.jsx(Bk,{language:"json",style:D5,showLineNumbers:!0,customStyle:{margin:0,padding:"1rem",background:"#1e1e1e",fontSize:"12px"},children:w})})})]}):x.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3 p-8 text-center",children:[x.jsx(ip,{size:40,className:"text-text-muted"}),x.jsx("p",{className:"text-sm text-text-secondary",children:"No project data to export."})]})}),i==="import"&&x.jsxs("div",{className:"flex-1 flex flex-col gap-4 p-4 overflow-auto",children:[x.jsx("input",{ref:m,type:"file",accept:".json,application/json",onChange:R,className:"hidden"}),x.jsxs("div",{onDragOver:I,onDragLeave:D,onDrop:B,onClick:()=>m.current?.click(),className:`flex flex-col items-center justify-center gap-3 p-8 border-2 border-dashed rounded-xl cursor-pointer transition-colors ${f?"border-primary bg-primary/10":"border-border hover:border-text-muted hover:bg-background-tertiary"}`,children:[x.jsx(Pw,{size:32,className:f?"text-primary":"text-text-muted"}),x.jsxs("div",{className:"text-center",children:[x.jsx("p",{className:"text-sm text-text-primary font-medium",children:f?"Drop JSON file here":"Drop a JSON file here or click to browse"}),x.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Accepts .json project files"})]})]}),r&&x.jsxs("div",{className:"flex items-center gap-2 p-3 bg-background-tertiary border border-border rounded-lg",children:[x.jsx(ip,{size:16,className:"text-text-secondary"}),x.jsxs("span",{className:"text-sm text-text-primary flex-1",children:[r.length.toLocaleString()," characters loaded"]}),x.jsx(Kt,{variant:"outline",size:"sm",onClick:()=>{a(""),c(null)},children:"Clear"}),x.jsx(Kt,{variant:"outline",size:"sm",onClick:$,disabled:l,children:l?"Validating...":"Re-validate"})]}),o&&x.jsxs("div",{className:"space-y-2",children:[o.valid&&x.jsxs("div",{className:"flex items-center gap-2 p-3 bg-primary/10 border border-primary/30 rounded-lg",children:[x.jsx(Sg,{size:16,className:"text-primary"}),x.jsx("span",{className:"text-sm text-primary",children:"Valid project JSON — ready to import"})]}),o.errors.length>0&&x.jsxs("div",{className:"p-3 bg-error/10 border border-error/30 rounded-lg space-y-1",children:[x.jsxs("div",{className:"flex items-center gap-2 text-error font-medium text-sm",children:[x.jsx(Ag,{size:16}),"Errors"]}),x.jsx("ul",{className:"list-disc list-inside text-xs text-error/80 space-y-0.5",children:o.errors.map((y,_)=>x.jsx("li",{children:y},_))})]}),o.warnings.length>0&&x.jsxs("div",{className:"p-3 bg-warning/10 border border-warning/30 rounded-lg space-y-1",children:[x.jsxs("div",{className:"flex items-center gap-2 text-warning font-medium text-sm",children:[x.jsx(A3,{size:16}),"Warnings"]}),x.jsx("ul",{className:"list-disc list-inside text-xs text-warning/80 space-y-0.5",children:o.warnings.map((y,_)=>x.jsx("li",{children:y},_))})]}),o.missingAssets&&o.missingAssets.length>0&&x.jsxs("div",{className:"p-3 bg-background-tertiary border border-border rounded-lg space-y-1",children:[x.jsxs("div",{className:"text-sm font-medium text-text-secondary",children:["Missing Assets (",o.missingAssets.length,")"]}),x.jsx("p",{className:"text-xs text-text-muted",children:"These assets will be imported as placeholders and can be replaced later."})]})]}),r&&x.jsxs(Kt,{onClick:V,disabled:!o?.valid,children:[x.jsx(Pw,{size:16}),"Import Project"]})]})]})]})}):null},Sk={playPause:"Space",undo:"Meta+z",redo:"Meta+Shift+z",delete:"Backspace",split:"s",copy:"Meta+c",paste:"Meta+v",cut:"Meta+x",selectAll:"Meta+a",zoomIn:"=",zoomOut:"-",zoomFit:"Shift+z"},Ck={enabled:!0,snapToGrid:!0,snapToClips:!0,snapToPlayhead:!0,snapToMarkers:!0,gridSize:1,snapThreshold:40},MQ={mediaLibrary:{visible:!0,width:300},inspector:{visible:!0,width:300},effects:{visible:!1,width:300},audioMixer:{visible:!1,width:300},colorGrading:{visible:!1,width:400},subtitles:{visible:!1,width:300}},Hl=Yl()(ty($k((s,e)=>({selectedItems:[],lastSelectedItem:null,effectApplicationClipId:null,effectApplicationLabel:null,snapSettings:Ck,panels:MQ,shortcuts:Sk,theme:"dark",showWaveforms:!0,showThumbnails:!0,showKeyframes:!0,autoScroll:!0,timelineMaximized:!1,activeModal:null,modalData:null,contextMenu:null,isDragging:!1,dragType:null,dragData:null,cropMode:!1,cropClipId:null,motionPathMode:!1,motionPathClipId:null,keyframeEditorOpen:!1,inspectorActiveTab:"transform",showWelcomeScreen:!0,skipWelcomeScreen:!1,exportState:{isExporting:!1,progress:0,phase:""},setExportState:t=>s({exportState:t}),startEffectApplication:(t,i)=>{s({effectApplicationClipId:t,effectApplicationLabel:i??null})},finishEffectApplication:()=>{s({effectApplicationClipId:null,effectApplicationLabel:null})},select:(t,i=!1)=>{const{selectedItems:n}=e();i?n.some(a=>a.id===t.id)||s({selectedItems:[...n,t],lastSelectedItem:t}):s({selectedItems:[t],lastSelectedItem:t})},selectMultiple:t=>{s({selectedItems:t,lastSelectedItem:t.length>0?t[t.length-1]:null})},deselect:t=>{const{selectedItems:i,lastSelectedItem:n}=e(),r=i.filter(a=>a.id!==t);s({selectedItems:r,lastSelectedItem:n?.id===t?r.length>0?r[r.length-1]:null:n})},clearSelection:()=>{s({selectedItems:[],lastSelectedItem:null})},isSelected:t=>{const{selectedItems:i}=e();return i.some(n=>n.id===t)},getSelectedClipIds:()=>{const{selectedItems:t}=e();return t.filter(i=>i.type==="clip"||i.type==="text-clip"||i.type==="shape-clip").map(i=>i.id)},getSelectedTrackIds:()=>{const{selectedItems:t}=e();return t.filter(i=>i.type==="track").map(i=>i.id)},setSnapEnabled:t=>{s(i=>({snapSettings:{...i.snapSettings,enabled:t}}))},setSnapToGrid:t=>{s(i=>({snapSettings:{...i.snapSettings,snapToGrid:t}}))},setSnapToClips:t=>{s(i=>({snapSettings:{...i.snapSettings,snapToClips:t}}))},setSnapToPlayhead:t=>{s(i=>({snapSettings:{...i.snapSettings,snapToPlayhead:t}}))},setSnapToMarkers:t=>{s(i=>({snapSettings:{...i.snapSettings,snapToMarkers:t}}))},setGridSize:t=>{s(i=>({snapSettings:{...i.snapSettings,gridSize:Math.max(.01,t)}}))},setSnapThreshold:t=>{s(i=>({snapSettings:{...i.snapSettings,snapThreshold:Math.max(1,t)}}))},toggleSnap:()=>{s(t=>({snapSettings:{...t.snapSettings,enabled:!t.snapSettings.enabled}}))},togglePanel:t=>{s(i=>({panels:{...i.panels,[t]:{...i.panels[t],visible:!i.panels[t].visible}}}))},setPanelVisible:(t,i)=>{s(n=>({panels:{...n.panels,[t]:{...n.panels[t],visible:i}}}))},setPanelWidth:(t,i)=>{s(n=>({panels:{...n.panels,[t]:{...n.panels[t],width:Math.max(200,Math.min(800,i))}}}))},setPanelCollapsed:(t,i)=>{s(n=>({panels:{...n.panels,[t]:{...n.panels[t],collapsed:i}}}))},setShortcut:(t,i)=>{s(n=>({shortcuts:{...n.shortcuts,[t]:i}}))},resetShortcuts:()=>{s({shortcuts:Sk})},setTheme:t=>{s({theme:t})},setShowWaveforms:t=>{s({showWaveforms:t})},setShowThumbnails:t=>{s({showThumbnails:t})},setShowKeyframes:t=>{s({showKeyframes:t})},setAutoScroll:t=>{s({autoScroll:t})},setTimelineMaximized:t=>{s({timelineMaximized:t})},toggleTimelineMaximized:()=>{s(t=>({timelineMaximized:!t.timelineMaximized}))},openModal:(t,i)=>{s({activeModal:t,modalData:i||null})},closeModal:()=>{s({activeModal:null,modalData:null})},showContextMenu:(t,i,n)=>{s({contextMenu:{visible:!0,x:t,y:i,items:n}})},hideContextMenu:()=>{s({contextMenu:null})},startDrag:(t,i)=>{s({isDragging:!0,dragType:t,dragData:i})},endDrag:()=>{s({isDragging:!1,dragType:null,dragData:null})},setCropMode:(t,i)=>{s({cropMode:t,cropClipId:t&&i||null})},setMotionPathMode:(t,i)=>{s({motionPathMode:t,motionPathClipId:t&&i||null})},setKeyframeEditorOpen:t=>{s({keyframeEditorOpen:t})},toggleKeyframeEditor:()=>{s(t=>({keyframeEditorOpen:!t.keyframeEditorOpen}))},setInspectorActiveTab:t=>{s({inspectorActiveTab:t})},setShowWelcomeScreen:t=>{s({showWelcomeScreen:t})},setSkipWelcomeScreen:t=>{s({skipWelcomeScreen:t,showWelcomeScreen:t?!1:e().showWelcomeScreen})}}),{name:"openreel-ui-preferences",version:1,migrate:(s,e)=>{const t=s;return e===0&&(t.snapSettings=Ck),t},partialize:s=>({snapSettings:s.snapSettings,panels:s.panels,shortcuts:s.shortcuts,theme:s.theme,showWaveforms:s.showWaveforms,showThumbnails:s.showThumbnails,showKeyframes:s.showKeyframes,autoScroll:s.autoScroll,timelineMaximized:s.timelineMaximized,skipWelcomeScreen:s.skipWelcomeScreen,inspectorActiveTab:s.inspectorActiveTab})}))),IQ=[{id:"transform",name:"Transform",category:"Position & Size",keywords:["position","scale","rotate","move","resize","transform"],icon:sp,description:"Position, scale, and rotate the clip",sectionId:"transform",clipTypes:["video","image","text","shape"]},{id:"crop",name:"Crop",category:"Position & Size",keywords:["crop","cut","trim","frame","aspect"],icon:rj,description:"Crop and frame the clip",sectionId:"crop",clipTypes:["video","image"]},{id:"speed",name:"Speed Control",category:"Time",keywords:["speed","slow","fast","time","duration","playback"],icon:Cn,description:"Control playback speed and time remapping",sectionId:"speed",clipTypes:["video","audio"]},{id:"video-effects",name:"Video Effects",category:"Video",keywords:["brightness","contrast","saturation","blur","sharpen","vignette","effects"],icon:fd,description:"Brightness, contrast, saturation, blur, sharpen",sectionId:"video-effects",clipTypes:["video","image"]},{id:"color-grading",name:"Color Grading",category:"Video",keywords:["color","grade","wheels","curves","lut","hsl","exposure","temperature"],icon:Eg,description:"Color wheels, curves, LUTs, and HSL adjustments",sectionId:"color-grading",clipTypes:["video","image"]},{id:"green-screen",name:"Green Screen",category:"Video",keywords:["green","screen","chroma","key","background","remove"],icon:J$,description:"Chroma key for green/blue screen removal",sectionId:"green-screen",clipTypes:["video","image"]},{id:"background-removal",name:"Background Removal",category:"Video",keywords:["background","remove","ai","mask","cutout","person"],icon:qj,description:"AI-powered background removal",sectionId:"background-removal",clipTypes:["video","image"]},{id:"masking",name:"Masking",category:"Video",keywords:["mask","shape","feather","reveal","hide","vignette"],icon:En,description:"Shape masks to reveal or hide areas",sectionId:"masking",clipTypes:["video","image"]},{id:"motion-tracking",name:"Motion Tracking",category:"Video",keywords:["motion","track","follow","pin","stabilize"],icon:sp,description:"Track motion and attach elements",sectionId:"motion-tracking",clipTypes:["video"]},{id:"pip",name:"Picture-in-Picture",category:"Video",keywords:["pip","picture","overlay","corner","position"],icon:Ys,description:"Position clips as picture-in-picture overlays",sectionId:"pip",clipTypes:["video","image"]},{id:"blending",name:"Blend Mode",category:"Video",keywords:["blend","mode","multiply","screen","overlay","opacity"],icon:En,description:"Blend modes and opacity controls",sectionId:"blending",clipTypes:["video","image"]},{id:"transform-3d",name:"3D Transform",category:"Video",keywords:["3d","perspective","rotate","flip","tilt"],icon:sp,description:"3D rotation and perspective effects",sectionId:"transform-3d",clipTypes:["video","image"]},{id:"keyframes",name:"Keyframes",category:"Animation",keywords:["keyframe","animate","animation","ease","interpolate"],icon:pd,description:"Animate properties over time",sectionId:"keyframes",clipTypes:["video","image","text","shape"]},{id:"transitions",name:"Transitions",category:"Animation",keywords:["transition","fade","dissolve","wipe","slide"],icon:pd,description:"Clip-to-clip transitions",sectionId:"transitions",clipTypes:["video","image"]},{id:"motion-presets",name:"Motion Presets",category:"Animation",keywords:["motion","preset","zoom","pan","shake","bounce"],icon:pd,description:"Pre-built motion animations",sectionId:"motion-presets",clipTypes:["video","image"]},{id:"audio-effects",name:"Audio Effects",category:"Audio",keywords:["audio","eq","equalizer","compressor","reverb","delay","sound"],icon:Cg,description:"EQ, compressor, reverb, and more",sectionId:"audio-effects",clipTypes:["audio","video"]},{id:"audio-ducking",name:"Audio Ducking",category:"Audio",keywords:["duck","ducking","voice","music","fade","auto"],icon:Cg,description:"Auto-duck music under voice",sectionId:"audio-ducking",clipTypes:["audio","video"]},{id:"text-properties",name:"Text Properties",category:"Text",keywords:["text","font","size","color","style","typography"],icon:rr,description:"Font, size, color, and text styling",sectionId:"text-properties",clipTypes:["text"]},{id:"text-animation",name:"Text Animation",category:"Text",keywords:["text","animate","typewriter","fade","slide","bounce"],icon:rr,description:"Animate text with presets",sectionId:"text-animation",clipTypes:["text"]},{id:"shape-properties",name:"Shape Properties",category:"Shapes",keywords:["shape","fill","stroke","corner","radius","shadow"],icon:Ys,description:"Shape fill, stroke, and effects",sectionId:"shape-properties",clipTypes:["shape"]}],PQ=[{id:"all",name:"All"},{id:"video",name:"Video",icon:Gj},{id:"audio",name:"Audio",icon:Cg},{id:"text",name:"Text",icon:rr},{id:"animation",name:"Animation",icon:pd}],RQ=({isOpen:s,onClose:e})=>{const[t,i]=F.useState(""),[n,r]=F.useState("all"),[a,o]=F.useState(0),c=F.useRef(null),l=F.useRef(null),{selectedItems:u,setPanelVisible:d}=Hl(),h=F.useMemo(()=>{const m=u.find(g=>g.type==="clip"||g.type==="text-clip"||g.type==="shape-clip");return m?m.type==="text-clip"?"text":m.type==="shape-clip"?"shape":"video":null},[u]),f=F.useMemo(()=>{let m=IQ;if(h&&(m=m.filter(g=>g.clipTypes.includes(h))),n!=="all"&&(m=m.filter(g=>g.category.toLowerCase().includes(n.toLowerCase()))),t.trim()){const g=t.toLowerCase().split(" ");m=m.filter(v=>{const w=[v.name,v.description,...v.keywords,v.category].join(" ").toLowerCase();return g.every(b=>w.includes(b))})}return m},[t,n,h]),p=F.useCallback(m=>{d("inspector",!0),setTimeout(()=>{const g=document.querySelector(`[data-section-id="${m.sectionId}"]`);if(g){g.scrollIntoView({behavior:"smooth",block:"start"});const v=g.querySelector("button");v&&v.click(),g.classList.add("ring-2","ring-primary","ring-offset-2"),setTimeout(()=>{g.classList.remove("ring-2","ring-primary","ring-offset-2")},2e3)}},100),e()},[e,d]);return F.useEffect(()=>{s&&c.current&&c.current.focus()},[s]),F.useEffect(()=>{o(0)},[t,n]),F.useEffect(()=>{if(!s)return;const m=g=>{g.key==="Escape"?e():g.key==="ArrowDown"?(g.preventDefault(),o(v=>Math.min(v+1,f.length-1))):g.key==="ArrowUp"?(g.preventDefault(),o(v=>Math.max(v-1,0))):g.key==="Enter"&&f[a]&&(g.preventDefault(),p(f[a]))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[s,e,f,a,p]),F.useEffect(()=>{if(l.current&&f[a]){const m=l.current.children[a];m&&m.scrollIntoView({behavior:"smooth",block:"nearest"})}},[a,f]),s?x.jsx(Vh,{open:!0,onOpenChange:m=>!m&&e(),children:x.jsxs(cu,{className:"max-w-2xl p-0 gap-0 top-[15vh] translate-y-0 bg-background-secondary border-border rounded-2xl overflow-hidden",children:[x.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border",children:[x.jsx(Mg,{size:18,className:"text-text-muted"}),x.jsx(ro,{ref:c,type:"text",value:t,onChange:m=>i(m.target.value),placeholder:h?`Search effects for ${h} clip...`:"Search all effects and tools...",className:"flex-1 bg-transparent border-0 text-text-primary focus-visible:ring-0"}),t&&x.jsx("button",{onClick:()=>i(""),className:"p-1 rounded hover:bg-background-tertiary text-text-muted hover:text-text-primary transition-colors",children:x.jsx(Xy,{size:14})}),x.jsx("div",{className:"flex items-center gap-1 px-2 py-1 rounded bg-background-tertiary border border-border",children:x.jsx("span",{className:"text-[10px] text-text-muted",children:"ESC"})})]}),x.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-background-tertiary/50",children:PQ.map(m=>x.jsx("button",{onClick:()=>r(m.id),className:`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${n===m.id?"bg-primary text-white":"text-text-secondary hover:text-text-primary hover:bg-background-elevated"}`,children:m.name},m.id))}),x.jsx("div",{ref:l,className:"max-h-[50vh] overflow-y-auto",children:f.length===0?x.jsxs("div",{className:"py-12 text-center",children:[x.jsx(Mg,{size:32,className:"mx-auto mb-3 text-text-muted opacity-50"}),x.jsx("p",{className:"text-sm text-text-muted",children:"No effects found"}),x.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Try a different search term or category"})]}):x.jsx("div",{className:"py-2",children:f.map((m,g)=>{const v=m.icon;return x.jsxs("button",{onClick:()=>p(m),className:`w-full flex items-center gap-4 px-4 py-3 text-left transition-all ${g===a?"bg-primary/10 border-l-2 border-primary":"hover:bg-background-tertiary border-l-2 border-transparent"}`,children:[x.jsx("div",{className:`p-2 rounded-lg ${g===a?"bg-primary text-white":"bg-background-tertiary text-text-secondary"}`,children:x.jsx(v,{size:16})}),x.jsxs("div",{className:"flex-1 min-w-0",children:[x.jsxs("div",{className:"flex items-center gap-2",children:[x.jsx("span",{className:`text-sm font-medium ${g===a?"text-primary":"text-text-primary"}`,children:m.name}),x.jsx("span",{className:"text-[10px] text-text-muted px-1.5 py-0.5 rounded bg-background-tertiary",children:m.category})]}),x.jsx("p",{className:"text-xs text-text-muted mt-0.5 truncate",children:m.description})]}),x.jsx("div",{className:"text-[10px] text-text-muted",children:"↵ to select"})]},m.id)})})}),x.jsxs("div",{className:"px-4 py-2 border-t border-border bg-background-tertiary/50 flex items-center justify-between",children:[x.jsxs("div",{className:"text-[10px] text-text-muted",children:[f.length," effect",f.length!==1?"s":""," available"]}),x.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-muted",children:[x.jsx("span",{children:"↑↓ Navigate"}),x.jsx("span",{children:"↵ Select"}),x.jsx("span",{children:"ESC Close"})]})]})]})}):null};function DQ(){const[s,e]=F.useState(!1);return F.useEffect(()=>{const t=()=>{const i=navigator.userAgent.toLowerCase(),r=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(i),a=window.innerWidth<768;e(r||a)};return t(),window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),s?x.jsx("div",{className:"fixed inset-0 z-[9999] bg-background flex items-center justify-center p-6",children:x.jsxs("div",{className:"max-w-md text-center space-y-8",children:[x.jsx("div",{className:"flex justify-center",children:x.jsx("div",{className:"bg-background-secondary border-2 border-primary/30 rounded-2xl p-8 shadow-glow-lg",children:x.jsx(Wr,{className:"w-20 h-20 text-primary",strokeWidth:1.5})})}),x.jsxs("div",{className:"space-y-3",children:[x.jsx("h1",{className:"text-5xl font-bold text-text-primary tracking-tight",children:"OpenReel"}),x.jsxs("div",{className:"flex items-center justify-center gap-2",children:[x.jsx("div",{className:"h-px w-8 bg-primary/50"}),x.jsx("p",{className:"text-lg text-text-secondary font-medium",children:"Desktop Only"}),x.jsx("div",{className:"h-px w-8 bg-primary/50"})]})]}),x.jsxs("div",{className:"space-y-4 bg-background-secondary/50 backdrop-blur-sm rounded-xl p-6 border border-border",children:[x.jsx("p",{className:"text-base text-text-primary leading-relaxed",children:"OpenReel is a professional video editor that requires a desktop or laptop computer."}),x.jsx("p",{className:"text-sm text-text-muted",children:"Please visit this page on your desktop or laptop to start creating amazing videos."})]}),x.jsx("div",{className:"pt-2",children:x.jsx("a",{href:"https://openreel.video",className:"inline-flex items-center gap-2 px-8 py-3 bg-primary hover:bg-primary-hover active:bg-primary-active text-white font-medium rounded-lg transition-all duration-200 shadow-glow hover:shadow-glow-lg transform hover:scale-[1.02] active:scale-[0.98]",children:"Learn More"})})]})}):null}const ob="https://openreel-cloud.niiyeboah1996.workers.dev",Vee="https://transcribe.openreel.video",Uee="https://cloud.openreel.video",FQ=ob;class LQ{apiUrl;constructor(e=FQ){this.apiUrl=e}async listTemplates(){try{const e=await fetch(`${this.apiUrl}/templates`);if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);return(await e.json()).templates||[]}catch(e){return console.error("Failed to list templates from cloud:",e),[]}}async getTemplate(e){try{const t=await fetch(`${this.apiUrl}/templates/${e}`);if(!t.ok){if(t.status===404)return null;throw new Error(`HTTP error! status: ${t.status}`)}return await t.json()}catch(t){return console.error(`Failed to get template ${e} from cloud:`,t),null}}async uploadTemplate(e){try{const t=await fetch(`${this.apiUrl}/templates`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await t.json();return t.ok?{success:!0}:{success:!1,error:i.error||"Upload failed"}}catch(t){return console.error("Failed to upload template to cloud:",t),{success:!1,error:t instanceof Error?t.message:"Upload failed"}}}async deleteTemplate(e){try{const t=await fetch(`${this.apiUrl}/templates/${e}`,{method:"DELETE"}),i=await t.json();return t.ok?{success:!0}:{success:!1,error:i.error||"Delete failed"}}catch(t){return console.error(`Failed to delete template ${e} from cloud:`,t),{success:!1,error:t instanceof Error?t.message:"Delete failed"}}}async checkHealth(){try{return(await fetch(`${this.apiUrl}/health`)).ok}catch{return!1}}async listScriptableTemplates(){try{const e=await fetch(`${this.apiUrl}/templates/scriptable`);return e.ok?(await e.json()).templates||[]:[]}catch(e){return console.error("Failed to list scriptable templates from cloud:",e),[]}}async getScriptableTemplate(e){try{const t=await fetch(`${this.apiUrl}/templates/scriptable/${e}`);if(!t.ok){if(t.status===404)return null;throw new Error(`HTTP error! status: ${t.status}`)}return await t.json()}catch(t){return console.error(`Failed to get scriptable template ${e} from cloud:`,t),null}}}const OQ=new LQ,Ek={tiktok:Ns,"instagram-reels":Ns,"instagram-stories":Ns,"instagram-post":Ys,"youtube-shorts":Ns,"youtube-video":Wr,facebook:Uj,twitter:M$,linkedin:D$,pinterest:P$,intro:dr,outro:dr,promo:Yy,"lower-third":rr,slideshow:En,custom:Ej,all:_3},BQ=["TikTok","Instagram","YouTube","General"],rd={TikTok:["tiktok"],Instagram:["instagram-reels","instagram-stories","instagram-post"],YouTube:["youtube-shorts","youtube-video"],General:["intro","outro","promo","lower-third","slideshow","custom"]},$Q=({selectedCategory:s,onSelectCategory:e,categoryStats:t})=>{const[i,n]=Xn.useState(null),r=a=>{if(i===a)n(null);else{n(a);const o=rd[a];o&&o.length===1&&e(o[0])}};return x.jsxs("div",{className:"space-y-3",children:[x.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1",children:[x.jsxs("button",{onClick:()=>{e("all"),n(null)},className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-all duration-200 ${s==="all"?"bg-primary text-black":"bg-background-tertiary text-text-secondary hover:text-text-primary hover:bg-background-elevated"}`,children:[x.jsx(_3,{size:14}),"All",x.jsx("span",{className:`text-xs ${s==="all"?"text-black/60":"text-text-muted"}`,children:t.all||0})]}),BQ.map(a=>{const o=rd[a],c=i===a,l=o.includes(s),u=Ek[o[0]]||Ys,d=o.reduce((h,f)=>h+(t[f]||0),0);return x.jsxs("button",{onClick:()=>r(a),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-all duration-200 ${l||c?"bg-primary text-black":"bg-background-tertiary text-text-secondary hover:text-text-primary hover:bg-background-elevated"}`,children:[x.jsx(u,{size:14}),a,d>0&&x.jsx("span",{className:`text-xs ${l||c?"text-black/60":"text-text-muted"}`,children:d})]},a)})]}),i&&rd[i].length>1&&x.jsx("div",{className:"flex items-center gap-2 pl-2 overflow-x-auto pb-1",children:rd[i].map(a=>{const o=LM.find(u=>u.id===a),c=t[a]||0,l=Ek[a]||Ys;return x.jsxs("button",{onClick:()=>e(a),className:`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-medium whitespace-nowrap transition-all duration-200 ${s===a?"bg-primary/20 text-primary border border-primary/30":"bg-background text-text-muted hover:text-text-secondary hover:bg-background-tertiary"}`,children:[x.jsx(l,{size:12}),o?.name||a,c>0&&x.jsx("span",{className:`text-[10px] ${s===a?"text-primary/70":"text-text-muted"}`,children:c})]},a)})})]})},jQ={tiktok:Ns,"instagram-reels":Ns,"instagram-stories":Ns,"instagram-post":Ys,"youtube-shorts":Ns,"youtube-video":Wr,facebook:Ys,twitter:Wr,linkedin:Wr,pinterest:Ns,intro:dr,outro:dr,promo:Yy,"lower-third":Wr,slideshow:En,custom:Ys},NQ={tiktok:"from-pink-500 to-cyan-500","instagram-reels":"from-purple-500 to-pink-500","instagram-stories":"from-amber-500 to-pink-500","instagram-post":"from-purple-500 to-pink-500","youtube-shorts":"from-red-500 to-orange-500","youtube-video":"from-red-600 to-red-400",facebook:"from-blue-600 to-blue-400",twitter:"from-sky-500 to-blue-500",linkedin:"from-blue-700 to-blue-500",pinterest:"from-red-500 to-rose-400",intro:"from-emerald-500 to-green-500",outro:"from-green-500 to-emerald-500",promo:"from-amber-500 to-orange-500","lower-third":"from-emerald-500 to-teal-500",slideshow:"from-teal-500 to-cyan-500",custom:"from-zinc-500 to-zinc-400"},VQ=({template:s,onClick:e})=>{const[t,i]=F.useState(!1),n=s.socialCategory||"custom",r=nh[n],a=r&&r.height>r.width,o=jQ[n]||Ys,c=NQ[n]||"from-primary to-emerald-500",l=u=>{if(u<60)return`${u}s`;const d=Math.floor(u/60),h=u%60;return h>0?`${d}m ${h}s`:`${d}m`};return x.jsxs("button",{onClick:e,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"group relative flex flex-col rounded-xl bg-background-tertiary border border-border overflow-hidden transition-all duration-200 hover:bg-background-elevated hover:border-border-hover hover:shadow-lg hover:-translate-y-0.5",children:[x.jsxs("div",{className:`relative flex items-center justify-center overflow-hidden ${a?"aspect-[9/16] max-h-48":"aspect-video"}`,children:[s.thumbnailUrl?x.jsx("img",{src:s.thumbnailUrl,alt:s.name,className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"}):x.jsx("div",{className:`w-full h-full bg-gradient-to-br ${c} opacity-40 flex items-center justify-center`,children:x.jsx(o,{size:32,className:"text-text-primary opacity-60 group-hover:opacity-80 transition-all duration-200"})}),x.jsx("div",{className:`absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent transition-opacity duration-200 ${t?"opacity-100":"opacity-0"}`}),s.previewVideoUrl&&t&&x.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:x.jsx("div",{className:"w-11 h-11 rounded-full bg-background/80 backdrop-blur-sm flex items-center justify-center border border-border",children:x.jsx(dr,{size:18,className:"text-text-primary ml-0.5",fill:"currentColor"})})}),s.featured&&x.jsxs("div",{className:"absolute top-2 left-2 px-2 py-0.5 bg-amber-500 text-black text-[10px] font-semibold rounded-full flex items-center gap-1",children:[x.jsx(Yy,{size:10,fill:"currentColor"}),"Featured"]}),s.premium&&x.jsx("div",{className:"absolute top-2 right-2 px-2 py-0.5 bg-primary text-black text-[10px] font-semibold rounded-full flex items-center gap-1",children:x.jsx(Y$,{size:10})})]}),x.jsxs("div",{className:"p-3 text-left",children:[x.jsx("h3",{className:"text-sm font-medium text-text-primary truncate group-hover:text-primary transition-colors",children:s.name}),x.jsxs("div",{className:"flex items-center gap-3 mt-1.5",children:[x.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-muted",children:[x.jsx(Cn,{size:11}),x.jsx("span",{children:l(s.timeline.duration)})]}),x.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-muted",children:[x.jsx(En,{size:11}),x.jsxs("span",{children:[s.placeholders.length," editable"]})]})]}),s.tags.length>0&&x.jsxs("div",{className:"flex items-center gap-1.5 mt-2 overflow-hidden",children:[s.tags.slice(0,2).map(u=>x.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-background rounded text-text-muted",children:u},u)),s.tags.length>2&&x.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",s.tags.length-2]})]})]})]})};function cb(){const s=BF(),e=F.useCallback((i,n)=>{s&&s.capture(i,n)},[s]),t=F.useCallback((i,n)=>{s&&s.identify(i,n)},[s]);return{track:e,identify:t,isEnabled:!!s}}const lb={PROJECT_CREATED:"project_created",PROJECT_OPENED:"project_opened",PROJECT_EXPORTED:"project_exported",CLIP_ADDED:"clip_added",TEXT_ADDED:"text_added",EFFECT_APPLIED:"effect_applied",PARTICLE_EFFECT_ADDED:"particle_effect_added",TEMPLATE_USED:"template_used"},UQ={text:rr,media:dj,subtitle:rr,shape:En,effect:fd,transform:fd,keyframe:fd,color:Eg,number:lj,boolean:Oj,audio:wj,style:Eg,font:rr,animation:dr},zQ=({template:s,onClose:e,onApply:t})=>{const i=q(b=>b.getTemplateEngine),n=q(b=>b.getTitleEngine),r=ys(b=>b.loadProject),{track:a}=cb(),[o,c]=F.useState({}),[l,u]=F.useState(!1),[d,h]=F.useState(null),[f,p]=F.useState(!1),m=F.useMemo(()=>{const b={main:[],advanced:[]};for(const k of s.placeholders)k.uiHints?.advanced?b.advanced.push(k):b.main.push(k);return b},[s.placeholders]),g=F.useCallback((b,k,A)=>{c(M=>({...M,[b]:{type:A,value:k}}))},[]),v=F.useCallback(async()=>{u(!0),h(null);try{const b=await i(),k=n(),A={...o};for(const D of s.placeholders)!A[D.id]&&D.defaultValue!==void 0&&(A[D.id]={type:D.type,value:D.defaultValue});const{project:M,result:R,textClips:I}=b.applyScriptableTemplate(s,A);if(!R.success&&R.errors.length>0){h(R.errors.map(D=>D.message).join(", ")),u(!1);return}if(k&&I.length>0)for(const D of I){const B=s.placeholders.find(V=>V.id===D.placeholderId),$=B?.label?.toLowerCase().includes("title")||B?.label?.toLowerCase().includes("headline");k.createTextClip({id:D.id,trackId:D.trackId,text:D.text,startTime:D.startTime,duration:D.duration,style:{fontFamily:"Inter",fontSize:$?48:32,fontWeight:600,fontStyle:"normal",color:"#ffffff",textAlign:"center",verticalAlign:"middle",letterSpacing:0,lineHeight:1.2},transform:D.transform,animation:{preset:"fade",params:{easing:"ease-out"},inDuration:.5,outDuration:.3}})}r({...M,modifiedAt:Date.now()}),a(lb.TEMPLATE_USED,{templateId:s.id,templateName:s.name,category:s.category,placeholderCount:s.placeholders.length}),t()}catch(b){h(b instanceof Error?b.message:"Failed to apply template")}finally{u(!1)}},[i,n,r,s,o,t,a]),w=b=>{if(b<60)return`${b}s`;const k=Math.floor(b/60),A=b%60;return A>0?`${k}m ${A}s`:`${k}m`};return x.jsx(Vh,{open:!0,onOpenChange:b=>!b&&e(),children:x.jsxs(cu,{className:"max-w-3xl max-h-[90vh] p-0 gap-0 bg-background-secondary border-border overflow-hidden flex flex-col",children:[x.jsxs(Uh,{className:"p-5 border-b border-border space-y-0 shrink-0",children:[x.jsx(zh,{className:"text-lg font-semibold text-text-primary",children:s.name}),x.jsx(Gh,{asChild:!0,children:x.jsxs("div",{className:"flex items-center gap-4 mt-1.5",children:[x.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-muted",children:[x.jsx(Cn,{size:12}),x.jsx("span",{children:w(s.timeline.duration)})]}),x.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-muted",children:[x.jsx(En,{size:12}),x.jsxs("span",{children:[s.placeholders.length," editable fields"]})]})]})})]}),x.jsx("div",{className:"flex-1 overflow-y-auto p-5",children:x.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[x.jsxs("div",{children:[x.jsx("div",{className:"aspect-video bg-background rounded-xl overflow-hidden mb-4 border border-border",children:s.thumbnailUrl?x.jsx("img",{src:s.thumbnailUrl,alt:s.name,className:"w-full h-full object-cover"}):x.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-emerald-500/20 flex items-center justify-center",children:x.jsx(dr,{size:40,className:"text-text-muted"})})}),s.description&&x.jsx("p",{className:"text-sm text-text-secondary mb-4",children:s.description}),s.scenes&&s.scenes.length>0&&x.jsxs("div",{className:"space-y-2",children:[x.jsx("h3",{className:"text-xs font-medium text-text-muted uppercase tracking-wide",children:"Scenes"}),x.jsx("div",{className:"flex flex-wrap gap-2",children:s.scenes.map(b=>x.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-background-tertiary rounded-lg text-xs border border-border",children:[x.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:b.color||"#22c55e"}}),x.jsx("span",{className:"text-text-secondary",children:b.label}),x.jsxs("span",{className:"text-text-muted",children:["(",w(b.endTime-b.startTime),")"]})]},b.id))})]})]}),x.jsxs("div",{className:"space-y-4",children:[x.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Customize Template"}),m.main.length>0&&x.jsx("div",{className:"space-y-4",children:m.main.map(b=>x.jsx(Mk,{placeholder:b,value:o[b.id]?.value,onChange:k=>g(b.id,k,b.type)},b.id))}),m.advanced.length>0&&x.jsxs(M1,{open:f,onOpenChange:p,children:[x.jsxs(CM,{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary transition-colors flex items-center gap-1",children:[x.jsx(Xd,{size:12,className:`transition-transform ${f?"rotate-90":""}`}),"Advanced Options (",m.advanced.length,")"]}),x.jsx(I1,{className:"mt-4 space-y-4 pl-4 border-l border-border",children:m.advanced.map(b=>x.jsx(Mk,{placeholder:b,value:o[b.id]?.value,onChange:k=>g(b.id,k,b.type)},b.id))})]}),d&&x.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:x.jsx("p",{className:"text-sm text-red-400",children:d})})]})]})}),x.jsxs("div",{className:"p-5 border-t border-border flex items-center justify-end gap-3 shrink-0",children:[x.jsx(Kt,{variant:"ghost",onClick:e,children:"Cancel"}),x.jsx(Kt,{onClick:v,disabled:l,className:"shadow-glow",children:l?x.jsxs(x.Fragment,{children:[x.jsx("div",{className:"w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin"}),"Applying..."]}):x.jsxs(x.Fragment,{children:["Use Template",x.jsx(Xd,{size:16})]})})]})]})})},Mk=({placeholder:s,value:e,onChange:t})=>{const i=UQ[s.type]||rr,n=e??s.defaultValue??"",r=()=>{switch(s.type){case"text":case"subtitle":{const a=s.constraints?.maxLength;return x.jsxs("div",{className:"space-y-1",children:[x.jsx("textarea",{value:String(n),onChange:o=>t(o.target.value),maxLength:a,rows:2,placeholder:String(s.defaultValue||""),className:"w-full px-3 py-2.5 text-sm bg-background-tertiary border border-border rounded-lg focus:border-primary focus:outline-none text-text-primary placeholder:text-text-muted resize-none transition-colors"}),a&&x.jsxs("p",{className:"text-[10px] text-text-muted text-right",children:[String(n).length,"/",a]})]})}case"number":{const a=s.constraints?.min??0,o=s.constraints?.max??100,c=s.constraints?.step||1;return s.uiHints?.inputType==="slider"?x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx(su,{value:[Number(n)||0],onValueChange:u=>t(u[0]),min:a,max:o,step:c,className:"flex-1"}),x.jsx("span",{className:"text-xs text-text-muted w-12 text-right font-mono",children:Number(n).toFixed(c<1?1:0)})]}):x.jsx(ro,{type:"number",value:Number(n)||0,onChange:u=>t(Number(u.target.value)),min:a,max:o,step:c,className:"bg-background-tertiary border-border text-text-primary"})}case"boolean":return x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx(R1,{checked:!!n,onCheckedChange:a=>t(a)}),x.jsx(P1,{className:"text-sm text-text-secondary cursor-pointer",children:s.description||"Enabled"})]});case"color":return x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx("input",{type:"color",value:String(n)||"#000000",onChange:a=>t(a.target.value),className:"w-10 h-10 rounded-lg cursor-pointer border border-border"}),x.jsx(ro,{type:"text",value:String(n)||"#000000",onChange:a=>t(a.target.value),placeholder:"#000000",className:"flex-1 bg-background-tertiary border-border text-text-primary font-mono"})]});default:return x.jsx(ro,{type:"text",value:String(n),onChange:a=>t(a.target.value),placeholder:String(s.defaultValue||""),className:"bg-background-tertiary border-border text-text-primary"})}};return x.jsxs("div",{className:"space-y-2",children:[x.jsxs("label",{className:"flex items-center gap-2",children:[x.jsx(i,{size:14,className:"text-text-muted"}),x.jsx("span",{className:"text-sm font-medium text-text-primary",children:s.label}),s.required&&x.jsx("span",{className:"text-red-400 text-xs",children:"*"})]}),s.description&&s.type!=="boolean"&&x.jsx("p",{className:"text-xs text-text-muted",children:s.description}),r()]})},GQ=({onTemplateApplied:s})=>{const e=q(b=>b.getTemplateEngine),[t,i]=F.useState([]),[n,r]=F.useState(!0),[a,o]=F.useState(""),[c,l]=F.useState("all"),[u,d]=F.useState(null),[h,f]=F.useState(!1);F.useEffect(()=>{(async()=>{r(!0);try{const k=await e();await k.initialize();const A=k.getBuiltinTemplates(),M=await OQ.listScriptableTemplates(),R=[...A.map(D=>{const B=new Map;for(const $ of D.timeline.tracks)for(const V of $.clips){const y=V;y.isPlaceholder&&y.placeholderId&&B.set(y.placeholderId,{clipId:V.id,trackId:$.id})}return{...D,placeholders:D.placeholders.map($=>{const V=B.get($.id);return{...$,targets:V?[{clipId:V.clipId,trackId:V.trackId,property:"content"}]:[],defaultValue:$.defaultValue}}),socialCategory:WQ(D.category)}}),...M],I=Array.from(new Map(R.map(D=>[D.id,D])).values());i(I)}catch(k){console.error("Failed to load templates:",k)}finally{r(!1)}})()},[e]);const p=F.useMemo(()=>{let b=t;if(c!=="all"&&(b=b.filter(k=>k.socialCategory===c||k.category===c)),a.trim()){const k=a.toLowerCase();b=b.filter(A=>A.name.toLowerCase().includes(k)||A.description.toLowerCase().includes(k)||A.tags.some(M=>M.toLowerCase().includes(k)))}return b},[t,c,a]),m=F.useCallback(b=>{d(b),f(!0)},[]),g=F.useCallback(()=>{f(!1),d(null)},[]),v=F.useCallback(()=>{g(),s?.()},[g,s]),w=F.useMemo(()=>{const b={all:t.length};for(const k of LM)b[k.id]=t.filter(A=>A.socialCategory===k.id||A.category===k.id).length;return b},[t]);return n?x.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[x.jsxs("div",{className:"relative",children:[x.jsx("div",{className:"absolute inset-0 bg-primary/20 rounded-full blur-xl"}),x.jsx(T3,{className:"relative w-10 h-10 text-primary animate-spin"})]}),x.jsx("p",{className:"text-sm text-text-muted mt-6",children:"Loading templates..."})]}):x.jsxs("div",{className:"space-y-6",children:[x.jsx("div",{className:"flex items-center gap-4",children:x.jsxs("div",{className:"relative flex-1 max-w-md",children:[x.jsx(Mg,{size:18,className:"absolute left-4 top-1/2 -translate-y-1/2 text-text-muted z-10"}),x.jsx(ro,{type:"text",value:a,onChange:b=>o(b.target.value),placeholder:"Search templates...",className:"pl-11 bg-background-tertiary border-border rounded-xl text-text-primary"})]})}),x.jsx($Q,{selectedCategory:c,onSelectCategory:l,categoryStats:w}),p.length===0?x.jsxs("div",{className:"flex flex-col items-center justify-center py-16",children:[x.jsx("div",{className:"w-14 h-14 rounded-2xl bg-background-tertiary flex items-center justify-center mb-4",children:x.jsx(En,{size:24,className:"text-text-muted"})}),x.jsx("p",{className:"text-base font-medium text-text-primary mb-1",children:"No templates found"}),x.jsx("p",{className:"text-sm text-text-muted",children:"Try adjusting your search or filter"})]}):x.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:p.map(b=>x.jsx(VQ,{template:b,onClick:()=>m(b)},b.id))}),h&&u&&x.jsx(zQ,{template:u,onClose:g,onApply:v})]})};function WQ(s){return{"social-media":"tiktok",youtube:"youtube-video",tiktok:"tiktok",instagram:"instagram-reels",business:"promo",personal:"custom",slideshow:"slideshow","intro-outro":"intro","lower-third":"lower-third",custom:"custom"}[s]||"custom"}const qQ=({onProjectSelected:s})=>{const[e,t]=F.useState([]),[i,n]=F.useState(!0),[r,a]=F.useState(null),o=ys(h=>h.recoverFromAutoSave),{track:c}=cb();F.useEffect(()=>{async function h(){try{const f=await hQ(),p=new Map;for(const g of f)p.has(g.projectId)||p.set(g.projectId,g);const m=Array.from(p.values()).sort((g,v)=>v.timestamp-g.timestamp).slice(0,10).map(g=>({id:g.projectId,saveId:g.id,name:g.projectName,lastModified:g.timestamp}));t(m)}catch(f){console.error("Failed to load recent projects:",f)}finally{n(!1)}}h()},[]);const l=F.useCallback(async h=>{a(h.id);try{await o(h.saveId)&&(c(lb.PROJECT_OPENED,{source:"recent_projects"}),s?.())}catch(f){console.error("Failed to load project:",f)}finally{a(null)}},[o,s,c]),u=F.useCallback((h,f)=>{f.stopPropagation(),t(p=>p.filter(m=>m.id!==h))},[]),d=h=>{const f=new Date(h),m=Math.floor((new Date().getTime()-f.getTime())/(1e3*60*60*24));return m===0?"Today":m===1?"Yesterday":m<7?`${m} days ago`:m<30?`${Math.floor(m/7)} weeks ago`:f.toLocaleDateString()};return i?x.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[x.jsx("div",{className:"w-8 h-8 border-2 border-primary/30 border-t-primary rounded-full animate-spin mb-4"}),x.jsx("p",{className:"text-sm text-text-secondary",children:"Loading recent projects..."})]}):e.length===0?x.jsxs("div",{className:"flex flex-col items-center justify-center py-16",children:[x.jsx("div",{className:"w-14 h-14 rounded-2xl bg-background-tertiary flex items-center justify-center mb-4",children:x.jsx(Cn,{size:24,className:"text-text-muted"})}),x.jsx("h3",{className:"text-base font-medium text-text-primary mb-2",children:"No Recent Projects"}),x.jsx("p",{className:"text-sm text-text-muted text-center max-w-md",children:"Your recently opened projects will appear here. Start a new project or use a template to get started."})]}):x.jsxs("div",{className:"space-y-6",children:[x.jsx("div",{className:"flex items-center justify-between",children:x.jsxs("h3",{className:"text-sm font-medium text-text-primary",children:["Recent Projects (",e.length,")"]})}),x.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4",children:e.map(h=>{const f=r===h.id;return x.jsxs("div",{className:"group relative flex flex-col bg-background-tertiary rounded-xl border border-border hover:border-primary/40 hover:bg-background-elevated transition-all overflow-hidden",children:[x.jsxs("button",{onClick:()=>l(h),disabled:f,className:"flex flex-col flex-1 text-left disabled:opacity-70",children:[x.jsx("div",{className:"aspect-video w-full bg-background flex items-center justify-center border-b border-border",children:f?x.jsx("div",{className:"w-8 h-8 border-2 border-primary/30 border-t-primary rounded-full animate-spin"}):x.jsx(sj,{size:32,className:"text-text-muted/50 group-hover:text-primary/50 transition-colors"})}),x.jsxs("div",{className:"p-3 flex-1",children:[x.jsx("h4",{className:"text-sm font-medium text-text-primary truncate group-hover:text-primary transition-colors",children:h.name}),x.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 text-xs text-text-muted",children:[x.jsx(Cn,{size:11}),x.jsx("span",{children:d(h.lastModified)})]})]})]}),x.jsx("button",{onClick:p=>u(h.id,p),className:"absolute top-2 right-2 p-1.5 text-text-muted hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all rounded-lg bg-background/80 hover:bg-red-500/10 backdrop-blur-sm",title:"Remove from recent",children:x.jsx(k3,{size:14})})]},h.id)})}),x.jsx("p",{className:"text-xs text-text-muted text-center",children:"Recent projects are stored locally in your browser"})]})};function Ik(s){const e=s.replace(/^#\/?/,""),[t,i]=e.split("?"),n={};i&&new URLSearchParams(i).forEach((l,u)=>{n[u]=l});const r=t.split("/");let a=r[0]||"welcome";const o=["welcome","editor","new","templates","recent","share"];return a==="share"&&r[1]&&(n.shareId=r[1]),{route:o.includes(a)?a:"welcome",params:n}}function Mm(s,e){let t=`#/${s}`;if(e&&Object.keys(e).length>0){const i=new URLSearchParams;Object.entries(e).forEach(([r,a])=>{a!=null&&i.set(r,String(a))});const n=i.toString();n&&(t+=`?${n}`)}return t}function A5(){const[s,e]=F.useState(()=>typeof window<"u"?Ik(window.location.hash):{route:"welcome",params:{}});F.useEffect(()=>{const o=()=>{e(Ik(window.location.hash))};return window.addEventListener("hashchange",o),()=>window.removeEventListener("hashchange",o)},[]);const t=F.useCallback((o,c)=>{const l=Mm(o,c);window.location.hash=l},[]),i=F.useCallback(o=>{const c=Mm(s.route,{...s.params,...o});window.location.hash=c},[s.route,s.params]),n=F.useCallback(()=>{const o=Mm(s.route);window.location.hash=o},[s.route]),r=F.useMemo(()=>{const{dimensions:o,width:c,height:l}=s.params;if(o){const u=o.match(/^(\d+)x(\d+)$/i);if(u)return{width:parseInt(u[1],10),height:parseInt(u[2],10)}}return c&&l?{width:parseInt(c,10),height:parseInt(l,10)}:null},[s.params]),a=F.useMemo(()=>{const{fps:o}=s.params;if(o){const c=parseInt(o,10);if(!isNaN(c)&&c>0&&c<=120)return c}return 30},[s.params]);return{route:s.route,params:s.params,navigate:t,updateParams:i,clearParams:n,parsedDimensions:r,fps:a}}let Pk=!1;function HQ(s){const e=F.useRef(!1);F.useEffect(()=>{if(e.current||Pk)return;Pk=!0,e.current=!0;const t=()=>{ii(()=>import("./EditorInterface-C-F8FyLk.js").then(i=>i.W),__vite__mapDeps([0,1,2,3]))};"requestIdleCallback"in window?window.requestIdleCallback(t,{timeout:2e3}):setTimeout(t,100)},[s])}const YQ=[{id:"vertical",preset:"tiktok",label:"Vertical",description:"TikTok, Reels, Shorts",dimensions:"1080 × 1920",icon:Ns,gradient:"from-violet-500/20 to-fuchsia-500/20"},{id:"horizontal",preset:"youtube-video",label:"Horizontal",description:"YouTube, Vimeo, Web",dimensions:"1920 × 1080",icon:Wr,gradient:"from-blue-500/20 to-cyan-500/20"},{id:"square",preset:"instagram-post",label:"Square",description:"Instagram, Facebook",dimensions:"1080 × 1080",icon:Ys,gradient:"from-orange-500/20 to-rose-500/20"}],XQ=({className:s=""})=>x.jsxs("svg",{viewBox:"0 0 490 490",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,children:[x.jsx("path",{d:"M245 24.5C123.223 24.5 24.5 123.223 24.5 245s98.723 220.5 220.5 220.5 220.5-98.723 220.5-220.5S366.777 24.5 245 24.5Z",stroke:"currentColor",strokeWidth:"30.625"}),x.jsxs("g",{children:[x.jsx("path",{d:"M245 98v73.5",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"M392 245h-73.5",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"M245 392v-73.5",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"M98 245h73.5",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"m348.941 141.059-51.965 51.965",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"m348.941 348.941-51.965-51.965",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"m141.059 348.941 51.965-51.965",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"}),x.jsx("path",{d:"m141.059 141.059 51.965 51.965",stroke:"currentColor",strokeWidth:"24.5",strokeLinecap:"round"})]}),x.jsx("path",{d:"M294 245a49 49 0 0 1-49 49 49 49 0 0 1-49-49 49 49 0 0 1 98 0",fill:"currentColor"})]}),KQ=({initialTab:s})=>{const e=Hl(f=>f.setSkipWelcomeScreen),t=Hl(f=>f.skipWelcomeScreen),i=ys(f=>f.createNewProject),{navigate:n}=A5(),{track:r}=cb(),[a,o]=F.useState(s??"home"),[c,l]=F.useState(null);HQ(!0);const u=F.useCallback(f=>{const p=nh[f.preset];i(`New ${f.label} Video`,{width:p.width,height:p.height,frameRate:p.frameRate}),r(lb.PROJECT_CREATED,{preset:f.preset,width:p.width,height:p.height,frameRate:p.frameRate??30,source:"quick_start"}),n("editor")},[i,n,r]),d=F.useCallback(()=>{n("editor")},[n]),h=F.useCallback(()=>{n("editor")},[n]);return F.useEffect(()=>{t&&n("editor")},[t,n]),F.useEffect(()=>{const f=p=>{p.key==="Escape"&&(a!=="home"?o("home"):n("editor"))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,a]),a==="templates"?x.jsxs("div",{className:"fixed inset-0 z-50 bg-background flex flex-col",children:[x.jsxs("header",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[x.jsxs(Kt,{variant:"ghost",size:"sm",onClick:()=>o("home"),children:[x.jsx(tp,{className:"rotate-180",size:16}),"Back"]}),x.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Templates"}),x.jsx("div",{className:"w-16"})]}),x.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:x.jsx(GQ,{onTemplateApplied:d})})]}):a==="recent"?x.jsxs("div",{className:"fixed inset-0 z-50 bg-background flex flex-col",children:[x.jsxs("header",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[x.jsxs(Kt,{variant:"ghost",size:"sm",onClick:()=>o("home"),children:[x.jsx(tp,{className:"rotate-180",size:16}),"Back"]}),x.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Recent Projects"}),x.jsx("div",{className:"w-16"})]}),x.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:x.jsx(qQ,{onProjectSelected:h})})]}):x.jsxs("div",{className:"fixed inset-0 z-50 bg-background overflow-hidden",children:[x.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(34,197,94,0.05),transparent_60%)]"}),x.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom_right,rgba(34,197,94,0.03),transparent_50%)]"}),x.jsxs("div",{className:"relative h-full flex flex-col items-center justify-center px-6",children:[x.jsxs("div",{className:"w-full max-w-3xl",children:[x.jsxs("div",{className:"flex flex-col items-center text-center mb-12",children:[x.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[x.jsx("div",{className:"w-12 h-12 text-primary",children:x.jsx(XQ,{className:"w-full h-full"})}),x.jsx("span",{className:"text-xl font-semibold text-text-primary tracking-tight",children:"Open Reel Video"})]}),x.jsx("h1",{className:"text-4xl sm:text-5xl font-bold text-text-primary tracking-tight mb-3",children:"From idea to export."}),x.jsx("p",{className:"text-xl text-text-secondary mb-8",children:"In your browser."}),x.jsx("p",{className:"text-base text-text-muted max-w-md",children:"Pick a format and start creating. You can change this anytime."})]}),x.jsx("div",{className:"grid grid-cols-3 gap-4 mb-10",children:YQ.map(f=>{const p=f.icon,m=c===f.id;return x.jsxs("button",{onClick:()=>u(f),onMouseEnter:()=>l(f.id),onMouseLeave:()=>l(null),className:` + group relative flex flex-col items-center p-6 rounded-2xl + bg-background-secondary border border-border + hover:border-primary/40 hover:bg-background-tertiary + transition-all duration-200 + ${m?"scale-[1.02] shadow-lg shadow-primary/5":""} + `,children:[x.jsx("div",{className:` + absolute inset-0 rounded-2xl bg-gradient-to-br ${f.gradient} + opacity-0 group-hover:opacity-100 transition-opacity duration-300 + `}),x.jsxs("div",{className:"relative z-10 flex flex-col items-center",children:[x.jsx("div",{className:` + w-16 h-16 mb-4 rounded-xl flex items-center justify-center + bg-background-tertiary group-hover:bg-primary/10 + transition-colors duration-200 + `,children:x.jsx(p,{size:28,className:"text-text-muted group-hover:text-primary transition-colors"})}),x.jsx("h3",{className:"text-lg font-semibold text-text-primary mb-1",children:f.label}),x.jsx("p",{className:"text-sm text-text-muted mb-3",children:f.description}),x.jsx("span",{className:"text-xs font-mono text-text-muted/70 bg-background-tertiary px-2 py-1 rounded",children:f.dimensions})]}),x.jsxs("div",{className:` + absolute bottom-4 left-1/2 -translate-x-1/2 + flex items-center gap-1 text-sm font-medium text-primary + opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 + transition-all duration-200 + `,children:["Start creating",x.jsx(tp,{size:14})]})]},f.id)})}),x.jsxs("div",{className:"flex items-center justify-center gap-3",children:[x.jsxs(Kt,{variant:"outline",onClick:()=>o("templates"),className:"rounded-xl",children:[x.jsx(En,{size:16}),"Browse templates"]}),x.jsxs(Kt,{variant:"outline",onClick:()=>o("recent"),className:"rounded-xl",children:[x.jsx(Cn,{size:16}),"Recent projects"]}),x.jsxs(Kt,{variant:"outline",onClick:()=>n("editor"),className:"rounded-xl",children:[x.jsx(oj,{size:16}),"Open editor"]})]})]}),x.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex items-center gap-4",children:[x.jsxs("div",{className:"flex items-center gap-2",children:[x.jsx(R1,{id:"skip-welcome",checked:t,onCheckedChange:e}),x.jsx(P1,{htmlFor:"skip-welcome",className:"text-xs text-text-muted cursor-pointer",children:"Skip on startup"})]}),x.jsx("span",{className:"text-text-muted/30",children:"·"}),x.jsxs("p",{className:"text-xs text-text-muted/60",children:["Press"," ",x.jsx("kbd",{className:"px-1.5 py-0.5 bg-background-tertiary border border-border rounded text-text-muted font-mono text-[10px]",children:"Esc"})," ","to skip"]})]})]})]})};function Rk(s){const e=Math.floor((Date.now()-s)/1e3);if(e<60)return"just now";if(e<3600){const i=Math.floor(e/60);return`${i} ${i===1?"minute":"minutes"} ago`}if(e<86400){const i=Math.floor(e/3600);return`${i} ${i===1?"hour":"hours"} ago`}const t=Math.floor(e/86400);return`${t} ${t===1?"day":"days"} ago`}function Dk(s){return new Date(s).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const QQ=({saves:s,onRecover:e,onDismiss:t,onClearAll:i})=>{const[n,r]=F.useState(!1),[a,o]=F.useState(null),[c,l]=F.useState(!1),u=s[0],d=s.slice(1),h=async()=>{i&&(l(!0),await i(),l(!1),t())},f=p=>{o(p),e(p)};return x.jsx(Vh,{open:!0,onOpenChange:p=>!p&&t(),children:x.jsxs(cu,{className:"max-w-md p-0 gap-0 bg-background-secondary border-border overflow-hidden",children:[x.jsx(Uh,{className:"p-5 border-b border-border space-y-0",children:x.jsxs("div",{className:"flex items-center gap-3",children:[x.jsx("div",{className:"p-2.5 bg-primary/10 rounded-xl shrink-0",children:x.jsx(Aj,{className:"w-5 h-5 text-primary"})}),x.jsxs("div",{children:[x.jsx(zh,{className:"text-base font-semibold text-text-primary",children:"Recover Your Work"}),x.jsx(Gh,{className:"text-sm text-text-secondary mt-0.5",children:"We found an unsaved project"})]})]})}),x.jsxs("div",{className:"p-5",children:[x.jsxs("button",{onClick:()=>f(u.id),disabled:a===u.id,className:"w-full bg-background-tertiary rounded-xl border border-border p-4 mb-4 text-left hover:border-primary/50 hover:bg-background-elevated transition-all group disabled:opacity-70",children:[x.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[x.jsx(tj,{className:"w-5 h-5 text-text-muted group-hover:text-primary transition-colors"}),x.jsx("span",{className:"font-medium text-text-primary truncate",children:u.projectName})]}),x.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[x.jsx(Cn,{className:"w-4 h-4 shrink-0"}),x.jsxs("span",{children:["Last saved ",Rk(u.timestamp)]}),x.jsx("span",{className:"text-text-muted/50",children:"•"}),x.jsx("span",{className:"text-text-muted/70 truncate",children:Dk(u.timestamp)})]})]}),x.jsxs("div",{className:"flex gap-3",children:[x.jsx(Kt,{variant:"outline",onClick:t,className:"flex-1",children:"Start Fresh"}),x.jsx(Kt,{onClick:()=>f(u.id),disabled:a===u.id,className:"flex-1",children:a===u.id?"Recovering...":"Recover Project"})]}),d.length>0&&x.jsxs(M1,{open:n,onOpenChange:r,className:"mt-4 pt-4 border-t border-border",children:[x.jsxs("div",{className:"flex items-center justify-between",children:[x.jsxs(CM,{className:"flex items-center gap-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:[x.jsx(Hy,{className:`w-4 h-4 transition-transform duration-200 ${n?"rotate-180":""}`}),x.jsxs("span",{children:[d.length," older ",d.length===1?"save":"saves"," available"]})]}),i&&x.jsx("button",{onClick:h,disabled:c,className:"p-1.5 rounded-lg text-text-muted hover:text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50",title:"Clear all saved projects",children:x.jsx(k3,{className:"w-4 h-4"})})]}),x.jsx(I1,{className:"mt-3 space-y-2 max-h-48 overflow-y-auto pr-1 scrollbar-thin",children:d.map(p=>x.jsx("button",{onClick:()=>f(p.id),disabled:a===p.id,className:"w-full text-left p-3 rounded-lg bg-background-tertiary border border-border hover:border-border-hover hover:bg-background-elevated transition-all group disabled:opacity-70",children:x.jsxs("div",{className:"flex items-center justify-between gap-2",children:[x.jsxs("div",{className:"flex-1 min-w-0",children:[x.jsx("div",{className:"text-sm font-medium text-text-primary truncate group-hover:text-primary transition-colors",children:p.projectName}),x.jsx("div",{className:"text-xs text-text-muted mt-1",children:Dk(p.timestamp)})]}),x.jsx("div",{className:"text-xs text-text-muted/70 shrink-0",children:Rk(p.timestamp)})]})},p.id))})]})]})]})})};async function JQ(s){try{const e=await fetch(`${ob}/shares/${s}`);if(e.status===404)return null;if(e.status===410)throw new Error("This share link has expired");if(!e.ok)throw new Error(`Failed to get share info: ${e.status}`);return await e.json()}catch(e){throw e instanceof Error?e:new Error("Failed to get share info")}}function ZQ(s){return`${ob}/shares/${s}/download`}function eJ(s){const e=Date.now(),t=s-e;if(t<=0)return"Expired";const i=Math.floor(t/(1e3*60*60)),n=Math.floor(t%(1e3*60*60)/(1e3*60));return i>0?`${i}h ${n}m remaining`:`${n}m remaining`}function tJ(s){return Date.now()>s}const iJ=({shareId:s})=>{const[e,t]=F.useState("loading"),[i,n]=F.useState(null),[r,a]=F.useState(null);F.useEffect(()=>{(async()=>{try{const u=await JQ(s);if(!u){t("not-found");return}if(tJ(u.expiresAt)){t("expired");return}n(u),t("ready")}catch(u){u instanceof Error&&u.message.includes("expired")?t("expired"):(a(u instanceof Error?u.message:"Failed to load share"),t("error"))}})()},[s]);const o=ZQ(s),c=()=>{window.location.hash="#/editor"};return e==="loading"?x.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:x.jsxs("div",{className:"text-center space-y-4",children:[x.jsx(T3,{size:48,className:"text-primary animate-spin mx-auto"}),x.jsx("p",{className:"text-text-muted",children:"Loading video..."})]})}):e==="not-found"?x.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:x.jsxs("div",{className:"text-center space-y-6 max-w-md px-6",children:[x.jsx("div",{className:"w-20 h-20 mx-auto bg-text-muted/10 rounded-full flex items-center justify-center",children:x.jsx(Ag,{size:40,className:"text-text-muted"})}),x.jsxs("div",{children:[x.jsx("h1",{className:"text-2xl font-bold text-text-primary",children:"Video Not Found"}),x.jsx("p",{className:"text-text-muted mt-2",children:"This video doesn't exist or the link is invalid."})]}),x.jsxs("button",{onClick:c,className:"inline-flex items-center gap-2 px-6 py-3 bg-primary hover:bg-primary-hover text-white font-bold rounded-lg transition-colors",children:[x.jsx(Iw,{size:18}),"Create Your Own Video"]})]})}):e==="expired"?x.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:x.jsxs("div",{className:"text-center space-y-6 max-w-md px-6",children:[x.jsx("div",{className:"w-20 h-20 mx-auto bg-warning/10 rounded-full flex items-center justify-center",children:x.jsx(Cn,{size:40,className:"text-warning"})}),x.jsxs("div",{children:[x.jsx("h1",{className:"text-2xl font-bold text-text-primary",children:"Link Expired"}),x.jsx("p",{className:"text-text-muted mt-2",children:"This share link has expired. Share links are only valid for 24 hours."})]}),x.jsxs("button",{onClick:c,className:"inline-flex items-center gap-2 px-6 py-3 bg-primary hover:bg-primary-hover text-white font-bold rounded-lg transition-colors",children:[x.jsx(Iw,{size:18}),"Create Your Own Video"]})]})}):e==="error"?x.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:x.jsxs("div",{className:"text-center space-y-6 max-w-md px-6",children:[x.jsx("div",{className:"w-20 h-20 mx-auto bg-error/10 rounded-full flex items-center justify-center",children:x.jsx(Ag,{size:40,className:"text-error"})}),x.jsxs("div",{children:[x.jsx("h1",{className:"text-2xl font-bold text-text-primary",children:"Error"}),x.jsx("p",{className:"text-text-muted mt-2",children:r||"Something went wrong"})]}),x.jsx("button",{onClick:()=>window.location.reload(),className:"inline-flex items-center gap-2 px-6 py-3 bg-primary hover:bg-primary-hover text-white font-bold rounded-lg transition-colors",children:"Try Again"})]})}):x.jsx("div",{className:"min-h-screen bg-background",children:x.jsxs("div",{className:"max-w-4xl mx-auto px-6 py-12 space-y-8",children:[x.jsxs("div",{className:"text-center space-y-2",children:[x.jsx("h1",{className:"text-2xl font-bold text-text-primary",children:i?.filename||"Shared Video"}),i&&x.jsxs("div",{className:"flex items-center justify-center gap-4 text-sm text-text-muted",children:[x.jsxs("span",{children:[(i.size/(1024*1024)).toFixed(1)," MB"]}),x.jsx("span",{children:"•"}),x.jsxs("div",{className:"flex items-center gap-1",children:[x.jsx(Cn,{size:14}),x.jsx("span",{children:eJ(i.expiresAt)})]})]})]}),x.jsx("div",{className:"relative aspect-video bg-black rounded-xl overflow-hidden shadow-2xl",children:x.jsx("video",{src:o,controls:!0,className:"w-full h-full",poster:"",children:"Your browser does not support the video tag."})}),x.jsxs("div",{className:"flex items-center justify-center gap-4",children:[x.jsxs("a",{href:o,download:i?.filename,className:"inline-flex items-center gap-2 px-6 py-3 bg-primary hover:bg-primary-hover text-white font-bold rounded-lg transition-colors",children:[x.jsx(w3,{size:18}),"Download"]}),x.jsxs("button",{onClick:c,className:"inline-flex items-center gap-2 px-6 py-3 bg-background-secondary hover:bg-background-tertiary border border-border text-text-primary font-medium rounded-lg transition-colors",children:[x.jsx(dr,{size:18}),"Create Your Own"]})]}),x.jsx("div",{className:"text-center",children:x.jsxs("p",{className:"text-xs text-text-muted",children:["Made with"," ",x.jsx("a",{href:"#/editor",className:"text-primary hover:underline",children:"Open Reel Video"})]})})]})})};function sJ(){const[s,e]=F.useState({isChecking:!0,availableSaves:[],showDialog:!1}),t=ys(a=>a.recoverFromAutoSave);F.useEffect(()=>{(async()=>{try{await Us.initialize();const o=await Us.checkForRecovery();o.length>0?e({isChecking:!1,availableSaves:o,showDialog:!0}):e({isChecking:!1,availableSaves:[],showDialog:!1})}catch(o){console.warn("[Recovery] Failed to check for saves:",o),e({isChecking:!1,availableSaves:[],showDialog:!1})}})()},[]);const i=F.useCallback(async a=>{const o=await t(a);return o&&e(c=>({...c,showDialog:!1})),o},[t]),n=F.useCallback(()=>{e(a=>({...a,showDialog:!1}))},[]),r=F.useCallback(async()=>{await Us.clearAllSaves(),await wQ(),e(a=>({...a,availableSaves:[],showDialog:!1}))},[]);return{isChecking:s.isChecking,availableSaves:s.availableSaves,showDialog:s.showDialog,recover:i,dismiss:n,clearAll:r}}const Im=10,Ic=Yl()($k((s,e)=>({tasks:[],addTask:t=>s(i=>({tasks:[...i.tasks,{...t,retries:0,failed:!1}]})),removeTask:t=>s(i=>({tasks:i.tasks.filter(n=>n.taskId!==t)})),incrementRetry:t=>s(i=>({tasks:i.tasks.map(n=>n.taskId===t?{...n,retries:n.retries+1}:n)})),markFailed:t=>s(i=>({tasks:i.tasks.map(n=>n.taskId===t?{...n,failed:!0}:n)})),retryTask:t=>s(i=>({tasks:i.tasks.map(n=>n.taskId===t?{...n,retries:0,failed:!1}:n)})),getTasksForProject:t=>e().tasks.filter(i=>i.projectId===t)}),{name:"kieai-pending-tasks"})),nJ="openreel-secure",rJ=1,Ms="secrets",vs="meta",aJ=1e5,S5=16,oJ=12;let gn=null,bs=null,go=null;const cJ=5,Fk=1e3;let Ur=0,Ed=0;const Md=[];function zee(s){return Md.push(s),()=>{const e=Md.indexOf(s);e>=0&&Md.splice(e,1)}}const lJ=30*60*1e3;function bu(){go&&clearTimeout(go),go=setTimeout(()=>{C5()},lJ)}function uJ(){return new Promise((s,e)=>{const t=indexedDB.open(nJ,rJ);t.onerror=()=>{e(new Error(`Failed to open secure database: ${t.error?.message}`))},t.onsuccess=()=>{s(t.result)},t.onupgradeneeded=i=>{const n=i.target.result;n.objectStoreNames.contains(Ms)||n.createObjectStore(Ms,{keyPath:"id"}),n.objectStoreNames.contains(vs)||n.createObjectStore(vs,{keyPath:"id"})}})}async function kr(){return gn||(gn=await uJ(),gn.onclose=()=>{gn=null},gn)}function hi(s,e,t,i){return new Promise((n,r)=>{const o=s.transaction(e,t).objectStore(e),c=i(o);c.onsuccess=()=>n(c.result),c.onerror=()=>r(new Error(`IDB operation failed: ${c.error?.message}`))})}async function ub(s,e){const t=new TextEncoder,i=await crypto.subtle.importKey("raw",t.encode(s),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e.buffer,iterations:aJ,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Eh(s,e){const t=crypto.getRandomValues(new Uint8Array(oJ)),i=new TextEncoder;return{encrypted:await crypto.subtle.encrypt({name:"AES-GCM",iv:t.buffer},e,i.encode(s)),iv:t}}async function db(s,e,t){const i=await crypto.subtle.decrypt({name:"AES-GCM",iv:e.buffer},t,s);return new TextDecoder().decode(i)}async function dJ(){const s=await kr();return!!await hi(s,vs,"readonly",t=>t.get("verification"))}function Gee(){return bs!==null}async function Wee(s){if(s.length<8)throw new Error("Master password must be at least 8 characters");if(await dJ())throw new Error("Master password already configured. Use changeMasterPassword instead.");const t=crypto.getRandomValues(new Uint8Array(S5)),i=await ub(s,t),n="openreel-verify-v1",{encrypted:r,iv:a}=await Eh(n,i),o=await kr();await hi(o,vs,"readwrite",c=>c.put({id:"salt",value:t})),await hi(o,vs,"readwrite",c=>c.put({id:"verification",value:r})),await hi(o,vs,"readwrite",c=>c.put({id:"verification_iv",value:a})),bs=i,bu()}function hJ(){if(Ur===0)return 0;const s=Date.now();return Math.max(0,Ed-s)}async function fJ(s){if(Ur>=cJ)throw new Error("Account locked after too many failed attempts. Reset secure storage to regain access.");const e=hJ();if(e>0)throw new Error(`Too many failed attempts. Try again in ${Math.ceil(e/1e3)}s.`);const t=await kr(),i=await hi(t,vs,"readonly",c=>c.get("salt")),n=await hi(t,vs,"readonly",c=>c.get("verification")),r=await hi(t,vs,"readonly",c=>c.get("verification_iv"));if(!i||!n||!r)throw new Error("Master password not configured");const a=i.value instanceof Uint8Array?i.value:new Uint8Array(i.value),o=await ub(s,a);try{const c=r.value instanceof Uint8Array?r.value:new Uint8Array(r.value);if(await db(n.value,c,o)!=="openreel-verify-v1")return Ur++,Ed=Date.now()+Fk*Math.pow(2,Ur-1),!1}catch{return Ur++,Ed=Date.now()+Fk*Math.pow(2,Ur-1),!1}return Ur=0,Ed=0,bs=o,bu(),!0}function C5(){bs=null,go&&(clearTimeout(go),go=null);for(const s of Md)s()}async function qee(s,e){if(e.length<8)throw new Error("New password must be at least 8 characters");if(!await fJ(s)||!bs)return!1;const i=bs,n=await kr(),r=await new Promise((h,f)=>{const g=n.transaction(Ms,"readonly").objectStore(Ms).getAll();g.onsuccess=()=>h(g.result),g.onerror=()=>f(g.error)}),a=[];for(const h of r){const f=h.iv instanceof Uint8Array?h.iv:new Uint8Array(h.iv),p=await db(h.encryptedData,f,i);a.push({id:h.id,label:h.label,value:p,createdAt:h.createdAt})}const o=crypto.getRandomValues(new Uint8Array(S5)),c=await ub(e,o),l="openreel-verify-v1",{encrypted:u,iv:d}=await Eh(l,c);await hi(n,vs,"readwrite",h=>h.put({id:"salt",value:o})),await hi(n,vs,"readwrite",h=>h.put({id:"verification",value:u})),await hi(n,vs,"readwrite",h=>h.put({id:"verification_iv",value:d}));for(const h of a){const{encrypted:f,iv:p}=await Eh(h.value,c),m={id:h.id,label:h.label,encryptedData:f,iv:p,createdAt:h.createdAt,updatedAt:Date.now()};await hi(n,Ms,"readwrite",g=>g.put(m))}return bs=c,bu(),!0}async function Hee(s,e,t){if(!bs)throw new Error("Session is locked. Unlock with master password first.");bu();const{encrypted:i,iv:n}=await Eh(t,bs),r=await kr(),a=await hi(r,Ms,"readonly",c=>c.get(s)),o={id:s,label:e,encryptedData:i,iv:n,createdAt:a?.createdAt??Date.now(),updatedAt:Date.now()};await hi(r,Ms,"readwrite",c=>c.put(o))}async function pJ(s){if(!bs)throw new Error("Session is locked. Unlock with master password first.");bu();const e=await kr(),t=await hi(e,Ms,"readonly",n=>n.get(s));if(!t)return null;const i=t.iv instanceof Uint8Array?t.iv:new Uint8Array(t.iv);return await db(t.encryptedData,i,bs)}async function Yee(s){if(!bs)throw new Error("Session is locked");const e=await kr();await hi(e,Ms,"readwrite",t=>t.delete(s))}async function Xee(){const s=await kr();return(await new Promise((t,i)=>{const a=s.transaction(Ms,"readonly").objectStore(Ms).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>i(a.error)})).map(t=>({id:t.id,label:t.label,createdAt:t.createdAt,updatedAt:t.updatedAt}))}typeof window<"u"&&window.addEventListener("beforeunload",()=>{C5(),gn&&(gn.close(),gn=null)});class $i extends Error{code;msg;constructor(e,t){super(`KieAI error ${e}: ${t}`),this.name="KieAIError",this.code=e,this.msg=t}}const E5="https://kieai.redpandaai.co",hb="https://api.kie.ai",mJ="kie-ai";async function fb(){const s=await pJ(mJ);if(!s)throw new $i(401,"KieAI API key not configured. Add it in Settings → API Keys.");return s}async function gJ(s,e,t=E5){const i=await fb(),n=await fetch(`${t}${s}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(e)});if(!n.ok)throw new $i(n.status,`HTTP ${n.status}: ${n.statusText}`);const r=await n.json();if(r.code!==200)throw new $i(r.code,r.msg);return r.data}async function yJ(s,e,t=hb){const i=await fb(),n=new URL(`${t}${s}`);for(const[o,c]of Object.entries(e))n.searchParams.set(o,c);const r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${i}`}});if(!r.ok)throw new $i(r.status,`HTTP ${r.status}: ${r.statusText}`);const a=await r.json();if(a.code!==200)throw new $i(a.code,a.msg);return a.data}async function Kee(s,e){const t=await fb(),i=await fetch(`${E5}${s}`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:e});if(!i.ok)throw new $i(i.status,`HTTP ${i.status}: ${i.statusText}`);const n=await i.json();if(n.code!==200)throw new $i(n.code,n.msg);return n.data}const Qee={SEEDREAM:"seedream/5-lite-image-to-image",Z_IMAGE:"z-image",NANO_BANANA2:"nano-banana-2",FLUX2:"flux-2/pro-image-to-image",GROK:"grok-imagine/image-to-image",QWEN:"qwen/image-to-image"};async function Jee(s,e){return(await gJ("/api/v1/jobs/createTask",{model:s,input:e},hb)).taskId}async function vJ(s){return yJ("/api/v1/jobs/recordInfo",{taskId:s},hb)}function bJ(s){let e=null;if(typeof s.resultJson=="string")try{e=JSON.parse(s.resultJson)}catch{throw new $i(500,"Failed to parse resultJson from API")}else e=s.resultJson;const t=[e?.resultUrls,e?.result_urls,e?.images,e?.outputs,e?.urls];for(const n of t)if(Array.isArray(n)&&typeof n[0]=="string"&&n[0])return n[0];const i=["resultUrl","result_url","url","image_url","output","imageUrl"];for(const n of i){const r=e?.[n];if(typeof r=="string"&&r)return r}for(const n of["result","data","output"]){const r=e?.[n];if(r&&typeof r=="object"){for(const a of["url","image_url","imageUrl","resultUrl"])if(typeof r[a]=="string"&&r[a])return r[a];if(Array.isArray(r.urls)&&typeof r.urls[0]=="string")return r.urls[0]}}throw new $i(500,"No result URL in completed task — check console for raw record")}const Lk=5e3,xJ=3e4,wJ=12e4,_J=3*24*60*60*1e3,TJ=new Set(["tempfile.aiquickdraw.com","cdn.kie.ai"]);function kJ(s){try{const e=new URL(s);return TJ.has(e.hostname)}catch{return!1}}function AJ(){const s=Ic(h=>h.tasks),e=Ic(h=>h.removeTask),t=Ic(h=>h.incrementRetry),i=Ic(h=>h.markFailed),n=ys(h=>h.project?.id),r=ys(h=>h.replacePlaceholderMedia),a=ys(h=>h.setKieAIItemState),o=F.useRef(new Map),c=F.useRef(new Set),l=F.useRef(r);l.current=r;const u=F.useRef(a);u.current=a;const d=F.useCallback((h,f)=>{i(h),u.current(f,!1,!0)},[i]);F.useEffect(()=>{const h=s.filter(f=>f.projectId===n&&!f.failed);for(const f of h){if(o.current.has(f.taskId)||c.current.has(f.taskId))continue;if(Date.now()-f.createdAt>_J){d(f.taskId,f.mediaId);continue}const p=f.type==="video"?wJ:xJ,m=Date.now()-f.createdAt,g=m{if(o.current.delete(f.taskId),!c.current.has(f.taskId)){c.current.add(f.taskId);try{const b=await vJ(f.taskId);if(b.state==="success")try{const k=bJ(b);if(!kJ(k))throw new $i(403,`Result URL host not allowed: ${k}`);const A=await fetch(k);if(!A.ok)throw new $i(A.status,`Download failed: HTTP ${A.status}`);const M=await A.blob();if(M.size===0)throw new $i(500,"Downloaded result is empty");await l.current(f.mediaId,M,f.suggestedName),e(f.taskId)}catch(k){console.error(`[KieAIPoller] download failed for ${f.taskId}:`,k),i(f.taskId),u.current(f.mediaId,!1,!0)}else if(b.state==="fail")console.warn(`[KieAIPoller] task ${f.taskId} failed: ${b.failMsg}`),u.current(f.mediaId,!1,!0),i(f.taskId);else{const k=setTimeout(v,p);o.current.set(f.taskId,k)}}catch(b){if(b instanceof $i&&b.code===401){console.warn("[KieAIPoller] auth error — stopping poll for",f.taskId),i(f.taskId),u.current(f.mediaId,!1,!0);return}t(f.taskId);const k=Ic.getState().tasks.find(M=>M.taskId===f.taskId);if((k?k.retries:Im)>=Im)console.warn(`[KieAIPoller] ${f.taskId} exhausted ${Im} retries — marking failed`),i(f.taskId),u.current(f.mediaId,!1,!0);else{const M=setTimeout(v,p);o.current.set(f.taskId,M)}}finally{c.current.delete(f.taskId)}}},w=setTimeout(v,g);o.current.set(f.taskId,w)}for(const[f,p]of o.current)h.some(g=>g.taskId===f)||(clearTimeout(p),o.current.delete(f))},[s,n,e,t,i,d]),F.useEffect(()=>{const h=o.current;return()=>{for(const f of h.values())clearTimeout(f);h.clear()}},[])}const SJ=F.lazy(()=>ii(()=>import("./EditorInterface-C-F8FyLk.js").then(s=>s.W),__vite__mapDeps([0,1,2,3])).then(s=>({default:s.EditorInterface}))),CJ=({message:s})=>x.jsxs("div",{className:"h-screen w-screen bg-background flex flex-col items-center justify-center",children:[x.jsx("div",{className:"w-10 h-10 border-2 border-primary border-t-transparent rounded-full animate-spin mb-3"}),x.jsx("p",{className:"text-sm text-text-secondary",children:s})]}),EJ={"1080x1920":"tiktok","1920x1080":"youtube-video","1080x1080":"instagram-post","720x1280":"instagram-stories","1280x720":"youtube-video"};function MJ(){const{activeModal:s,closeModal:e,skipWelcomeScreen:t}=Hl(),{openModal:i}=Hl(),n=ys(k=>k.createNewProject),{showDialog:r,availableSaves:a,recover:o,dismiss:c,clearAll:l}=sJ(),{route:u,params:d,navigate:h,parsedDimensions:f,fps:p}=A5(),m=F.useRef(!1);AJ(),F.useEffect(()=>{if(!m.current)if(u==="new"){m.current=!0;let k="New Project",A=1920,M=1080,R=p;if(d.preset){const I=d.preset,D=nh[I];D&&(A=D.width,M=D.height,R=D.frameRate||p,k=`New ${I.charAt(0).toUpperCase()+I.slice(1).replace(/-/g," ")} Project`)}else if(f){A=f.width,M=f.height;const I=`${A}x${M}`,D=EJ[I];D&&(R=nh[D].frameRate||p);const B=A/M;B<1?k="New Vertical Video":B>1?k="New Horizontal Video":k="New Square Video"}n(k,{width:A,height:M,frameRate:R}),h("editor")}else(u==="editor"&&t||["welcome","templates","recent"].includes(u))&&(m.current=!0)},[u,d,f,p,n,h,t]);const g=F.useCallback(k=>{k.key==="Escape"&&u!=="editor"&&h("editor"),(k.metaKey||k.ctrlKey)&&k.key==="k"&&(k.preventDefault(),i("search"))},[u,h,i]);F.useEffect(()=>(window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)),[g]);const v=["welcome","templates","recent"].includes(u)&&!t,w=u==="templates"?"templates":u==="recent"?"recent":void 0,b=u==="share"&&d.shareId;return x.jsx(I7,{children:x.jsxs("div",{className:"h-screen w-screen bg-background text-text-primary overflow-hidden",children:[x.jsx(DQ,{}),b?x.jsx(iJ,{shareId:d.shareId}):v?x.jsx(KQ,{initialTab:w}):x.jsx(F.Suspense,{fallback:x.jsx(CJ,{message:"Loading editor..."}),children:x.jsx(SJ,{})}),x.jsx(Zj,{}),x.jsx(EQ,{isOpen:s==="scriptView",onClose:e}),x.jsx(RQ,{isOpen:s==="search",onClose:e}),r&&a.length>0&&x.jsx(QQ,{saves:a,onRecover:async k=>{await o(k)&&h("editor")},onDismiss:c,onClearAll:l})]})})}class IJ{registration=null;listeners=new Map;isOnline=typeof navigator<"u"?navigator.onLine:!0;constructor(){typeof window<"u"&&(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline))}isSupported(){return typeof navigator<"u"&&"serviceWorker"in navigator}async register(){if(!this.isSupported())return console.warn("[SW Manager] Service workers not supported"),null;try{const e=await navigator.serviceWorker.register("/sw.js",{scope:"/"});return this.registration=e,e.addEventListener("updatefound",()=>{this.handleUpdateFound(e)}),setInterval(()=>{this.checkForUpdates()},60*60*1e3),this.emit("registered",{registration:e}),e}catch(e){return console.error("[SW Manager] Registration failed:",e),this.emit("error",{error:e}),null}}async unregister(){if(!this.registration)return!1;try{const e=await this.registration.unregister();return e&&(this.registration=null),e}catch(e){return console.error("[SW Manager] Unregistration failed:",e),!1}}async checkForUpdates(){if(this.registration)try{await this.registration.update()}catch(e){console.error("[SW Manager] Update check failed:",e)}}async skipWaiting(){this.registration?.waiting&&this.sendMessage({type:"SKIP_WAITING"})}getStatus(){return{supported:this.isSupported(),registered:!!this.registration,active:!!this.registration?.active,waiting:!!this.registration?.waiting,updateAvailable:!!this.registration?.waiting}}async getCacheStatus(){return this.sendMessageWithResponse({type:"GET_CACHE_STATUS"})}async clearCache(){await this.sendMessageWithResponse({type:"CLEAR_CACHE"})}getOnlineStatus(){return this.isOnline}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}sendMessage(e){this.registration?.active&&this.registration.active.postMessage(e)}sendMessageWithResponse(e){return new Promise(t=>{if(!this.registration?.active){t(null);return}const i=new MessageChannel;i.port1.onmessage=n=>{t(n.data?.payload||null)},this.registration.active.postMessage(e,[i.port2]),setTimeout(()=>t(null),5e3)})}handleUpdateFound(e){const t=e.installing;t&&t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&this.emit("updated",{registration:e})})}handleOnline=()=>{this.isOnline=!0,this.emit("online")};handleOffline=()=>{this.isOnline=!1,this.emit("offline")};emit(e,t){this.listeners.get(e)?.forEach(i=>{try{i(t)}catch(n){console.error("[SW Manager] Event callback error:",n)}})}destroy(){typeof window<"u"&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline)),this.listeners.clear()}}const PJ=new IJ;async function RJ(){return PJ.register()}const ey="openreel:custom-fonts-updated",DJ="openreel-custom-fonts",FJ=1,No="fonts",Vo=[],Zee={Popular:["Inter","Poppins","Montserrat","Roboto","Open Sans","Lato","Outfit","DM Sans"],"Display & Headlines":["Bebas Neue","Anton","Oswald","Teko","Staatliches","Alfa Slab One","Archivo Black","Black Ops One","Titan One","Righteous","Concert One","Fredoka One","Bungee"],"Elegant & Serif":["Playfair Display","Cinzel","Lora","Merriweather","DM Serif Display","Abril Fatface","Roboto Slab","Zilla Slab"],"Modern & Clean":["Lexend","Quicksand","Nunito","Rubik","Work Sans","Raleway","Ubuntu","Space Grotesk","Comfortaa"],"Handwritten & Script":["Pacifico","Lobster","Dancing Script","Great Vibes","Caveat","Sacramento","Satisfy","Yellowtail","Rock Salt","Permanent Marker"],"Fun & Creative":["Bangers","Creepster","Press Start 2P"],Monospace:["Roboto Mono","Space Mono"],System:["Arial","Helvetica","Times New Roman","Georgia","Verdana"]},LJ=/\.(ttf|otf|woff2?)$/i,ete=".ttf,.otf,.woff,.woff2";function M5(){typeof window<"u"&&window.dispatchEvent(new CustomEvent(ey))}function OJ(s){const e=s.trim()||"Custom Font";let t=e,i=2;for(;Vo.includes(t);)t=`${e} ${i}`,i+=1;return t}function I5(){return new Promise(s=>{if(typeof indexedDB>"u"){s(null);return}const e=indexedDB.open(DJ,FJ);e.onerror=()=>s(null),e.onsuccess=()=>s(e.result),e.onupgradeneeded=t=>{const i=t.target.result;i.objectStoreNames.contains(No)||i.createObjectStore(No,{keyPath:"family"})}})}async function BJ(s,e){const t=await I5();t&&(await new Promise(i=>{const n=t.transaction(No,"readwrite"),r=n.objectStore(No),a={family:s,data:e,uploadedAt:Date.now()};r.put(a),n.oncomplete=()=>i(),n.onerror=()=>i(),n.onabort=()=>i()}),t.close())}async function $J(){const s=await I5();if(!s)return[];const e=await new Promise(t=>{const r=s.transaction(No,"readonly").objectStore(No).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>t([])});return s.close(),e}let ad=null;function P5(){return ad||(ad=(async()=>{if(typeof FontFace>"u"||typeof document>"u")return;const s=await $J();let e=!1;for(const{family:t,data:i}of s)if(!Vo.includes(t))try{const n=new FontFace(t,i);await n.load(),document.fonts.add(n),Vo.push(t),e=!0}catch{}e&&M5()})(),ad)}function Ok(){return[...Vo]}function tte(){const[s,e]=F.useState(()=>Ok());return F.useEffect(()=>{const t=()=>e(Ok());return window.addEventListener(ey,t),P5().then(t),()=>window.removeEventListener(ey,t)},[]),s}async function ite(s){if(!LJ.test(s.name))return{success:!1,error:"Please upload a .ttf, .otf, .woff, or .woff2 font file."};if(typeof FontFace>"u"||typeof document>"u")return{success:!1,error:"Custom font upload is not supported in this environment."};try{const e=s.name.replace(/\.[^/.]+$/,""),t=OJ(e),i=await s.arrayBuffer(),n=new FontFace(t,i);return await n.load(),document.fonts.add(n),Vo.includes(t)||(Vo.push(t),M5()),await BJ(t,i).catch(()=>{}),{success:!0,fontFamily:t}}catch{return{success:!1,error:"Could not load this font file."}}}RJ().then(s=>{});P5();const jJ=document.getElementById("root");F5.createRoot(jJ).render(x.jsx(Xn.StrictMode,{children:x.jsx(MJ,{})}));export{TG as $,F7 as A,jM as B,NM as C,pi as D,ab as E,B1 as F,UM as G,ol as H,j7 as I,t0 as J,i0 as K,s0 as L,BM as M,W7 as N,Fv as O,z7 as P,YI as Q,lu as R,nh as S,Tee as T,Wq as U,Gn as V,VM as W,qq as X,Hq as Y,Jq as Z,zM as _,km as a,BH as a$,Wh as a0,Zq as a1,eH as a2,Aee as a3,tH as a4,iH as a5,sH as a6,kG as a7,AG as a8,SG as a9,GG as aA,WG as aB,m_ as aC,YG as aD,XG as aE,KG as aF,QG as aG,aH,cH as aI,mH as aJ,gH as aK,lH as aL,uH as aM,dH as aN,hH as aO,TT as aP,kT as aQ,fH as aR,yH as aS,wH as aT,C0 as aU,XI as aV,zH as aW,aP as aX,iP as aY,sP as aZ,rP as a_,Dp as aa,MG as ab,IG as ac,d_ as ad,a0 as ae,h_ as af,r0 as ag,GM as ah,PG as ai,BG as aj,jG as ak,$G as al,NG as am,Bp as an,JG as ao,fi as ap,nH as aq,Ac as ar,rH as as,Fl as at,cG as au,Yr as av,lG as aw,qG as ax,HG as ay,zG as az,gk as b,FY as b$,Eee as b0,Lv as b1,TH as b2,KI as b3,kH as b4,Ov as b5,jH as b6,NH as b7,Mee as b8,SH as b9,n0 as bA,Bv as bB,cm as bC,OT as bD,BT as bE,tY as bF,iY as bG,sY as bH,$v as bI,lm as bJ,_Y as bK,Pp as bL,oh as bM,oG as bN,As as bO,TY as bP,kY as bQ,Pee as bR,AY as bS,SY as bT,CY as bU,EY as bV,MY as bW,lP as bX,PY as bY,$T as bZ,DY as b_,ZI as ba,CH as bb,MT as bc,Cee as bd,vH as be,bH as bf,Ct as bg,AT as bh,See as bi,cP as bj,Iee as bk,qH as bl,QH as bm,XH as bn,KH as bo,JH as bp,ZH as bq,eY as br,oP as bs,GH as bt,WH as bu,sG as bv,nG as bw,aG as bx,na as by,rG as bz,LM as c,tj as c$,LY as c0,OY as c1,I0 as c2,BY as c3,dm as c4,qY as c5,bT as c6,$q as c7,jq as c8,kee as c9,yee as cA,m7 as cB,bee as cC,g7 as cD,v7 as cE,P1 as cF,ro as cG,su as cH,R1 as cI,fj as cJ,Kt as cK,dr as cL,wj as cM,Wr as cN,Gj as cO,Ys as cP,Xy as cQ,x3 as cR,Ag as cS,ys as cT,Hy as cU,Xd as cV,P$ as cW,k3 as cX,x7 as cY,ip as cZ,rr as c_,Bq as ca,S0 as cb,Ss as cc,_ee as cd,XK as ce,Ree as cf,pk as cg,HK as ch,YK as ci,mk as cj,zq as ck,xT as cl,he as cm,Vh as cn,cu as co,Uh as cp,w3 as cq,zh as cr,T7 as cs,k7 as ct,A7 as cu,Yy as cv,Ej as cw,S7 as cx,pd as cy,Cn as cz,Ap as d,Qz as d$,iu as d0,oj as d1,Us as d2,zee as d3,Gh as d4,J$ as d5,A3 as d6,n7 as d7,dJ as d8,Gee as d9,T3 as dA,Pw as dB,sj as dC,q as dD,Vee as dE,Eg as dF,qj as dG,OQ as dH,Aj as dI,dj as dJ,D$ as dK,Ns as dL,En as dM,Sg as dN,Kee as dO,Qee as dP,Ic as dQ,Jee as dR,ve as dS,jee as dT,Nee as dU,$ee as dV,tp as dW,_3 as dX,hee as dY,fee as dZ,Kz as d_,Xee as da,Wee as db,Kj as dc,fJ as dd,qee as de,Hee as df,Yee as dg,pJ as dh,C5 as di,Iw as dj,Ea as dk,zO as dl,Hl as dm,A5 as dn,cb as dp,lb as dq,xee as dr,wee as ds,Mg as dt,P7 as du,mee as dv,gee as dw,o7 as dx,c7 as dy,h7 as dz,D7 as e,J0 as e0,Bs as e1,p7 as e2,U$ as e3,sp as e4,ie as e5,d7 as e6,w7 as e7,q$ as e8,ite as e9,Lee as eA,iG as eB,ete as ea,tte as eb,Zee as ec,vee as ed,y7 as ee,rN as ef,eN as eg,tN as eh,V3 as ei,Z8 as ej,M1 as ek,CM as el,I1 as em,Uee as en,t7 as eo,e7 as ep,i7 as eq,pee as er,Yz as es,Xz as et,$$ as eu,Bee as ev,Fee as ew,Oee as ex,xk as ey,Dee as ez,Ou as f,nQ as g,zc as h,N7 as i,V7 as j,ne as k,OM as l,U7 as m,Tc as n,G7 as o,sa as p,D1 as q,F1 as r,R7 as s,L1 as t,O1 as u,e0 as v,$1 as w,rh as x,ao as y,$M as z}; diff --git a/resources/video-editor/assets/index-DxTomwdq.css b/resources/video-editor/assets/index-DxTomwdq.css new file mode 100644 index 00000000..9439c4f7 --- /dev/null +++ b/resources/video-editor/assets/index-DxTomwdq.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700;800&display=swap";@import"https://fonts.googleapis.com/css2?family=Geist+Mono:wght@400;500;600&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Geist,-apple-system,BlinkMacSystemFont,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:Geist Mono,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{font-family:Geist,-apple-system,BlinkMacSystemFont,Segoe UI,system-ui,sans-serif;line-height:1.5;font-weight:400;letter-spacing:-.005em;--d-text: 12.5px;--d-text-sm: 11px;--tl-height: 58vh;--tl-track: 56px;--tl-rail: 196px;--media-w: 460px;--inspector-w: 360px;--topbar-h: 40px;--toolnav-h: 64px;color-scheme:dark}:root,[data-theme=light]{--bg: oklch(.98 .003 240);--bg-1: oklch(1 0 0);--bg-2: oklch(.965 .004 240);--bg-3: oklch(.94 .005 240);--bg-elev: oklch(1 0 0);--border: oklch(.91 .005 240);--border-strong: oklch(.84 .006 240);--fg: oklch(.18 .01 240);--fg-2: oklch(.42 .012 240);--fg-3: oklch(.58 .012 240);--fg-muted: oklch(.7 .01 240);--hover: oklch(.96 .005 240);--selected: oklch(.94 .008 240);--shadow-sm: 0 1px 0 oklch(0 0 0 / .04), 0 1px 2px oklch(0 0 0 / .04);--shadow-md: 0 1px 0 oklch(0 0 0 / .04), 0 6px 20px oklch(0 0 0 / .06);--shadow-lg: 0 1px 0 oklch(0 0 0 / .05), 0 24px 60px oklch(0 0 0 / .1);--track-bg: oklch(.95 .005 240);--tl-bg: oklch(.93 .005 240);--waveform: oklch(.72 .16 162 / .55);--stage-bg: oklch(1 0 0);--screen-bg: oklch(1 0 0);--accent: oklch(.72 .16 162);--accent-strong: oklch(.66 .18 162);--accent-soft: oklch(.72 .16 162 / .16);--accent-fg: oklch(.99 0 0);--accent-glow: oklch(.72 .16 162 / .4);--c-video: oklch(.6 .13 200);--c-text: oklch(.78 .13 80);--c-audio: oklch(.7 .16 162);--c-music: oklch(.7 .14 295)}[data-theme=dark],.dark{--bg: oklch(.12 .005 240);--bg-1: oklch(.16 .006 240);--bg-2: oklch(.2 .007 240);--bg-3: oklch(.24 .008 240);--bg-elev: oklch(.22 .007 240);--border: oklch(.26 .008 240);--border-strong: oklch(.34 .01 240);--fg: oklch(.97 .003 240);--fg-2: oklch(.78 .008 240);--fg-3: oklch(.6 .012 240);--fg-muted: oklch(.48 .012 240);--hover: oklch(.22 .009 240);--selected: oklch(.28 .012 240);--shadow-sm: 0 1px 0 oklch(0 0 0 / .4), 0 1px 2px oklch(0 0 0 / .3);--shadow-md: 0 1px 0 oklch(0 0 0 / .5), 0 6px 24px oklch(0 0 0 / .4);--shadow-lg: 0 1px 0 oklch(0 0 0 / .6), 0 24px 60px oklch(0 0 0 / .5);--track-bg: oklch(.12 .006 240);--tl-bg: oklch(.1 .005 240);--waveform: oklch(.78 .16 162 / .85);--stage-bg: oklch(.08 .004 240);--screen-bg: oklch(0 0 0);--accent: oklch(.72 .16 162);--accent-strong: oklch(.66 .18 162);--accent-soft: oklch(.72 .16 162 / .16);--accent-fg: oklch(.99 0 0);--accent-glow: oklch(.72 .16 162 / .4)}[data-density=compact]{--d-text: 12px;--d-text-sm: 10.5px;--tl-track: 46px;--tl-rail: 168px;--toolnav-h: 56px;--topbar-h: 36px}:root,[data-theme=light]{--background: 0 0% 100%;--foreground: 240 10% 4%;--card: 0 0% 100%;--card-foreground: 240 10% 4%;--popover: 0 0% 100%;--popover-foreground: 240 10% 4%;--primary: 158 64% 52%;--primary-foreground: 0 0% 100%;--secondary: 240 5% 96%;--secondary-foreground: 240 6% 10%;--muted: 240 5% 96%;--muted-foreground: 240 4% 46%;--accent-hsl: 240 5% 96%;--accent-foreground: 240 6% 10%;--destructive: 0 84% 60%;--destructive-foreground: 0 0% 98%;--input: 240 6% 90%;--ring: 158 64% 52%;--radius: .5rem}[data-theme=dark],.dark{--background: 220 12% 9%;--foreground: 0 0% 95%;--card: 220 10% 13%;--card-foreground: 0 0% 95%;--popover: 220 10% 13%;--popover-foreground: 0 0% 95%;--primary: 158 64% 52%;--primary-foreground: 0 0% 100%;--secondary: 220 8% 18%;--secondary-foreground: 0 0% 95%;--muted: 220 8% 18%;--muted-foreground: 220 8% 65%;--accent-hsl: 220 8% 22%;--accent-foreground: 0 0% 95%;--destructive: 0 62% 50%;--destructive-foreground: 0 0% 95%;--input: 220 8% 24%;--ring: 158 64% 52%}html,body{margin:0;padding:0;height:100%;overflow:hidden}body{font-family:Geist,-apple-system,BlinkMacSystemFont,system-ui,sans-serif;font-size:var(--d-text);color:var(--fg);background:var(--bg);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:-.005em}button{cursor:pointer}.\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\!container{max-width:1536px!important}.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.\!visible{visibility:visible!important}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-px{inset:-1px}.inset-0{inset:0}.inset-4{inset:1rem}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.-bottom-2{bottom:-.5rem}.-bottom-4{bottom:-1rem}.-left-2{left:-.5rem}.-right-1{right:-.25rem}.-right-2{right:-.5rem}.-top-0\.5{top:-.125rem}.-top-1{top:-.25rem}.-top-2{top:-.5rem}.-top-6{top:-1.5rem}.-top-8{top:-2rem}.bottom-0{bottom:0}.bottom-0\.5{bottom:.125rem}.bottom-1{bottom:.25rem}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.bottom-full{bottom:100%}.left-0{left:0}.left-1{left:.25rem}.left-1\/2{left:50%}.left-2{left:.5rem}.left-2\.5{left:.625rem}.left-20{left:5rem}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-0\.5{right:.125rem}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-3{top:.75rem}.top-4{top:1rem}.top-\[15vh\]{top:15vh}.top-\[7px\]{top:7px}.top-full{top:100%}.top-topbar{top:var(--topbar-h)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[102\]{z-index:102}.z-\[200\]{z-index:200}.z-\[9999\]{z-index:9999}.col-span-2{grid-column:span 2 / span 2}.col-span-6{grid-column:span 6 / span 6}.m-0{margin:0}.m-2{margin:.5rem}.m-auto{margin:auto}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-1\.5{margin-left:.375rem;margin-right:.375rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-1{margin-top:.25rem;margin-bottom:.25rem}.-mb-px{margin-bottom:-1px}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-5{margin-left:1.25rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mr-2{margin-right:.5rem}.mt-0{margin-top:0}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-2\.5{margin-top:.625rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.box-border{box-sizing:border-box}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-\[9\/16\]{aspect-ratio:9/16}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.h-0{height:0px}.h-0\.5{height:.125rem}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-1\/3{height:33.333333%}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[11px\]{height:11px}.h-\[22px\]{height:22px}.h-\[26px\]{height:26px}.h-\[30px\]{height:30px}.h-\[5px\]{height:5px}.h-\[calc\(100\%-49px\)\]{height:calc(100% - 49px)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.h-topbar{height:var(--topbar-h)}.max-h-24{max-height:6rem}.max-h-32{max-height:8rem}.max-h-48{max-height:12rem}.max-h-60{max-height:15rem}.max-h-64{max-height:16rem}.max-h-72{max-height:18rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[--radix-context-menu-content-available-height\]{max-height:var(--radix-context-menu-content-available-height)}.max-h-\[--radix-select-content-available-height\]{max-height:var(--radix-select-content-available-height)}.max-h-\[200px\]{max-height:200px}.max-h-\[400px\]{max-height:400px}.max-h-\[50vh\]{max-height:50vh}.max-h-\[70vh\]{max-height:70vh}.max-h-\[80vh\]{max-height:80vh}.max-h-\[85vh\]{max-height:85vh}.max-h-\[90vh\]{max-height:90vh}.max-h-\[var\(--radix-dropdown-menu-content-available-height\)\]{max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-full{max-height:100%}.min-h-0{min-height:0px}.min-h-\[38px\]{min-height:38px}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-0\.5{width:.125rem}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-1\/3{width:33.333333%}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-80{width:20rem}.w-\[11px\]{width:11px}.w-\[160px\]{width:160px}.w-\[180px\]{width:180px}.w-\[22px\]{width:22px}.w-\[26px\]{width:26px}.w-\[2px\]{width:2px}.w-\[30px\]{width:30px}.w-\[5px\]{width:5px}.w-\[70px\]{width:70px}.w-\[var\(--radix-popover-trigger-width\)\]{width:var(--radix-popover-trigger-width)}.w-auto{width:auto}.w-full{width:100%}.w-px{width:1px}.w-screen{width:100vw}.min-w-0{min-width:0px}.min-w-10{min-width:2.5rem}.min-w-11{min-width:2.75rem}.min-w-9{min-width:2.25rem}.min-w-\[100px\]{min-width:100px}.min-w-\[140px\]{min-width:140px}.min-w-\[160px\]{min-width:160px}.min-w-\[180px\]{min-width:180px}.min-w-\[200px\]{min-width:200px}.min-w-\[220px\]{min-width:220px}.min-w-\[320px\]{min-width:320px}.min-w-\[50px\]{min-width:50px}.min-w-\[60px\]{min-width:60px}.min-w-\[80px\]{min-width:80px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.min-w-full{min-width:100%}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-\[120px\]{max-width:120px}.max-w-\[140px\]{max-width:140px}.max-w-\[150px\]{max-width:150px}.max-w-\[170px\]{max-width:170px}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-\[240px\]{max-width:240px}.max-w-\[256px\]{max-width:256px}.max-w-\[420px\]{max-width:420px}.max-w-\[70px\]{max-width:70px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-\[--radix-select-content-transform-origin\]{transform-origin:var(--radix-select-content-transform-origin)}.origin-\[--radix-tooltip-content-transform-origin\]{transform-origin:var(--radix-tooltip-content-transform-origin)}.origin-left{transform-origin:left}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0\.5{--tw-translate-x: .125rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-4{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-5{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-2{--tw-translate-y: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rotate-90{--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-45{--tw-rotate: 45deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-\[-45deg\]{--tw-rotate: -45deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-0{--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-75{--tw-scale-x: .75;--tw-scale-y: .75;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\!transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))!important}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-col-resize{cursor:col-resize}.cursor-crosshair{cursor:crosshair}.cursor-default{cursor:default}.cursor-e-resize{cursor:e-resize}.cursor-ew-resize{cursor:ew-resize}.cursor-grab{cursor:grab}.cursor-grabbing{cursor:grabbing}.cursor-move{cursor:move}.cursor-n-resize{cursor:n-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-not-allowed{cursor:not-allowed}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-nwse-resize{cursor:nwse-resize}.cursor-pointer{cursor:pointer}.cursor-row-resize{cursor:row-resize}.cursor-s-resize{cursor:s-resize}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.cursor-text{cursor:text}.cursor-w-resize{cursor:w-resize}.cursor-wait{cursor:wait}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.grid-cols-\[1fr_auto_1fr\]{grid-template-columns:1fr auto 1fr}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.place-content-center{place-content:center}.place-items-center{place-items:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.gap-0{gap:0px}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-px{gap:1px}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.self-stretch{align-self:stretch}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-clip{text-overflow:clip}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.rounded-b-xl{border-bottom-right-radius:.75rem;border-bottom-left-radius:.75rem}.rounded-t-lg{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-r{border-right-width:1px}.border-r-2{border-right-width:2px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-accent{border-color:var(--accent)}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-amber-300\/80{border-color:#fcd34dcc}.border-amber-400{--tw-border-opacity: 1;border-color:rgb(251 191 36 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/30{border-color:#f59e0b4d}.border-black\/20{border-color:#0003}.border-black\/30{border-color:#0000004d}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500\/30{border-color:#3b82f64d}.border-blue-500\/50{border-color:#3b82f680}.border-border{border-color:var(--border)}.border-border-strong{border-color:var(--border-strong)}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-cyan-500\/50{border-color:#06b6d480}.border-cyan-500\/60{border-color:#06b6d499}.border-destructive\/50{border-color:hsl(var(--destructive) / .5)}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-500\/30{border-color:#10b9814d}.border-emerald-500\/60{border-color:#10b98199}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-green-400{--tw-border-opacity: 1;border-color:rgb(74 222 128 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-green-500\/20{border-color:#22c55e33}.border-green-500\/30{border-color:#22c55e4d}.border-green-500\/50{border-color:#22c55e80}.border-indigo-500\/30{border-color:#6366f14d}.border-input{border-color:hsl(var(--input))}.border-orange-500\/50{border-color:#f9731680}.border-pink-500\/30{border-color:#ec48994d}.border-pink-500\/50{border-color:#ec489980}.border-primary{border-color:hsl(var(--primary))}.border-primary\/20{border-color:hsl(var(--primary) / .2)}.border-primary\/30{border-color:hsl(var(--primary) / .3)}.border-primary\/40{border-color:hsl(var(--primary) / .4)}.border-primary\/50{border-color:hsl(var(--primary) / .5)}.border-purple-400{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-500\/30{border-color:#a855f74d}.border-purple-500\/50{border-color:#a855f780}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-500\/20{border-color:#ef444433}.border-red-500\/30{border-color:#ef44444d}.border-status-error\/40{border-color:#ef444466}.border-text-muted{border-color:var(--fg-3)}.border-transparent{border-color:transparent}.border-violet-500\/60{border-color:#8b5cf699}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/30{border-color:#ffffff4d}.border-white\/80{border-color:#fffc}.border-yellow-500{--tw-border-opacity: 1;border-color:rgb(234 179 8 / var(--tw-border-opacity, 1))}.border-yellow-500\/30{border-color:#eab3084d}.border-yellow-500\/40{border-color:#eab30866}.border-yellow-600{--tw-border-opacity: 1;border-color:rgb(202 138 4 / var(--tw-border-opacity, 1))}.border-l-transparent{border-left-color:transparent}.border-t-black{--tw-border-opacity: 1;border-top-color:rgb(0 0 0 / var(--tw-border-opacity, 1))}.border-t-primary{border-top-color:hsl(var(--primary))}.border-t-transparent{border-top-color:transparent}.border-t-white{--tw-border-opacity: 1;border-top-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-opacity-30{--tw-border-opacity: .3}.bg-\[oklch\(0\.78_0\.14_80\)\]{background-color:#e6ac3d}.bg-\[oklch\(0\.7_0\.15_145\)\]{background-color:#5bb661}.bg-\[oklch\(0\.7_0\.18_25\)\]{background-color:#fa6863}.bg-\[var\(--screen-bg\)\]{background-color:var(--screen-bg)}.bg-accent{background-color:var(--accent)}.bg-accent-soft{background-color:var(--accent-soft)}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-400\/10{background-color:#fbbf241a}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-500\/15{background-color:#f59e0b26}.bg-amber-500\/20{background-color:#f59e0b33}.bg-amber-500\/5{background-color:#f59e0b0d}.bg-amber-900\/60{background-color:#78350f99}.bg-background{background-color:hsl(var(--background))}.bg-background-elevated{background-color:var(--bg-elev)}.bg-background-secondary{background-color:var(--bg-1)}.bg-background-tertiary{background-color:var(--bg-2)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-bg{background-color:var(--bg)}.bg-bg-1{background-color:var(--bg-1)}.bg-bg-2{background-color:var(--bg-2)}.bg-bg-3{background-color:var(--bg-3)}.bg-bg-elev{background-color:var(--bg-elev)}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/0{background-color:#0000}.bg-black\/20{background-color:#0003}.bg-black\/30{background-color:#0000004d}.bg-black\/40{background-color:#0006}.bg-black\/5{background-color:#0000000d}.bg-black\/50{background-color:#00000080}.bg-black\/55{background-color:#0000008c}.bg-black\/60{background-color:#0009}.bg-black\/70{background-color:#000000b3}.bg-black\/80{background-color:#000c}.bg-black\/90{background-color:#000000e6}.bg-blue-300{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/10{background-color:#3b82f61a}.bg-blue-500\/20{background-color:#3b82f633}.bg-border{background-color:var(--border)}.bg-card{background-color:hsl(var(--card))}.bg-cyan-500{--tw-bg-opacity: 1;background-color:rgb(6 182 212 / var(--tw-bg-opacity, 1))}.bg-cyan-500\/10{background-color:#06b6d41a}.bg-cyan-500\/20{background-color:#06b6d433}.bg-cyan-500\/80{background-color:#06b6d4cc}.bg-cyan-600\/25{background-color:#0891b240}.bg-destructive{background-color:hsl(var(--destructive))}.bg-destructive\/10{background-color:hsl(var(--destructive) / .1)}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-600\/25{background-color:#05966940}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-500\/20{background-color:#6b728033}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-500\/15{background-color:#22c55e26}.bg-green-500\/20{background-color:#22c55e33}.bg-green-500\/30{background-color:#22c55e4d}.bg-green-500\/80{background-color:#22c55ecc}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900\/60{background-color:#14532d99}.bg-indigo-500\/10{background-color:#6366f11a}.bg-indigo-500\/20{background-color:#6366f133}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/40{background-color:hsl(var(--muted) / .4)}.bg-orange-400\/30{background-color:#fb923c4d}.bg-orange-400\/50{background-color:#fb923c80}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-orange-500\/10{background-color:#f973161a}.bg-orange-500\/20{background-color:#f9731633}.bg-orange-500\/60{background-color:#f9731699}.bg-pink-500\/10{background-color:#ec48991a}.bg-pink-500\/20{background-color:#ec489933}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary-foreground\/80{background-color:hsl(var(--primary-foreground) / .8)}.bg-primary\/10{background-color:hsl(var(--primary) / .1)}.bg-primary\/15{background-color:hsl(var(--primary) / .15)}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-primary\/5{background-color:hsl(var(--primary) / .05)}.bg-primary\/50{background-color:hsl(var(--primary) / .5)}.bg-primary\/80{background-color:hsl(var(--primary) / .8)}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-500\/10{background-color:#a855f71a}.bg-purple-500\/20{background-color:#a855f733}.bg-red-400\/10{background-color:#f871711a}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/20{background-color:#ef444433}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-stage-bg{background-color:var(--stage-bg)}.bg-status-error\/10{background-color:#ef44441a}.bg-status-info\/20{background-color:#3b82f633}.bg-text-muted{background-color:var(--fg-3)}.bg-text-primary{background-color:var(--fg)}.bg-text-secondary{background-color:var(--fg-2)}.bg-tl-bg{background-color:var(--tl-bg)}.bg-transparent{background-color:transparent}.bg-violet-600\/25{background-color:#7c3aed40}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/20{background-color:#fff3}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/10{background-color:#eab3081a}.bg-yellow-500\/20{background-color:#eab30833}.bg-yellow-500\/5{background-color:#eab3080d}.bg-zinc-900\/95{background-color:#18181bf2}.bg-\[linear-gradient\(110deg\,transparent_0\%\,rgba\(255\,255\,255\,0\.08\)_28\%\,rgba\(251\,191\,36\,0\.28\)_50\%\,rgba\(255\,255\,255\,0\.08\)_72\%\,transparent_100\%\)\]{background-image:linear-gradient(110deg,transparent 0%,rgba(255,255,255,.08) 28%,rgba(251,191,36,.28) 50%,rgba(255,255,255,.08) 72%,transparent 100%)}.bg-\[radial-gradient\(ellipse_at_bottom_right\,rgba\(34\,197\,94\,0\.03\)\,transparent_50\%\)\]{background-image:radial-gradient(ellipse at bottom right,rgba(34,197,94,.03),transparent 50%)}.bg-\[radial-gradient\(ellipse_at_top\,rgba\(34\,197\,94\,0\.05\)\,transparent_60\%\)\]{background-image:radial-gradient(ellipse at top,rgba(34,197,94,.05),transparent 60%)}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-l{background-image:linear-gradient(to left,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.bg-gradient-to-t{background-image:linear-gradient(to top,var(--tw-gradient-stops))}.from-amber-500{--tw-gradient-from: #f59e0b var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-background-secondary{--tw-gradient-from: var(--bg-1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-black\/50{--tw-gradient-from: rgb(0 0 0 / .5) var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500\/20{--tw-gradient-from: rgb(59 130 246 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-700{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-500{--tw-gradient-from: #10b981 var(--tw-gradient-from-position);--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500\/20{--tw-gradient-from: rgb(34 197 94 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-indigo-500\/20{--tw-gradient-from: rgb(99 102 241 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-orange-500\/20{--tw-gradient-from: rgb(249 115 22 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-pink-500{--tw-gradient-from: #ec4899 var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-pink-500\/20{--tw-gradient-from: rgb(236 72 153 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-primary{--tw-gradient-from: hsl(var(--primary)) var(--tw-gradient-from-position);--tw-gradient-to: hsl(var(--primary) / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-primary\/20{--tw-gradient-from: hsl(var(--primary) / .2) var(--tw-gradient-from-position);--tw-gradient-to: hsl(var(--primary) / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/20{--tw-gradient-from: rgb(168 85 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-500{--tw-gradient-from: #ef4444 var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-sky-500{--tw-gradient-from: #0ea5e9 var(--tw-gradient-from-position);--tw-gradient-to: rgb(14 165 233 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-teal-500{--tw-gradient-from: #14b8a6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(20 184 166 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-violet-500\/20{--tw-gradient-from: rgb(139 92 246 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-zinc-500{--tw-gradient-from: #71717a var(--tw-gradient-from-position);--tw-gradient-to: rgb(113 113 122 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-transparent{--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), transparent var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-background-tertiary{--tw-gradient-to: var(--bg-2) var(--tw-gradient-to-position)}.to-blue-400{--tw-gradient-to: #60a5fa var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-cyan-500{--tw-gradient-to: #06b6d4 var(--tw-gradient-to-position)}.to-cyan-500\/20{--tw-gradient-to: rgb(6 182 212 / .2) var(--tw-gradient-to-position)}.to-emerald-500{--tw-gradient-to: #10b981 var(--tw-gradient-to-position)}.to-emerald-500\/20{--tw-gradient-to: rgb(16 185 129 / .2) var(--tw-gradient-to-position)}.to-fuchsia-500\/20{--tw-gradient-to: rgb(217 70 239 / .2) var(--tw-gradient-to-position)}.to-green-500{--tw-gradient-to: #22c55e var(--tw-gradient-to-position)}.to-orange-500{--tw-gradient-to: #f97316 var(--tw-gradient-to-position)}.to-pink-500{--tw-gradient-to: #ec4899 var(--tw-gradient-to-position)}.to-pink-600{--tw-gradient-to: #db2777 var(--tw-gradient-to-position)}.to-primary-hover{--tw-gradient-to: var(--accent-strong) var(--tw-gradient-to-position)}.to-primary\/10{--tw-gradient-to: hsl(var(--primary) / .1) var(--tw-gradient-to-position)}.to-primary\/5{--tw-gradient-to: hsl(var(--primary) / .05) var(--tw-gradient-to-position)}.to-purple-500\/10{--tw-gradient-to: rgb(168 85 247 / .1) var(--tw-gradient-to-position)}.to-red-400{--tw-gradient-to: #f87171 var(--tw-gradient-to-position)}.to-rose-400{--tw-gradient-to: #fb7185 var(--tw-gradient-to-position)}.to-rose-500\/20{--tw-gradient-to: rgb(244 63 94 / .2) var(--tw-gradient-to-position)}.to-teal-500{--tw-gradient-to: #14b8a6 var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.to-violet-500\/20{--tw-gradient-to: rgb(139 92 246 / .2) var(--tw-gradient-to-position)}.to-zinc-400{--tw-gradient-to: #a1a1aa var(--tw-gradient-to-position)}.bg-cover{background-size:cover}.bg-center{background-position:center}.fill-amber-400{fill:#fbbf24}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.fill-white{fill:#fff}.fill-yellow-500{fill:#eab308}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-0\.5{padding-left:.125rem;padding-right:.125rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.py-\[5px\]{padding-top:5px;padding-bottom:5px}.pb-1{padding-bottom:.25rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pb-3\.5{padding-bottom:.875rem}.pb-4{padding-bottom:1rem}.pl-1{padding-left:.25rem}.pl-11{padding-left:2.75rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pl-8{padding-left:2rem}.pl-9{padding-left:2.25rem}.pr-1{padding-right:.25rem}.pr-1\.5{padding-right:.375rem}.pr-10{padding-right:2.5rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-1{padding-top:.25rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:Geist Mono,monospace}.font-sans{font-family:Geist,-apple-system,BlinkMacSystemFont,system-ui,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-\[10\.5px\]{font-size:10.5px}.text-\[10px\]{font-size:10px}.text-\[11\.5px\]{font-size:11.5px}.text-\[11px\]{font-size:11px}.text-\[12\.5px\]{font-size:12.5px}.text-\[12px\]{font-size:12px}.text-\[13px\]{font-size:13px}.text-\[15px\]{font-size:15px}.text-\[180px\]{font-size:180px}.text-\[8\.5px\]{font-size:8.5px}.text-\[8px\]{font-size:8px}.text-\[9\.5px\]{font-size:9.5px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-snug{line-height:1.375}.leading-tight{line-height:1.25}.tracking-\[0\.12em\]{letter-spacing:.12em}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent{color:var(--accent)}.text-accent-fg{color:var(--accent-fg)}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-black\/60{color:#0009}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-clip-audio{color:var(--c-audio)}.text-clip-music{color:var(--c-music)}.text-clip-text{color:var(--c-text)}.text-clip-video{color:var(--c-video)}.text-current{color:currentColor}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-fg{color:var(--fg)}.text-fg-2{color:var(--fg-2)}.text-fg-3{color:var(--fg-3)}.text-fg-muted{color:var(--fg-muted)}.text-foreground{color:hsl(var(--foreground))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-300\/70{color:#86efacb3}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-indigo-400{--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-pink-400{--tw-text-opacity: 1;color:rgb(244 114 182 / var(--tw-text-opacity, 1))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary\/50{color:hsl(var(--primary) / .5)}.text-primary\/70{color:hsl(var(--primary) / .7)}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-400\/50{color:#c084fc80}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-300\/80{color:#fca5a5cc}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-400\/60{color:#f8717199}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-status-error{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-status-info{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-status-info\/50{color:#3b82f680}.text-status-warning{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-text-muted{color:var(--fg-3)}.text-text-primary{color:var(--fg)}.text-text-secondary{color:var(--fg-2)}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/60{color:#fff9}.text-white\/85{color:#ffffffd9}.text-white\/90{color:#ffffffe6}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-500\/50{color:#eab30880}.text-yellow-500\/70{color:#eab308b3}.text-zinc-100{--tw-text-opacity: 1;color:rgb(244 244 245 / var(--tw-text-opacity, 1))}.text-zinc-400{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity, 1))}.text-zinc-500{--tw-text-opacity: 1;color:rgb(113 113 122 / var(--tw-text-opacity, 1))}.text-zinc-600{--tw-text-opacity: 1;color:rgb(82 82 91 / var(--tw-text-opacity, 1))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.accent-\[var\(--color-primary\,\#22c55e\)\]{accent-color:var(--color-primary,#22c55e)}.accent-primary{accent-color:hsl(var(--primary))}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_10px_rgba\(168\,85\,247\,0\.3\)\]{--tw-shadow: 0 0 10px rgba(168,85,247,.3);--tw-shadow-colored: 0 0 10px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_10px_rgba\(234\,179\,8\,0\.3\)\]{--tw-shadow: 0 0 10px rgba(234,179,8,.3);--tw-shadow-colored: 0 0 10px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_10px_rgba\(239\,68\,68\,0\.3\)\]{--tw-shadow: 0 0 10px rgba(239,68,68,.3);--tw-shadow-colored: 0 0 10px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_10px_rgba\(34\,197\,94\,0\.2\)\]{--tw-shadow: 0 0 10px rgba(34,197,94,.2);--tw-shadow-colored: 0 0 10px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_18px_rgba\(251\,191\,36\,0\.55\)\]{--tw-shadow: 0 0 18px rgba(251,191,36,.55);--tw-shadow-colored: 0 0 18px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_50px_rgba\(0\,0\,0\,0\.5\)\]{--tw-shadow: 0 0 50px rgba(0,0,0,.5);--tw-shadow-colored: 0 0 50px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_8px_\#22c55e\]{--tw-shadow: 0 0 8px #22c55e;--tw-shadow-colored: 0 0 8px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_10px_40px_rgba\(0\,0\,0\,0\.1\)\]{--tw-shadow: 0 10px 40px rgba(0,0,0,.1);--tw-shadow-colored: 0 10px 40px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-glow{--tw-shadow: 0 2px 8px var(--accent-glow);--tw-shadow-colored: 0 2px 8px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-glow-lg{--tw-shadow: 0 4px 14px var(--accent-glow);--tw-shadow-colored: 0 4px 14px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: var(--shadow-lg);--tw-shadow-colored: var(--shadow-lg);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: var(--shadow-md);--tw-shadow-colored: var(--shadow-md);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: var(--shadow-sm);--tw-shadow-colored: var(--shadow-sm);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-primary\/20{--tw-shadow-color: hsl(var(--primary) / .2);--tw-shadow: var(--tw-shadow-colored)}.shadow-primary\/5{--tw-shadow-color: hsl(var(--primary) / .05);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-inset{--tw-ring-inset: inset}.ring-accent{--tw-ring-color: var(--accent)}.ring-amber-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(251 191 36 / var(--tw-ring-opacity, 1))}.ring-blue-500\/30{--tw-ring-color: rgb(59 130 246 / .3)}.ring-border{--tw-ring-color: var(--border)}.ring-cyan-500\/30{--tw-ring-color: rgb(6 182 212 / .3)}.ring-green-500\/30{--tw-ring-color: rgb(34 197 94 / .3)}.ring-orange-500\/30{--tw-ring-color: rgb(249 115 22 / .3)}.ring-pink-500\/30{--tw-ring-color: rgb(236 72 153 / .3)}.ring-primary{--tw-ring-color: hsl(var(--primary))}.ring-primary\/20{--tw-ring-color: hsl(var(--primary) / .2)}.ring-primary\/50{--tw-ring-color: hsl(var(--primary) / .5)}.ring-purple-500\/30{--tw-ring-color: rgb(168 85 247 / .3)}.ring-purple-500\/50{--tw-ring-color: rgb(168 85 247 / .5)}.ring-red-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.ring-red-500\/50{--tw-ring-color: rgb(239 68 68 / .5)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.ring-yellow-500\/50{--tw-ring-color: rgb(234 179 8 / .5)}.ring-offset-1{--tw-ring-offset-width: 1px}.ring-offset-2{--tw-ring-offset-width: 2px}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.ring-offset-background-secondary{--tw-ring-offset-color: var(--bg-1)}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-xl{--tw-blur: blur(24px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow-md{--tw-drop-shadow: drop-shadow(0 4px 3px rgb(0 0 0 / .07)) drop-shadow(0 2px 2px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.sepia{--tw-sepia: sepia(100%);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-\[1px\]{--tw-backdrop-blur: blur(1px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.\!transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter!important;transition-timing-function:cubic-bezier(.4,0,.2,1)!important;transition-duration:.15s!important}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-100{transition-duration:.1s}.duration-150{transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-75{transition-duration:75ms}.ease-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in,.fade-in-0{--tw-enter-opacity: 0}.fade-out{--tw-exit-opacity: 0}.zoom-in{--tw-enter-scale: 0}.zoom-in-95{--tw-enter-scale: .95}.zoom-out{--tw-exit-scale: 0}.slide-in-from-left-1{--tw-enter-translate-x: -.25rem}.slide-in-from-right{--tw-enter-translate-x: 100%}.slide-in-from-top-2{--tw-enter-translate-y: -.5rem}.duration-100{animation-duration:.1s}.duration-150{animation-duration:.15s}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.duration-75{animation-duration:75ms}.ease-in{animation-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-out{animation-timing-function:cubic-bezier(0,0,.2,1)}.running{animation-play-state:running}.paused{animation-play-state:paused}.\[direction\:rtl\]{direction:rtl}.\[pause\:200ms\]{pause:.2s}.\[writing-mode\:vertical-lr\]{writing-mode:vertical-lr}.scrollbar-none{scrollbar-width:none;-ms-overflow-style:none}.scrollbar-none::-webkit-scrollbar{display:none}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border-strong);border-radius:99px;border:3px solid transparent;background-clip:padding-box}::-webkit-scrollbar-thumb:hover{background:var(--fg-muted);background-clip:padding-box;border:3px solid transparent}[data-tip]{position:relative}[data-tip]:hover:after{content:attr(data-tip);position:absolute;bottom:calc(100% + 6px);left:50%;transform:translate(-50%);background:var(--fg);color:var(--bg-1);padding:3px 7px;border-radius:4px;font-size:10.5px;white-space:nowrap;z-index:100;pointer-events:none;font-weight:500}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.file\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-text-muted::-moz-placeholder{color:var(--fg-3)}.placeholder\:text-text-muted::placeholder{color:var(--fg-3)}.last\:border-b-0:last-child{border-bottom-width:0px}.hover\:h-2\.5:hover{height:.625rem}.hover\:-translate-y-0\.5:hover{--tw-translate-y: -.125rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-110:hover{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-\[1\.02\]:hover{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-accent:hover{border-color:var(--accent)}.hover\:border-amber-500\/60:hover{border-color:#f59e0b99}.hover\:border-border:hover{border-color:var(--border)}.hover\:border-border-hover:hover,.hover\:border-border-strong:hover{border-color:var(--border-strong)}.hover\:border-primary:hover{border-color:hsl(var(--primary))}.hover\:border-primary\/30:hover{border-color:hsl(var(--primary) / .3)}.hover\:border-primary\/40:hover{border-color:hsl(var(--primary) / .4)}.hover\:border-primary\/50:hover{border-color:hsl(var(--primary) / .5)}.hover\:border-primary\/60:hover{border-color:hsl(var(--primary) / .6)}.hover\:border-red-500\/30:hover{border-color:#ef44444d}.hover\:border-red-500\/50:hover{border-color:#ef444480}.hover\:border-text-muted:hover{border-color:var(--fg-3)}.hover\:border-text-secondary:hover{border-color:var(--fg-2)}.hover\:border-white:hover{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.hover\:border-yellow-500\/50:hover{border-color:#eab30880}.hover\:border-opacity-60:hover{--tw-border-opacity: .6}.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-accent-strong:hover{background-color:var(--accent-strong)}.hover\:bg-amber-400\/50:hover{background-color:#fbbf2480}.hover\:bg-amber-500\/25:hover{background-color:#f59e0b40}.hover\:bg-amber-600:hover{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.hover\:bg-background-elevated:hover{background-color:var(--bg-elev)}.hover\:bg-background-secondary:hover{background-color:var(--bg-1)}.hover\:bg-background-tertiary:hover{background-color:var(--bg-2)}.hover\:bg-black\/5:hover{background-color:#0000000d}.hover\:bg-blue-400\/50:hover{background-color:#60a5fa80}.hover\:bg-cyan-500:hover{--tw-bg-opacity: 1;background-color:rgb(6 182 212 / var(--tw-bg-opacity, 1))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-green-400\/50:hover{background-color:#4ade8080}.hover\:bg-green-500:hover{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.hover\:bg-green-500\/30:hover{background-color:#22c55e4d}.hover\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-hover:hover{background-color:var(--hover)}.hover\:bg-indigo-500\/10:hover{background-color:#6366f11a}.hover\:bg-indigo-500\/30:hover{background-color:#6366f14d}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary-hover:hover{background-color:var(--accent-strong)}.hover\:bg-primary\/10:hover{background-color:hsl(var(--primary) / .1)}.hover\:bg-primary\/20:hover{background-color:hsl(var(--primary) / .2)}.hover\:bg-primary\/30:hover{background-color:hsl(var(--primary) / .3)}.hover\:bg-primary\/40:hover{background-color:hsl(var(--primary) / .4)}.hover\:bg-primary\/5:hover{background-color:hsl(var(--primary) / .05)}.hover\:bg-primary\/50:hover{background-color:hsl(var(--primary) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/85:hover{background-color:hsl(var(--primary) / .85)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-purple-400\/50:hover{background-color:#c084fc80}.hover\:bg-purple-500\/40:hover{background-color:#a855f766}.hover\:bg-purple-500\/50:hover{background-color:#a855f780}.hover\:bg-red-400\/10:hover{background-color:#f871711a}.hover\:bg-red-500\/10:hover{background-color:#ef44441a}.hover\:bg-red-500\/20:hover{background-color:#ef444433}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-red-500\/40:hover{background-color:#ef444466}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-text-muted:hover{background-color:var(--fg-3)}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:bg-white\/20:hover{background-color:#fff3}.hover\:bg-yellow-500\/15:hover{background-color:#eab30826}.hover\:bg-yellow-500\/30:hover{background-color:#eab3084d}.hover\:bg-yellow-500\/40:hover{background-color:#eab30866}.hover\:from-purple-500:hover{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-pink-500:hover{--tw-gradient-to: #ec4899 var(--tw-gradient-to-position)}.hover\:text-accent:hover{color:var(--accent)}.hover\:text-accent-foreground:hover{color:var(--accent-fg)}.hover\:text-amber-400:hover{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.hover\:text-fg:hover{color:var(--fg)}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-indigo-400:hover{--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary:hover{color:hsl(var(--primary))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover,.hover\:text-status-error:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-text-primary:hover{color:var(--fg)}.hover\:text-text-secondary:hover{color:var(--fg-2)}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:text-zinc-300:hover{--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity, 1))}.hover\:text-zinc-600:hover{--tw-text-opacity: 1;color:rgb(82 82 91 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-90:hover{opacity:.9}.hover\:shadow-glow-lg:hover{--tw-shadow: 0 4px 14px var(--accent-glow);--tw-shadow-colored: 0 4px 14px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: var(--shadow-lg);--tw-shadow-colored: var(--shadow-lg);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:ring-2:hover{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.hover\:ring-primary\/50:hover{--tw-ring-color: hsl(var(--primary) / .5)}.hover\:brightness-110:hover{--tw-brightness: brightness(1.1);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.focus\:border-amber-500\/50:focus{border-color:#f59e0b80}.focus\:border-primary:focus{border-color:hsl(var(--primary))}.focus\:border-primary\/50:focus{border-color:hsl(var(--primary) / .5)}.focus\:bg-accent:focus{background-color:var(--accent)}.focus\:bg-bg-2:focus{background-color:var(--bg-2)}.focus\:bg-hover:focus{background-color:var(--hover)}.focus\:text-accent-foreground:focus{color:var(--accent-fg)}.focus\:text-red-400:focus{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary\/50:focus{--tw-ring-color: hsl(var(--primary) / .5)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-0:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.active\:scale-\[0\.98\]:active{--tw-scale-x: .98;--tw-scale-y: .98;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:cursor-grabbing:active{cursor:grabbing}.active\:bg-primary-active:active{background-color:var(--accent-strong)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:cursor-wait:disabled{cursor:wait}.disabled\:bg-primary\/50:disabled{background-color:hsl(var(--primary) / .5)}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:hover .group-hover\:translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:border-primary\/30{border-color:hsl(var(--primary) / .3)}.group:hover .group-hover\:bg-background-tertiary{background-color:var(--bg-2)}.group:hover .group-hover\:bg-black\/30{background-color:#0000004d}.group:hover .group-hover\:bg-primary\/10{background-color:hsl(var(--primary) / .1)}.group:hover .group-hover\:bg-primary\/20{background-color:hsl(var(--primary) / .2)}.group:hover .group-hover\:text-fg{color:var(--fg)}.group:hover .group-hover\:text-primary{color:hsl(var(--primary))}.group:hover .group-hover\:text-primary\/50{color:hsl(var(--primary) / .5)}.group:hover .group-hover\:text-text-primary{color:var(--fg)}.group:hover .group-hover\:text-text-secondary{color:var(--fg-2)}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:opacity-60{opacity:.6}.group:hover .group-hover\:opacity-80{opacity:.8}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=open\]\:rotate-90[data-state=open]{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:border-primary[data-state=active]{border-color:hsl(var(--primary))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--accent)}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:hsl(var(--muted-foreground))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=active\]\:text-primary[data-state=active]{color:hsl(var(--primary))}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--accent-fg)}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.dark\:border-destructive:is([data-theme=dark] *){border-color:hsl(var(--destructive))}.dark\:bg-white\/5:is([data-theme=dark] *){background-color:#ffffff0d}@media (min-width: 640px){.sm\:inline{display:inline}.sm\:max-w-2xl{max-width:42rem}.sm\:max-w-md{max-width:28rem}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.sm\:text-5xl{font-size:3rem;line-height:1}}@media (min-width: 768px){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:text-sm{font-size:.875rem;line-height:1.25rem}}@media (min-width: 1024px){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:\:-moz-range-thumb\]\:h-3::-moz-range-thumb{height:.75rem}.\[\&\:\:-moz-range-thumb\]\:h-6::-moz-range-thumb{height:1.5rem}.\[\&\:\:-moz-range-thumb\]\:w-3::-moz-range-thumb{width:.75rem}.\[\&\:\:-moz-range-thumb\]\:w-4::-moz-range-thumb{width:1rem}.\[\&\:\:-moz-range-thumb\]\:cursor-pointer::-moz-range-thumb{cursor:pointer}.\[\&\:\:-moz-range-thumb\]\:rounded::-moz-range-thumb{border-radius:.25rem}.\[\&\:\:-moz-range-thumb\]\:rounded-full::-moz-range-thumb{border-radius:9999px}.\[\&\:\:-moz-range-thumb\]\:border-0::-moz-range-thumb{border-width:0px}.\[\&\:\:-moz-range-thumb\]\:bg-blue-500::-moz-range-thumb{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.\[\&\:\:-moz-range-thumb\]\:bg-gray-300::-moz-range-thumb{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.\[\&\:\:-moz-range-thumb\]\:bg-orange-500::-moz-range-thumb{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.\[\&\:\:-webkit-slider-thumb\]\:h-3::-webkit-slider-thumb{height:.75rem}.\[\&\:\:-webkit-slider-thumb\]\:h-6::-webkit-slider-thumb{height:1.5rem}.\[\&\:\:-webkit-slider-thumb\]\:w-3::-webkit-slider-thumb{width:.75rem}.\[\&\:\:-webkit-slider-thumb\]\:w-4::-webkit-slider-thumb{width:1rem}.\[\&\:\:-webkit-slider-thumb\]\:cursor-pointer::-webkit-slider-thumb{cursor:pointer}.\[\&\:\:-webkit-slider-thumb\]\:appearance-none::-webkit-slider-thumb{-webkit-appearance:none;appearance:none}.\[\&\:\:-webkit-slider-thumb\]\:rounded::-webkit-slider-thumb{border-radius:.25rem}.\[\&\:\:-webkit-slider-thumb\]\:rounded-full::-webkit-slider-thumb{border-radius:9999px}.\[\&\:\:-webkit-slider-thumb\]\:bg-blue-500::-webkit-slider-thumb{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.\[\&\:\:-webkit-slider-thumb\]\:bg-gray-300::-webkit-slider-thumb{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.\[\&\:\:-webkit-slider-thumb\]\:bg-orange-500::-webkit-slider-thumb{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.\[\&\:\:-webkit-slider-thumb\]\:shadow-md::-webkit-slider-thumb{--tw-shadow: var(--shadow-md);--tw-shadow-colored: var(--shadow-md);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.\[\&\>div\]\:\!block>div{display:block!important}.\[\&\>div\]\:\!min-w-0>div{min-width:0px!important}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>span\]\:truncate>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:text-destructive>svg{color:hsl(var(--destructive))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:size-3\.5 svg{width:.875rem;height:.875rem}.\[\&_svg\]\:size-4 svg{width:1rem;height:1rem}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0} diff --git a/resources/video-editor/assets/radix-DNxS_rDm.js b/resources/video-editor/assets/radix-DNxS_rDm.js new file mode 100644 index 00000000..95c727f0 --- /dev/null +++ b/resources/video-editor/assets/radix-DNxS_rDm.js @@ -0,0 +1,10 @@ +import{r as a,j as p,R as Wn,a as Ft,b as dc,c as Bt,d as Y}from"./react-kyfdMflE.js";function Ao(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function lt(...e){return t=>{let n=!1;const o=e.map(r=>{const s=Ao(r,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let r=0;r{const{children:s,...i}=o,c=a.Children.toArray(s),l=c.find(mc);if(l){const f=l.props.children,u=c.map(d=>d===l?a.Children.count(f)>1?a.Children.only(null):a.isValidElement(f)?f.props.children:null:d);return p.jsx(t,{...i,ref:r,children:a.isValidElement(f)?a.cloneElement(f,void 0,u):null})}return p.jsx(t,{...i,ref:r,children:s})});return n.displayName=`${e}.Slot`,n}var Xp=_e("Slot");function fc(e){const t=a.forwardRef((n,o)=>{const{children:r,...s}=n;if(a.isValidElement(r)){const i=vc(r),c=hc(s,r.props);return r.type!==a.Fragment&&(c.ref=o?lt(o,i):i),a.cloneElement(r,c)}return a.Children.count(r)>1?a.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var er=Symbol("radix.slottable");function pc(e){const t=({children:n})=>p.jsx(p.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=er,t}function mc(e){return a.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===er}function hc(e,t){const n={...t};for(const o in t){const r=e[o],s=t[o];/^on[A-Z]/.test(o)?r&&s?n[o]=(...c)=>{const l=s(...c);return r(...c),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...s}:o==="className"&&(n[o]=[r,s].filter(Boolean).join(" "))}return{...e,...n}}function vc(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function gc(e,t){const n=a.createContext(t),o=s=>{const{children:i,...c}=s,l=a.useMemo(()=>c,Object.values(c));return p.jsx(n.Provider,{value:l,children:i})};o.displayName=e+"Provider";function r(s){const i=a.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[o,r]}function Z(e,t=[]){let n=[];function o(s,i){const c=a.createContext(i),l=n.length;n=[...n,i];const f=d=>{const{scope:m,children:h,...g}=d,v=m?.[e]?.[l]||c,x=a.useMemo(()=>g,Object.values(g));return p.jsx(v.Provider,{value:x,children:h})};f.displayName=s+"Provider";function u(d,m){const h=m?.[e]?.[l]||c,g=a.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${s}\``)}return[f,u]}const r=()=>{const s=n.map(i=>a.createContext(i));return function(c){const l=c?.[e]||s;return a.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return r.scopeName=e,[o,xc(r,...t)]}function xc(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(s){const i=o.reduce((c,{useScope:l,scopeName:f})=>{const d=l(s)[`__scope${f}`];return{...c,...d}},{});return a.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function S(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}var X=globalThis?.document?a.useLayoutEffect:()=>{},wc=Wn[" useInsertionEffect ".trim().toString()]||X;function J({prop:e,defaultProp:t,onChange:n=()=>{},caller:o}){const[r,s,i]=Cc({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:r;{const u=a.useRef(e!==void 0);a.useEffect(()=>{const d=u.current;d!==c&&console.warn(`${o} is changing from ${d?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=c},[c,o])}const f=a.useCallback(u=>{if(c){const d=bc(u)?u(e):u;d!==e&&i.current?.(d)}else s(u)},[c,e,s,i]);return[l,f]}function Cc({defaultProp:e,onChange:t}){const[n,o]=a.useState(e),r=a.useRef(n),s=a.useRef(t);return wc(()=>{s.current=t},[t]),a.useEffect(()=>{r.current!==n&&(s.current?.(n),r.current=n)},[n,r]),[n,o,s]}function bc(e){return typeof e=="function"}function Vt(e){const t=a.useRef({value:e,previous:e});return a.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Ht(e){const[t,n]=a.useState(void 0);return X(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const o=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let i,c;if("borderBoxSize"in s){const l=s.borderBoxSize,f=Array.isArray(l)?l[0]:l;i=f.inlineSize,c=f.blockSize}else i=e.offsetWidth,c=e.offsetHeight;n({width:i,height:c})});return o.observe(e,{box:"border-box"}),()=>o.unobserve(e)}else n(void 0)},[e]),t}function yc(e,t){return a.useReducer((n,o)=>t[n][o]??n,e)}var q=e=>{const{present:t,children:n}=e,o=Sc(t),r=typeof n=="function"?n({present:o.isPresent}):a.Children.only(n),s=L(o.ref,Pc(r));return typeof n=="function"||o.isPresent?a.cloneElement(r,{ref:s}):null};q.displayName="Presence";function Sc(e){const[t,n]=a.useState(),o=a.useRef(null),r=a.useRef(e),s=a.useRef("none"),i=e?"mounted":"unmounted",[c,l]=yc(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return a.useEffect(()=>{const f=Ct(o.current);s.current=c==="mounted"?f:"none"},[c]),X(()=>{const f=o.current,u=r.current;if(u!==e){const m=s.current,h=Ct(f);e?l("MOUNT"):h==="none"||f?.display==="none"?l("UNMOUNT"):l(u&&m!==h?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,l]),X(()=>{if(t){let f;const u=t.ownerDocument.defaultView??window,d=h=>{const v=Ct(o.current).includes(CSS.escape(h.animationName));if(h.target===t&&v&&(l("ANIMATION_END"),!r.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",f=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},m=h=>{h.target===t&&(s.current=Ct(o.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{u.clearTimeout(f),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:a.useCallback(f=>{o.current=f?getComputedStyle(f):null,n(f)},[])}}function Ct(e){return e?.animationName||"none"}function Pc(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Rc=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_=Rc.reduce((e,t)=>{const n=_e(`Primitive.${t}`),o=a.forwardRef((r,s)=>{const{asChild:i,...c}=r,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,{...c,ref:s})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function tr(e,t){e&&Ft.flushSync(()=>e.dispatchEvent(t))}var Wt="Checkbox",[Ec]=Z(Wt),[_c,Gn]=Ec(Wt);function Tc(e){const{__scopeCheckbox:t,checked:n,children:o,defaultChecked:r,disabled:s,form:i,name:c,onCheckedChange:l,required:f,value:u="on",internal_do_not_use_render:d}=e,[m,h]=J({prop:n,defaultProp:r??!1,onChange:l,caller:Wt}),[g,v]=a.useState(null),[x,w]=a.useState(null),C=a.useRef(!1),b=g?!!i||!!g.closest("form"):!0,y={checked:m,disabled:s,setChecked:h,control:g,setControl:v,name:c,form:i,value:u,hasConsumerStoppedPropagationRef:C,required:f,defaultChecked:Ee(r)?!1:r,isFormControl:b,bubbleInput:x,setBubbleInput:w};return p.jsx(_c,{scope:t,...y,children:Ic(d)?d(y):o})}var nr="CheckboxTrigger",or=a.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:n,...o},r)=>{const{control:s,value:i,disabled:c,checked:l,required:f,setControl:u,setChecked:d,hasConsumerStoppedPropagationRef:m,isFormControl:h,bubbleInput:g}=Gn(nr,e),v=L(r,u),x=a.useRef(l);return a.useEffect(()=>{const w=s?.form;if(w){const C=()=>d(x.current);return w.addEventListener("reset",C),()=>w.removeEventListener("reset",C)}},[s,d]),p.jsx(_.button,{type:"button",role:"checkbox","aria-checked":Ee(l)?"mixed":l,"aria-required":f,"data-state":ar(l),"data-disabled":c?"":void 0,disabled:c,value:i,...o,ref:v,onKeyDown:S(t,w=>{w.key==="Enter"&&w.preventDefault()}),onClick:S(n,w=>{d(C=>Ee(C)?!0:!C),g&&h&&(m.current=w.isPropagationStopped(),m.current||w.stopPropagation())})})});or.displayName=nr;var Mc=a.forwardRef((e,t)=>{const{__scopeCheckbox:n,name:o,checked:r,defaultChecked:s,required:i,disabled:c,value:l,onCheckedChange:f,form:u,...d}=e;return p.jsx(Tc,{__scopeCheckbox:n,checked:r,defaultChecked:s,disabled:c,required:i,onCheckedChange:f,name:o,form:u,value:l,internal_do_not_use_render:({isFormControl:m})=>p.jsxs(p.Fragment,{children:[p.jsx(or,{...d,ref:t,__scopeCheckbox:n}),m&&p.jsx(ir,{__scopeCheckbox:n})]})})});Mc.displayName=Wt;var rr="CheckboxIndicator",Ac=a.forwardRef((e,t)=>{const{__scopeCheckbox:n,forceMount:o,...r}=e,s=Gn(rr,n);return p.jsx(q,{present:o||Ee(s.checked)||s.checked===!0,children:p.jsx(_.span,{"data-state":ar(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t,style:{pointerEvents:"none",...e.style}})})});Ac.displayName=rr;var sr="CheckboxBubbleInput",ir=a.forwardRef(({__scopeCheckbox:e,...t},n)=>{const{control:o,hasConsumerStoppedPropagationRef:r,checked:s,defaultChecked:i,required:c,disabled:l,name:f,value:u,form:d,bubbleInput:m,setBubbleInput:h}=Gn(sr,e),g=L(n,h),v=Vt(s),x=Ht(o);a.useEffect(()=>{const C=m;if(!C)return;const b=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(b,"checked").set,A=!r.current;if(v!==s&&P){const R=new Event("click",{bubbles:A});C.indeterminate=Ee(s),P.call(C,Ee(s)?!1:s),C.dispatchEvent(R)}},[m,v,s,r]);const w=a.useRef(Ee(s)?!1:s);return p.jsx(_.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??w.current,required:c,disabled:l,name:f,value:u,form:d,...t,tabIndex:-1,ref:g,style:{...t.style,...x,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});ir.displayName=sr;function Ic(e){return typeof e=="function"}function Ee(e){return e==="indeterminate"}function ar(e){return Ee(e)?"indeterminate":e?"checked":"unchecked"}function z(e){const t=a.useRef(e);return a.useEffect(()=>{t.current=e}),a.useMemo(()=>(...n)=>t.current?.(...n),[])}function Nc(e,t=globalThis?.document){const n=z(e);a.useEffect(()=>{const o=r=>{r.key==="Escape"&&n(r)};return t.addEventListener("keydown",o,{capture:!0}),()=>t.removeEventListener("keydown",o,{capture:!0})},[n,t])}var Oc="DismissableLayer",_n="dismissableLayer.update",Dc="dismissableLayer.pointerDownOutside",jc="dismissableLayer.focusOutside",Io,cr=a.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Xe=a.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:o,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:i,onDismiss:c,...l}=e,f=a.useContext(cr),[u,d]=a.useState(null),m=u?.ownerDocument??globalThis?.document,[,h]=a.useState({}),g=L(t,R=>d(R)),v=Array.from(f.layers),[x]=[...f.layersWithOutsidePointerEventsDisabled].slice(-1),w=v.indexOf(x),C=u?v.indexOf(u):-1,b=f.layersWithOutsidePointerEventsDisabled.size>0,y=C>=w,P=$c(R=>{const I=R.target,O=[...f.branches].some(N=>N.contains(I));!y||O||(r?.(R),i?.(R),R.defaultPrevented||c?.())},m),A=Fc(R=>{const I=R.target;[...f.branches].some(N=>N.contains(I))||(s?.(R),i?.(R),R.defaultPrevented||c?.())},m);return Nc(R=>{C===f.layers.size-1&&(o?.(R),!R.defaultPrevented&&c&&(R.preventDefault(),c()))},m),a.useEffect(()=>{if(u)return n&&(f.layersWithOutsidePointerEventsDisabled.size===0&&(Io=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),f.layersWithOutsidePointerEventsDisabled.add(u)),f.layers.add(u),No(),()=>{n&&f.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Io)}},[u,m,n,f]),a.useEffect(()=>()=>{u&&(f.layers.delete(u),f.layersWithOutsidePointerEventsDisabled.delete(u),No())},[u,f]),a.useEffect(()=>{const R=()=>h({});return document.addEventListener(_n,R),()=>document.removeEventListener(_n,R)},[]),p.jsx(_.div,{...l,ref:g,style:{pointerEvents:b?y?"auto":"none":void 0,...e.style},onFocusCapture:S(e.onFocusCapture,A.onFocusCapture),onBlurCapture:S(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:S(e.onPointerDownCapture,P.onPointerDownCapture)})});Xe.displayName=Oc;var Lc="DismissableLayerBranch",kc=a.forwardRef((e,t)=>{const n=a.useContext(cr),o=a.useRef(null),r=L(t,o);return a.useEffect(()=>{const s=o.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),p.jsx(_.div,{...e,ref:r})});kc.displayName=Lc;function $c(e,t=globalThis?.document){const n=z(e),o=a.useRef(!1),r=a.useRef(()=>{});return a.useEffect(()=>{const s=c=>{if(c.target&&!o.current){let l=function(){lr(Dc,n,f,{discrete:!0})};const f={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=l,t.addEventListener("click",r.current,{once:!0})):l()}else t.removeEventListener("click",r.current);o.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>o.current=!0}}function Fc(e,t=globalThis?.document){const n=z(e),o=a.useRef(!1);return a.useEffect(()=>{const r=s=>{s.target&&!o.current&&lr(jc,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",r),()=>t.removeEventListener("focusin",r)},[t,n]),{onFocusCapture:()=>o.current=!0,onBlurCapture:()=>o.current=!1}}function No(){const e=new CustomEvent(_n);document.dispatchEvent(e)}function lr(e,t,n,{discrete:o}){const r=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),o?tr(r,s):r.dispatchEvent(s)}var Cn=0;function Gt(){a.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Oo()),document.body.insertAdjacentElement("beforeend",e[1]??Oo()),Cn++,()=>{Cn===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Cn--}},[])}function Oo(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var bn="focusScope.autoFocusOnMount",yn="focusScope.autoFocusOnUnmount",Do={bubbles:!1,cancelable:!0},Bc="FocusScope",ut=a.forwardRef((e,t)=>{const{loop:n=!1,trapped:o=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...i}=e,[c,l]=a.useState(null),f=z(r),u=z(s),d=a.useRef(null),m=L(t,v=>l(v)),h=a.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;a.useEffect(()=>{if(o){let v=function(b){if(h.paused||!c)return;const y=b.target;c.contains(y)?d.current=y:Re(d.current,{select:!0})},x=function(b){if(h.paused||!c)return;const y=b.relatedTarget;y!==null&&(c.contains(y)||Re(d.current,{select:!0}))},w=function(b){if(document.activeElement===document.body)for(const P of b)P.removedNodes.length>0&&Re(c)};document.addEventListener("focusin",v),document.addEventListener("focusout",x);const C=new MutationObserver(w);return c&&C.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",x),C.disconnect()}}},[o,c,h.paused]),a.useEffect(()=>{if(c){Lo.add(h);const v=document.activeElement;if(!c.contains(v)){const w=new CustomEvent(bn,Do);c.addEventListener(bn,f),c.dispatchEvent(w),w.defaultPrevented||(Vc(Kc(ur(c)),{select:!0}),document.activeElement===v&&Re(c))}return()=>{c.removeEventListener(bn,f),setTimeout(()=>{const w=new CustomEvent(yn,Do);c.addEventListener(yn,u),c.dispatchEvent(w),w.defaultPrevented||Re(v??document.body,{select:!0}),c.removeEventListener(yn,u),Lo.remove(h)},0)}}},[c,f,u,h]);const g=a.useCallback(v=>{if(!n&&!o||h.paused)return;const x=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,w=document.activeElement;if(x&&w){const C=v.currentTarget,[b,y]=Hc(C);b&&y?!v.shiftKey&&w===y?(v.preventDefault(),n&&Re(b,{select:!0})):v.shiftKey&&w===b&&(v.preventDefault(),n&&Re(y,{select:!0})):w===C&&v.preventDefault()}},[n,o,h.paused]);return p.jsx(_.div,{tabIndex:-1,...i,ref:m,onKeyDown:g})});ut.displayName=Bc;function Vc(e,{select:t=!1}={}){const n=document.activeElement;for(const o of e)if(Re(o,{select:t}),document.activeElement!==n)return}function Hc(e){const t=ur(e),n=jo(t,e),o=jo(t.reverse(),e);return[n,o]}function ur(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const r=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||r?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function jo(e,t){for(const n of e)if(!Wc(n,{upTo:t}))return n}function Wc(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Gc(e){return e instanceof HTMLInputElement&&"select"in e}function Re(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Gc(e)&&t&&e.select()}}var Lo=Uc();function Uc(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ko(e,t),e.unshift(t)},remove(t){e=ko(e,t),e[0]?.resume()}}}function ko(e,t){const n=[...e],o=n.indexOf(t);return o!==-1&&n.splice(o,1),n}function Kc(e){return e.filter(t=>t.tagName!=="A")}var zc=Wn[" useId ".trim().toString()]||(()=>{}),Yc=0;function ne(e){const[t,n]=a.useState(zc());return X(()=>{n(o=>o??String(Yc++))},[e]),e||(t?`radix-${t}`:"")}const Xc=["top","right","bottom","left"],Te=Math.min,se=Math.max,Et=Math.round,bt=Math.floor,ge=e=>({x:e,y:e}),qc={left:"right",right:"left",bottom:"top",top:"bottom"},Zc={start:"end",end:"start"};function Tn(e,t,n){return se(e,Te(t,n))}function Se(e,t){return typeof e=="function"?e(t):e}function Pe(e){return e.split("-")[0]}function qe(e){return e.split("-")[1]}function Un(e){return e==="x"?"y":"x"}function Kn(e){return e==="y"?"height":"width"}const Jc=new Set(["top","bottom"]);function ve(e){return Jc.has(Pe(e))?"y":"x"}function zn(e){return Un(ve(e))}function Qc(e,t,n){n===void 0&&(n=!1);const o=qe(e),r=zn(e),s=Kn(r);let i=r==="x"?o===(n?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=_t(i)),[i,_t(i)]}function el(e){const t=_t(e);return[Mn(e),t,Mn(t)]}function Mn(e){return e.replace(/start|end/g,t=>Zc[t])}const $o=["left","right"],Fo=["right","left"],tl=["top","bottom"],nl=["bottom","top"];function ol(e,t,n){switch(e){case"top":case"bottom":return n?t?Fo:$o:t?$o:Fo;case"left":case"right":return t?tl:nl;default:return[]}}function rl(e,t,n,o){const r=qe(e);let s=ol(Pe(e),n==="start",o);return r&&(s=s.map(i=>i+"-"+r),t&&(s=s.concat(s.map(Mn)))),s}function _t(e){return e.replace(/left|right|bottom|top/g,t=>qc[t])}function sl(e){return{top:0,right:0,bottom:0,left:0,...e}}function dr(e){return typeof e!="number"?sl(e):{top:e,right:e,bottom:e,left:e}}function Tt(e){const{x:t,y:n,width:o,height:r}=e;return{width:o,height:r,top:n,left:t,right:t+o,bottom:n+r,x:t,y:n}}function Bo(e,t,n){let{reference:o,floating:r}=e;const s=ve(t),i=zn(t),c=Kn(i),l=Pe(t),f=s==="y",u=o.x+o.width/2-r.width/2,d=o.y+o.height/2-r.height/2,m=o[c]/2-r[c]/2;let h;switch(l){case"top":h={x:u,y:o.y-r.height};break;case"bottom":h={x:u,y:o.y+o.height};break;case"right":h={x:o.x+o.width,y:d};break;case"left":h={x:o.x-r.width,y:d};break;default:h={x:o.x,y:o.y}}switch(qe(t)){case"start":h[i]-=m*(n&&f?-1:1);break;case"end":h[i]+=m*(n&&f?-1:1);break}return h}const il=async(e,t,n)=>{const{placement:o="bottom",strategy:r="absolute",middleware:s=[],platform:i}=n,c=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let f=await i.getElementRects({reference:e,floating:t,strategy:r}),{x:u,y:d}=Bo(f,o,l),m=o,h={},g=0;for(let v=0;v({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:r,rects:s,platform:i,elements:c,middlewareData:l}=t,{element:f,padding:u=0}=Se(e,t)||{};if(f==null)return{};const d=dr(u),m={x:n,y:o},h=zn(r),g=Kn(h),v=await i.getDimensions(f),x=h==="y",w=x?"top":"left",C=x?"bottom":"right",b=x?"clientHeight":"clientWidth",y=s.reference[g]+s.reference[h]-m[h]-s.floating[g],P=m[h]-s.reference[h],A=await(i.getOffsetParent==null?void 0:i.getOffsetParent(f));let R=A?A[b]:0;(!R||!await(i.isElement==null?void 0:i.isElement(A)))&&(R=c.floating[b]||s.floating[g]);const I=y/2-P/2,O=R/2-v[g]/2-1,N=Te(d[w],O),D=Te(d[C],O),k=N,B=R-v[g]-D,$=R/2-v[g]/2+I,V=Tn(k,$,B),j=!l.arrow&&qe(r)!=null&&$!==V&&s.reference[g]/2-($$<=0)){var D,k;const $=(((D=s.flip)==null?void 0:D.index)||0)+1,V=R[$];if(V&&(!(d==="alignment"?C!==ve(V):!1)||N.every(M=>ve(M.placement)===C?M.overflows[0]>0:!0)))return{data:{index:$,overflows:N},reset:{placement:V}};let j=(k=N.filter(F=>F.overflows[0]<=0).sort((F,M)=>F.overflows[1]-M.overflows[1])[0])==null?void 0:k.placement;if(!j)switch(h){case"bestFit":{var B;const F=(B=N.filter(M=>{if(A){const E=ve(M.placement);return E===C||E==="y"}return!0}).map(M=>[M.placement,M.overflows.filter(E=>E>0).reduce((E,U)=>E+U,0)]).sort((M,E)=>M[1]-E[1])[0])==null?void 0:B[0];F&&(j=F);break}case"initialPlacement":j=c;break}if(r!==j)return{reset:{placement:j}}}return{}}}};function Vo(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Ho(e){return Xc.some(t=>e[t]>=0)}const ll=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:o="referenceHidden",...r}=Se(e,t);switch(o){case"referenceHidden":{const s=await ot(t,{...r,elementContext:"reference"}),i=Vo(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Ho(i)}}}case"escaped":{const s=await ot(t,{...r,altBoundary:!0}),i=Vo(s,n.floating);return{data:{escapedOffsets:i,escaped:Ho(i)}}}default:return{}}}}},fr=new Set(["left","top"]);async function ul(e,t){const{placement:n,platform:o,elements:r}=e,s=await(o.isRTL==null?void 0:o.isRTL(r.floating)),i=Pe(n),c=qe(n),l=ve(n)==="y",f=fr.has(i)?-1:1,u=s&&l?-1:1,d=Se(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return c&&typeof g=="number"&&(h=c==="end"?g*-1:g),l?{x:h*u,y:m*f}:{x:m*f,y:h*u}}const dl=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:r,y:s,placement:i,middlewareData:c}=t,l=await ul(t,e);return i===((n=c.offset)==null?void 0:n.placement)&&(o=c.arrow)!=null&&o.alignmentOffset?{}:{x:r+l.x,y:s+l.y,data:{...l,placement:i}}}}},fl=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:r}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:c={fn:x=>{let{x:w,y:C}=x;return{x:w,y:C}}},...l}=Se(e,t),f={x:n,y:o},u=await ot(t,l),d=ve(Pe(r)),m=Un(d);let h=f[m],g=f[d];if(s){const x=m==="y"?"top":"left",w=m==="y"?"bottom":"right",C=h+u[x],b=h-u[w];h=Tn(C,h,b)}if(i){const x=d==="y"?"top":"left",w=d==="y"?"bottom":"right",C=g+u[x],b=g-u[w];g=Tn(C,g,b)}const v=c.fn({...t,[m]:h,[d]:g});return{...v,data:{x:v.x-n,y:v.y-o,enabled:{[m]:s,[d]:i}}}}}},pl=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:o,placement:r,rects:s,middlewareData:i}=t,{offset:c=0,mainAxis:l=!0,crossAxis:f=!0}=Se(e,t),u={x:n,y:o},d=ve(r),m=Un(d);let h=u[m],g=u[d];const v=Se(c,t),x=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(l){const b=m==="y"?"height":"width",y=s.reference[m]-s.floating[b]+x.mainAxis,P=s.reference[m]+s.reference[b]-x.mainAxis;hP&&(h=P)}if(f){var w,C;const b=m==="y"?"width":"height",y=fr.has(Pe(r)),P=s.reference[d]-s.floating[b]+(y&&((w=i.offset)==null?void 0:w[d])||0)+(y?0:x.crossAxis),A=s.reference[d]+s.reference[b]+(y?0:((C=i.offset)==null?void 0:C[d])||0)-(y?x.crossAxis:0);gA&&(g=A)}return{[m]:h,[d]:g}}}},ml=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,o;const{placement:r,rects:s,platform:i,elements:c}=t,{apply:l=()=>{},...f}=Se(e,t),u=await ot(t,f),d=Pe(r),m=qe(r),h=ve(r)==="y",{width:g,height:v}=s.floating;let x,w;d==="top"||d==="bottom"?(x=d,w=m===(await(i.isRTL==null?void 0:i.isRTL(c.floating))?"start":"end")?"left":"right"):(w=d,x=m==="end"?"top":"bottom");const C=v-u.top-u.bottom,b=g-u.left-u.right,y=Te(v-u[x],C),P=Te(g-u[w],b),A=!t.middlewareData.shift;let R=y,I=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(I=b),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(R=C),A&&!m){const N=se(u.left,0),D=se(u.right,0),k=se(u.top,0),B=se(u.bottom,0);h?I=g-2*(N!==0||D!==0?N+D:se(u.left,u.right)):R=v-2*(k!==0||B!==0?k+B:se(u.top,u.bottom))}await l({...t,availableWidth:I,availableHeight:R});const O=await i.getDimensions(c.floating);return g!==O.width||v!==O.height?{reset:{rects:!0}}:{}}}};function Ut(){return typeof window<"u"}function Ze(e){return pr(e)?(e.nodeName||"").toLowerCase():"#document"}function ie(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function we(e){var t;return(t=(pr(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function pr(e){return Ut()?e instanceof Node||e instanceof ie(e).Node:!1}function pe(e){return Ut()?e instanceof Element||e instanceof ie(e).Element:!1}function xe(e){return Ut()?e instanceof HTMLElement||e instanceof ie(e).HTMLElement:!1}function Wo(e){return!Ut()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof ie(e).ShadowRoot}const hl=new Set(["inline","contents"]);function dt(e){const{overflow:t,overflowX:n,overflowY:o,display:r}=me(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!hl.has(r)}const vl=new Set(["table","td","th"]);function gl(e){return vl.has(Ze(e))}const xl=[":popover-open",":modal"];function Kt(e){return xl.some(t=>{try{return e.matches(t)}catch{return!1}})}const wl=["transform","translate","scale","rotate","perspective"],Cl=["transform","translate","scale","rotate","perspective","filter"],bl=["paint","layout","strict","content"];function Yn(e){const t=Xn(),n=pe(e)?me(e):e;return wl.some(o=>n[o]?n[o]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Cl.some(o=>(n.willChange||"").includes(o))||bl.some(o=>(n.contain||"").includes(o))}function yl(e){let t=Me(e);for(;xe(t)&&!Ue(t);){if(Yn(t))return t;if(Kt(t))return null;t=Me(t)}return null}function Xn(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Sl=new Set(["html","body","#document"]);function Ue(e){return Sl.has(Ze(e))}function me(e){return ie(e).getComputedStyle(e)}function zt(e){return pe(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Me(e){if(Ze(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Wo(e)&&e.host||we(e);return Wo(t)?t.host:t}function mr(e){const t=Me(e);return Ue(t)?e.ownerDocument?e.ownerDocument.body:e.body:xe(t)&&dt(t)?t:mr(t)}function rt(e,t,n){var o;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=mr(e),s=r===((o=e.ownerDocument)==null?void 0:o.body),i=ie(r);if(s){const c=An(i);return t.concat(i,i.visualViewport||[],dt(r)?r:[],c&&n?rt(c):[])}return t.concat(r,rt(r,[],n))}function An(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hr(e){const t=me(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const r=xe(e),s=r?e.offsetWidth:n,i=r?e.offsetHeight:o,c=Et(n)!==s||Et(o)!==i;return c&&(n=s,o=i),{width:n,height:o,$:c}}function qn(e){return pe(e)?e:e.contextElement}function Ge(e){const t=qn(e);if(!xe(t))return ge(1);const n=t.getBoundingClientRect(),{width:o,height:r,$:s}=hr(t);let i=(s?Et(n.width):n.width)/o,c=(s?Et(n.height):n.height)/r;return(!i||!Number.isFinite(i))&&(i=1),(!c||!Number.isFinite(c))&&(c=1),{x:i,y:c}}const Pl=ge(0);function vr(e){const t=ie(e);return!Xn()||!t.visualViewport?Pl:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Rl(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==ie(e)?!1:t}function ke(e,t,n,o){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),s=qn(e);let i=ge(1);t&&(o?pe(o)&&(i=Ge(o)):i=Ge(e));const c=Rl(s,n,o)?vr(s):ge(0);let l=(r.left+c.x)/i.x,f=(r.top+c.y)/i.y,u=r.width/i.x,d=r.height/i.y;if(s){const m=ie(s),h=o&&pe(o)?ie(o):o;let g=m,v=An(g);for(;v&&o&&h!==g;){const x=Ge(v),w=v.getBoundingClientRect(),C=me(v),b=w.left+(v.clientLeft+parseFloat(C.paddingLeft))*x.x,y=w.top+(v.clientTop+parseFloat(C.paddingTop))*x.y;l*=x.x,f*=x.y,u*=x.x,d*=x.y,l+=b,f+=y,g=ie(v),v=An(g)}}return Tt({width:u,height:d,x:l,y:f})}function Yt(e,t){const n=zt(e).scrollLeft;return t?t.left+n:ke(we(e)).left+n}function gr(e,t){const n=e.getBoundingClientRect(),o=n.left+t.scrollLeft-Yt(e,n),r=n.top+t.scrollTop;return{x:o,y:r}}function El(e){let{elements:t,rect:n,offsetParent:o,strategy:r}=e;const s=r==="fixed",i=we(o),c=t?Kt(t.floating):!1;if(o===i||c&&s)return n;let l={scrollLeft:0,scrollTop:0},f=ge(1);const u=ge(0),d=xe(o);if((d||!d&&!s)&&((Ze(o)!=="body"||dt(i))&&(l=zt(o)),xe(o))){const h=ke(o);f=Ge(o),u.x=h.x+o.clientLeft,u.y=h.y+o.clientTop}const m=i&&!d&&!s?gr(i,l):ge(0);return{width:n.width*f.x,height:n.height*f.y,x:n.x*f.x-l.scrollLeft*f.x+u.x+m.x,y:n.y*f.y-l.scrollTop*f.y+u.y+m.y}}function _l(e){return Array.from(e.getClientRects())}function Tl(e){const t=we(e),n=zt(e),o=e.ownerDocument.body,r=se(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),s=se(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let i=-n.scrollLeft+Yt(e);const c=-n.scrollTop;return me(o).direction==="rtl"&&(i+=se(t.clientWidth,o.clientWidth)-r),{width:r,height:s,x:i,y:c}}const Go=25;function Ml(e,t){const n=ie(e),o=we(e),r=n.visualViewport;let s=o.clientWidth,i=o.clientHeight,c=0,l=0;if(r){s=r.width,i=r.height;const u=Xn();(!u||u&&t==="fixed")&&(c=r.offsetLeft,l=r.offsetTop)}const f=Yt(o);if(f<=0){const u=o.ownerDocument,d=u.body,m=getComputedStyle(d),h=u.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(o.clientWidth-d.clientWidth-h);g<=Go&&(s-=g)}else f<=Go&&(s+=f);return{width:s,height:i,x:c,y:l}}const Al=new Set(["absolute","fixed"]);function Il(e,t){const n=ke(e,!0,t==="fixed"),o=n.top+e.clientTop,r=n.left+e.clientLeft,s=xe(e)?Ge(e):ge(1),i=e.clientWidth*s.x,c=e.clientHeight*s.y,l=r*s.x,f=o*s.y;return{width:i,height:c,x:l,y:f}}function Uo(e,t,n){let o;if(t==="viewport")o=Ml(e,n);else if(t==="document")o=Tl(we(e));else if(pe(t))o=Il(t,n);else{const r=vr(e);o={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return Tt(o)}function xr(e,t){const n=Me(e);return n===t||!pe(n)||Ue(n)?!1:me(n).position==="fixed"||xr(n,t)}function Nl(e,t){const n=t.get(e);if(n)return n;let o=rt(e,[],!1).filter(c=>pe(c)&&Ze(c)!=="body"),r=null;const s=me(e).position==="fixed";let i=s?Me(e):e;for(;pe(i)&&!Ue(i);){const c=me(i),l=Yn(i);!l&&c.position==="fixed"&&(r=null),(s?!l&&!r:!l&&c.position==="static"&&!!r&&Al.has(r.position)||dt(i)&&!l&&xr(e,i))?o=o.filter(u=>u!==i):r=c,i=Me(i)}return t.set(e,o),o}function Ol(e){let{element:t,boundary:n,rootBoundary:o,strategy:r}=e;const i=[...n==="clippingAncestors"?Kt(t)?[]:Nl(t,this._c):[].concat(n),o],c=i[0],l=i.reduce((f,u)=>{const d=Uo(t,u,r);return f.top=se(d.top,f.top),f.right=Te(d.right,f.right),f.bottom=Te(d.bottom,f.bottom),f.left=se(d.left,f.left),f},Uo(t,c,r));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Dl(e){const{width:t,height:n}=hr(e);return{width:t,height:n}}function jl(e,t,n){const o=xe(t),r=we(t),s=n==="fixed",i=ke(e,!0,s,t);let c={scrollLeft:0,scrollTop:0};const l=ge(0);function f(){l.x=Yt(r)}if(o||!o&&!s)if((Ze(t)!=="body"||dt(r))&&(c=zt(t)),o){const h=ke(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else r&&f();s&&!o&&r&&f();const u=r&&!o&&!s?gr(r,c):ge(0),d=i.left+c.scrollLeft-l.x-u.x,m=i.top+c.scrollTop-l.y-u.y;return{x:d,y:m,width:i.width,height:i.height}}function Sn(e){return me(e).position==="static"}function Ko(e,t){if(!xe(e)||me(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return we(e)===n&&(n=n.ownerDocument.body),n}function wr(e,t){const n=ie(e);if(Kt(e))return n;if(!xe(e)){let r=Me(e);for(;r&&!Ue(r);){if(pe(r)&&!Sn(r))return r;r=Me(r)}return n}let o=Ko(e,t);for(;o&&gl(o)&&Sn(o);)o=Ko(o,t);return o&&Ue(o)&&Sn(o)&&!Yn(o)?n:o||yl(e)||n}const Ll=async function(e){const t=this.getOffsetParent||wr,n=this.getDimensions,o=await n(e.floating);return{reference:jl(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function kl(e){return me(e).direction==="rtl"}const $l={convertOffsetParentRelativeRectToViewportRelativeRect:El,getDocumentElement:we,getClippingRect:Ol,getOffsetParent:wr,getElementRects:Ll,getClientRects:_l,getDimensions:Dl,getScale:Ge,isElement:pe,isRTL:kl};function Cr(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Fl(e,t){let n=null,o;const r=we(e);function s(){var c;clearTimeout(o),(c=n)==null||c.disconnect(),n=null}function i(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),s();const f=e.getBoundingClientRect(),{left:u,top:d,width:m,height:h}=f;if(c||t(),!m||!h)return;const g=bt(d),v=bt(r.clientWidth-(u+m)),x=bt(r.clientHeight-(d+h)),w=bt(u),b={rootMargin:-g+"px "+-v+"px "+-x+"px "+-w+"px",threshold:se(0,Te(1,l))||1};let y=!0;function P(A){const R=A[0].intersectionRatio;if(R!==l){if(!y)return i();R?i(!1,R):o=setTimeout(()=>{i(!1,1e-7)},1e3)}R===1&&!Cr(f,e.getBoundingClientRect())&&i(),y=!1}try{n=new IntersectionObserver(P,{...b,root:r.ownerDocument})}catch{n=new IntersectionObserver(P,b)}n.observe(e)}return i(!0),s}function Bl(e,t,n,o){o===void 0&&(o={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=o,f=qn(e),u=r||s?[...f?rt(f):[],...rt(t)]:[];u.forEach(w=>{r&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const d=f&&c?Fl(f,n):null;let m=-1,h=null;i&&(h=new ResizeObserver(w=>{let[C]=w;C&&C.target===f&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),n()}),f&&!l&&h.observe(f),h.observe(t));let g,v=l?ke(e):null;l&&x();function x(){const w=ke(e);v&&!Cr(v,w)&&n(),v=w,g=requestAnimationFrame(x)}return n(),()=>{var w;u.forEach(C=>{r&&C.removeEventListener("scroll",n),s&&C.removeEventListener("resize",n)}),d?.(),(w=h)==null||w.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const Vl=dl,Hl=fl,Wl=cl,Gl=ml,Ul=ll,zo=al,Kl=pl,zl=(e,t,n)=>{const o=new Map,r={platform:$l,...n},s={...r.platform,_c:o};return il(e,t,{...r,platform:s})};var Yl=typeof document<"u",Xl=function(){},Rt=Yl?a.useLayoutEffect:Xl;function Mt(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,o,r;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(o=n;o--!==0;)if(!Mt(e[o],t[o]))return!1;return!0}if(r=Object.keys(e),n=r.length,n!==Object.keys(t).length)return!1;for(o=n;o--!==0;)if(!{}.hasOwnProperty.call(t,r[o]))return!1;for(o=n;o--!==0;){const s=r[o];if(!(s==="_owner"&&e.$$typeof)&&!Mt(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function br(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yo(e,t){const n=br(e);return Math.round(t*n)/n}function Pn(e){const t=a.useRef(e);return Rt(()=>{t.current=e}),t}function ql(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:o=[],platform:r,elements:{reference:s,floating:i}={},transform:c=!0,whileElementsMounted:l,open:f}=e,[u,d]=a.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=a.useState(o);Mt(m,o)||h(o);const[g,v]=a.useState(null),[x,w]=a.useState(null),C=a.useCallback(M=>{M!==A.current&&(A.current=M,v(M))},[]),b=a.useCallback(M=>{M!==R.current&&(R.current=M,w(M))},[]),y=s||g,P=i||x,A=a.useRef(null),R=a.useRef(null),I=a.useRef(u),O=l!=null,N=Pn(l),D=Pn(r),k=Pn(f),B=a.useCallback(()=>{if(!A.current||!R.current)return;const M={placement:t,strategy:n,middleware:m};D.current&&(M.platform=D.current),zl(A.current,R.current,M).then(E=>{const U={...E,isPositioned:k.current!==!1};$.current&&!Mt(I.current,U)&&(I.current=U,Ft.flushSync(()=>{d(U)}))})},[m,t,n,D,k]);Rt(()=>{f===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,d(M=>({...M,isPositioned:!1})))},[f]);const $=a.useRef(!1);Rt(()=>($.current=!0,()=>{$.current=!1}),[]),Rt(()=>{if(y&&(A.current=y),P&&(R.current=P),y&&P){if(N.current)return N.current(y,P,B);B()}},[y,P,B,N,O]);const V=a.useMemo(()=>({reference:A,floating:R,setReference:C,setFloating:b}),[C,b]),j=a.useMemo(()=>({reference:y,floating:P}),[y,P]),F=a.useMemo(()=>{const M={position:n,left:0,top:0};if(!j.floating)return M;const E=Yo(j.floating,u.x),U=Yo(j.floating,u.y);return c?{...M,transform:"translate("+E+"px, "+U+"px)",...br(j.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:E,top:U}},[n,c,j.floating,u.x,u.y]);return a.useMemo(()=>({...u,update:B,refs:V,elements:j,floatingStyles:F}),[u,B,V,j,F])}const Zl=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:o,padding:r}=typeof e=="function"?e(n):e;return o&&t(o)?o.current!=null?zo({element:o.current,padding:r}).fn(n):{}:o?zo({element:o,padding:r}).fn(n):{}}}},Jl=(e,t)=>({...Vl(e),options:[e,t]}),Ql=(e,t)=>({...Hl(e),options:[e,t]}),eu=(e,t)=>({...Kl(e),options:[e,t]}),tu=(e,t)=>({...Wl(e),options:[e,t]}),nu=(e,t)=>({...Gl(e),options:[e,t]}),ou=(e,t)=>({...Ul(e),options:[e,t]}),ru=(e,t)=>({...Zl(e),options:[e,t]});var su="Arrow",yr=a.forwardRef((e,t)=>{const{children:n,width:o=10,height:r=5,...s}=e;return p.jsx(_.svg,{...s,ref:t,width:o,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:p.jsx("polygon",{points:"0,0 30,0 15,10"})})});yr.displayName=su;var iu=yr,Zn="Popper",[Sr,Ae]=Z(Zn),[au,Pr]=Sr(Zn),Rr=e=>{const{__scopePopper:t,children:n}=e,[o,r]=a.useState(null);return p.jsx(au,{scope:t,anchor:o,onAnchorChange:r,children:n})};Rr.displayName=Zn;var Er="PopperAnchor",_r=a.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:o,...r}=e,s=Pr(Er,n),i=a.useRef(null),c=L(t,i),l=a.useRef(null);return a.useEffect(()=>{const f=l.current;l.current=o?.current||i.current,f!==l.current&&s.onAnchorChange(l.current)}),o?null:p.jsx(_.div,{...r,ref:c})});_r.displayName=Er;var Jn="PopperContent",[cu,lu]=Sr(Jn),Tr=a.forwardRef((e,t)=>{const{__scopePopper:n,side:o="bottom",sideOffset:r=0,align:s="center",alignOffset:i=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:f=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:m=!1,updatePositionStrategy:h="optimized",onPlaced:g,...v}=e,x=Pr(Jn,n),[w,C]=a.useState(null),b=L(t,T=>C(T)),[y,P]=a.useState(null),A=Ht(y),R=A?.width??0,I=A?.height??0,O=o+(s!=="center"?"-"+s:""),N=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},D=Array.isArray(f)?f:[f],k=D.length>0,B={padding:N,boundary:D.filter(du),altBoundary:k},{refs:$,floatingStyles:V,placement:j,isPositioned:F,middlewareData:M}=ql({strategy:"fixed",placement:O,whileElementsMounted:(...T)=>Bl(...T,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[Jl({mainAxis:r+I,alignmentAxis:i}),l&&Ql({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?eu():void 0,...B}),l&&tu({...B}),nu({...B,apply:({elements:T,rects:H,availableWidth:te,availableHeight:W})=>{const{width:G,height:K}=H.reference,ce=T.floating.style;ce.setProperty("--radix-popper-available-width",`${te}px`),ce.setProperty("--radix-popper-available-height",`${W}px`),ce.setProperty("--radix-popper-anchor-width",`${G}px`),ce.setProperty("--radix-popper-anchor-height",`${K}px`)}}),y&&ru({element:y,padding:c}),fu({arrowWidth:R,arrowHeight:I}),m&&ou({strategy:"referenceHidden",...B})]}),[E,U]=Ir(j),ee=z(g);X(()=>{F&&ee?.()},[F,ee]);const de=M.arrow?.x,be=M.arrow?.y,ae=M.arrow?.centerOffset!==0,[ye,re]=a.useState();return X(()=>{w&&re(window.getComputedStyle(w).zIndex)},[w]),p.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:F?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ye,"--radix-popper-transform-origin":[M.transformOrigin?.x,M.transformOrigin?.y].join(" "),...M.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:p.jsx(cu,{scope:n,placedSide:E,onArrowChange:P,arrowX:de,arrowY:be,shouldHideArrow:ae,children:p.jsx(_.div,{"data-side":E,"data-align":U,...v,ref:b,style:{...v.style,animation:F?void 0:"none"}})})})});Tr.displayName=Jn;var Mr="PopperArrow",uu={top:"bottom",right:"left",bottom:"top",left:"right"},Ar=a.forwardRef(function(t,n){const{__scopePopper:o,...r}=t,s=lu(Mr,o),i=uu[s.placedSide];return p.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:p.jsx(iu,{...r,ref:n,style:{...r.style,display:"block"}})})});Ar.displayName=Mr;function du(e){return e!==null}var fu=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:o,middlewareData:r}=t,i=r.arrow?.centerOffset!==0,c=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[f,u]=Ir(n),d={start:"0%",center:"50%",end:"100%"}[u],m=(r.arrow?.x??0)+c/2,h=(r.arrow?.y??0)+l/2;let g="",v="";return f==="bottom"?(g=i?d:`${m}px`,v=`${-l}px`):f==="top"?(g=i?d:`${m}px`,v=`${o.floating.height+l}px`):f==="right"?(g=`${-l}px`,v=i?d:`${h}px`):f==="left"&&(g=`${o.floating.width+l}px`,v=i?d:`${h}px`),{data:{x:g,y:v}}}});function Ir(e){const[t,n="center"]=e.split("-");return[t,n]}var ft=Rr,pt=_r,Xt=Tr,qt=Ar,pu="Portal",mt=a.forwardRef((e,t)=>{const{container:n,...o}=e,[r,s]=a.useState(!1);X(()=>s(!0),[]);const i=n||r&&globalThis?.document?.body;return i?dc.createPortal(p.jsx(_.div,{...o,ref:t}),i):null});mt.displayName=pu;var mu=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},We=new WeakMap,yt=new WeakMap,St={},Rn=0,Nr=function(e){return e&&(e.host||Nr(e.parentNode))},hu=function(e,t){return t.map(function(n){if(e.contains(n))return n;var o=Nr(n);return o&&e.contains(o)?o:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},vu=function(e,t,n,o){var r=hu(t,Array.isArray(e)?e:[e]);St[n]||(St[n]=new WeakMap);var s=St[n],i=[],c=new Set,l=new Set(r),f=function(d){!d||c.has(d)||(c.add(d),f(d.parentNode))};r.forEach(f);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(m){if(c.has(m))u(m);else try{var h=m.getAttribute(o),g=h!==null&&h!=="false",v=(We.get(m)||0)+1,x=(s.get(m)||0)+1;We.set(m,v),s.set(m,x),i.push(m),v===1&&g&&yt.set(m,!0),x===1&&m.setAttribute(n,"true"),g||m.setAttribute(o,"true")}catch(w){console.error("aria-hidden: cannot operate on ",m,w)}})};return u(t),c.clear(),Rn++,function(){i.forEach(function(d){var m=We.get(d)-1,h=s.get(d)-1;We.set(d,m),s.set(d,h),m||(yt.has(d)||d.removeAttribute(o),yt.delete(d)),h||d.removeAttribute(n)}),Rn--,Rn||(We=new WeakMap,We=new WeakMap,yt=new WeakMap,St={})}},Zt=function(e,t,n){n===void 0&&(n="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),r=mu(e);return r?(o.push.apply(o,Array.from(r.querySelectorAll("[aria-live], script"))),vu(o,r,n,"aria-hidden")):function(){return null}},Jt="Popover",[Or]=Z(Jt,[Ae]),ht=Ae(),[gu,Ie]=Or(Jt),Dr=e=>{const{__scopePopover:t,children:n,open:o,defaultOpen:r,onOpenChange:s,modal:i=!1}=e,c=ht(t),l=a.useRef(null),[f,u]=a.useState(!1),[d,m]=J({prop:o,defaultProp:r??!1,onChange:s,caller:Jt});return p.jsx(ft,{...c,children:p.jsx(gu,{scope:t,contentId:ne(),triggerRef:l,open:d,onOpenChange:m,onOpenToggle:a.useCallback(()=>m(h=>!h),[m]),hasCustomAnchor:f,onCustomAnchorAdd:a.useCallback(()=>u(!0),[]),onCustomAnchorRemove:a.useCallback(()=>u(!1),[]),modal:i,children:n})})};Dr.displayName=Jt;var jr="PopoverAnchor",xu=a.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=Ie(jr,n),s=ht(n),{onCustomAnchorAdd:i,onCustomAnchorRemove:c}=r;return a.useEffect(()=>(i(),()=>c()),[i,c]),p.jsx(pt,{...s,...o,ref:t})});xu.displayName=jr;var Lr="PopoverTrigger",kr=a.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=Ie(Lr,n),s=ht(n),i=L(t,r.triggerRef),c=p.jsx(_.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":Hr(r.open),...o,ref:i,onClick:S(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?c:p.jsx(pt,{asChild:!0,...s,children:c})});kr.displayName=Lr;var Qn="PopoverPortal",[wu,Cu]=Or(Qn,{forceMount:void 0}),$r=e=>{const{__scopePopover:t,forceMount:n,children:o,container:r}=e,s=Ie(Qn,t);return p.jsx(wu,{scope:t,forceMount:n,children:p.jsx(q,{present:n||s.open,children:p.jsx(mt,{asChild:!0,container:r,children:o})})})};$r.displayName=Qn;var Ke="PopoverContent",Fr=a.forwardRef((e,t)=>{const n=Cu(Ke,e.__scopePopover),{forceMount:o=n.forceMount,...r}=e,s=Ie(Ke,e.__scopePopover);return p.jsx(q,{present:o||s.open,children:s.modal?p.jsx(yu,{...r,ref:t}):p.jsx(Su,{...r,ref:t})})});Fr.displayName=Ke;var bu=_e("PopoverContent.RemoveScroll"),yu=a.forwardRef((e,t)=>{const n=Ie(Ke,e.__scopePopover),o=a.useRef(null),r=L(t,o),s=a.useRef(!1);return a.useEffect(()=>{const i=o.current;if(i)return Zt(i)},[]),p.jsx(Bt,{as:bu,allowPinchZoom:!0,children:p.jsx(Br,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:S(e.onCloseAutoFocus,i=>{i.preventDefault(),s.current||n.triggerRef.current?.focus()}),onPointerDownOutside:S(e.onPointerDownOutside,i=>{const c=i.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,f=c.button===2||l;s.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:S(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),Su=a.forwardRef((e,t)=>{const n=Ie(Ke,e.__scopePopover),o=a.useRef(!1),r=a.useRef(!1);return p.jsx(Br,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(o.current||n.triggerRef.current?.focus(),s.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(o.current=!0,s.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const i=s.target;n.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&r.current&&s.preventDefault()}})}),Br=a.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:s,disableOutsidePointerEvents:i,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:f,onInteractOutside:u,...d}=e,m=Ie(Ke,n),h=ht(n);return Gt(),p.jsx(ut,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:s,children:p.jsx(Xe,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:f,onDismiss:()=>m.onOpenChange(!1),children:p.jsx(Xt,{"data-state":Hr(m.open),role:"dialog",id:m.contentId,...h,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Vr="PopoverClose",Pu=a.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=Ie(Vr,n);return p.jsx(_.button,{type:"button",...o,ref:t,onClick:S(e.onClick,()=>r.onOpenChange(!1))})});Pu.displayName=Vr;var Ru="PopoverArrow",Eu=a.forwardRef((e,t)=>{const{__scopePopover:n,...o}=e,r=ht(n);return p.jsx(qt,{...r,...o,ref:t})});Eu.displayName=Ru;function Hr(e){return e?"open":"closed"}var qp=Dr,Zp=kr,Jp=$r,Qp=Fr;function st(e,[t,n]){return Math.min(n,Math.max(t,e))}var _u=a.createContext(void 0);function Ve(e){const t=a.useContext(_u);return e||t||"ltr"}function Qt(e){const t=e+"CollectionProvider",[n,o]=Z(t),[r,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=v=>{const{scope:x,children:w}=v,C=Y.useRef(null),b=Y.useRef(new Map).current;return p.jsx(r,{scope:x,itemMap:b,collectionRef:C,children:w})};i.displayName=t;const c=e+"CollectionSlot",l=_e(c),f=Y.forwardRef((v,x)=>{const{scope:w,children:C}=v,b=s(c,w),y=L(x,b.collectionRef);return p.jsx(l,{ref:y,children:C})});f.displayName=c;const u=e+"CollectionItemSlot",d="data-radix-collection-item",m=_e(u),h=Y.forwardRef((v,x)=>{const{scope:w,children:C,...b}=v,y=Y.useRef(null),P=L(x,y),A=s(u,w);return Y.useEffect(()=>(A.itemMap.set(y,{ref:y,...b}),()=>void A.itemMap.delete(y))),p.jsx(m,{[d]:"",ref:P,children:C})});h.displayName=u;function g(v){const x=s(e+"CollectionConsumer",v);return Y.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const b=Array.from(C.querySelectorAll(`[${d}]`));return Array.from(x.itemMap.values()).sort((A,R)=>b.indexOf(A.ref.current)-b.indexOf(R.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:i,Slot:f,ItemSlot:h},g,o]}var Wr=["PageUp","PageDown"],Gr=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ur={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Je="Slider",[In,Tu,Mu]=Qt(Je),[Kr]=Z(Je,[Mu]),[Au,en]=Kr(Je),zr=a.forwardRef((e,t)=>{const{name:n,min:o=0,max:r=100,step:s=1,orientation:i="horizontal",disabled:c=!1,minStepsBetweenThumbs:l=0,defaultValue:f=[o],value:u,onValueChange:d=()=>{},onValueCommit:m=()=>{},inverted:h=!1,form:g,...v}=e,x=a.useRef(new Set),w=a.useRef(0),b=i==="horizontal"?Iu:Nu,[y=[],P]=J({prop:u,defaultProp:f,onChange:D=>{[...x.current][w.current]?.focus(),d(D)}}),A=a.useRef(y);function R(D){const k=ku(y,D);N(D,k)}function I(D){N(D,w.current)}function O(){const D=A.current[w.current];y[w.current]!==D&&m(y)}function N(D,k,{commit:B}={commit:!1}){const $=Vu(s),V=Hu(Math.round((D-o)/s)*s+o,$),j=st(V,[o,r]);P((F=[])=>{const M=ju(F,j,k);if(Bu(M,l*s)){w.current=M.indexOf(j);const E=String(M)!==String(F);return E&&B&&m(M),E?M:F}else return F})}return p.jsx(Au,{scope:e.__scopeSlider,name:n,disabled:c,min:o,max:r,valueIndexToChangeRef:w,thumbs:x.current,values:y,orientation:i,form:g,children:p.jsx(In.Provider,{scope:e.__scopeSlider,children:p.jsx(In.Slot,{scope:e.__scopeSlider,children:p.jsx(b,{"aria-disabled":c,"data-disabled":c?"":void 0,...v,ref:t,onPointerDown:S(v.onPointerDown,()=>{c||(A.current=y)}),min:o,max:r,inverted:h,onSlideStart:c?void 0:R,onSlideMove:c?void 0:I,onSlideEnd:c?void 0:O,onHomeKeyDown:()=>!c&&N(o,0,{commit:!0}),onEndKeyDown:()=>!c&&N(r,y.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:k})=>{if(!c){const V=Wr.includes(D.key)||D.shiftKey&&Gr.includes(D.key)?10:1,j=w.current,F=y[j],M=s*V*k;N(F+M,j,{commit:!0})}}})})})})});zr.displayName=Je;var[Yr,Xr]=Kr(Je,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Iu=a.forwardRef((e,t)=>{const{min:n,max:o,dir:r,inverted:s,onSlideStart:i,onSlideMove:c,onSlideEnd:l,onStepKeyDown:f,...u}=e,[d,m]=a.useState(null),h=L(t,b=>m(b)),g=a.useRef(void 0),v=Ve(r),x=v==="ltr",w=x&&!s||!x&&s;function C(b){const y=g.current||d.getBoundingClientRect(),P=[0,y.width],R=eo(P,w?[n,o]:[o,n]);return g.current=y,R(b-y.left)}return p.jsx(Yr,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:p.jsx(qr,{dir:v,"data-orientation":"horizontal",...u,ref:h,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{const y=C(b.clientX);i?.(y)},onSlideMove:b=>{const y=C(b.clientX);c?.(y)},onSlideEnd:()=>{g.current=void 0,l?.()},onStepKeyDown:b=>{const P=Ur[w?"from-left":"from-right"].includes(b.key);f?.({event:b,direction:P?-1:1})}})})}),Nu=a.forwardRef((e,t)=>{const{min:n,max:o,inverted:r,onSlideStart:s,onSlideMove:i,onSlideEnd:c,onStepKeyDown:l,...f}=e,u=a.useRef(null),d=L(t,u),m=a.useRef(void 0),h=!r;function g(v){const x=m.current||u.current.getBoundingClientRect(),w=[0,x.height],b=eo(w,h?[o,n]:[n,o]);return m.current=x,b(v-x.top)}return p.jsx(Yr,{scope:e.__scopeSlider,startEdge:h?"bottom":"top",endEdge:h?"top":"bottom",size:"height",direction:h?1:-1,children:p.jsx(qr,{"data-orientation":"vertical",...f,ref:d,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{const x=g(v.clientY);s?.(x)},onSlideMove:v=>{const x=g(v.clientY);i?.(x)},onSlideEnd:()=>{m.current=void 0,c?.()},onStepKeyDown:v=>{const w=Ur[h?"from-bottom":"from-top"].includes(v.key);l?.({event:v,direction:w?-1:1})}})})}),qr=a.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:o,onSlideMove:r,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:c,onStepKeyDown:l,...f}=e,u=en(Je,n);return p.jsx(_.span,{...f,ref:t,onKeyDown:S(e.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(c(d),d.preventDefault()):Wr.concat(Gr).includes(d.key)&&(l(d),d.preventDefault())}),onPointerDown:S(e.onPointerDown,d=>{const m=d.target;m.setPointerCapture(d.pointerId),d.preventDefault(),u.thumbs.has(m)?m.focus():o(d)}),onPointerMove:S(e.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&r(d)}),onPointerUp:S(e.onPointerUp,d=>{const m=d.target;m.hasPointerCapture(d.pointerId)&&(m.releasePointerCapture(d.pointerId),s(d))})})}),Zr="SliderTrack",Jr=a.forwardRef((e,t)=>{const{__scopeSlider:n,...o}=e,r=en(Zr,n);return p.jsx(_.span,{"data-disabled":r.disabled?"":void 0,"data-orientation":r.orientation,...o,ref:t})});Jr.displayName=Zr;var Nn="SliderRange",Qr=a.forwardRef((e,t)=>{const{__scopeSlider:n,...o}=e,r=en(Nn,n),s=Xr(Nn,n),i=a.useRef(null),c=L(t,i),l=r.values.length,f=r.values.map(m=>ns(m,r.min,r.max)),u=l>1?Math.min(...f):0,d=100-Math.max(...f);return p.jsx(_.span,{"data-orientation":r.orientation,"data-disabled":r.disabled?"":void 0,...o,ref:c,style:{...e.style,[s.startEdge]:u+"%",[s.endEdge]:d+"%"}})});Qr.displayName=Nn;var On="SliderThumb",es=a.forwardRef((e,t)=>{const n=Tu(e.__scopeSlider),[o,r]=a.useState(null),s=L(t,c=>r(c)),i=a.useMemo(()=>o?n().findIndex(c=>c.ref.current===o):-1,[n,o]);return p.jsx(Ou,{...e,ref:s,index:i})}),Ou=a.forwardRef((e,t)=>{const{__scopeSlider:n,index:o,name:r,...s}=e,i=en(On,n),c=Xr(On,n),[l,f]=a.useState(null),u=L(t,C=>f(C)),d=l?i.form||!!l.closest("form"):!0,m=Ht(l),h=i.values[o],g=h===void 0?0:ns(h,i.min,i.max),v=Lu(o,i.values.length),x=m?.[c.size],w=x?$u(x,g,c.direction):0;return a.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),p.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${g}% + ${w}px)`},children:[p.jsx(In.ItemSlot,{scope:e.__scopeSlider,children:p.jsx(_.span,{role:"slider","aria-label":e["aria-label"]||v,"aria-valuemin":i.min,"aria-valuenow":h,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:u,style:h===void 0?{display:"none"}:e.style,onFocus:S(e.onFocus,()=>{i.valueIndexToChangeRef.current=o})})}),d&&p.jsx(ts,{name:r??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:h},o)]})});es.displayName=On;var Du="RadioBubbleInput",ts=a.forwardRef(({__scopeSlider:e,value:t,...n},o)=>{const r=a.useRef(null),s=L(r,o),i=Vt(t);return a.useEffect(()=>{const c=r.current;if(!c)return;const l=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&u){const d=new Event("input",{bubbles:!0});u.call(c,t),c.dispatchEvent(d)}},[i,t]),p.jsx(_.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});ts.displayName=Du;function ju(e=[],t,n){const o=[...e];return o[n]=t,o.sort((r,s)=>r-s)}function ns(e,t,n){const s=100/(n-t)*(e-t);return st(s,[0,100])}function Lu(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function ku(e,t){if(e.length===1)return 0;const n=e.map(r=>Math.abs(r-t)),o=Math.min(...n);return n.indexOf(o)}function $u(e,t,n){const o=e/2,s=eo([0,50],[0,o]);return(o-s(t)*n)*n}function Fu(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Bu(e,t){if(t>0){const n=Fu(e);return Math.min(...n)>=t}return!0}function eo(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const o=(t[1]-t[0])/(e[1]-e[0]);return t[0]+o*(n-e[0])}}function Vu(e){return(String(e).split(".")[1]||"").length}function Hu(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var em=zr,tm=Jr,nm=Qr,om=es,tn="Collapsible",[Wu]=Z(tn),[Gu,to]=Wu(tn),os=a.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:o,defaultOpen:r,disabled:s,onOpenChange:i,...c}=e,[l,f]=J({prop:o,defaultProp:r??!1,onChange:i,caller:tn});return p.jsx(Gu,{scope:n,disabled:s,contentId:ne(),open:l,onOpenToggle:a.useCallback(()=>f(u=>!u),[f]),children:p.jsx(_.div,{"data-state":oo(l),"data-disabled":s?"":void 0,...c,ref:t})})});os.displayName=tn;var rs="CollapsibleTrigger",Uu=a.forwardRef((e,t)=>{const{__scopeCollapsible:n,...o}=e,r=to(rs,n);return p.jsx(_.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":oo(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...o,ref:t,onClick:S(e.onClick,r.onOpenToggle)})});Uu.displayName=rs;var no="CollapsibleContent",Ku=a.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=to(no,e.__scopeCollapsible);return p.jsx(q,{present:n||r.open,children:({present:s})=>p.jsx(zu,{...o,ref:t,present:s})})});Ku.displayName=no;var zu=a.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:o,children:r,...s}=e,i=to(no,n),[c,l]=a.useState(o),f=a.useRef(null),u=L(t,f),d=a.useRef(0),m=d.current,h=a.useRef(0),g=h.current,v=i.open||c,x=a.useRef(v),w=a.useRef(void 0);return a.useEffect(()=>{const C=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(C)},[]),X(()=>{const C=f.current;if(C){w.current=w.current||{transitionDuration:C.style.transitionDuration,animationName:C.style.animationName},C.style.transitionDuration="0s",C.style.animationName="none";const b=C.getBoundingClientRect();d.current=b.height,h.current=b.width,x.current||(C.style.transitionDuration=w.current.transitionDuration,C.style.animationName=w.current.animationName),l(o)}},[i.open,o]),p.jsx(_.div,{"data-state":oo(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!v,...s,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:v&&r})});function oo(e){return e?"open":"closed"}var rm=os,En="rovingFocusGroup.onEntryFocus",Yu={bubbles:!1,cancelable:!0},vt="RovingFocusGroup",[Dn,ss,Xu]=Qt(vt),[qu,Qe]=Z(vt,[Xu]),[Zu,Ju]=qu(vt),is=a.forwardRef((e,t)=>p.jsx(Dn.Provider,{scope:e.__scopeRovingFocusGroup,children:p.jsx(Dn.Slot,{scope:e.__scopeRovingFocusGroup,children:p.jsx(Qu,{...e,ref:t})})}));is.displayName=vt;var Qu=a.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:o,loop:r=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:f,preventScrollOnEntryFocus:u=!1,...d}=e,m=a.useRef(null),h=L(t,m),g=Ve(s),[v,x]=J({prop:i,defaultProp:c??null,onChange:l,caller:vt}),[w,C]=a.useState(!1),b=z(f),y=ss(n),P=a.useRef(!1),[A,R]=a.useState(0);return a.useEffect(()=>{const I=m.current;if(I)return I.addEventListener(En,b),()=>I.removeEventListener(En,b)},[b]),p.jsx(Zu,{scope:n,orientation:o,dir:g,loop:r,currentTabStopId:v,onItemFocus:a.useCallback(I=>x(I),[x]),onItemShiftTab:a.useCallback(()=>C(!0),[]),onFocusableItemAdd:a.useCallback(()=>R(I=>I+1),[]),onFocusableItemRemove:a.useCallback(()=>R(I=>I-1),[]),children:p.jsx(_.div,{tabIndex:w||A===0?-1:0,"data-orientation":o,...d,ref:h,style:{outline:"none",...e.style},onMouseDown:S(e.onMouseDown,()=>{P.current=!0}),onFocus:S(e.onFocus,I=>{const O=!P.current;if(I.target===I.currentTarget&&O&&!w){const N=new CustomEvent(En,Yu);if(I.currentTarget.dispatchEvent(N),!N.defaultPrevented){const D=y().filter(j=>j.focusable),k=D.find(j=>j.active),B=D.find(j=>j.id===v),V=[k,B,...D].filter(Boolean).map(j=>j.ref.current);ls(V,u)}}P.current=!1}),onBlur:S(e.onBlur,()=>C(!1))})})}),as="RovingFocusGroupItem",cs=a.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:o=!0,active:r=!1,tabStopId:s,children:i,...c}=e,l=ne(),f=s||l,u=Ju(as,n),d=u.currentTabStopId===f,m=ss(n),{onFocusableItemAdd:h,onFocusableItemRemove:g,currentTabStopId:v}=u;return a.useEffect(()=>{if(o)return h(),()=>g()},[o,h,g]),p.jsx(Dn.ItemSlot,{scope:n,id:f,focusable:o,active:r,children:p.jsx(_.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:S(e.onMouseDown,x=>{o?u.onItemFocus(f):x.preventDefault()}),onFocus:S(e.onFocus,()=>u.onItemFocus(f)),onKeyDown:S(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){u.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const w=nd(x,u.orientation,u.dir);if(w!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let b=m().filter(y=>y.focusable).map(y=>y.ref.current);if(w==="last")b.reverse();else if(w==="prev"||w==="next"){w==="prev"&&b.reverse();const y=b.indexOf(x.currentTarget);b=u.loop?od(b,y+1):b.slice(y+1)}setTimeout(()=>ls(b))}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:v!=null}):i})})});cs.displayName=as;var ed={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function td(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function nd(e,t,n){const o=td(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(o))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(o)))return ed[o]}function ls(e,t=!1){const n=document.activeElement;for(const o of e)if(o===n||(o.focus({preventScroll:t}),document.activeElement!==n))return}function od(e,t){return e.map((n,o)=>e[(t+o)%e.length])}var ro=is,so=cs,jn=["Enter"," "],rd=["ArrowDown","PageUp","Home"],us=["ArrowUp","PageDown","End"],sd=[...rd,...us],id={ltr:[...jn,"ArrowRight"],rtl:[...jn,"ArrowLeft"]},ad={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gt="Menu",[it,cd,ld]=Qt(gt),[He,nn]=Z(gt,[ld,Ae,Qe]),xt=Ae(),ds=Qe(),[fs,Ne]=He(gt),[ud,wt]=He(gt),ps=e=>{const{__scopeMenu:t,open:n=!1,children:o,dir:r,onOpenChange:s,modal:i=!0}=e,c=xt(t),[l,f]=a.useState(null),u=a.useRef(!1),d=z(s),m=Ve(r);return a.useEffect(()=>{const h=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),p.jsx(ft,{...c,children:p.jsx(fs,{scope:t,open:n,onOpenChange:d,content:l,onContentChange:f,children:p.jsx(ud,{scope:t,onClose:a.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:m,modal:i,children:o})})})};ps.displayName=gt;var dd="MenuAnchor",io=a.forwardRef((e,t)=>{const{__scopeMenu:n,...o}=e,r=xt(n);return p.jsx(pt,{...r,...o,ref:t})});io.displayName=dd;var ao="MenuPortal",[fd,ms]=He(ao,{forceMount:void 0}),hs=e=>{const{__scopeMenu:t,forceMount:n,children:o,container:r}=e,s=Ne(ao,t);return p.jsx(fd,{scope:t,forceMount:n,children:p.jsx(q,{present:n||s.open,children:p.jsx(mt,{asChild:!0,container:r,children:o})})})};hs.displayName=ao;var le="MenuContent",[pd,co]=He(le),vs=a.forwardRef((e,t)=>{const n=ms(le,e.__scopeMenu),{forceMount:o=n.forceMount,...r}=e,s=Ne(le,e.__scopeMenu),i=wt(le,e.__scopeMenu);return p.jsx(it.Provider,{scope:e.__scopeMenu,children:p.jsx(q,{present:o||s.open,children:p.jsx(it.Slot,{scope:e.__scopeMenu,children:i.modal?p.jsx(md,{...r,ref:t}):p.jsx(hd,{...r,ref:t})})})})}),md=a.forwardRef((e,t)=>{const n=Ne(le,e.__scopeMenu),o=a.useRef(null),r=L(t,o);return a.useEffect(()=>{const s=o.current;if(s)return Zt(s)},[]),p.jsx(lo,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:S(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),hd=a.forwardRef((e,t)=>{const n=Ne(le,e.__scopeMenu);return p.jsx(lo,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),vd=_e("MenuContent.ScrollLock"),lo=a.forwardRef((e,t)=>{const{__scopeMenu:n,loop:o=!1,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:f,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:m,onDismiss:h,disableOutsideScroll:g,...v}=e,x=Ne(le,n),w=wt(le,n),C=xt(n),b=ds(n),y=cd(n),[P,A]=a.useState(null),R=a.useRef(null),I=L(t,R,x.onContentChange),O=a.useRef(0),N=a.useRef(""),D=a.useRef(0),k=a.useRef(null),B=a.useRef("right"),$=a.useRef(0),V=g?Bt:a.Fragment,j=g?{as:vd,allowPinchZoom:!0}:void 0,F=E=>{const U=N.current+E,ee=y().filter(T=>!T.disabled),de=document.activeElement,be=ee.find(T=>T.ref.current===de)?.textValue,ae=ee.map(T=>T.textValue),ye=Td(ae,U,be),re=ee.find(T=>T.textValue===ye)?.ref.current;(function T(H){N.current=H,window.clearTimeout(O.current),H!==""&&(O.current=window.setTimeout(()=>T(""),1e3))})(U),re&&setTimeout(()=>re.focus())};a.useEffect(()=>()=>window.clearTimeout(O.current),[]),Gt();const M=a.useCallback(E=>B.current===k.current?.side&&Ad(E,k.current?.area),[]);return p.jsx(pd,{scope:n,searchRef:N,onItemEnter:a.useCallback(E=>{M(E)&&E.preventDefault()},[M]),onItemLeave:a.useCallback(E=>{M(E)||(R.current?.focus(),A(null))},[M]),onTriggerLeave:a.useCallback(E=>{M(E)&&E.preventDefault()},[M]),pointerGraceTimerRef:D,onPointerGraceIntentChange:a.useCallback(E=>{k.current=E},[]),children:p.jsx(V,{...j,children:p.jsx(ut,{asChild:!0,trapped:r,onMountAutoFocus:S(s,E=>{E.preventDefault(),R.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:p.jsx(Xe,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:f,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:m,onDismiss:h,children:p.jsx(ro,{asChild:!0,...b,dir:w.dir,orientation:"vertical",loop:o,currentTabStopId:P,onCurrentTabStopIdChange:A,onEntryFocus:S(l,E=>{w.isUsingKeyboardRef.current||E.preventDefault()}),preventScrollOnEntryFocus:!0,children:p.jsx(Xt,{role:"menu","aria-orientation":"vertical","data-state":Os(x.open),"data-radix-menu-content":"",dir:w.dir,...C,...v,ref:I,style:{outline:"none",...v.style},onKeyDown:S(v.onKeyDown,E=>{const ee=E.target.closest("[data-radix-menu-content]")===E.currentTarget,de=E.ctrlKey||E.altKey||E.metaKey,be=E.key.length===1;ee&&(E.key==="Tab"&&E.preventDefault(),!de&&be&&F(E.key));const ae=R.current;if(E.target!==ae||!sd.includes(E.key))return;E.preventDefault();const re=y().filter(T=>!T.disabled).map(T=>T.ref.current);us.includes(E.key)&&re.reverse(),Ed(re)}),onBlur:S(e.onBlur,E=>{E.currentTarget.contains(E.target)||(window.clearTimeout(O.current),N.current="")}),onPointerMove:S(e.onPointerMove,at(E=>{const U=E.target,ee=$.current!==E.clientX;if(E.currentTarget.contains(U)&&ee){const de=E.clientX>$.current?"right":"left";B.current=de,$.current=E.clientX}}))})})})})})})});vs.displayName=le;var gd="MenuGroup",uo=a.forwardRef((e,t)=>{const{__scopeMenu:n,...o}=e;return p.jsx(_.div,{role:"group",...o,ref:t})});uo.displayName=gd;var xd="MenuLabel",gs=a.forwardRef((e,t)=>{const{__scopeMenu:n,...o}=e;return p.jsx(_.div,{...o,ref:t})});gs.displayName=xd;var At="MenuItem",Xo="menu.itemSelect",on=a.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:o,...r}=e,s=a.useRef(null),i=wt(At,e.__scopeMenu),c=co(At,e.__scopeMenu),l=L(t,s),f=a.useRef(!1),u=()=>{const d=s.current;if(!n&&d){const m=new CustomEvent(Xo,{bubbles:!0,cancelable:!0});d.addEventListener(Xo,h=>o?.(h),{once:!0}),tr(d,m),m.defaultPrevented?f.current=!1:i.onClose()}};return p.jsx(xs,{...r,ref:l,disabled:n,onClick:S(e.onClick,u),onPointerDown:d=>{e.onPointerDown?.(d),f.current=!0},onPointerUp:S(e.onPointerUp,d=>{f.current||d.currentTarget?.click()}),onKeyDown:S(e.onKeyDown,d=>{const m=c.searchRef.current!=="";n||m&&d.key===" "||jn.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});on.displayName=At;var xs=a.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:o=!1,textValue:r,...s}=e,i=co(At,n),c=ds(n),l=a.useRef(null),f=L(t,l),[u,d]=a.useState(!1),[m,h]=a.useState("");return a.useEffect(()=>{const g=l.current;g&&h((g.textContent??"").trim())},[s.children]),p.jsx(it.ItemSlot,{scope:n,disabled:o,textValue:r??m,children:p.jsx(so,{asChild:!0,...c,focusable:!o,children:p.jsx(_.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":o||void 0,"data-disabled":o?"":void 0,...s,ref:f,onPointerMove:S(e.onPointerMove,at(g=>{o?i.onItemLeave(g):(i.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:S(e.onPointerLeave,at(g=>i.onItemLeave(g))),onFocus:S(e.onFocus,()=>d(!0)),onBlur:S(e.onBlur,()=>d(!1))})})})}),wd="MenuCheckboxItem",ws=a.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:o,...r}=e;return p.jsx(Ps,{scope:e.__scopeMenu,checked:n,children:p.jsx(on,{role:"menuitemcheckbox","aria-checked":It(n)?"mixed":n,...r,ref:t,"data-state":mo(n),onSelect:S(r.onSelect,()=>o?.(It(n)?!0:!n),{checkForDefaultPrevented:!1})})})});ws.displayName=wd;var Cs="MenuRadioGroup",[Cd,bd]=He(Cs,{value:void 0,onValueChange:()=>{}}),bs=a.forwardRef((e,t)=>{const{value:n,onValueChange:o,...r}=e,s=z(o);return p.jsx(Cd,{scope:e.__scopeMenu,value:n,onValueChange:s,children:p.jsx(uo,{...r,ref:t})})});bs.displayName=Cs;var ys="MenuRadioItem",Ss=a.forwardRef((e,t)=>{const{value:n,...o}=e,r=bd(ys,e.__scopeMenu),s=n===r.value;return p.jsx(Ps,{scope:e.__scopeMenu,checked:s,children:p.jsx(on,{role:"menuitemradio","aria-checked":s,...o,ref:t,"data-state":mo(s),onSelect:S(o.onSelect,()=>r.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});Ss.displayName=ys;var fo="MenuItemIndicator",[Ps,yd]=He(fo,{checked:!1}),Rs=a.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:o,...r}=e,s=yd(fo,n);return p.jsx(q,{present:o||It(s.checked)||s.checked===!0,children:p.jsx(_.span,{...r,ref:t,"data-state":mo(s.checked)})})});Rs.displayName=fo;var Sd="MenuSeparator",Es=a.forwardRef((e,t)=>{const{__scopeMenu:n,...o}=e;return p.jsx(_.div,{role:"separator","aria-orientation":"horizontal",...o,ref:t})});Es.displayName=Sd;var Pd="MenuArrow",_s=a.forwardRef((e,t)=>{const{__scopeMenu:n,...o}=e,r=xt(n);return p.jsx(qt,{...r,...o,ref:t})});_s.displayName=Pd;var po="MenuSub",[Rd,Ts]=He(po),Ms=e=>{const{__scopeMenu:t,children:n,open:o=!1,onOpenChange:r}=e,s=Ne(po,t),i=xt(t),[c,l]=a.useState(null),[f,u]=a.useState(null),d=z(r);return a.useEffect(()=>(s.open===!1&&d(!1),()=>d(!1)),[s.open,d]),p.jsx(ft,{...i,children:p.jsx(fs,{scope:t,open:o,onOpenChange:d,content:f,onContentChange:u,children:p.jsx(Rd,{scope:t,contentId:ne(),triggerId:ne(),trigger:c,onTriggerChange:l,children:n})})})};Ms.displayName=po;var tt="MenuSubTrigger",As=a.forwardRef((e,t)=>{const n=Ne(tt,e.__scopeMenu),o=wt(tt,e.__scopeMenu),r=Ts(tt,e.__scopeMenu),s=co(tt,e.__scopeMenu),i=a.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=s,f={__scopeMenu:e.__scopeMenu},u=a.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return a.useEffect(()=>u,[u]),a.useEffect(()=>{const d=c.current;return()=>{window.clearTimeout(d),l(null)}},[c,l]),p.jsx(io,{asChild:!0,...f,children:p.jsx(xs,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":r.contentId,"data-state":Os(n.open),...e,ref:lt(t,r.onTriggerChange),onClick:d=>{e.onClick?.(d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:S(e.onPointerMove,at(d=>{s.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:S(e.onPointerLeave,at(d=>{u();const m=n.content?.getBoundingClientRect();if(m){const h=n.content?.dataset.side,g=h==="right",v=g?-5:5,x=m[g?"left":"right"],w=m[g?"right":"left"];s.onPointerGraceIntentChange({area:[{x:d.clientX+v,y:d.clientY},{x,y:m.top},{x:w,y:m.top},{x:w,y:m.bottom},{x,y:m.bottom}],side:h}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(d),d.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:S(e.onKeyDown,d=>{const m=s.searchRef.current!=="";e.disabled||m&&d.key===" "||id[o.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});As.displayName=tt;var Is="MenuSubContent",Ns=a.forwardRef((e,t)=>{const n=ms(le,e.__scopeMenu),{forceMount:o=n.forceMount,...r}=e,s=Ne(le,e.__scopeMenu),i=wt(le,e.__scopeMenu),c=Ts(Is,e.__scopeMenu),l=a.useRef(null),f=L(t,l);return p.jsx(it.Provider,{scope:e.__scopeMenu,children:p.jsx(q,{present:o||s.open,children:p.jsx(it.Slot,{scope:e.__scopeMenu,children:p.jsx(lo,{id:c.contentId,"aria-labelledby":c.triggerId,...r,ref:f,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{i.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:S(e.onFocusOutside,u=>{u.target!==c.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:S(e.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:S(e.onKeyDown,u=>{const d=u.currentTarget.contains(u.target),m=ad[i.dir].includes(u.key);d&&m&&(s.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});Ns.displayName=Is;function Os(e){return e?"open":"closed"}function It(e){return e==="indeterminate"}function mo(e){return It(e)?"indeterminate":e?"checked":"unchecked"}function Ed(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function _d(e,t){return e.map((n,o)=>e[(t+o)%e.length])}function Td(e,t,n){const r=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=_d(e,Math.max(s,0));r.length===1&&(i=i.filter(f=>f!==n));const l=i.find(f=>f.toLowerCase().startsWith(r.toLowerCase()));return l!==n?l:void 0}function Md(e,t){const{x:n,y:o}=e;let r=!1;for(let s=0,i=t.length-1;so!=m>o&&n<(d-f)*(o-u)/(m-u)+f&&(r=!r)}return r}function Ad(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Md(n,t)}function at(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Ds=ps,js=io,Ls=hs,ks=vs,$s=uo,Fs=gs,Bs=on,Vs=ws,Hs=bs,Ws=Ss,Gs=Rs,Us=Es,Ks=_s,Id=Ms,zs=As,Ys=Ns,ho="ContextMenu",[Nd]=Z(ho,[nn]),Q=nn(),[Od,Xs]=Nd(ho),qs=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:o,dir:r,modal:s=!0}=e,[i,c]=a.useState(!1),l=Q(t),f=z(o),u=a.useCallback(d=>{c(d),f(d)},[f]);return p.jsx(Od,{scope:t,open:i,onOpenChange:u,modal:s,children:p.jsx(Ds,{...l,dir:r,open:i,onOpenChange:u,modal:s,children:n})})};qs.displayName=ho;var Zs="ContextMenuTrigger",Js=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:o=!1,...r}=e,s=Xs(Zs,n),i=Q(n),c=a.useRef({x:0,y:0}),l=a.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...c.current})}),f=a.useRef(0),u=a.useCallback(()=>window.clearTimeout(f.current),[]),d=m=>{c.current={x:m.clientX,y:m.clientY},s.onOpenChange(!0)};return a.useEffect(()=>u,[u]),a.useEffect(()=>void(o&&u()),[o,u]),p.jsxs(p.Fragment,{children:[p.jsx(js,{...i,virtualRef:l}),p.jsx(_.span,{"data-state":s.open?"open":"closed","data-disabled":o?"":void 0,...r,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:o?e.onContextMenu:S(e.onContextMenu,m=>{u(),d(m),m.preventDefault()}),onPointerDown:o?e.onPointerDown:S(e.onPointerDown,Pt(m=>{u(),f.current=window.setTimeout(()=>d(m),700)})),onPointerMove:o?e.onPointerMove:S(e.onPointerMove,Pt(u)),onPointerCancel:o?e.onPointerCancel:S(e.onPointerCancel,Pt(u)),onPointerUp:o?e.onPointerUp:S(e.onPointerUp,Pt(u))})]})});Js.displayName=Zs;var Dd="ContextMenuPortal",Qs=e=>{const{__scopeContextMenu:t,...n}=e,o=Q(t);return p.jsx(Ls,{...o,...n})};Qs.displayName=Dd;var ei="ContextMenuContent",ti=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Xs(ei,n),s=Q(n),i=a.useRef(!1);return p.jsx(ks,{...s,...o,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:c=>{e.onCloseAutoFocus?.(c),!c.defaultPrevented&&i.current&&c.preventDefault(),i.current=!1},onInteractOutside:c=>{e.onInteractOutside?.(c),!c.defaultPrevented&&!r.modal&&(i.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ti.displayName=ei;var jd="ContextMenuGroup",Ld=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx($s,{...r,...o,ref:t})});Ld.displayName=jd;var kd="ContextMenuLabel",ni=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Fs,{...r,...o,ref:t})});ni.displayName=kd;var $d="ContextMenuItem",oi=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Bs,{...r,...o,ref:t})});oi.displayName=$d;var Fd="ContextMenuCheckboxItem",ri=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Vs,{...r,...o,ref:t})});ri.displayName=Fd;var Bd="ContextMenuRadioGroup",Vd=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Hs,{...r,...o,ref:t})});Vd.displayName=Bd;var Hd="ContextMenuRadioItem",si=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Ws,{...r,...o,ref:t})});si.displayName=Hd;var Wd="ContextMenuItemIndicator",ii=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Gs,{...r,...o,ref:t})});ii.displayName=Wd;var Gd="ContextMenuSeparator",ai=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Us,{...r,...o,ref:t})});ai.displayName=Gd;var Ud="ContextMenuArrow",Kd=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Ks,{...r,...o,ref:t})});Kd.displayName=Ud;var ci="ContextMenuSub",li=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:o,open:r,defaultOpen:s}=e,i=Q(t),[c,l]=J({prop:r,defaultProp:s??!1,onChange:o,caller:ci});return p.jsx(Id,{...i,open:c,onOpenChange:l,children:n})};li.displayName=ci;var zd="ContextMenuSubTrigger",ui=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(zs,{...r,...o,ref:t})});ui.displayName=zd;var Yd="ContextMenuSubContent",di=a.forwardRef((e,t)=>{const{__scopeContextMenu:n,...o}=e,r=Q(n);return p.jsx(Ys,{...r,...o,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});di.displayName=Yd;function Pt(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var sm=qs,im=Js,am=Qs,cm=ti,lm=ni,um=oi,dm=ri,fm=si,pm=ii,mm=ai,hm=li,vm=ui,gm=di,rn="Dialog",[fi]=Z(rn),[Xd,he]=fi(rn),pi=e=>{const{__scopeDialog:t,children:n,open:o,defaultOpen:r,onOpenChange:s,modal:i=!0}=e,c=a.useRef(null),l=a.useRef(null),[f,u]=J({prop:o,defaultProp:r??!1,onChange:s,caller:rn});return p.jsx(Xd,{scope:t,triggerRef:c,contentRef:l,contentId:ne(),titleId:ne(),descriptionId:ne(),open:f,onOpenChange:u,onOpenToggle:a.useCallback(()=>u(d=>!d),[u]),modal:i,children:n})};pi.displayName=rn;var mi="DialogTrigger",qd=a.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=he(mi,n),s=L(t,r.triggerRef);return p.jsx(_.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":xo(r.open),...o,ref:s,onClick:S(e.onClick,r.onOpenToggle)})});qd.displayName=mi;var vo="DialogPortal",[Zd,hi]=fi(vo,{forceMount:void 0}),vi=e=>{const{__scopeDialog:t,forceMount:n,children:o,container:r}=e,s=he(vo,t);return p.jsx(Zd,{scope:t,forceMount:n,children:a.Children.map(o,i=>p.jsx(q,{present:n||s.open,children:p.jsx(mt,{asChild:!0,container:r,children:i})}))})};vi.displayName=vo;var Nt="DialogOverlay",gi=a.forwardRef((e,t)=>{const n=hi(Nt,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,s=he(Nt,e.__scopeDialog);return s.modal?p.jsx(q,{present:o||s.open,children:p.jsx(Qd,{...r,ref:t})}):null});gi.displayName=Nt;var Jd=_e("DialogOverlay.RemoveScroll"),Qd=a.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=he(Nt,n);return p.jsx(Bt,{as:Jd,allowPinchZoom:!0,shards:[r.contentRef],children:p.jsx(_.div,{"data-state":xo(r.open),...o,ref:t,style:{pointerEvents:"auto",...o.style}})})}),$e="DialogContent",xi=a.forwardRef((e,t)=>{const n=hi($e,e.__scopeDialog),{forceMount:o=n.forceMount,...r}=e,s=he($e,e.__scopeDialog);return p.jsx(q,{present:o||s.open,children:s.modal?p.jsx(ef,{...r,ref:t}):p.jsx(tf,{...r,ref:t})})});xi.displayName=$e;var ef=a.forwardRef((e,t)=>{const n=he($e,e.__scopeDialog),o=a.useRef(null),r=L(t,n.contentRef,o);return a.useEffect(()=>{const s=o.current;if(s)return Zt(s)},[]),p.jsx(wi,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:S(e.onCloseAutoFocus,s=>{s.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:S(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&s.preventDefault()}),onFocusOutside:S(e.onFocusOutside,s=>s.preventDefault())})}),tf=a.forwardRef((e,t)=>{const n=he($e,e.__scopeDialog),o=a.useRef(!1),r=a.useRef(!1);return p.jsx(wi,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(o.current||n.triggerRef.current?.focus(),s.preventDefault()),o.current=!1,r.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(o.current=!0,s.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const i=s.target;n.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&r.current&&s.preventDefault()}})}),wi=a.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:o,onOpenAutoFocus:r,onCloseAutoFocus:s,...i}=e,c=he($e,n),l=a.useRef(null),f=L(t,l);return Gt(),p.jsxs(p.Fragment,{children:[p.jsx(ut,{asChild:!0,loop:!0,trapped:o,onMountAutoFocus:r,onUnmountAutoFocus:s,children:p.jsx(Xe,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":xo(c.open),...i,ref:f,onDismiss:()=>c.onOpenChange(!1)})}),p.jsxs(p.Fragment,{children:[p.jsx(nf,{titleId:c.titleId}),p.jsx(rf,{contentRef:l,descriptionId:c.descriptionId})]})]})}),go="DialogTitle",Ci=a.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=he(go,n);return p.jsx(_.h2,{id:r.titleId,...o,ref:t})});Ci.displayName=go;var bi="DialogDescription",yi=a.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=he(bi,n);return p.jsx(_.p,{id:r.descriptionId,...o,ref:t})});yi.displayName=bi;var Si="DialogClose",Pi=a.forwardRef((e,t)=>{const{__scopeDialog:n,...o}=e,r=he(Si,n);return p.jsx(_.button,{type:"button",...o,ref:t,onClick:S(e.onClick,()=>r.onOpenChange(!1))})});Pi.displayName=Si;function xo(e){return e?"open":"closed"}var Ri="DialogTitleWarning",[xm,Ei]=gc(Ri,{contentName:$e,titleName:go,docsSlug:"dialog"}),nf=({titleId:e})=>{const t=Ei(Ri),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return a.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},of="DialogDescriptionWarning",rf=({contentRef:e,descriptionId:t})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Ei(of).contentName}}.`;return a.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(o))},[o,e,t]),null},wm=pi,Cm=vi,bm=gi,ym=xi,Sm=Ci,Pm=yi,Rm=Pi,sn="DropdownMenu",[sf]=Z(sn,[nn]),oe=nn(),[af,_i]=sf(sn),Ti=e=>{const{__scopeDropdownMenu:t,children:n,dir:o,open:r,defaultOpen:s,onOpenChange:i,modal:c=!0}=e,l=oe(t),f=a.useRef(null),[u,d]=J({prop:r,defaultProp:s??!1,onChange:i,caller:sn});return p.jsx(af,{scope:t,triggerId:ne(),triggerRef:f,contentId:ne(),open:u,onOpenChange:d,onOpenToggle:a.useCallback(()=>d(m=>!m),[d]),modal:c,children:p.jsx(Ds,{...l,open:u,onOpenChange:d,dir:o,modal:c,children:n})})};Ti.displayName=sn;var Mi="DropdownMenuTrigger",Ai=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:o=!1,...r}=e,s=_i(Mi,n),i=oe(n);return p.jsx(js,{asChild:!0,...i,children:p.jsx(_.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":o?"":void 0,disabled:o,...r,ref:lt(t,s.triggerRef),onPointerDown:S(e.onPointerDown,c=>{!o&&c.button===0&&c.ctrlKey===!1&&(s.onOpenToggle(),s.open||c.preventDefault())}),onKeyDown:S(e.onKeyDown,c=>{o||(["Enter"," "].includes(c.key)&&s.onOpenToggle(),c.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});Ai.displayName=Mi;var cf="DropdownMenuPortal",Ii=e=>{const{__scopeDropdownMenu:t,...n}=e,o=oe(t);return p.jsx(Ls,{...o,...n})};Ii.displayName=cf;var Ni="DropdownMenuContent",Oi=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=_i(Ni,n),s=oe(n),i=a.useRef(!1);return p.jsx(ks,{id:r.contentId,"aria-labelledby":r.triggerId,...s,...o,ref:t,onCloseAutoFocus:S(e.onCloseAutoFocus,c=>{i.current||r.triggerRef.current?.focus(),i.current=!1,c.preventDefault()}),onInteractOutside:S(e.onInteractOutside,c=>{const l=c.detail.originalEvent,f=l.button===0&&l.ctrlKey===!0,u=l.button===2||f;(!r.modal||u)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Oi.displayName=Ni;var lf="DropdownMenuGroup",uf=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx($s,{...r,...o,ref:t})});uf.displayName=lf;var df="DropdownMenuLabel",Di=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Fs,{...r,...o,ref:t})});Di.displayName=df;var ff="DropdownMenuItem",ji=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Bs,{...r,...o,ref:t})});ji.displayName=ff;var pf="DropdownMenuCheckboxItem",Li=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Vs,{...r,...o,ref:t})});Li.displayName=pf;var mf="DropdownMenuRadioGroup",hf=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Hs,{...r,...o,ref:t})});hf.displayName=mf;var vf="DropdownMenuRadioItem",ki=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Ws,{...r,...o,ref:t})});ki.displayName=vf;var gf="DropdownMenuItemIndicator",$i=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Gs,{...r,...o,ref:t})});$i.displayName=gf;var xf="DropdownMenuSeparator",Fi=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Us,{...r,...o,ref:t})});Fi.displayName=xf;var wf="DropdownMenuArrow",Cf=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Ks,{...r,...o,ref:t})});Cf.displayName=wf;var bf="DropdownMenuSubTrigger",Bi=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(zs,{...r,...o,ref:t})});Bi.displayName=bf;var yf="DropdownMenuSubContent",Vi=a.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...o}=e,r=oe(n);return p.jsx(Ys,{...r,...o,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Vi.displayName=yf;var Em=Ti,_m=Ai,Tm=Ii,Mm=Oi,Am=Di,Im=ji,Nm=Li,Om=ki,Dm=$i,jm=Fi,Lm=Bi,km=Vi,Sf=Symbol.for("react.lazy"),Ot=Wn[" use ".trim().toString()];function Pf(e){return typeof e=="object"&&e!==null&&"then"in e}function Hi(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Sf&&"_payload"in e&&Pf(e._payload)}function Rf(e){const t=Ef(e),n=a.forwardRef((o,r)=>{let{children:s,...i}=o;Hi(s)&&typeof Ot=="function"&&(s=Ot(s._payload));const c=a.Children.toArray(s),l=c.find(Tf);if(l){const f=l.props.children,u=c.map(d=>d===l?a.Children.count(f)>1?a.Children.only(null):a.isValidElement(f)?f.props.children:null:d);return p.jsx(t,{...i,ref:r,children:a.isValidElement(f)?a.cloneElement(f,void 0,u):null})}return p.jsx(t,{...i,ref:r,children:s})});return n.displayName=`${e}.Slot`,n}function Ef(e){const t=a.forwardRef((n,o)=>{let{children:r,...s}=n;if(Hi(r)&&typeof Ot=="function"&&(r=Ot(r._payload)),a.isValidElement(r)){const i=Af(r),c=Mf(s,r.props);return r.type!==a.Fragment&&(c.ref=o?lt(o,i):i),a.cloneElement(r,c)}return a.Children.count(r)>1?a.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var _f=Symbol("radix.slottable");function Tf(e){return a.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===_f}function Mf(e,t){const n={...t};for(const o in t){const r=e[o],s=t[o];/^on[A-Z]/.test(o)?r&&s?n[o]=(...c)=>{const l=s(...c);return r(...c),l}:r&&(n[o]=r):o==="style"?n[o]={...r,...s}:o==="className"&&(n[o]=[r,s].filter(Boolean).join(" "))}return{...e,...n}}function Af(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var If=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],wo=If.reduce((e,t)=>{const n=Rf(`Primitive.${t}`),o=a.forwardRef((r,s)=>{const{asChild:i,...c}=r,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,{...c,ref:s})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{}),Nf="Label",Wi=a.forwardRef((e,t)=>p.jsx(wo.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Wi.displayName=Nf;var $m=Wi;function Of(e,t=[]){let n=[];function o(s,i){const c=a.createContext(i);c.displayName=s+"Context";const l=n.length;n=[...n,i];const f=d=>{const{scope:m,children:h,...g}=d,v=m?.[e]?.[l]||c,x=a.useMemo(()=>g,Object.values(g));return p.jsx(v.Provider,{value:x,children:h})};f.displayName=s+"Provider";function u(d,m){const h=m?.[e]?.[l]||c,g=a.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${s}\``)}return[f,u]}const r=()=>{const s=n.map(i=>a.createContext(i));return function(c){const l=c?.[e]||s;return a.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return r.scopeName=e,[o,Df(r,...t)]}function Df(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const o=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(s){const i=o.reduce((c,{useScope:l,scopeName:f})=>{const d=l(s)[`__scope${f}`];return{...c,...d}},{});return a.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Co="Progress",bo=100,[jf]=Of(Co),[Lf,kf]=jf(Co),Gi=a.forwardRef((e,t)=>{const{__scopeProgress:n,value:o=null,max:r,getValueLabel:s=$f,...i}=e;(r||r===0)&&!qo(r)&&console.error(Ff(`${r}`,"Progress"));const c=qo(r)?r:bo;o!==null&&!Zo(o,c)&&console.error(Bf(`${o}`,"Progress"));const l=Zo(o,c)?o:null,f=Dt(l)?s(l,c):void 0;return p.jsx(Lf,{scope:n,value:l,max:c,children:p.jsx(wo.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":Dt(l)?l:void 0,"aria-valuetext":f,role:"progressbar","data-state":zi(l,c),"data-value":l??void 0,"data-max":c,...i,ref:t})})});Gi.displayName=Co;var Ui="ProgressIndicator",Ki=a.forwardRef((e,t)=>{const{__scopeProgress:n,...o}=e,r=kf(Ui,n);return p.jsx(wo.div,{"data-state":zi(r.value,r.max),"data-value":r.value??void 0,"data-max":r.max,...o,ref:t})});Ki.displayName=Ui;function $f(e,t){return`${Math.round(e/t*100)}%`}function zi(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function Dt(e){return typeof e=="number"}function qo(e){return Dt(e)&&!isNaN(e)&&e>0}function Zo(e,t){return Dt(e)&&!isNaN(e)&&e<=t&&e>=0}function Ff(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${bo}\`.`}function Bf(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${bo} if no \`max\` prop is set) + - \`null\` or \`undefined\` if the progress is indeterminate. + +Defaulting to \`null\`.`}var Fm=Gi,Bm=Ki,Yi=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Vf="VisuallyHidden",Xi=a.forwardRef((e,t)=>p.jsx(_.span,{...e,ref:t,style:{...Yi,...e.style}}));Xi.displayName=Vf;var Hf=Xi,Wf=[" ","Enter","ArrowUp","ArrowDown"],Gf=[" ","Enter"],Fe="Select",[an,cn,Uf]=Qt(Fe),[et]=Z(Fe,[Uf,Ae]),ln=Ae(),[Kf,Oe]=et(Fe),[zf,Yf]=et(Fe),qi=e=>{const{__scopeSelect:t,children:n,open:o,defaultOpen:r,onOpenChange:s,value:i,defaultValue:c,onValueChange:l,dir:f,name:u,autoComplete:d,disabled:m,required:h,form:g}=e,v=ln(t),[x,w]=a.useState(null),[C,b]=a.useState(null),[y,P]=a.useState(!1),A=Ve(f),[R,I]=J({prop:o,defaultProp:r??!1,onChange:s,caller:Fe}),[O,N]=J({prop:i,defaultProp:c,onChange:l,caller:Fe}),D=a.useRef(null),k=x?g||!!x.closest("form"):!0,[B,$]=a.useState(new Set),V=Array.from(B).map(j=>j.props.value).join(";");return p.jsx(ft,{...v,children:p.jsxs(Kf,{required:h,scope:t,trigger:x,onTriggerChange:w,valueNode:C,onValueNodeChange:b,valueNodeHasChildren:y,onValueNodeHasChildrenChange:P,contentId:ne(),value:O,onValueChange:N,open:R,onOpenChange:I,dir:A,triggerPointerDownPosRef:D,disabled:m,children:[p.jsx(an.Provider,{scope:t,children:p.jsx(zf,{scope:e.__scopeSelect,onNativeOptionAdd:a.useCallback(j=>{$(F=>new Set(F).add(j))},[]),onNativeOptionRemove:a.useCallback(j=>{$(F=>{const M=new Set(F);return M.delete(j),M})},[]),children:n})}),k?p.jsxs(ba,{"aria-hidden":!0,required:h,tabIndex:-1,name:u,autoComplete:d,value:O,onChange:j=>N(j.target.value),disabled:m,form:g,children:[O===void 0?p.jsx("option",{value:""}):null,Array.from(B)]},V):null]})})};qi.displayName=Fe;var Zi="SelectTrigger",Ji=a.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:o=!1,...r}=e,s=ln(n),i=Oe(Zi,n),c=i.disabled||o,l=L(t,i.onTriggerChange),f=cn(n),u=a.useRef("touch"),[d,m,h]=Sa(v=>{const x=f().filter(b=>!b.disabled),w=x.find(b=>b.value===i.value),C=Pa(x,v,w);C!==void 0&&i.onValueChange(C.value)}),g=v=>{c||(i.onOpenChange(!0),h()),v&&(i.triggerPointerDownPosRef.current={x:Math.round(v.pageX),y:Math.round(v.pageY)})};return p.jsx(pt,{asChild:!0,...s,children:p.jsx(_.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":ya(i.value)?"":void 0,...r,ref:l,onClick:S(r.onClick,v=>{v.currentTarget.focus(),u.current!=="mouse"&&g(v)}),onPointerDown:S(r.onPointerDown,v=>{u.current=v.pointerType;const x=v.target;x.hasPointerCapture(v.pointerId)&&x.releasePointerCapture(v.pointerId),v.button===0&&v.ctrlKey===!1&&v.pointerType==="mouse"&&(g(v),v.preventDefault())}),onKeyDown:S(r.onKeyDown,v=>{const x=d.current!=="";!(v.ctrlKey||v.altKey||v.metaKey)&&v.key.length===1&&m(v.key),!(x&&v.key===" ")&&Wf.includes(v.key)&&(g(),v.preventDefault())})})})});Ji.displayName=Zi;var Qi="SelectValue",ea=a.forwardRef((e,t)=>{const{__scopeSelect:n,className:o,style:r,children:s,placeholder:i="",...c}=e,l=Oe(Qi,n),{onValueNodeHasChildrenChange:f}=l,u=s!==void 0,d=L(t,l.onValueNodeChange);return X(()=>{f(u)},[f,u]),p.jsx(_.span,{...c,ref:d,style:{pointerEvents:"none"},children:ya(l.value)?p.jsx(p.Fragment,{children:i}):s})});ea.displayName=Qi;var Xf="SelectIcon",ta=a.forwardRef((e,t)=>{const{__scopeSelect:n,children:o,...r}=e;return p.jsx(_.span,{"aria-hidden":!0,...r,ref:t,children:o||"▼"})});ta.displayName=Xf;var qf="SelectPortal",na=e=>p.jsx(mt,{asChild:!0,...e});na.displayName=qf;var Be="SelectContent",oa=a.forwardRef((e,t)=>{const n=Oe(Be,e.__scopeSelect),[o,r]=a.useState();if(X(()=>{r(new DocumentFragment)},[]),!n.open){const s=o;return s?Ft.createPortal(p.jsx(ra,{scope:e.__scopeSelect,children:p.jsx(an.Slot,{scope:e.__scopeSelect,children:p.jsx("div",{children:e.children})})}),s):null}return p.jsx(sa,{...e,ref:t})});oa.displayName=Be;var fe=10,[ra,De]=et(Be),Zf="SelectContentImpl",Jf=_e("SelectContent.RemoveScroll"),sa=a.forwardRef((e,t)=>{const{__scopeSelect:n,position:o="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:i,side:c,sideOffset:l,align:f,alignOffset:u,arrowPadding:d,collisionBoundary:m,collisionPadding:h,sticky:g,hideWhenDetached:v,avoidCollisions:x,...w}=e,C=Oe(Be,n),[b,y]=a.useState(null),[P,A]=a.useState(null),R=L(t,T=>y(T)),[I,O]=a.useState(null),[N,D]=a.useState(null),k=cn(n),[B,$]=a.useState(!1),V=a.useRef(!1);a.useEffect(()=>{if(b)return Zt(b)},[b]),Gt();const j=a.useCallback(T=>{const[H,...te]=k().map(K=>K.ref.current),[W]=te.slice(-1),G=document.activeElement;for(const K of T)if(K===G||(K?.scrollIntoView({block:"nearest"}),K===H&&P&&(P.scrollTop=0),K===W&&P&&(P.scrollTop=P.scrollHeight),K?.focus(),document.activeElement!==G))return},[k,P]),F=a.useCallback(()=>j([I,b]),[j,I,b]);a.useEffect(()=>{B&&F()},[B,F]);const{onOpenChange:M,triggerPointerDownPosRef:E}=C;a.useEffect(()=>{if(b){let T={x:0,y:0};const H=W=>{T={x:Math.abs(Math.round(W.pageX)-(E.current?.x??0)),y:Math.abs(Math.round(W.pageY)-(E.current?.y??0))}},te=W=>{T.x<=10&&T.y<=10?W.preventDefault():b.contains(W.target)||M(!1),document.removeEventListener("pointermove",H),E.current=null};return E.current!==null&&(document.addEventListener("pointermove",H),document.addEventListener("pointerup",te,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",H),document.removeEventListener("pointerup",te,{capture:!0})}}},[b,M,E]),a.useEffect(()=>{const T=()=>M(!1);return window.addEventListener("blur",T),window.addEventListener("resize",T),()=>{window.removeEventListener("blur",T),window.removeEventListener("resize",T)}},[M]);const[U,ee]=Sa(T=>{const H=k().filter(G=>!G.disabled),te=H.find(G=>G.ref.current===document.activeElement),W=Pa(H,T,te);W&&setTimeout(()=>W.ref.current.focus())}),de=a.useCallback((T,H,te)=>{const W=!V.current&&!te;(C.value!==void 0&&C.value===H||W)&&(O(T),W&&(V.current=!0))},[C.value]),be=a.useCallback(()=>b?.focus(),[b]),ae=a.useCallback((T,H,te)=>{const W=!V.current&&!te;(C.value!==void 0&&C.value===H||W)&&D(T)},[C.value]),ye=o==="popper"?Ln:ia,re=ye===Ln?{side:c,sideOffset:l,align:f,alignOffset:u,arrowPadding:d,collisionBoundary:m,collisionPadding:h,sticky:g,hideWhenDetached:v,avoidCollisions:x}:{};return p.jsx(ra,{scope:n,content:b,viewport:P,onViewportChange:A,itemRefCallback:de,selectedItem:I,onItemLeave:be,itemTextRefCallback:ae,focusSelectedItem:F,selectedItemText:N,position:o,isPositioned:B,searchRef:U,children:p.jsx(Bt,{as:Jf,allowPinchZoom:!0,children:p.jsx(ut,{asChild:!0,trapped:C.open,onMountAutoFocus:T=>{T.preventDefault()},onUnmountAutoFocus:S(r,T=>{C.trigger?.focus({preventScroll:!0}),T.preventDefault()}),children:p.jsx(Xe,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:T=>T.preventDefault(),onDismiss:()=>C.onOpenChange(!1),children:p.jsx(ye,{role:"listbox",id:C.contentId,"data-state":C.open?"open":"closed",dir:C.dir,onContextMenu:T=>T.preventDefault(),...w,...re,onPlaced:()=>$(!0),ref:R,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:S(w.onKeyDown,T=>{const H=T.ctrlKey||T.altKey||T.metaKey;if(T.key==="Tab"&&T.preventDefault(),!H&&T.key.length===1&&ee(T.key),["ArrowUp","ArrowDown","Home","End"].includes(T.key)){let W=k().filter(G=>!G.disabled).map(G=>G.ref.current);if(["ArrowUp","End"].includes(T.key)&&(W=W.slice().reverse()),["ArrowUp","ArrowDown"].includes(T.key)){const G=T.target,K=W.indexOf(G);W=W.slice(K+1)}setTimeout(()=>j(W)),T.preventDefault()}})})})})})})});sa.displayName=Zf;var Qf="SelectItemAlignedPosition",ia=a.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:o,...r}=e,s=Oe(Be,n),i=De(Be,n),[c,l]=a.useState(null),[f,u]=a.useState(null),d=L(t,R=>u(R)),m=cn(n),h=a.useRef(!1),g=a.useRef(!0),{viewport:v,selectedItem:x,selectedItemText:w,focusSelectedItem:C}=i,b=a.useCallback(()=>{if(s.trigger&&s.valueNode&&c&&f&&v&&x&&w){const R=s.trigger.getBoundingClientRect(),I=f.getBoundingClientRect(),O=s.valueNode.getBoundingClientRect(),N=w.getBoundingClientRect();if(s.dir!=="rtl"){const G=N.left-I.left,K=O.left-G,ce=R.left-K,Le=R.width+ce,gn=Math.max(Le,I.width),xn=window.innerWidth-fe,wn=st(K,[fe,Math.max(fe,xn-gn)]);c.style.minWidth=Le+"px",c.style.left=wn+"px"}else{const G=I.right-N.right,K=window.innerWidth-O.right-G,ce=window.innerWidth-R.right-K,Le=R.width+ce,gn=Math.max(Le,I.width),xn=window.innerWidth-fe,wn=st(K,[fe,Math.max(fe,xn-gn)]);c.style.minWidth=Le+"px",c.style.right=wn+"px"}const D=m(),k=window.innerHeight-fe*2,B=v.scrollHeight,$=window.getComputedStyle(f),V=parseInt($.borderTopWidth,10),j=parseInt($.paddingTop,10),F=parseInt($.borderBottomWidth,10),M=parseInt($.paddingBottom,10),E=V+j+B+M+F,U=Math.min(x.offsetHeight*5,E),ee=window.getComputedStyle(v),de=parseInt(ee.paddingTop,10),be=parseInt(ee.paddingBottom,10),ae=R.top+R.height/2-fe,ye=k-ae,re=x.offsetHeight/2,T=x.offsetTop+re,H=V+j+T,te=E-H;if(H<=ae){const G=D.length>0&&x===D[D.length-1].ref.current;c.style.bottom="0px";const K=f.clientHeight-v.offsetTop-v.offsetHeight,ce=Math.max(ye,re+(G?be:0)+K+F),Le=H+ce;c.style.height=Le+"px"}else{const G=D.length>0&&x===D[0].ref.current;c.style.top="0px";const ce=Math.max(ae,V+v.offsetTop+(G?de:0)+re)+te;c.style.height=ce+"px",v.scrollTop=H-ae+v.offsetTop}c.style.margin=`${fe}px 0`,c.style.minHeight=U+"px",c.style.maxHeight=k+"px",o?.(),requestAnimationFrame(()=>h.current=!0)}},[m,s.trigger,s.valueNode,c,f,v,x,w,s.dir,o]);X(()=>b(),[b]);const[y,P]=a.useState();X(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const A=a.useCallback(R=>{R&&g.current===!0&&(b(),C?.(),g.current=!1)},[b,C]);return p.jsx(tp,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:h,onScrollButtonChange:A,children:p.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:y},children:p.jsx(_.div,{...r,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});ia.displayName=Qf;var ep="SelectPopperPosition",Ln=a.forwardRef((e,t)=>{const{__scopeSelect:n,align:o="start",collisionPadding:r=fe,...s}=e,i=ln(n);return p.jsx(Xt,{...i,...s,ref:t,align:o,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ln.displayName=ep;var[tp,yo]=et(Be,{}),kn="SelectViewport",aa=a.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:o,...r}=e,s=De(kn,n),i=yo(kn,n),c=L(t,s.onViewportChange),l=a.useRef(0);return p.jsxs(p.Fragment,{children:[p.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),p.jsx(an.Slot,{scope:n,children:p.jsx(_.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:S(r.onScroll,f=>{const u=f.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:m}=i;if(m?.current&&d){const h=Math.abs(l.current-u.scrollTop);if(h>0){const g=window.innerHeight-fe*2,v=parseFloat(d.style.minHeight),x=parseFloat(d.style.height),w=Math.max(v,x);if(w0?y:0,d.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});aa.displayName=kn;var ca="SelectGroup",[np,op]=et(ca),la=a.forwardRef((e,t)=>{const{__scopeSelect:n,...o}=e,r=ne();return p.jsx(np,{scope:n,id:r,children:p.jsx(_.div,{role:"group","aria-labelledby":r,...o,ref:t})})});la.displayName=ca;var ua="SelectLabel",da=a.forwardRef((e,t)=>{const{__scopeSelect:n,...o}=e,r=op(ua,n);return p.jsx(_.div,{id:r.id,...o,ref:t})});da.displayName=ua;var jt="SelectItem",[rp,fa]=et(jt),pa=a.forwardRef((e,t)=>{const{__scopeSelect:n,value:o,disabled:r=!1,textValue:s,...i}=e,c=Oe(jt,n),l=De(jt,n),f=c.value===o,[u,d]=a.useState(s??""),[m,h]=a.useState(!1),g=L(t,C=>l.itemRefCallback?.(C,o,r)),v=ne(),x=a.useRef("touch"),w=()=>{r||(c.onValueChange(o),c.onOpenChange(!1))};if(o==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return p.jsx(rp,{scope:n,value:o,disabled:r,textId:v,isSelected:f,onItemTextChange:a.useCallback(C=>{d(b=>b||(C?.textContent??"").trim())},[]),children:p.jsx(an.ItemSlot,{scope:n,value:o,disabled:r,textValue:u,children:p.jsx(_.div,{role:"option","aria-labelledby":v,"data-highlighted":m?"":void 0,"aria-selected":f&&m,"data-state":f?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...i,ref:g,onFocus:S(i.onFocus,()=>h(!0)),onBlur:S(i.onBlur,()=>h(!1)),onClick:S(i.onClick,()=>{x.current!=="mouse"&&w()}),onPointerUp:S(i.onPointerUp,()=>{x.current==="mouse"&&w()}),onPointerDown:S(i.onPointerDown,C=>{x.current=C.pointerType}),onPointerMove:S(i.onPointerMove,C=>{x.current=C.pointerType,r?l.onItemLeave?.():x.current==="mouse"&&C.currentTarget.focus({preventScroll:!0})}),onPointerLeave:S(i.onPointerLeave,C=>{C.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:S(i.onKeyDown,C=>{l.searchRef?.current!==""&&C.key===" "||(Gf.includes(C.key)&&w(),C.key===" "&&C.preventDefault())})})})})});pa.displayName=jt;var nt="SelectItemText",ma=a.forwardRef((e,t)=>{const{__scopeSelect:n,className:o,style:r,...s}=e,i=Oe(nt,n),c=De(nt,n),l=fa(nt,n),f=Yf(nt,n),[u,d]=a.useState(null),m=L(t,w=>d(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),h=u?.textContent,g=a.useMemo(()=>p.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:v,onNativeOptionRemove:x}=f;return X(()=>(v(g),()=>x(g)),[v,x,g]),p.jsxs(p.Fragment,{children:[p.jsx(_.span,{id:l.textId,...s,ref:m}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Ft.createPortal(s.children,i.valueNode):null]})});ma.displayName=nt;var ha="SelectItemIndicator",va=a.forwardRef((e,t)=>{const{__scopeSelect:n,...o}=e;return fa(ha,n).isSelected?p.jsx(_.span,{"aria-hidden":!0,...o,ref:t}):null});va.displayName=ha;var $n="SelectScrollUpButton",ga=a.forwardRef((e,t)=>{const n=De($n,e.__scopeSelect),o=yo($n,e.__scopeSelect),[r,s]=a.useState(!1),i=L(t,o.onScrollButtonChange);return X(()=>{if(n.viewport&&n.isPositioned){let c=function(){const f=l.scrollTop>0;s(f)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),r?p.jsx(wa,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});ga.displayName=$n;var Fn="SelectScrollDownButton",xa=a.forwardRef((e,t)=>{const n=De(Fn,e.__scopeSelect),o=yo(Fn,e.__scopeSelect),[r,s]=a.useState(!1),i=L(t,o.onScrollButtonChange);return X(()=>{if(n.viewport&&n.isPositioned){let c=function(){const f=l.scrollHeight-l.clientHeight,u=Math.ceil(l.scrollTop)l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),r?p.jsx(wa,{...e,ref:i,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});xa.displayName=Fn;var wa=a.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:o,...r}=e,s=De("SelectScrollButton",n),i=a.useRef(null),c=cn(n),l=a.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return a.useEffect(()=>()=>l(),[l]),X(()=>{c().find(u=>u.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),p.jsx(_.div,{"aria-hidden":!0,...r,ref:t,style:{flexShrink:0,...r.style},onPointerDown:S(r.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(o,50))}),onPointerMove:S(r.onPointerMove,()=>{s.onItemLeave?.(),i.current===null&&(i.current=window.setInterval(o,50))}),onPointerLeave:S(r.onPointerLeave,()=>{l()})})}),sp="SelectSeparator",Ca=a.forwardRef((e,t)=>{const{__scopeSelect:n,...o}=e;return p.jsx(_.div,{"aria-hidden":!0,...o,ref:t})});Ca.displayName=sp;var Bn="SelectArrow",ip=a.forwardRef((e,t)=>{const{__scopeSelect:n,...o}=e,r=ln(n),s=Oe(Bn,n),i=De(Bn,n);return s.open&&i.position==="popper"?p.jsx(qt,{...r,...o,ref:t}):null});ip.displayName=Bn;var ap="SelectBubbleInput",ba=a.forwardRef(({__scopeSelect:e,value:t,...n},o)=>{const r=a.useRef(null),s=L(o,r),i=Vt(t);return a.useEffect(()=>{const c=r.current;if(!c)return;const l=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&u){const d=new Event("change",{bubbles:!0});u.call(c,t),c.dispatchEvent(d)}},[i,t]),p.jsx(_.select,{...n,style:{...Yi,...n.style},ref:s,defaultValue:t})});ba.displayName=ap;function ya(e){return e===""||e===void 0}function Sa(e){const t=z(e),n=a.useRef(""),o=a.useRef(0),r=a.useCallback(i=>{const c=n.current+i;t(c),function l(f){n.current=f,window.clearTimeout(o.current),f!==""&&(o.current=window.setTimeout(()=>l(""),1e3))}(c)},[t]),s=a.useCallback(()=>{n.current="",window.clearTimeout(o.current)},[]);return a.useEffect(()=>()=>window.clearTimeout(o.current),[]),[n,r,s]}function Pa(e,t,n){const r=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=cp(e,Math.max(s,0));r.length===1&&(i=i.filter(f=>f!==n));const l=i.find(f=>f.textValue.toLowerCase().startsWith(r.toLowerCase()));return l!==n?l:void 0}function cp(e,t){return e.map((n,o)=>e[(t+o)%e.length])}var Vm=qi,Hm=Ji,Wm=ea,Gm=ta,Um=na,Km=oa,zm=aa,Ym=la,Xm=da,qm=pa,Zm=ma,Jm=va,Qm=ga,eh=xa,th=Ca;function lp(e,t){return a.useReducer((n,o)=>t[n][o]??n,e)}var So="ScrollArea",[Ra]=Z(So),[up,ue]=Ra(So),Ea=a.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:o="hover",dir:r,scrollHideDelay:s=600,...i}=e,[c,l]=a.useState(null),[f,u]=a.useState(null),[d,m]=a.useState(null),[h,g]=a.useState(null),[v,x]=a.useState(null),[w,C]=a.useState(0),[b,y]=a.useState(0),[P,A]=a.useState(!1),[R,I]=a.useState(!1),O=L(t,D=>l(D)),N=Ve(r);return p.jsx(up,{scope:n,type:o,dir:N,scrollHideDelay:s,scrollArea:c,viewport:f,onViewportChange:u,content:d,onContentChange:m,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:P,onScrollbarXEnabledChange:A,scrollbarY:v,onScrollbarYChange:x,scrollbarYEnabled:R,onScrollbarYEnabledChange:I,onCornerWidthChange:C,onCornerHeightChange:y,children:p.jsx(_.div,{dir:N,...i,ref:O,style:{position:"relative","--radix-scroll-area-corner-width":w+"px","--radix-scroll-area-corner-height":b+"px",...e.style}})})});Ea.displayName=So;var _a="ScrollAreaViewport",Ta=a.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:o,nonce:r,...s}=e,i=ue(_a,n),c=a.useRef(null),l=L(t,c,i.onViewportChange);return p.jsxs(p.Fragment,{children:[p.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),p.jsx(_.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:p.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:o})})]})});Ta.displayName=_a;var Ce="ScrollAreaScrollbar",dp=a.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=ue(Ce,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=r,c=e.orientation==="horizontal";return a.useEffect(()=>(c?s(!0):i(!0),()=>{c?s(!1):i(!1)}),[c,s,i]),r.type==="hover"?p.jsx(fp,{...o,ref:t,forceMount:n}):r.type==="scroll"?p.jsx(pp,{...o,ref:t,forceMount:n}):r.type==="auto"?p.jsx(Ma,{...o,ref:t,forceMount:n}):r.type==="always"?p.jsx(Po,{...o,ref:t}):null});dp.displayName=Ce;var fp=a.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=ue(Ce,e.__scopeScrollArea),[s,i]=a.useState(!1);return a.useEffect(()=>{const c=r.scrollArea;let l=0;if(c){const f=()=>{window.clearTimeout(l),i(!0)},u=()=>{l=window.setTimeout(()=>i(!1),r.scrollHideDelay)};return c.addEventListener("pointerenter",f),c.addEventListener("pointerleave",u),()=>{window.clearTimeout(l),c.removeEventListener("pointerenter",f),c.removeEventListener("pointerleave",u)}}},[r.scrollArea,r.scrollHideDelay]),p.jsx(q,{present:n||s,children:p.jsx(Ma,{"data-state":s?"visible":"hidden",...o,ref:t})})}),pp=a.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=ue(Ce,e.__scopeScrollArea),s=e.orientation==="horizontal",i=dn(()=>l("SCROLL_END"),100),[c,l]=lp("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return a.useEffect(()=>{if(c==="idle"){const f=window.setTimeout(()=>l("HIDE"),r.scrollHideDelay);return()=>window.clearTimeout(f)}},[c,r.scrollHideDelay,l]),a.useEffect(()=>{const f=r.viewport,u=s?"scrollLeft":"scrollTop";if(f){let d=f[u];const m=()=>{const h=f[u];d!==h&&(l("SCROLL"),i()),d=h};return f.addEventListener("scroll",m),()=>f.removeEventListener("scroll",m)}},[r.viewport,s,l,i]),p.jsx(q,{present:n||c!=="hidden",children:p.jsx(Po,{"data-state":c==="hidden"?"hidden":"visible",...o,ref:t,onPointerEnter:S(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:S(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Ma=a.forwardRef((e,t)=>{const n=ue(Ce,e.__scopeScrollArea),{forceMount:o,...r}=e,[s,i]=a.useState(!1),c=e.orientation==="horizontal",l=dn(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...o}=e,r=ue(Ce,e.__scopeScrollArea),s=a.useRef(null),i=a.useRef(0),[c,l]=a.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=Oa(c.viewport,c.content),u={...o,sizes:c,onSizesChange:l,hasThumb:f>0&&f<1,onThumbChange:m=>s.current=m,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:m=>i.current=m};function d(m,h){return Cp(m,i.current,c,h)}return n==="horizontal"?p.jsx(mp,{...u,ref:t,onThumbPositionChange:()=>{if(r.viewport&&s.current){const m=r.viewport.scrollLeft,h=Jo(m,c,r.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:m=>{r.viewport&&(r.viewport.scrollLeft=m)},onDragScroll:m=>{r.viewport&&(r.viewport.scrollLeft=d(m,r.dir))}}):n==="vertical"?p.jsx(hp,{...u,ref:t,onThumbPositionChange:()=>{if(r.viewport&&s.current){const m=r.viewport.scrollTop,h=Jo(m,c);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:m=>{r.viewport&&(r.viewport.scrollTop=m)},onDragScroll:m=>{r.viewport&&(r.viewport.scrollTop=d(m))}}):null}),mp=a.forwardRef((e,t)=>{const{sizes:n,onSizesChange:o,...r}=e,s=ue(Ce,e.__scopeScrollArea),[i,c]=a.useState(),l=a.useRef(null),f=L(t,l,s.onScrollbarXChange);return a.useEffect(()=>{l.current&&c(getComputedStyle(l.current))},[l]),p.jsx(Ia,{"data-orientation":"horizontal",...r,ref:f,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":un(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.x),onDragScroll:u=>e.onDragScroll(u.x),onWheelScroll:(u,d)=>{if(s.viewport){const m=s.viewport.scrollLeft+u.deltaX;e.onWheelScroll(m),ja(m,d)&&u.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&o({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:kt(i.paddingLeft),paddingEnd:kt(i.paddingRight)}})}})}),hp=a.forwardRef((e,t)=>{const{sizes:n,onSizesChange:o,...r}=e,s=ue(Ce,e.__scopeScrollArea),[i,c]=a.useState(),l=a.useRef(null),f=L(t,l,s.onScrollbarYChange);return a.useEffect(()=>{l.current&&c(getComputedStyle(l.current))},[l]),p.jsx(Ia,{"data-orientation":"vertical",...r,ref:f,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":un(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.y),onDragScroll:u=>e.onDragScroll(u.y),onWheelScroll:(u,d)=>{if(s.viewport){const m=s.viewport.scrollTop+u.deltaY;e.onWheelScroll(m),ja(m,d)&&u.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&o({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:kt(i.paddingTop),paddingEnd:kt(i.paddingBottom)}})}})}),[vp,Aa]=Ra(Ce),Ia=a.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:o,hasThumb:r,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:c,onThumbPositionChange:l,onDragScroll:f,onWheelScroll:u,onResize:d,...m}=e,h=ue(Ce,n),[g,v]=a.useState(null),x=L(t,O=>v(O)),w=a.useRef(null),C=a.useRef(""),b=h.viewport,y=o.content-o.viewport,P=z(u),A=z(l),R=dn(d,10);function I(O){if(w.current){const N=O.clientX-w.current.left,D=O.clientY-w.current.top;f({x:N,y:D})}}return a.useEffect(()=>{const O=N=>{const D=N.target;g?.contains(D)&&P(N,y)};return document.addEventListener("wheel",O,{passive:!1}),()=>document.removeEventListener("wheel",O,{passive:!1})},[b,g,y,P]),a.useEffect(A,[o,A]),ze(g,R),ze(h.content,R),p.jsx(vp,{scope:n,scrollbar:g,hasThumb:r,onThumbChange:z(s),onThumbPointerUp:z(i),onThumbPositionChange:A,onThumbPointerDown:z(c),children:p.jsx(_.div,{...m,ref:x,style:{position:"absolute",...m.style},onPointerDown:S(e.onPointerDown,O=>{O.button===0&&(O.target.setPointerCapture(O.pointerId),w.current=g.getBoundingClientRect(),C.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),I(O))}),onPointerMove:S(e.onPointerMove,I),onPointerUp:S(e.onPointerUp,O=>{const N=O.target;N.hasPointerCapture(O.pointerId)&&N.releasePointerCapture(O.pointerId),document.body.style.webkitUserSelect=C.current,h.viewport&&(h.viewport.style.scrollBehavior=""),w.current=null})})})}),Lt="ScrollAreaThumb",gp=a.forwardRef((e,t)=>{const{forceMount:n,...o}=e,r=Aa(Lt,e.__scopeScrollArea);return p.jsx(q,{present:n||r.hasThumb,children:p.jsx(xp,{ref:t,...o})})}),xp=a.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:o,...r}=e,s=ue(Lt,n),i=Aa(Lt,n),{onThumbPositionChange:c}=i,l=L(t,d=>i.onThumbChange(d)),f=a.useRef(void 0),u=dn(()=>{f.current&&(f.current(),f.current=void 0)},100);return a.useEffect(()=>{const d=s.viewport;if(d){const m=()=>{if(u(),!f.current){const h=bp(d,c);f.current=h,c()}};return c(),d.addEventListener("scroll",m),()=>d.removeEventListener("scroll",m)}},[s.viewport,u,c]),p.jsx(_.div,{"data-state":i.hasThumb?"visible":"hidden",...r,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...o},onPointerDownCapture:S(e.onPointerDownCapture,d=>{const h=d.target.getBoundingClientRect(),g=d.clientX-h.left,v=d.clientY-h.top;i.onThumbPointerDown({x:g,y:v})}),onPointerUp:S(e.onPointerUp,i.onThumbPointerUp)})});gp.displayName=Lt;var Ro="ScrollAreaCorner",Na=a.forwardRef((e,t)=>{const n=ue(Ro,e.__scopeScrollArea),o=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&o?p.jsx(wp,{...e,ref:t}):null});Na.displayName=Ro;var wp=a.forwardRef((e,t)=>{const{__scopeScrollArea:n,...o}=e,r=ue(Ro,n),[s,i]=a.useState(0),[c,l]=a.useState(0),f=!!(s&&c);return ze(r.scrollbarX,()=>{const u=r.scrollbarX?.offsetHeight||0;r.onCornerHeightChange(u),l(u)}),ze(r.scrollbarY,()=>{const u=r.scrollbarY?.offsetWidth||0;r.onCornerWidthChange(u),i(u)}),f?p.jsx(_.div,{...o,ref:t,style:{width:s,height:c,position:"absolute",right:r.dir==="ltr"?0:void 0,left:r.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function kt(e){return e?parseInt(e,10):0}function Oa(e,t){const n=e/t;return isNaN(n)?0:n}function un(e){const t=Oa(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=(e.scrollbar.size-n)*t;return Math.max(o,18)}function Cp(e,t,n,o="ltr"){const r=un(n),s=r/2,i=t||s,c=r-i,l=n.scrollbar.paddingStart+i,f=n.scrollbar.size-n.scrollbar.paddingEnd-c,u=n.content-n.viewport,d=o==="ltr"?[0,u]:[u*-1,0];return Da([l,f],d)(e)}function Jo(e,t,n="ltr"){const o=un(t),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-r,i=t.content-t.viewport,c=s-o,l=n==="ltr"?[0,i]:[i*-1,0],f=st(e,l);return Da([0,i],[0,c])(f)}function Da(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const o=(t[1]-t[0])/(e[1]-e[0]);return t[0]+o*(n-e[0])}}function ja(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},o=0;return function r(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,c=n.top!==s.top;(i||c)&&t(),n=s,o=window.requestAnimationFrame(r)}(),()=>window.cancelAnimationFrame(o)};function dn(e,t){const n=z(e),o=a.useRef(0);return a.useEffect(()=>()=>window.clearTimeout(o.current),[]),a.useCallback(()=>{window.clearTimeout(o.current),o.current=window.setTimeout(n,t)},[n,t])}function ze(e,t){const n=z(t);X(()=>{let o=0;if(e){const r=new ResizeObserver(()=>{cancelAnimationFrame(o),o=window.requestAnimationFrame(n)});return r.observe(e),()=>{window.cancelAnimationFrame(o),r.unobserve(e)}}},[e,n])}var nh=Ea,oh=Ta,rh=Na,fn="Switch",[yp]=Z(fn),[Sp,Pp]=yp(fn),La=a.forwardRef((e,t)=>{const{__scopeSwitch:n,name:o,checked:r,defaultChecked:s,required:i,disabled:c,value:l="on",onCheckedChange:f,form:u,...d}=e,[m,h]=a.useState(null),g=L(t,b=>h(b)),v=a.useRef(!1),x=m?u||!!m.closest("form"):!0,[w,C]=J({prop:r,defaultProp:s??!1,onChange:f,caller:fn});return p.jsxs(Sp,{scope:n,checked:w,disabled:c,children:[p.jsx(_.button,{type:"button",role:"switch","aria-checked":w,"aria-required":i,"data-state":Ba(w),"data-disabled":c?"":void 0,disabled:c,value:l,...d,ref:g,onClick:S(e.onClick,b=>{C(y=>!y),x&&(v.current=b.isPropagationStopped(),v.current||b.stopPropagation())})}),x&&p.jsx(Fa,{control:m,bubbles:!v.current,name:o,value:l,checked:w,required:i,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});La.displayName=fn;var ka="SwitchThumb",$a=a.forwardRef((e,t)=>{const{__scopeSwitch:n,...o}=e,r=Pp(ka,n);return p.jsx(_.span,{"data-state":Ba(r.checked),"data-disabled":r.disabled?"":void 0,...o,ref:t})});$a.displayName=ka;var Rp="SwitchBubbleInput",Fa=a.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:o=!0,...r},s)=>{const i=a.useRef(null),c=L(i,s),l=Vt(n),f=Ht(t);return a.useEffect(()=>{const u=i.current;if(!u)return;const d=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(d,"checked").set;if(l!==n&&h){const g=new Event("click",{bubbles:o});h.call(u,n),u.dispatchEvent(g)}},[l,n,o]),p.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...r,tabIndex:-1,ref:c,style:{...r.style,...f,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Fa.displayName=Rp;function Ba(e){return e?"checked":"unchecked"}var sh=La,ih=$a,pn="Tabs",[Ep]=Z(pn,[Qe]),Va=Qe(),[_p,Eo]=Ep(pn),Ha=a.forwardRef((e,t)=>{const{__scopeTabs:n,value:o,onValueChange:r,defaultValue:s,orientation:i="horizontal",dir:c,activationMode:l="automatic",...f}=e,u=Ve(c),[d,m]=J({prop:o,onChange:r,defaultProp:s??"",caller:pn});return p.jsx(_p,{scope:n,baseId:ne(),value:d,onValueChange:m,orientation:i,dir:u,activationMode:l,children:p.jsx(_.div,{dir:u,"data-orientation":i,...f,ref:t})})});Ha.displayName=pn;var Wa="TabsList",Ga=a.forwardRef((e,t)=>{const{__scopeTabs:n,loop:o=!0,...r}=e,s=Eo(Wa,n),i=Va(n);return p.jsx(ro,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:o,children:p.jsx(_.div,{role:"tablist","aria-orientation":s.orientation,...r,ref:t})})});Ga.displayName=Wa;var Ua="TabsTrigger",Ka=a.forwardRef((e,t)=>{const{__scopeTabs:n,value:o,disabled:r=!1,...s}=e,i=Eo(Ua,n),c=Va(n),l=Xa(i.baseId,o),f=qa(i.baseId,o),u=o===i.value;return p.jsx(so,{asChild:!0,...c,focusable:!r,active:u,children:p.jsx(_.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":f,"data-state":u?"active":"inactive","data-disabled":r?"":void 0,disabled:r,id:l,...s,ref:t,onMouseDown:S(e.onMouseDown,d=>{!r&&d.button===0&&d.ctrlKey===!1?i.onValueChange(o):d.preventDefault()}),onKeyDown:S(e.onKeyDown,d=>{[" ","Enter"].includes(d.key)&&i.onValueChange(o)}),onFocus:S(e.onFocus,()=>{const d=i.activationMode!=="manual";!u&&!r&&d&&i.onValueChange(o)})})})});Ka.displayName=Ua;var za="TabsContent",Ya=a.forwardRef((e,t)=>{const{__scopeTabs:n,value:o,forceMount:r,children:s,...i}=e,c=Eo(za,n),l=Xa(c.baseId,o),f=qa(c.baseId,o),u=o===c.value,d=a.useRef(u);return a.useEffect(()=>{const m=requestAnimationFrame(()=>d.current=!1);return()=>cancelAnimationFrame(m)},[]),p.jsx(q,{present:r||u,children:({present:m})=>p.jsx(_.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:f,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:d.current?"0s":void 0},children:m&&s})})});Ya.displayName=za;function Xa(e,t){return`${e}-trigger-${t}`}function qa(e,t){return`${e}-content-${t}`}var ah=Ha,ch=Ga,lh=Ka,uh=Ya,Za="Toggle",_o=a.forwardRef((e,t)=>{const{pressed:n,defaultPressed:o,onPressedChange:r,...s}=e,[i,c]=J({prop:n,onChange:r,defaultProp:o??!1,caller:Za});return p.jsx(_.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:t,onClick:S(e.onClick,()=>{e.disabled||c(!i)})})});_o.displayName=Za;var dh=_o,je="ToggleGroup",[Ja]=Z(je,[Qe]),Qa=Qe(),To=Y.forwardRef((e,t)=>{const{type:n,...o}=e;if(n==="single"){const r=o;return p.jsx(Tp,{...r,ref:t})}if(n==="multiple"){const r=o;return p.jsx(Mp,{...r,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${je}\``)});To.displayName=je;var[ec,tc]=Ja(je),Tp=Y.forwardRef((e,t)=>{const{value:n,defaultValue:o,onValueChange:r=()=>{},...s}=e,[i,c]=J({prop:n,defaultProp:o??"",onChange:r,caller:je});return p.jsx(ec,{scope:e.__scopeToggleGroup,type:"single",value:Y.useMemo(()=>i?[i]:[],[i]),onItemActivate:c,onItemDeactivate:Y.useCallback(()=>c(""),[c]),children:p.jsx(nc,{...s,ref:t})})}),Mp=Y.forwardRef((e,t)=>{const{value:n,defaultValue:o,onValueChange:r=()=>{},...s}=e,[i,c]=J({prop:n,defaultProp:o??[],onChange:r,caller:je}),l=Y.useCallback(u=>c((d=[])=>[...d,u]),[c]),f=Y.useCallback(u=>c((d=[])=>d.filter(m=>m!==u)),[c]);return p.jsx(ec,{scope:e.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:l,onItemDeactivate:f,children:p.jsx(nc,{...s,ref:t})})});To.displayName=je;var[Ap,Ip]=Ja(je),nc=Y.forwardRef((e,t)=>{const{__scopeToggleGroup:n,disabled:o=!1,rovingFocus:r=!0,orientation:s,dir:i,loop:c=!0,...l}=e,f=Qa(n),u=Ve(i),d={role:"group",dir:u,...l};return p.jsx(Ap,{scope:n,rovingFocus:r,disabled:o,children:r?p.jsx(ro,{asChild:!0,...f,orientation:s,dir:u,loop:c,children:p.jsx(_.div,{...d,ref:t})}):p.jsx(_.div,{...d,ref:t})})}),$t="ToggleGroupItem",oc=Y.forwardRef((e,t)=>{const n=tc($t,e.__scopeToggleGroup),o=Ip($t,e.__scopeToggleGroup),r=Qa(e.__scopeToggleGroup),s=n.value.includes(e.value),i=o.disabled||e.disabled,c={...e,pressed:s,disabled:i},l=Y.useRef(null);return o.rovingFocus?p.jsx(so,{asChild:!0,...r,focusable:!i,active:s,ref:l,children:p.jsx(Qo,{...c,ref:t})}):p.jsx(Qo,{...c,ref:t})});oc.displayName=$t;var Qo=Y.forwardRef((e,t)=>{const{__scopeToggleGroup:n,value:o,...r}=e,s=tc($t,n),i={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},c=s.type==="single"?i:void 0;return p.jsx(_o,{...c,...r,ref:t,onPressedChange:l=>{l?s.onItemActivate(o):s.onItemDeactivate(o)}})}),fh=To,ph=oc,[mn]=Z("Tooltip",[Ae]),hn=Ae(),rc="TooltipProvider",Np=700,Vn="tooltip.open",[Op,Mo]=mn(rc),sc=e=>{const{__scopeTooltip:t,delayDuration:n=Np,skipDelayDuration:o=300,disableHoverableContent:r=!1,children:s}=e,i=a.useRef(!0),c=a.useRef(!1),l=a.useRef(0);return a.useEffect(()=>{const f=l.current;return()=>window.clearTimeout(f)},[]),p.jsx(Op,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:a.useCallback(()=>{window.clearTimeout(l.current),i.current=!1},[]),onClose:a.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.current=!0,o)},[o]),isPointerInTransitRef:c,onPointerInTransitChange:a.useCallback(f=>{c.current=f},[]),disableHoverableContent:r,children:s})};sc.displayName=rc;var ct="Tooltip",[Dp,vn]=mn(ct),ic=e=>{const{__scopeTooltip:t,children:n,open:o,defaultOpen:r,onOpenChange:s,disableHoverableContent:i,delayDuration:c}=e,l=Mo(ct,e.__scopeTooltip),f=hn(t),[u,d]=a.useState(null),m=ne(),h=a.useRef(0),g=i??l.disableHoverableContent,v=c??l.delayDuration,x=a.useRef(!1),[w,C]=J({prop:o,defaultProp:r??!1,onChange:R=>{R?(l.onOpen(),document.dispatchEvent(new CustomEvent(Vn))):l.onClose(),s?.(R)},caller:ct}),b=a.useMemo(()=>w?x.current?"delayed-open":"instant-open":"closed",[w]),y=a.useCallback(()=>{window.clearTimeout(h.current),h.current=0,x.current=!1,C(!0)},[C]),P=a.useCallback(()=>{window.clearTimeout(h.current),h.current=0,C(!1)},[C]),A=a.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{x.current=!0,C(!0),h.current=0},v)},[v,C]);return a.useEffect(()=>()=>{h.current&&(window.clearTimeout(h.current),h.current=0)},[]),p.jsx(ft,{...f,children:p.jsx(Dp,{scope:t,contentId:m,open:w,stateAttribute:b,trigger:u,onTriggerChange:d,onTriggerEnter:a.useCallback(()=>{l.isOpenDelayedRef.current?A():y()},[l.isOpenDelayedRef,A,y]),onTriggerLeave:a.useCallback(()=>{g?P():(window.clearTimeout(h.current),h.current=0)},[P,g]),onOpen:y,onClose:P,disableHoverableContent:g,children:n})})};ic.displayName=ct;var Hn="TooltipTrigger",ac=a.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=vn(Hn,n),s=Mo(Hn,n),i=hn(n),c=a.useRef(null),l=L(t,c,r.onTriggerChange),f=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(()=>f.current=!1,[]);return a.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),p.jsx(pt,{asChild:!0,...i,children:p.jsx(_.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...o,ref:l,onPointerMove:S(e.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!s.isPointerInTransitRef.current&&(r.onTriggerEnter(),u.current=!0)}),onPointerLeave:S(e.onPointerLeave,()=>{r.onTriggerLeave(),u.current=!1}),onPointerDown:S(e.onPointerDown,()=>{r.open&&r.onClose(),f.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:S(e.onFocus,()=>{f.current||r.onOpen()}),onBlur:S(e.onBlur,r.onClose),onClick:S(e.onClick,r.onClose)})})});ac.displayName=Hn;var jp="TooltipPortal",[mh,Lp]=mn(jp,{forceMount:void 0}),Ye="TooltipContent",cc=a.forwardRef((e,t)=>{const n=Lp(Ye,e.__scopeTooltip),{forceMount:o=n.forceMount,side:r="top",...s}=e,i=vn(Ye,e.__scopeTooltip);return p.jsx(q,{present:o||i.open,children:i.disableHoverableContent?p.jsx(lc,{side:r,...s,ref:t}):p.jsx(kp,{side:r,...s,ref:t})})}),kp=a.forwardRef((e,t)=>{const n=vn(Ye,e.__scopeTooltip),o=Mo(Ye,e.__scopeTooltip),r=a.useRef(null),s=L(t,r),[i,c]=a.useState(null),{trigger:l,onClose:f}=n,u=r.current,{onPointerInTransitChange:d}=o,m=a.useCallback(()=>{c(null),d(!1)},[d]),h=a.useCallback((g,v)=>{const x=g.currentTarget,w={x:g.clientX,y:g.clientY},C=Hp(w,x.getBoundingClientRect()),b=Wp(w,C),y=Gp(v.getBoundingClientRect()),P=Kp([...b,...y]);c(P),d(!0)},[d]);return a.useEffect(()=>()=>m(),[m]),a.useEffect(()=>{if(l&&u){const g=x=>h(x,u),v=x=>h(x,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",v),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",v)}}},[l,u,h,m]),a.useEffect(()=>{if(i){const g=v=>{const x=v.target,w={x:v.clientX,y:v.clientY},C=l?.contains(x)||u?.contains(x),b=!Up(w,i);C?m():b&&(m(),f())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,i,f,m]),p.jsx(lc,{...e,ref:s})}),[$p,Fp]=mn(ct,{isInside:!1}),Bp=pc("TooltipContent"),lc=a.forwardRef((e,t)=>{const{__scopeTooltip:n,children:o,"aria-label":r,onEscapeKeyDown:s,onPointerDownOutside:i,...c}=e,l=vn(Ye,n),f=hn(n),{onClose:u}=l;return a.useEffect(()=>(document.addEventListener(Vn,u),()=>document.removeEventListener(Vn,u)),[u]),a.useEffect(()=>{if(l.trigger){const d=m=>{m.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),p.jsx(Xe,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:p.jsxs(Xt,{"data-state":l.stateAttribute,...f,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[p.jsx(Bp,{children:o}),p.jsx($p,{scope:n,isInside:!0,children:p.jsx(Hf,{id:l.contentId,role:"tooltip",children:r||o})})]})})});cc.displayName=Ye;var uc="TooltipArrow",Vp=a.forwardRef((e,t)=>{const{__scopeTooltip:n,...o}=e,r=hn(n);return Fp(uc,n).isInside?null:p.jsx(qt,{...r,...o,ref:t})});Vp.displayName=uc;function Hp(e,t){const n=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,o,r,s)){case s:return"left";case r:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function Wp(e,t,n=5){const o=[];switch(t){case"top":o.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":o.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":o.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":o.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return o}function Gp(e){const{top:t,right:n,bottom:o,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:o},{x:r,y:o}]}function Up(e,t){const{x:n,y:o}=e;let r=!1;for(let s=0,i=t.length-1;so!=m>o&&n<(d-f)*(o-u)/(m-u)+f&&(r=!r)}return r}function Kp(e){const t=e.slice();return t.sort((n,o)=>n.xo.x?1:n.yo.y?1:0),zp(t)}function zp(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o=2;){const s=t[t.length-1],i=t[t.length-2];if((s.x-i.x)*(r.y-i.y)>=(s.y-i.y)*(r.x-i.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let o=e.length-1;o>=0;o--){const r=e[o];for(;n.length>=2;){const s=n[n.length-1],i=n[n.length-2];if((s.x-i.x)*(r.y-i.y)>=(s.y-i.y)*(r.x-i.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var hh=sc,vh=ic,gh=ac,xh=cc;export{Um as $,km as A,Tm as B,Mc as C,Pm as D,Mm as E,Im as F,Nm as G,Dm as H,um as I,Om as J,Am as K,lm as L,jm as M,Em as N,bm as O,Jp as P,_m as Q,qp as R,Xp as S,Zp as T,$m as U,Fm as V,Bm as W,Hm as X,Gm as Y,Qm as Z,eh as _,Ac as a,Km as a0,zm as a1,Xm as a2,qm as a3,Jm as a4,Zm as a5,th as a6,Vm as a7,Wm as a8,Ym as a9,nh as aa,oh as ab,rh as ac,dp as ad,gp as ae,sh as af,ih as ag,ah,ch as ai,lh as aj,uh as ak,dh as al,fh as am,ph as an,xh as ao,vh as ap,gh as aq,hh as ar,Qp as b,em as c,tm as d,nm as e,om as f,rm as g,Ku as h,Uu as i,vm as j,gm as k,am as l,cm as m,dm as n,pm as o,fm as p,mm as q,sm as r,im as s,hm as t,Cm as u,ym as v,Rm as w,Sm as x,wm as y,Lm as z}; diff --git a/resources/video-editor/assets/react-kyfdMflE.js b/resources/video-editor/assets/react-kyfdMflE.js new file mode 100644 index 00000000..cb290732 --- /dev/null +++ b/resources/video-editor/assets/react-kyfdMflE.js @@ -0,0 +1,88 @@ +function id(e,t){for(var n=0;nr[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function Wi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ma={exports:{}},Gl={},ya={exports:{}},U={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Dr=Symbol.for("react.element"),ud=Symbol.for("react.portal"),sd=Symbol.for("react.fragment"),ad=Symbol.for("react.strict_mode"),cd=Symbol.for("react.profiler"),fd=Symbol.for("react.provider"),dd=Symbol.for("react.context"),pd=Symbol.for("react.forward_ref"),hd=Symbol.for("react.suspense"),gd=Symbol.for("react.memo"),vd=Symbol.for("react.lazy"),Qu=Symbol.iterator;function md(e){return e===null||typeof e!="object"?null:(e=Qu&&e[Qu]||e["@@iterator"],typeof e=="function"?e:null)}var wa={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Sa=Object.assign,Ea={};function Vn(e,t,n){this.props=e,this.context=t,this.refs=Ea,this.updater=n||wa}Vn.prototype.isReactComponent={};Vn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Vn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ka(){}ka.prototype=Vn.prototype;function Qi(e,t,n){this.props=e,this.context=t,this.refs=Ea,this.updater=n||wa}var Ki=Qi.prototype=new ka;Ki.constructor=Qi;Sa(Ki,Vn.prototype);Ki.isPureReactComponent=!0;var Ku=Array.isArray,Ca=Object.prototype.hasOwnProperty,Gi={current:null},Na={key:!0,ref:!0,__self:!0,__source:!0};function xa(e,t,n){var r,l={},o=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(o=""+t.key),t)Ca.call(t,r)&&!Na.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1>>1,K=x[V];if(0>>1;Vl(z,T))Al(G,z)?(x[V]=G,x[A]=T,V=A):(x[V]=z,x[_]=T,V=_);else if(Al(G,T))x[V]=G,x[A]=T,V=A;else break e}}return D}function l(x,D){var T=x.sortIndex-D.sortIndex;return T!==0?T:x.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var i=Date,u=i.now();e.unstable_now=function(){return i.now()-u}}var s=[],a=[],d=1,h=null,g=3,m=!1,S=!1,v=!1,R=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function p(x){for(var D=n(a);D!==null;){if(D.callback===null)r(a);else if(D.startTime<=x)r(a),D.sortIndex=D.expirationTime,t(s,D);else break;D=n(a)}}function y(x){if(v=!1,p(x),!S)if(n(s)!==null)S=!0,Xe(E);else{var D=n(a);D!==null&&Ae(y,D.startTime-x)}}function E(x,D){S=!1,v&&(v=!1,f(P),P=-1),m=!0;var T=g;try{for(p(D),h=n(s);h!==null&&(!(h.expirationTime>D)||x&&!re());){var V=h.callback;if(typeof V=="function"){h.callback=null,g=h.priorityLevel;var K=V(h.expirationTime<=D);D=e.unstable_now(),typeof K=="function"?h.callback=K:h===n(s)&&r(s),p(D)}else r(s);h=n(s)}if(h!==null)var w=!0;else{var _=n(a);_!==null&&Ae(y,_.startTime-D),w=!1}return w}finally{h=null,g=T,m=!1}}var C=!1,N=null,P=-1,$=5,I=-1;function re(){return!(e.unstable_now()-I<$)}function Ce(){if(N!==null){var x=e.unstable_now();I=x;var D=!0;try{D=N(!0,x)}finally{D?ze():(C=!1,N=null)}}else C=!1}var ze;if(typeof c=="function")ze=function(){c(Ce)};else if(typeof MessageChannel<"u"){var Ye=new MessageChannel,pe=Ye.port2;Ye.port1.onmessage=Ce,ze=function(){pe.postMessage(null)}}else ze=function(){R(Ce,0)};function Xe(x){N=x,C||(C=!0,ze())}function Ae(x,D){P=R(function(){x(e.unstable_now())},D)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(x){x.callback=null},e.unstable_continueExecution=function(){S||m||(S=!0,Xe(E))},e.unstable_forceFrameRate=function(x){0>x||125V?(x.sortIndex=T,t(a,x),n(s)===null&&x===n(a)&&(v?(f(P),P=-1):v=!0,Ae(y,T-V))):(x.sortIndex=K,t(s,x),S||m||(S=!0,Xe(E))),x},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(x){var D=g;return function(){var T=g;g=D;try{return x.apply(this,arguments)}finally{g=T}}}})(Oa);Ra.exports=Oa;var Ld=Ra.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Rd=j,De=Ld;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Go=Object.prototype.hasOwnProperty,Od=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Xu={},Zu={};function Td(e){return Go.call(Zu,e)?!0:Go.call(Xu,e)?!1:Od.test(e)?Zu[e]=!0:(Xu[e]=!0,!1)}function Md(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Dd(e,t,n,r){if(t===null||typeof t>"u"||Md(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ke(e,t,n,r,l,o,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=i}var de={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){de[e]=new ke(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];de[t]=new ke(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){de[e]=new ke(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){de[e]=new ke(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){de[e]=new ke(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){de[e]=new ke(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){de[e]=new ke(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){de[e]=new ke(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){de[e]=new ke(e,5,!1,e.toLowerCase(),null,!1,!1)});var Xi=/[\-:]([a-z])/g;function Zi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Xi,Zi);de[t]=new ke(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Xi,Zi);de[t]=new ke(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Xi,Zi);de[t]=new ke(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){de[e]=new ke(e,1,!1,e.toLowerCase(),null,!1,!1)});de.xlinkHref=new ke("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){de[e]=new ke(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ji(e,t,n,r){var l=de.hasOwnProperty(t)?de[t]:null;(l!==null?l.type!==0:r||!(2u||l[i]!==o[u]){var s=` +`+l[i].replace(" at new "," at ");return e.displayName&&s.includes("")&&(s=s.replace("",e.displayName)),s}while(1<=i&&0<=u);break}}}finally{mo=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?er(e):""}function Id(e){switch(e.tag){case 5:return er(e.type);case 16:return er("Lazy");case 13:return er("Suspense");case 19:return er("SuspenseList");case 0:case 2:case 15:return e=yo(e.type,!1),e;case 11:return e=yo(e.type.render,!1),e;case 1:return e=yo(e.type,!0),e;default:return""}}function Jo(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case vn:return"Fragment";case gn:return"Portal";case Yo:return"Profiler";case qi:return"StrictMode";case Xo:return"Suspense";case Zo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Da:return(e.displayName||"Context")+".Consumer";case Ma:return(e._context.displayName||"Context")+".Provider";case bi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case eu:return t=e.displayName||null,t!==null?t:Jo(e.type)||"Memo";case xt:t=e._payload,e=e._init;try{return Jo(e(t))}catch{}}return null}function jd(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Jo(t);case 8:return t===qi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function $t(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ja(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function zd(e){var t=ja(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Vr(e){e._valueTracker||(e._valueTracker=zd(e))}function za(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ja(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Cl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function qo(e,t){var n=t.checked;return ee({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function qu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=$t(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Aa(e,t){t=t.checked,t!=null&&Ji(e,"checked",t,!1)}function bo(e,t){Aa(e,t);var n=$t(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ei(e,t.type,n):t.hasOwnProperty("defaultValue")&&ei(e,t.type,$t(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function bu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ei(e,t,n){(t!=="number"||Cl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tr=Array.isArray;function Ln(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Wr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function hr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var lr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ad=["Webkit","ms","Moz","O"];Object.keys(lr).forEach(function(e){Ad.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),lr[t]=lr[e]})});function $a(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||lr.hasOwnProperty(e)&&lr[e]?(""+t).trim():t+"px"}function Ha(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=$a(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Bd=ee({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ri(e,t){if(t){if(Bd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function li(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var oi=null;function tu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ii=null,Rn=null,On=null;function ns(e){if(e=zr(e)){if(typeof ii!="function")throw Error(k(280));var t=e.stateNode;t&&(t=ql(t),ii(e.stateNode,e.type,t))}}function Va(e){Rn?On?On.push(e):On=[e]:Rn=e}function Wa(){if(Rn){var e=Rn,t=On;if(On=Rn=null,ns(e),t)for(e=0;e>>=0,e===0?32:31-(Xd(e)/Zd|0)|0}var Qr=64,Kr=4194304;function nr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Pl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=nr(u):(o&=i,o!==0&&(r=nr(o)))}else i=n&~l,i!==0?r=nr(i):o!==0&&(r=nr(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ir(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-tt(t),e[t]=n}function ep(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ir),fs=" ",ds=!1;function cc(e,t){switch(e){case"keyup":return Lp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var mn=!1;function Op(e,t){switch(e){case"compositionend":return fc(t);case"keypress":return t.which!==32?null:(ds=!0,fs);case"textInput":return e=t.data,e===fs&&ds?null:e;default:return null}}function Tp(e,t){if(mn)return e==="compositionend"||!au&&cc(e,t)?(e=sc(),cl=iu=Rt=null,mn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=vs(n)}}function gc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vc(){for(var e=window,t=Cl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Cl(e.document)}return t}function cu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Up(e){var t=vc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gc(n.ownerDocument.documentElement,n)){if(r!==null&&cu(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=ms(n,o);var i=ms(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,yn=null,di=null,sr=null,pi=!1;function ys(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;pi||yn==null||yn!==Cl(r)||(r=yn,"selectionStart"in r&&cu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),sr&&Sr(sr,r)||(sr=r,r=Ol(di,"onSelect"),0En||(e.current=wi[En],wi[En]=null,En--)}function Y(e,t){En++,wi[En]=e.current,e.current=t}var Ht={},me=Wt(Ht),Pe=Wt(!1),tn=Ht;function An(e,t){var n=e.type.contextTypes;if(!n)return Ht;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function Le(e){return e=e.childContextTypes,e!=null}function Ml(){Z(Pe),Z(me)}function xs(e,t,n){if(me.current!==Ht)throw Error(k(168));Y(me,t),Y(Pe,n)}function xc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(k(108,jd(e)||"Unknown",l));return ee({},n,r)}function Dl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ht,tn=me.current,Y(me,e),Y(Pe,Pe.current),!0}function _s(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=xc(e,t,tn),r.__reactInternalMemoizedMergedChildContext=e,Z(Pe),Z(me),Y(me,e)):Z(Pe),Y(Pe,n)}var dt=null,bl=!1,Mo=!1;function _c(e){dt===null?dt=[e]:dt.push(e)}function qp(e){bl=!0,_c(e)}function Qt(){if(!Mo&&dt!==null){Mo=!0;var e=0,t=W;try{var n=dt;for(W=1;e>=i,l-=i,ht=1<<32-tt(t)+l|n<P?($=N,N=null):$=N.sibling;var I=g(f,N,p[P],y);if(I===null){N===null&&(N=$);break}e&&N&&I.alternate===null&&t(f,N),c=o(I,c,P),C===null?E=I:C.sibling=I,C=I,N=$}if(P===p.length)return n(f,N),J&&Yt(f,P),E;if(N===null){for(;PP?($=N,N=null):$=N.sibling;var re=g(f,N,I.value,y);if(re===null){N===null&&(N=$);break}e&&N&&re.alternate===null&&t(f,N),c=o(re,c,P),C===null?E=re:C.sibling=re,C=re,N=$}if(I.done)return n(f,N),J&&Yt(f,P),E;if(N===null){for(;!I.done;P++,I=p.next())I=h(f,I.value,y),I!==null&&(c=o(I,c,P),C===null?E=I:C.sibling=I,C=I);return J&&Yt(f,P),E}for(N=r(f,N);!I.done;P++,I=p.next())I=m(N,f,P,I.value,y),I!==null&&(e&&I.alternate!==null&&N.delete(I.key===null?P:I.key),c=o(I,c,P),C===null?E=I:C.sibling=I,C=I);return e&&N.forEach(function(Ce){return t(f,Ce)}),J&&Yt(f,P),E}function R(f,c,p,y){if(typeof p=="object"&&p!==null&&p.type===vn&&p.key===null&&(p=p.props.children),typeof p=="object"&&p!==null){switch(p.$$typeof){case Hr:e:{for(var E=p.key,C=c;C!==null;){if(C.key===E){if(E=p.type,E===vn){if(C.tag===7){n(f,C.sibling),c=l(C,p.props.children),c.return=f,f=c;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===xt&&Rs(E)===C.type){n(f,C.sibling),c=l(C,p.props),c.ref=Jn(f,C,p),c.return=f,f=c;break e}n(f,C);break}else t(f,C);C=C.sibling}p.type===vn?(c=en(p.props.children,f.mode,y,p.key),c.return=f,f=c):(y=yl(p.type,p.key,p.props,null,f.mode,y),y.ref=Jn(f,c,p),y.return=f,f=y)}return i(f);case gn:e:{for(C=p.key;c!==null;){if(c.key===C)if(c.tag===4&&c.stateNode.containerInfo===p.containerInfo&&c.stateNode.implementation===p.implementation){n(f,c.sibling),c=l(c,p.children||[]),c.return=f,f=c;break e}else{n(f,c);break}else t(f,c);c=c.sibling}c=Uo(p,f.mode,y),c.return=f,f=c}return i(f);case xt:return C=p._init,R(f,c,C(p._payload),y)}if(tr(p))return S(f,c,p,y);if(Kn(p))return v(f,c,p,y);br(f,p)}return typeof p=="string"&&p!==""||typeof p=="number"?(p=""+p,c!==null&&c.tag===6?(n(f,c.sibling),c=l(c,p),c.return=f,f=c):(n(f,c),c=Fo(p,f.mode,y),c.return=f,f=c),i(f)):n(f,c)}return R}var Fn=Oc(!0),Tc=Oc(!1),zl=Wt(null),Al=null,Nn=null,hu=null;function gu(){hu=Nn=Al=null}function vu(e){var t=zl.current;Z(zl),e._currentValue=t}function ki(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Mn(e,t){Al=e,hu=Nn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(_e=!0),e.firstContext=null)}function Ke(e){var t=e._currentValue;if(hu!==e)if(e={context:e,memoizedValue:t,next:null},Nn===null){if(Al===null)throw Error(k(308));Nn=e,Al.dependencies={lanes:0,firstContext:e}}else Nn=Nn.next=e;return t}var Jt=null;function mu(e){Jt===null?Jt=[e]:Jt.push(e)}function Mc(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,mu(t)):(n.next=l.next,l.next=n),t.interleaved=n,wt(e,r)}function wt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var _t=!1;function yu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Dc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function vt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function At(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,H&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,wt(e,n)}return l=r.interleaved,l===null?(t.next=t,mu(r)):(t.next=l.next,l.next=t),r.interleaved=t,wt(e,n)}function dl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ru(e,n)}}function Os(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=i:o=o.next=i,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Bl(e,t,n,r){var l=e.updateQueue;_t=!1;var o=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var s=u,a=s.next;s.next=null,i===null?o=a:i.next=a,i=s;var d=e.alternate;d!==null&&(d=d.updateQueue,u=d.lastBaseUpdate,u!==i&&(u===null?d.firstBaseUpdate=a:u.next=a,d.lastBaseUpdate=s))}if(o!==null){var h=l.baseState;i=0,d=a=s=null,u=o;do{var g=u.lane,m=u.eventTime;if((r&g)===g){d!==null&&(d=d.next={eventTime:m,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var S=e,v=u;switch(g=t,m=n,v.tag){case 1:if(S=v.payload,typeof S=="function"){h=S.call(m,h,g);break e}h=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=v.payload,g=typeof S=="function"?S.call(m,h,g):S,g==null)break e;h=ee({},h,g);break e;case 2:_t=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,g=l.effects,g===null?l.effects=[u]:g.push(u))}else m={eventTime:m,lane:g,tag:u.tag,payload:u.payload,callback:u.callback,next:null},d===null?(a=d=m,s=h):d=d.next=m,i|=g;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;g=u,u=g.next,g.next=null,l.lastBaseUpdate=g,l.shared.pending=null}}while(!0);if(d===null&&(s=h),l.baseState=s,l.firstBaseUpdate=a,l.lastBaseUpdate=d,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);ln|=i,e.lanes=i,e.memoizedState=h}}function Ts(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Io.transition;Io.transition={};try{e(!1),t()}finally{W=n,Io.transition=r}}function Zc(){return Ge().memoizedState}function nh(e,t,n){var r=Ft(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jc(e))qc(t,n);else if(n=Mc(e,t,n,r),n!==null){var l=Se();nt(n,e,r,l),bc(n,t,r)}}function rh(e,t,n){var r=Ft(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jc(e))qc(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var i=t.lastRenderedState,u=o(i,n);if(l.hasEagerState=!0,l.eagerState=u,rt(u,i)){var s=t.interleaved;s===null?(l.next=l,mu(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=Mc(e,t,l,r),n!==null&&(l=Se(),nt(n,e,r,l),bc(n,t,r))}}function Jc(e){var t=e.alternate;return e===b||t!==null&&t===b}function qc(e,t){ar=Ul=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function bc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ru(e,n)}}var $l={readContext:Ke,useCallback:he,useContext:he,useEffect:he,useImperativeHandle:he,useInsertionEffect:he,useLayoutEffect:he,useMemo:he,useReducer:he,useRef:he,useState:he,useDebugValue:he,useDeferredValue:he,useTransition:he,useMutableSource:he,useSyncExternalStore:he,useId:he,unstable_isNewReconciler:!1},lh={readContext:Ke,useCallback:function(e,t){return ot().memoizedState=[e,t===void 0?null:t],e},useContext:Ke,useEffect:Ds,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,hl(4194308,4,Qc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return hl(4194308,4,e,t)},useInsertionEffect:function(e,t){return hl(4,2,e,t)},useMemo:function(e,t){var n=ot();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ot();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=nh.bind(null,b,e),[r.memoizedState,e]},useRef:function(e){var t=ot();return e={current:e},t.memoizedState=e},useState:Ms,useDebugValue:_u,useDeferredValue:function(e){return ot().memoizedState=e},useTransition:function(){var e=Ms(!1),t=e[0];return e=th.bind(null,e[1]),ot().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=b,l=ot();if(J){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),ae===null)throw Error(k(349));rn&30||Ac(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Ds(Fc.bind(null,r,o,e),[e]),r.flags|=2048,Lr(9,Bc.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=ot(),t=ae.identifierPrefix;if(J){var n=gt,r=ht;n=(r&~(1<<32-tt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=_r++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[it]=t,e[Cr]=r,cf(e,t,!1,!1),t.stateNode=e;e:{switch(i=li(n,r),n){case"dialog":X("cancel",e),X("close",e),l=r;break;case"iframe":case"object":case"embed":X("load",e),l=r;break;case"video":case"audio":for(l=0;lHn&&(t.flags|=128,r=!0,qn(o,!1),t.lanes=4194304)}else{if(!r)if(e=Fl(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),qn(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!J)return ge(t),null}else 2*ne()-o.renderingStartTime>Hn&&n!==1073741824&&(t.flags|=128,r=!0,qn(o,!1),t.lanes=4194304);o.isBackwards?(i.sibling=t.child,t.child=i):(n=o.last,n!==null?n.sibling=i:t.child=i,o.last=i)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=ne(),t.sibling=null,n=q.current,Y(q,r?n&1|2:n&1),t):(ge(t),null);case 22:case 23:return Mu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Oe&1073741824&&(ge(t),t.subtreeFlags&6&&(t.flags|=8192)):ge(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function dh(e,t){switch(du(t),t.tag){case 1:return Le(t.type)&&Ml(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Un(),Z(Pe),Z(me),Eu(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Su(t),null;case 13:if(Z(q),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));Bn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Z(q),null;case 4:return Un(),null;case 10:return vu(t.type._context),null;case 22:case 23:return Mu(),null;case 24:return null;default:return null}}var tl=!1,ve=!1,ph=typeof WeakSet=="function"?WeakSet:Set,L=null;function xn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){te(e,t,r)}else n.current=null}function Ti(e,t,n){try{n()}catch(r){te(e,t,r)}}var Ws=!1;function hh(e,t){if(hi=Ll,e=vc(),cu(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var i=0,u=-1,s=-1,a=0,d=0,h=e,g=null;t:for(;;){for(var m;h!==n||l!==0&&h.nodeType!==3||(u=i+l),h!==o||r!==0&&h.nodeType!==3||(s=i+r),h.nodeType===3&&(i+=h.nodeValue.length),(m=h.firstChild)!==null;)g=h,h=m;for(;;){if(h===e)break t;if(g===n&&++a===l&&(u=i),g===o&&++d===r&&(s=i),(m=h.nextSibling)!==null)break;h=g,g=h.parentNode}h=m}n=u===-1||s===-1?null:{start:u,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(gi={focusedElem:e,selectionRange:n},Ll=!1,L=t;L!==null;)if(t=L,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,L=e;else for(;L!==null;){t=L;try{var S=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var v=S.memoizedProps,R=S.memoizedState,f=t.stateNode,c=f.getSnapshotBeforeUpdate(t.elementType===t.type?v:qe(t.type,v),R);f.__reactInternalSnapshotBeforeUpdate=c}break;case 3:var p=t.stateNode.containerInfo;p.nodeType===1?p.textContent="":p.nodeType===9&&p.documentElement&&p.removeChild(p.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(y){te(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,L=e;break}L=t.return}return S=Ws,Ws=!1,S}function cr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&Ti(t,n,o)}l=l.next}while(l!==r)}}function no(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Mi(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pf(e){var t=e.alternate;t!==null&&(e.alternate=null,pf(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[it],delete t[Cr],delete t[yi],delete t[Zp],delete t[Jp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hf(e){return e.tag===5||e.tag===3||e.tag===4}function Qs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Di(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Tl));else if(r!==4&&(e=e.child,e!==null))for(Di(e,t,n),e=e.sibling;e!==null;)Di(e,t,n),e=e.sibling}function Ii(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ii(e,t,n),e=e.sibling;e!==null;)Ii(e,t,n),e=e.sibling}var ce=null,be=!1;function Nt(e,t,n){for(n=n.child;n!==null;)gf(e,t,n),n=n.sibling}function gf(e,t,n){if(at&&typeof at.onCommitFiberUnmount=="function")try{at.onCommitFiberUnmount(Yl,n)}catch{}switch(n.tag){case 5:ve||xn(n,t);case 6:var r=ce,l=be;ce=null,Nt(e,t,n),ce=r,be=l,ce!==null&&(be?(e=ce,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ce.removeChild(n.stateNode));break;case 18:ce!==null&&(be?(e=ce,n=n.stateNode,e.nodeType===8?To(e.parentNode,n):e.nodeType===1&&To(e,n),yr(e)):To(ce,n.stateNode));break;case 4:r=ce,l=be,ce=n.stateNode.containerInfo,be=!0,Nt(e,t,n),ce=r,be=l;break;case 0:case 11:case 14:case 15:if(!ve&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,i=o.destroy;o=o.tag,i!==void 0&&(o&2||o&4)&&Ti(n,t,i),l=l.next}while(l!==r)}Nt(e,t,n);break;case 1:if(!ve&&(xn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){te(n,t,u)}Nt(e,t,n);break;case 21:Nt(e,t,n);break;case 22:n.mode&1?(ve=(r=ve)||n.memoizedState!==null,Nt(e,t,n),ve=r):Nt(e,t,n);break;default:Nt(e,t,n)}}function Ks(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new ph),t.forEach(function(r){var l=Ch.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Je(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=i),r&=~o}if(r=l,r=ne()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*vh(r/1960))-r,10e?16:e,Ot===null)var r=!1;else{if(e=Ot,Ot=null,Wl=0,H&6)throw Error(k(331));var l=H;for(H|=4,L=e.current;L!==null;){var o=L,i=o.child;if(L.flags&16){var u=o.deletions;if(u!==null){for(var s=0;sne()-Ou?bt(e,0):Ru|=n),Re(e,t)}function Cf(e,t){t===0&&(e.mode&1?(t=Kr,Kr<<=1,!(Kr&130023424)&&(Kr=4194304)):t=1);var n=Se();e=wt(e,t),e!==null&&(Ir(e,t,n),Re(e,n))}function kh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Cf(e,n)}function Ch(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),Cf(e,n)}var Nf;Nf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Pe.current)_e=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return _e=!1,ch(e,t,n);_e=!!(e.flags&131072)}else _e=!1,J&&t.flags&1048576&&Pc(t,jl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;gl(e,t),e=t.pendingProps;var l=An(t,me.current);Mn(t,n),l=Cu(null,t,r,e,l,n);var o=Nu();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Le(r)?(o=!0,Dl(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,yu(t),l.updater=to,t.stateNode=l,l._reactInternals=t,Ni(t,r,e,n),t=Pi(null,t,r,!0,o,n)):(t.tag=0,J&&o&&fu(t),we(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(gl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=xh(r),e=qe(r,e),l){case 0:t=_i(null,t,r,e,n);break e;case 1:t=$s(null,t,r,e,n);break e;case 11:t=Fs(null,t,r,e,n);break e;case 14:t=Us(null,t,r,qe(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:qe(r,l),_i(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:qe(r,l),$s(e,t,r,l,n);case 3:e:{if(uf(t),e===null)throw Error(k(387));r=t.pendingProps,o=t.memoizedState,l=o.element,Dc(e,t),Bl(t,r,null,n);var i=t.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=$n(Error(k(423)),t),t=Hs(e,t,r,n,l);break e}else if(r!==l){l=$n(Error(k(424)),t),t=Hs(e,t,r,n,l);break e}else for(Te=zt(t.stateNode.containerInfo.firstChild),Me=t,J=!0,et=null,n=Tc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Bn(),r===l){t=St(e,t,n);break e}we(e,t,r,n)}t=t.child}return t;case 5:return Ic(t),e===null&&Ei(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,i=l.children,vi(r,l)?i=null:o!==null&&vi(r,o)&&(t.flags|=32),of(e,t),we(e,t,i,n),t.child;case 6:return e===null&&Ei(t),null;case 13:return sf(e,t,n);case 4:return wu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Fn(t,null,r,n):we(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:qe(r,l),Fs(e,t,r,l,n);case 7:return we(e,t,t.pendingProps,n),t.child;case 8:return we(e,t,t.pendingProps.children,n),t.child;case 12:return we(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,i=l.value,Y(zl,r._currentValue),r._currentValue=i,o!==null)if(rt(o.value,i)){if(o.children===l.children&&!Pe.current){t=St(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){i=o.child;for(var s=u.firstContext;s!==null;){if(s.context===r){if(o.tag===1){s=vt(-1,n&-n),s.tag=2;var a=o.updateQueue;if(a!==null){a=a.shared;var d=a.pending;d===null?s.next=s:(s.next=d.next,d.next=s),a.pending=s}}o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),ki(o.return,n,t),u.lanes|=n;break}s=s.next}}else if(o.tag===10)i=o.type===t.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(k(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),ki(i,n,t),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===t){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}we(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Mn(t,n),l=Ke(l),r=r(l),t.flags|=1,we(e,t,r,n),t.child;case 14:return r=t.type,l=qe(r,t.pendingProps),l=qe(r.type,l),Us(e,t,r,l,n);case 15:return rf(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:qe(r,l),gl(e,t),t.tag=1,Le(r)?(e=!0,Dl(t)):e=!1,Mn(t,n),ef(t,r,l),Ni(t,r,l,n),Pi(null,t,r,!0,e,n);case 19:return af(e,t,n);case 22:return lf(e,t,n)}throw Error(k(156,t.tag))};function xf(e,t){return Ja(e,t)}function Nh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function We(e,t,n,r){return new Nh(e,t,n,r)}function Iu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function xh(e){if(typeof e=="function")return Iu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===bi)return 11;if(e===eu)return 14}return 2}function Ut(e,t){var n=e.alternate;return n===null?(n=We(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function yl(e,t,n,r,l,o){var i=2;if(r=e,typeof e=="function")Iu(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case vn:return en(n.children,l,o,t);case qi:i=8,l|=8;break;case Yo:return e=We(12,n,t,l|2),e.elementType=Yo,e.lanes=o,e;case Xo:return e=We(13,n,t,l),e.elementType=Xo,e.lanes=o,e;case Zo:return e=We(19,n,t,l),e.elementType=Zo,e.lanes=o,e;case Ia:return lo(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ma:i=10;break e;case Da:i=9;break e;case bi:i=11;break e;case eu:i=14;break e;case xt:i=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=We(i,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function en(e,t,n,r){return e=We(7,e,r,t),e.lanes=n,e}function lo(e,t,n,r){return e=We(22,e,r,t),e.elementType=Ia,e.lanes=n,e.stateNode={isHidden:!1},e}function Fo(e,t,n){return e=We(6,e,null,t),e.lanes=n,e}function Uo(e,t,n){return t=We(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function _h(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=So(0),this.expirationTimes=So(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=So(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function ju(e,t,n,r,l,o,i,u,s){return e=new _h(e,t,n,u,s),t===1?(t=1,o===!0&&(t|=8)):t=0,o=We(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},yu(o),e}function Ph(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Rf)}catch(e){console.error(e)}}Rf(),La.exports=Ie;var Of=La.exports;const qv=Wi(Of);var ea=Of;Yu.createRoot=ea.createRoot,Yu.hydrateRoot=ea.hydrateRoot;const Mh="modulepreload",Dh=function(e){return"/"+e},ta={},bv=function(t,n,r){let l=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),u=i?.nonce||i?.getAttribute("nonce");l=Promise.allSettled(n.map(s=>{if(s=Dh(s),s in ta)return;ta[s]=!0;const a=s.endsWith(".css"),d=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${s}"]${d}`))return;const h=document.createElement("link");if(h.rel=a?"stylesheet":Mh,a||(h.as="script"),h.crossOrigin="",h.href=s,u&&h.setAttribute("nonce",u),document.head.appendChild(h),a)return new Promise((g,m)=>{h.addEventListener("load",g),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${s}`)))})}))}function o(i){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=i,window.dispatchEvent(u),!u.defaultPrevented)throw i}return l.then(i=>{for(const u of i||[])u.status==="rejected"&&o(u.reason);return t().catch(o)})};function Ih(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function jh(e,t){if(e==null)return{};var n,r,l=Ih(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;re.length)&&(t=e.length);for(var n=0,r=Array(t);n=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var $o={};function Vh(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return $o[t]||($o[t]=Hh(e)),$o[t]}function Wh(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(o){return o!=="token"}),l=Vh(r);return l.reduce(function(o,i){return Pn(Pn({},o),n[i])},t)}function ra(e){return e.join(" ")}function Qh(e,t){var n=0;return function(r){return n+=1,r.map(function(l,o){return Mf({node:l,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(o)})})}}function Mf(e){var t=e.node,n=e.stylesheet,r=e.style,l=r===void 0?{}:r,o=e.useInlineStyles,i=e.key,u=t.properties,s=t.type,a=t.tagName,d=t.value;if(s==="text")return d;if(a){var h=Qh(n,o),g;if(!o)g=Pn(Pn({},u),{},{className:ra(u.className)});else{var m=Object.keys(n).reduce(function(f,c){return c.split(".").forEach(function(p){f.includes(p)||f.push(p)}),f},[]),S=u.className&&u.className.includes("token")?["token"]:[],v=u.className&&S.concat(u.className.filter(function(f){return!m.includes(f)}));g=Pn(Pn({},u),{},{className:ra(v)||void 0,style:Wh(u.className,Object.assign({},u.style,l),n)})}var R=h(t.children);return pt.createElement(a,$i({key:i},g),R)}}const Kh=function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1};var Gh=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function la(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),n.push.apply(n,r)}return n}function Tt(e){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];e.length===void 0&&(e=[e]);for(var r=0;r2&&arguments[2]!==void 0?arguments[2]:[];return wl({children:E,lineNumber:C,lineNumberStyle:u,largestLineNumber:i,showInlineLineNumbers:l,lineProps:n,className:N,showLineNumbers:r,wrapLongLines:s,wrapLines:t})}function v(E,C){if(r&&C&&l){var N=If(u,C,i);E.unshift(Df(C,N))}return E}function R(E,C){var N=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||N.length>0?S(E,C,N):v(E,C)}for(var f=function(){var C=d[m],N=C.children[0].value,P=Xh(N);if(P){var $=N.split(` +`);$.forEach(function(I,re){var Ce=r&&h.length+o,ze={type:"text",value:"".concat(I,` +`)};if(re===0){var Ye=d.slice(g+1,m).concat(wl({children:[ze],className:C.properties.className})),pe=R(Ye,Ce);h.push(pe)}else if(re===$.length-1){var Xe=d[m+1]&&d[m+1].children&&d[m+1].children[0],Ae={type:"text",value:"".concat(I)};if(Xe){var x=wl({children:[Ae],className:C.properties.className});d.splice(m+1,0,x)}else{var D=[Ae],T=R(D,Ce,C.properties.className);h.push(T)}}else{var V=[ze],K=R(V,Ce,C.properties.className);h.push(K)}}),g=m}m++};m/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mt(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(r){for(const l in r)n[l]=r[l]}),n}const lg="",ia=e=>!!e.kind;class og{constructor(t,n){this.buffer="",this.classPrefix=n.classPrefix,t.walk(this)}addText(t){this.buffer+=In(t)}openNode(t){if(!ia(t))return;let n=t.kind;t.sublanguage||(n=`${this.classPrefix}${n}`),this.span(n)}closeNode(t){ia(t)&&(this.buffer+=lg)}value(){return this.buffer}span(t){this.buffer+=``}}class Uu{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(t){this.top.children.push(t)}openNode(t){const n={kind:t,children:[]};this.add(n),this.stack.push(n)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(t){return this.constructor._walk(t,this.rootNode)}static _walk(t,n){return typeof n=="string"?t.addText(n):n.children&&(t.openNode(n),n.children.forEach(r=>this._walk(t,r)),t.closeNode(n)),t}static _collapse(t){typeof t!="string"&&t.children&&(t.children.every(n=>typeof n=="string")?t.children=[t.children.join("")]:t.children.forEach(n=>{Uu._collapse(n)}))}}class ig extends Uu{constructor(t){super(),this.options=t}addKeyword(t,n){t!==""&&(this.openNode(n),this.addText(t),this.closeNode())}addText(t){t!==""&&this.add(t)}addSublanguage(t,n){const r=t.root;r.kind=n,r.sublanguage=!0,this.add(r)}toHTML(){return new og(this,this.options).value()}finalize(){return!0}}function ug(e){return new RegExp(e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}function Tr(e){return e?typeof e=="string"?e:e.source:null}function sg(...e){return e.map(n=>Tr(n)).join("")}function ag(...e){return"("+e.map(n=>Tr(n)).join("|")+")"}function cg(e){return new RegExp(e.toString()+"|").exec("").length-1}function fg(e,t){const n=e&&e.exec(t);return n&&n.index===0}const dg=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function pg(e,t="|"){let n=0;return e.map(r=>{n+=1;const l=n;let o=Tr(r),i="";for(;o.length>0;){const u=dg.exec(o);if(!u){i+=o;break}i+=o.substring(0,u.index),o=o.substring(u.index+u[0].length),u[0][0]==="\\"&&u[1]?i+="\\"+String(Number(u[1])+l):(i+=u[0],u[0]==="("&&n++)}return i}).map(r=>`(${r})`).join(t)}const hg=/\b\B/,Bf="[a-zA-Z]\\w*",$u="[a-zA-Z_]\\w*",Hu="\\b\\d+(\\.\\d+)?",Ff="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",Uf="\\b(0b[01]+)",gg="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",vg=(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=sg(t,/.*\b/,e.binary,/\b.*/)),Mt({className:"meta",begin:t,end:/$/,relevance:0,"on:begin":(n,r)=>{n.index!==0&&r.ignoreMatch()}},e)},Mr={begin:"\\\\[\\s\\S]",relevance:0},mg={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[Mr]},yg={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[Mr]},$f={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},ao=function(e,t,n={}){const r=Mt({className:"comment",begin:e,end:t,contains:[]},n);return r.contains.push($f),r.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),r},wg=ao("//","$"),Sg=ao("/\\*","\\*/"),Eg=ao("#","$"),kg={className:"number",begin:Hu,relevance:0},Cg={className:"number",begin:Ff,relevance:0},Ng={className:"number",begin:Uf,relevance:0},xg={className:"number",begin:Hu+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},_g={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[Mr,{begin:/\[/,end:/\]/,relevance:0,contains:[Mr]}]}]},Pg={className:"title",begin:Bf,relevance:0},Lg={className:"title",begin:$u,relevance:0},Rg={begin:"\\.\\s*"+$u,relevance:0},Og=function(e){return Object.assign(e,{"on:begin":(t,n)=>{n.data._beginMatch=t[1]},"on:end":(t,n)=>{n.data._beginMatch!==t[1]&&n.ignoreMatch()}})};var ll=Object.freeze({__proto__:null,MATCH_NOTHING_RE:hg,IDENT_RE:Bf,UNDERSCORE_IDENT_RE:$u,NUMBER_RE:Hu,C_NUMBER_RE:Ff,BINARY_NUMBER_RE:Uf,RE_STARTERS_RE:gg,SHEBANG:vg,BACKSLASH_ESCAPE:Mr,APOS_STRING_MODE:mg,QUOTE_STRING_MODE:yg,PHRASAL_WORDS_MODE:$f,COMMENT:ao,C_LINE_COMMENT_MODE:wg,C_BLOCK_COMMENT_MODE:Sg,HASH_COMMENT_MODE:Eg,NUMBER_MODE:kg,C_NUMBER_MODE:Cg,BINARY_NUMBER_MODE:Ng,CSS_NUMBER_MODE:xg,REGEXP_MODE:_g,TITLE_MODE:Pg,UNDERSCORE_TITLE_MODE:Lg,METHOD_GUARD:Rg,END_SAME_AS_BEGIN:Og});function Tg(e,t){e.input[e.index-1]==="."&&t.ignoreMatch()}function Mg(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=Tg,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function Dg(e,t){Array.isArray(e.illegal)&&(e.illegal=ag(...e.illegal))}function Ig(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function jg(e,t){e.relevance===void 0&&(e.relevance=1)}const zg=["of","and","for","in","not","or","if","then","parent","list","value"],Ag="keyword";function Hf(e,t,n=Ag){const r={};return typeof e=="string"?l(n,e.split(" ")):Array.isArray(e)?l(n,e):Object.keys(e).forEach(function(o){Object.assign(r,Hf(e[o],t,o))}),r;function l(o,i){t&&(i=i.map(u=>u.toLowerCase())),i.forEach(function(u){const s=u.split("|");r[s[0]]=[o,Bg(s[0],s[1])]})}}function Bg(e,t){return t?Number(t):Fg(e)?0:1}function Fg(e){return zg.includes(e.toLowerCase())}function Ug(e,{plugins:t}){function n(u,s){return new RegExp(Tr(u),"m"+(e.case_insensitive?"i":"")+(s?"g":""))}class r{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,a){a.position=this.position++,this.matchIndexes[this.matchAt]=a,this.regexes.push([a,s]),this.matchAt+=cg(s)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const s=this.regexes.map(a=>a[1]);this.matcherRe=n(pg(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const a=this.matcherRe.exec(s);if(!a)return null;const d=a.findIndex((g,m)=>m>0&&g!==void 0),h=this.matchIndexes[d];return a.splice(0,d),Object.assign(a,h)}}class l{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const a=new r;return this.rules.slice(s).forEach(([d,h])=>a.addRule(d,h)),a.compile(),this.multiRegexes[s]=a,a}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(s,a){this.rules.push([s,a]),a.type==="begin"&&this.count++}exec(s){const a=this.getMatcher(this.regexIndex);a.lastIndex=this.lastIndex;let d=a.exec(s);if(this.resumingScanAtSamePosition()&&!(d&&d.index===this.lastIndex)){const h=this.getMatcher(0);h.lastIndex=this.lastIndex+1,d=h.exec(s)}return d&&(this.regexIndex+=d.position+1,this.regexIndex===this.count&&this.considerAll()),d}}function o(u){const s=new l;return u.contains.forEach(a=>s.addRule(a.begin,{rule:a,type:"begin"})),u.terminatorEnd&&s.addRule(u.terminatorEnd,{type:"end"}),u.illegal&&s.addRule(u.illegal,{type:"illegal"}),s}function i(u,s){const a=u;if(u.isCompiled)return a;[Ig].forEach(h=>h(u,s)),e.compilerExtensions.forEach(h=>h(u,s)),u.__beforeBegin=null,[Mg,Dg,jg].forEach(h=>h(u,s)),u.isCompiled=!0;let d=null;if(typeof u.keywords=="object"&&(d=u.keywords.$pattern,delete u.keywords.$pattern),u.keywords&&(u.keywords=Hf(u.keywords,e.case_insensitive)),u.lexemes&&d)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return d=d||u.lexemes||/\w+/,a.keywordPatternRe=n(d,!0),s&&(u.begin||(u.begin=/\B|\b/),a.beginRe=n(u.begin),u.endSameAsBegin&&(u.end=u.begin),!u.end&&!u.endsWithParent&&(u.end=/\B|\b/),u.end&&(a.endRe=n(u.end)),a.terminatorEnd=Tr(u.end)||"",u.endsWithParent&&s.terminatorEnd&&(a.terminatorEnd+=(u.end?"|":"")+s.terminatorEnd)),u.illegal&&(a.illegalRe=n(u.illegal)),u.contains||(u.contains=[]),u.contains=[].concat(...u.contains.map(function(h){return $g(h==="self"?u:h)})),u.contains.forEach(function(h){i(h,a)}),u.starts&&i(u.starts,s),a.matcher=o(a),a}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=Mt(e.classNameAliases||{}),i(e)}function Vf(e){return e?e.endsWithParent||Vf(e.starts):!1}function $g(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return Mt(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:Vf(e)?Mt(e,{starts:e.starts?Mt(e.starts):null}):Object.isFrozen(e)?Mt(e):e}var Hg="10.7.3";function Vg(e){return!!(e||e==="")}function Wg(e){const t={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!e.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,In(this.code);let r={};return this.autoDetect?(r=e.highlightAuto(this.code),this.detectedLanguage=r.language):(r=e.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),r.value},autoDetect(){return!this.language||Vg(this.autodetect)},ignoreIllegals(){return!0}},render(r){return r("pre",{},[r("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:t,VuePlugin:{install(r){r.component("highlightjs",t)}}}}const Qg={"after:highlightElement":({el:e,result:t,text:n})=>{const r=ua(e);if(!r.length)return;const l=document.createElement("div");l.innerHTML=t.value,t.value=Kg(r,ua(l),n)}};function Hi(e){return e.nodeName.toLowerCase()}function ua(e){const t=[];return function n(r,l){for(let o=r.firstChild;o;o=o.nextSibling)o.nodeType===3?l+=o.nodeValue.length:o.nodeType===1&&(t.push({event:"start",offset:l,node:o}),l=n(o,l),Hi(o).match(/br|hr|img|input/)||t.push({event:"stop",offset:l,node:o}));return l}(e,0),t}function Kg(e,t,n){let r=0,l="";const o=[];function i(){return!e.length||!t.length?e.length?e:t:e[0].offset!==t[0].offset?e[0].offset"}function s(d){l+=""}function a(d){(d.event==="start"?u:s)(d.node)}for(;e.length||t.length;){let d=i();if(l+=In(n.substring(r,d[0].offset)),r=d[0].offset,d===e){o.reverse().forEach(s);do a(d.splice(0,1)[0]),d=i();while(d===e&&d.length&&d[0].offset===r);o.reverse().forEach(u)}else d[0].event==="start"?o.push(d[0].node):o.pop(),a(d.splice(0,1)[0])}return l+In(n.substr(r))}const sa={},Ho=e=>{console.error(e)},aa=(e,...t)=>{console.log(`WARN: ${e}`,...t)},$e=(e,t)=>{sa[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),sa[`${e}/${t}`]=!0)},Vo=In,ca=Mt,fa=Symbol("nomatch"),Gg=function(e){const t=Object.create(null),n=Object.create(null),r=[];let l=!0;const o=/(^(<[^>]+>|\t|)+|\n)/gm,i="Could not find the language '{}', did you forget to load/include a language module?",u={disableAutodetect:!0,name:"Plain text",contains:[]};let s={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:ig};function a(w){return s.noHighlightRe.test(w)}function d(w){let _=w.className+" ";_+=w.parentNode?w.parentNode.className:"";const z=s.languageDetectRe.exec(_);if(z){const A=pe(z[1]);return A||(aa(i.replace("{}",z[1])),aa("Falling back to no-highlight mode for this block.",w)),A?z[1]:"no-highlight"}return _.split(/\s+/).find(A=>a(A)||pe(A))}function h(w,_,z,A){let G="",Ze="";typeof _=="object"?(G=w,z=_.ignoreIllegals,Ze=_.language,A=void 0):($e("10.7.0","highlight(lang, code, ...args) has been deprecated."),$e("10.7.0",`Please use highlight(code, options) instead. +https://github.com/highlightjs/highlight.js/issues/2277`),Ze=w,G=_);const Be={code:G,language:Ze};T("before:highlight",Be);const Fe=Be.result?Be.result:g(Be.language,Be.code,z,A);return Fe.code=Be.code,T("after:highlight",Fe),Fe}function g(w,_,z,A){function G(O,M){const F=cn.case_insensitive?M[0].toLowerCase():M[0];return Object.prototype.hasOwnProperty.call(O.keywords,F)&&O.keywords[F]}function Ze(){if(!B.keywords){ye.addText(le);return}let O=0;B.keywordPatternRe.lastIndex=0;let M=B.keywordPatternRe.exec(le),F="";for(;M;){F+=le.substring(O,M.index);const Q=G(B,M);if(Q){const[Ne,Ur]=Q;if(ye.addText(F),F="",Fr+=Ur,Ne.startsWith("_"))F+=M[0];else{const od=cn.classNameAliases[Ne]||Ne;ye.addKeyword(M[0],od)}}else F+=M[0];O=B.keywordPatternRe.lastIndex,M=B.keywordPatternRe.exec(le)}F+=le.substr(O),ye.addText(F)}function Be(){if(le==="")return;let O=null;if(typeof B.subLanguage=="string"){if(!t[B.subLanguage]){ye.addText(le);return}O=g(B.subLanguage,le,!0,Wu[B.subLanguage]),Wu[B.subLanguage]=O.top}else O=S(le,B.subLanguage.length?B.subLanguage:null);B.relevance>0&&(Fr+=O.relevance),ye.addSublanguage(O.emitter,O.language)}function Fe(){B.subLanguage!=null?Be():Ze(),le=""}function Ue(O){return O.className&&ye.openNode(cn.classNameAliases[O.className]||O.className),B=Object.create(O,{parent:{value:B}}),B}function Ct(O,M,F){let Q=fg(O.endRe,F);if(Q){if(O["on:end"]){const Ne=new oa(O);O["on:end"](M,Ne),Ne.isMatchIgnored&&(Q=!1)}if(Q){for(;O.endsParent&&O.parent;)O=O.parent;return O}}if(O.endsWithParent)return Ct(O.parent,M,F)}function ed(O){return B.matcher.regexIndex===0?(le+=O[0],1):(ho=!0,0)}function td(O){const M=O[0],F=O.rule,Q=new oa(F),Ne=[F.__beforeBegin,F["on:begin"]];for(const Ur of Ne)if(Ur&&(Ur(O,Q),Q.isMatchIgnored))return ed(M);return F&&F.endSameAsBegin&&(F.endRe=ug(M)),F.skip?le+=M:(F.excludeBegin&&(le+=M),Fe(),!F.returnBegin&&!F.excludeBegin&&(le=M)),Ue(F),F.returnBegin?0:M.length}function nd(O){const M=O[0],F=_.substr(O.index),Q=Ct(B,O,F);if(!Q)return fa;const Ne=B;Ne.skip?le+=M:(Ne.returnEnd||Ne.excludeEnd||(le+=M),Fe(),Ne.excludeEnd&&(le=M));do B.className&&ye.closeNode(),!B.skip&&!B.subLanguage&&(Fr+=B.relevance),B=B.parent;while(B!==Q.parent);return Q.starts&&(Q.endSameAsBegin&&(Q.starts.endRe=Q.endRe),Ue(Q.starts)),Ne.returnEnd?0:M.length}function rd(){const O=[];for(let M=B;M!==cn;M=M.parent)M.className&&O.unshift(M.className);O.forEach(M=>ye.openNode(M))}let Br={};function Vu(O,M){const F=M&&M[0];if(le+=O,F==null)return Fe(),0;if(Br.type==="begin"&&M.type==="end"&&Br.index===M.index&&F===""){if(le+=_.slice(M.index,M.index+1),!l){const Q=new Error("0 width match regex");throw Q.languageName=w,Q.badRule=Br.rule,Q}return 1}if(Br=M,M.type==="begin")return td(M);if(M.type==="illegal"&&!z){const Q=new Error('Illegal lexeme "'+F+'" for mode "'+(B.className||"")+'"');throw Q.mode=B,Q}else if(M.type==="end"){const Q=nd(M);if(Q!==fa)return Q}if(M.type==="illegal"&&F==="")return 1;if(po>1e5&&po>M.index*3)throw new Error("potential infinite loop, way more iterations than matches");return le+=F,F.length}const cn=pe(w);if(!cn)throw Ho(i.replace("{}",w)),new Error('Unknown language: "'+w+'"');const ld=Ug(cn,{plugins:r});let fo="",B=A||ld;const Wu={},ye=new s.__emitter(s);rd();let le="",Fr=0,fn=0,po=0,ho=!1;try{for(B.matcher.considerAll();;){po++,ho?ho=!1:B.matcher.considerAll(),B.matcher.lastIndex=fn;const O=B.matcher.exec(_);if(!O)break;const M=_.substring(fn,O.index),F=Vu(M,O);fn=O.index+F}return Vu(_.substr(fn)),ye.closeAllNodes(),ye.finalize(),fo=ye.toHTML(),{relevance:Math.floor(Fr),value:fo,language:w,illegal:!1,emitter:ye,top:B}}catch(O){if(O.message&&O.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:O.message,context:_.slice(fn-100,fn+100),mode:O.mode},sofar:fo,relevance:0,value:Vo(_),emitter:ye};if(l)return{illegal:!1,relevance:0,value:Vo(_),emitter:ye,language:w,top:B,errorRaised:O};throw O}}function m(w){const _={relevance:0,emitter:new s.__emitter(s),value:Vo(w),illegal:!1,top:u};return _.emitter.addText(w),_}function S(w,_){_=_||s.languages||Object.keys(t);const z=m(w),A=_.filter(pe).filter(Ae).map(Ue=>g(Ue,w,!1));A.unshift(z);const G=A.sort((Ue,Ct)=>{if(Ue.relevance!==Ct.relevance)return Ct.relevance-Ue.relevance;if(Ue.language&&Ct.language){if(pe(Ue.language).supersetOf===Ct.language)return 1;if(pe(Ct.language).supersetOf===Ue.language)return-1}return 0}),[Ze,Be]=G,Fe=Ze;return Fe.second_best=Be,Fe}function v(w){return s.tabReplace||s.useBR?w.replace(o,_=>_===` +`?s.useBR?"
":_:s.tabReplace?_.replace(/\t/g,s.tabReplace):_):w}function R(w,_,z){const A=_?n[_]:z;w.classList.add("hljs"),A&&w.classList.add(A)}const f={"before:highlightElement":({el:w})=>{s.useBR&&(w.innerHTML=w.innerHTML.replace(/\n/g,"").replace(//g,` +`))},"after:highlightElement":({result:w})=>{s.useBR&&(w.value=w.value.replace(/\n/g,"
"))}},c=/^(<[^>]+>|\t)+/gm,p={"after:highlightElement":({result:w})=>{s.tabReplace&&(w.value=w.value.replace(c,_=>_.replace(/\t/g,s.tabReplace)))}};function y(w){let _=null;const z=d(w);if(a(z))return;T("before:highlightElement",{el:w,language:z}),_=w;const A=_.textContent,G=z?h(A,{language:z,ignoreIllegals:!0}):S(A);T("after:highlightElement",{el:w,result:G,text:A}),w.innerHTML=G.value,R(w,z,G.language),w.result={language:G.language,re:G.relevance,relavance:G.relevance},G.second_best&&(w.second_best={language:G.second_best.language,re:G.second_best.relevance,relavance:G.second_best.relevance})}function E(w){w.useBR&&($e("10.3.0","'useBR' will be removed entirely in v11.0"),$e("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),s=ca(s,w)}const C=()=>{if(C.called)return;C.called=!0,$e("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead."),document.querySelectorAll("pre code").forEach(y)};function N(){$e("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),P=!0}let P=!1;function $(){if(document.readyState==="loading"){P=!0;return}document.querySelectorAll("pre code").forEach(y)}function I(){P&&$()}typeof window<"u"&&window.addEventListener&&window.addEventListener("DOMContentLoaded",I,!1);function re(w,_){let z=null;try{z=_(e)}catch(A){if(Ho("Language definition for '{}' could not be registered.".replace("{}",w)),l)Ho(A);else throw A;z=u}z.name||(z.name=w),t[w]=z,z.rawDefinition=_.bind(null,e),z.aliases&&Xe(z.aliases,{languageName:w})}function Ce(w){delete t[w];for(const _ of Object.keys(n))n[_]===w&&delete n[_]}function ze(){return Object.keys(t)}function Ye(w){$e("10.4.0","requireLanguage will be removed entirely in v11."),$e("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const _=pe(w);if(_)return _;throw new Error("The '{}' language is required, but not loaded.".replace("{}",w))}function pe(w){return w=(w||"").toLowerCase(),t[w]||t[n[w]]}function Xe(w,{languageName:_}){typeof w=="string"&&(w=[w]),w.forEach(z=>{n[z.toLowerCase()]=_})}function Ae(w){const _=pe(w);return _&&!_.disableAutodetect}function x(w){w["before:highlightBlock"]&&!w["before:highlightElement"]&&(w["before:highlightElement"]=_=>{w["before:highlightBlock"](Object.assign({block:_.el},_))}),w["after:highlightBlock"]&&!w["after:highlightElement"]&&(w["after:highlightElement"]=_=>{w["after:highlightBlock"](Object.assign({block:_.el},_))})}function D(w){x(w),r.push(w)}function T(w,_){const z=w;r.forEach(function(A){A[z]&&A[z](_)})}function V(w){return $e("10.2.0","fixMarkup will be removed entirely in v11.0"),$e("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),v(w)}function K(w){return $e("10.7.0","highlightBlock will be removed entirely in v12.0"),$e("10.7.0","Please use highlightElement now."),y(w)}Object.assign(e,{highlight:h,highlightAuto:S,highlightAll:$,fixMarkup:V,highlightElement:y,highlightBlock:K,configure:E,initHighlighting:C,initHighlightingOnLoad:N,registerLanguage:re,unregisterLanguage:Ce,listLanguages:ze,getLanguage:pe,registerAliases:Xe,requireLanguage:Ye,autoDetection:Ae,inherit:ca,addPlugin:D,vuePlugin:Wg(e).VuePlugin}),e.debugMode=function(){l=!1},e.safeMode=function(){l=!0},e.versionString=Hg;for(const w in ll)typeof ll[w]=="object"&&Af(ll[w]);return Object.assign(e,ll),e.addPlugin(f),e.addPlugin(Qg),e.addPlugin(p),e};var Yg=Gg({}),Xg=Yg,Wf={exports:{}};(function(e){(function(){var t;t=e.exports=l,t.format=l,t.vsprintf=r,typeof console<"u"&&typeof console.log=="function"&&(t.printf=n);function n(){console.log(l.apply(null,arguments))}function r(o,i){return l.apply(null,[o].concat(i))}function l(o){for(var i=1,u=[].slice.call(arguments),s=0,a=o.length,d="",h,g=!1,m,S,v=!1,R,f=function(){return u[i++]},c=function(){for(var p="";/\d/.test(o[s]);)p+=o[s++],h=o[s];return p.length>0?parseInt(p):null};su.relevance&&(u=s),s.relevance>i.relevance&&(u=i,i=s));return u.language&&(i.secondBest=u),i}function tv(e,t){ut.registerLanguage(e,t)}function nv(){return ut.listLanguages()}function rv(e,t){var n=e,r;t&&(n={},n[e]=t);for(r in n)ut.registerAliases(n[r],{languageName:r})}function kt(e){this.options=e,this.rootNode={children:[]},this.stack=[this.rootNode]}function lv(e,t){this.openNode(t),this.addText(e),this.closeNode()}function ov(e,t){var n=this.stack,r=n[n.length-1],l=e.rootNode.children,o=t?{type:"element",tagName:"span",properties:{className:[t]},children:l}:l;r.children=r.children.concat(o)}function iv(e){var t=this.stack,n,r;e!==""&&(n=t[t.length-1],r=n.children[n.children.length-1],r&&r.type==="text"?r.value+=e:n.children.push({type:"text",value:e}))}function uv(e){var t=this.stack,n=this.options.classPrefix+e,r=t[t.length-1],l={type:"element",tagName:"span",properties:{className:[n]},children:[]};r.children.push(l),t.push(l)}function sv(){this.stack.pop()}function av(){return""}function Kf(){}function cv(e){const t={literal:"true false null"},n=[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],r=[e.QUOTE_STRING_MODE,e.C_NUMBER_MODE],l={end:",",endsWithParent:!0,excludeEnd:!0,contains:r,keywords:t},o={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE],illegal:"\\n"},e.inherit(l,{begin:/:/})].concat(n),illegal:"\\S"},i={begin:"\\[",end:"\\]",contains:[e.inherit(l)],illegal:"\\S"};return r.push(o,i),n.forEach(function(u){r.push(u)}),{name:"JSON",contains:r,keywords:t,illegal:"\\S"}}var fv=cv;const em=Wi(fv);var dv=ng(an,{});dv.registerLanguage=an.registerLanguage;const tm={hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#1E1E1E",color:"#DCDCDC"},"hljs-keyword":{color:"#569CD6"},"hljs-literal":{color:"#569CD6"},"hljs-symbol":{color:"#569CD6"},"hljs-name":{color:"#569CD6"},"hljs-link":{color:"#569CD6",textDecoration:"underline"},"hljs-built_in":{color:"#4EC9B0"},"hljs-type":{color:"#4EC9B0"},"hljs-number":{color:"#B8D7A3"},"hljs-class":{color:"#B8D7A3"},"hljs-string":{color:"#D69D85"},"hljs-meta-string":{color:"#D69D85"},"hljs-regexp":{color:"#9A5334"},"hljs-template-tag":{color:"#9A5334"},"hljs-subst":{color:"#DCDCDC"},"hljs-function":{color:"#DCDCDC"},"hljs-title":{color:"#DCDCDC"},"hljs-params":{color:"#DCDCDC"},"hljs-formula":{color:"#DCDCDC"},"hljs-comment":{color:"#57A64A",fontStyle:"italic"},"hljs-quote":{color:"#57A64A",fontStyle:"italic"},"hljs-doctag":{color:"#608B4E"},"hljs-meta":{color:"#9B9B9B"},"hljs-meta-keyword":{color:"#9B9B9B"},"hljs-tag":{color:"#9B9B9B"},"hljs-variable":{color:"#BD63C5"},"hljs-template-variable":{color:"#BD63C5"},"hljs-attr":{color:"#9CDCFE"},"hljs-attribute":{color:"#9CDCFE"},"hljs-builtin-name":{color:"#9CDCFE"},"hljs-section":{color:"gold"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{color:"#D7BA7D"},"hljs-selector-tag":{color:"#D7BA7D"},"hljs-selector-id":{color:"#D7BA7D"},"hljs-selector-class":{color:"#D7BA7D"},"hljs-selector-attr":{color:"#D7BA7D"},"hljs-selector-pseudo":{color:"#D7BA7D"},"hljs-addition":{backgroundColor:"#144212",display:"inline-block",width:"100%"},"hljs-deletion":{backgroundColor:"#600",display:"inline-block",width:"100%"}};var st=function(){return st=Object.assign||function(t){for(var n,r=1,l=arguments.length;r"u")return Rv;var t=Ov(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Mv=Zf(),jn="data-scroll-locked",Dv=function(e,t,n,r){var l=e.left,o=e.top,i=e.right,u=e.gap;return n===void 0&&(n="margin"),` + .`.concat(hv,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(u,"px ").concat(r,`; + } + body[`).concat(jn,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(l,`px; + padding-top: `).concat(o,`px; + padding-right: `).concat(i,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(u,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(u,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(El,` { + right: `).concat(u,"px ").concat(r,`; + } + + .`).concat(kl,` { + margin-right: `).concat(u,"px ").concat(r,`; + } + + .`).concat(El," .").concat(El,` { + right: 0 `).concat(r,`; + } + + .`).concat(kl," .").concat(kl,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(jn,`] { + `).concat(gv,": ").concat(u,`px; + } +`)},pa=function(){var e=parseInt(document.body.getAttribute(jn)||"0",10);return isFinite(e)?e:0},Iv=function(){j.useEffect(function(){return document.body.setAttribute(jn,(pa()+1).toString()),function(){var e=pa()-1;e<=0?document.body.removeAttribute(jn):document.body.setAttribute(jn,e.toString())}},[])},jv=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,l=r===void 0?"margin":r;Iv();var o=j.useMemo(function(){return Tv(l)},[l]);return j.createElement(Mv,{styles:Dv(o,!t,l,n?"":"!important")})},Vi=!1;if(typeof window<"u")try{var ol=Object.defineProperty({},"passive",{get:function(){return Vi=!0,!0}});window.addEventListener("test",ol,ol),window.removeEventListener("test",ol,ol)}catch{Vi=!1}var pn=Vi?{passive:!1}:!1,zv=function(e){return e.tagName==="TEXTAREA"},Jf=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!zv(e)&&n[t]==="visible")},Av=function(e){return Jf(e,"overflowY")},Bv=function(e){return Jf(e,"overflowX")},ha=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var l=qf(e,r);if(l){var o=bf(e,r),i=o[1],u=o[2];if(i>u)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Fv=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Uv=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},qf=function(e,t){return e==="v"?Av(t):Bv(t)},bf=function(e,t){return e==="v"?Fv(t):Uv(t)},$v=function(e,t){return e==="h"&&t==="rtl"?-1:1},Hv=function(e,t,n,r,l){var o=$v(e,window.getComputedStyle(t).direction),i=o*r,u=n.target,s=t.contains(u),a=!1,d=i>0,h=0,g=0;do{if(!u)break;var m=bf(e,u),S=m[0],v=m[1],R=m[2],f=v-R-o*S;(S||f)&&qf(e,u)&&(h+=f,g+=S);var c=u.parentNode;u=c&&c.nodeType===Node.DOCUMENT_FRAGMENT_NODE?c.host:c}while(!s&&u!==document.body||s&&(t.contains(u)||t===u));return(d&&Math.abs(h)<1||!d&&Math.abs(g)<1)&&(a=!0),a},il=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ga=function(e){return[e.deltaX,e.deltaY]},va=function(e){return e&&"current"in e?e.current:e},Vv=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Wv=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},Qv=0,hn=[];function Kv(e){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),l=j.useState(Qv++)[0],o=j.useState(Zf)[0],i=j.useRef(e);j.useEffect(function(){i.current=e},[e]),j.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(l));var v=pv([e.lockRef.current],(e.shards||[]).map(va),!0).filter(Boolean);return v.forEach(function(R){return R.classList.add("allow-interactivity-".concat(l))}),function(){document.body.classList.remove("block-interactivity-".concat(l)),v.forEach(function(R){return R.classList.remove("allow-interactivity-".concat(l))})}}},[e.inert,e.lockRef.current,e.shards]);var u=j.useCallback(function(v,R){if("touches"in v&&v.touches.length===2||v.type==="wheel"&&v.ctrlKey)return!i.current.allowPinchZoom;var f=il(v),c=n.current,p="deltaX"in v?v.deltaX:c[0]-f[0],y="deltaY"in v?v.deltaY:c[1]-f[1],E,C=v.target,N=Math.abs(p)>Math.abs(y)?"h":"v";if("touches"in v&&N==="h"&&C.type==="range")return!1;var P=ha(N,C);if(!P)return!0;if(P?E=N:(E=N==="v"?"h":"v",P=ha(N,C)),!P)return!1;if(!r.current&&"changedTouches"in v&&(p||y)&&(r.current=E),!E)return!0;var $=r.current||E;return Hv($,R,v,$==="h"?p:y)},[]),s=j.useCallback(function(v){var R=v;if(!(!hn.length||hn[hn.length-1]!==o)){var f="deltaY"in R?ga(R):il(R),c=t.current.filter(function(E){return E.name===R.type&&(E.target===R.target||R.target===E.shadowParent)&&Vv(E.delta,f)})[0];if(c&&c.should){R.cancelable&&R.preventDefault();return}if(!c){var p=(i.current.shards||[]).map(va).filter(Boolean).filter(function(E){return E.contains(R.target)}),y=p.length>0?u(R,p[0]):!i.current.noIsolation;y&&R.cancelable&&R.preventDefault()}}},[]),a=j.useCallback(function(v,R,f,c){var p={name:v,delta:R,target:f,should:c,shadowParent:Gv(f)};t.current.push(p),setTimeout(function(){t.current=t.current.filter(function(y){return y!==p})},1)},[]),d=j.useCallback(function(v){n.current=il(v),r.current=void 0},[]),h=j.useCallback(function(v){a(v.type,ga(v),v.target,u(v,e.lockRef.current))},[]),g=j.useCallback(function(v){a(v.type,il(v),v.target,u(v,e.lockRef.current))},[]);j.useEffect(function(){return hn.push(o),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",s,pn),document.addEventListener("touchmove",s,pn),document.addEventListener("touchstart",d,pn),function(){hn=hn.filter(function(v){return v!==o}),document.removeEventListener("wheel",s,pn),document.removeEventListener("touchmove",s,pn),document.removeEventListener("touchstart",d,pn)}},[]);var m=e.removeScrollBar,S=e.inert;return j.createElement(j.Fragment,null,S?j.createElement(o,{styles:Wv(l)}):null,m?j.createElement(jv,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Gv(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Yv=kv(Xf,Kv);var Xv=j.forwardRef(function(e,t){return j.createElement(co,st({},e,{ref:t,sideCar:Yv}))});Xv.classNames=co.classNames;export{Zv as R,dv as S,bv as _,Of as a,qv as b,Xv as c,pt as d,em as e,Yu as f,Wi as g,Jv as j,j as r,tm as v}; diff --git a/resources/video-editor/assets/three-D1sxpTQl.js b/resources/video-editor/assets/three-D1sxpTQl.js new file mode 100644 index 00000000..c264ce8d --- /dev/null +++ b/resources/video-editor/assets/three-D1sxpTQl.js @@ -0,0 +1,4020 @@ +/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */const Or="182";const ad=2;const od=1,ld=2,cd=3,ud=4;const cn="",Ft="srgb",Bn="srgb-linear",zi="linear",Qe="srgb";const ts="300 es";function Qs(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function Vi(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Ba(){const i=Vi("canvas");return i.style.display="block",i}const ns={};function is(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function Ye(...i){const e="THREE."+i.shift();console.error(e,...i)}function ii(...i){const e=i.join(" ");e in ns||(ns[e]=!0,Oe(...i))}function Ga(i,e,t){return new Promise(function(n,r){function s(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:r();break;case i.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}class Vn{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const r=n[e];if(r!==void 0){const s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const r=n.slice(0);for(let s=0,a=r.length;s>8&255]+xt[i>>16&255]+xt[i>>24&255]+"-"+xt[e&255]+xt[e>>8&255]+"-"+xt[e>>16&15|64]+xt[e>>24&255]+"-"+xt[t&63|128]+xt[t>>8&255]+"-"+xt[t>>16&255]+xt[t>>24&255]+xt[n&255]+xt[n>>8&255]+xt[n>>16&255]+xt[n>>24&255]).toLowerCase()}function Xe(i,e,t){return Math.max(e,Math.min(t,i))}function za(i,e){return(i%e+e)%e}function Ki(i,e,t){return(1-t)*i+t*e}function qn(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function bt(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class fe{constructor(e=0,t=0){fe.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Xe(this.x,e.x,t.x),this.y=Xe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Xe(this.x,e,t),this.y=Xe(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Xe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Xe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),r=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*r+e.x,this.y=s*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class li{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,s,a,o){let c=n[r+0],l=n[r+1],u=n[r+2],h=n[r+3],d=s[a+0],p=s[a+1],_=s[a+2],v=s[a+3];if(o<=0){e[t+0]=c,e[t+1]=l,e[t+2]=u,e[t+3]=h;return}if(o>=1){e[t+0]=d,e[t+1]=p,e[t+2]=_,e[t+3]=v;return}if(h!==v||c!==d||l!==p||u!==_){let m=c*d+l*p+u*_+h*v;m<0&&(d=-d,p=-p,_=-_,v=-v,m=-m);let f=1-o;if(m<.9995){const T=Math.acos(m),S=Math.sin(T);f=Math.sin(f*T)/S,o=Math.sin(o*T)/S,c=c*f+d*o,l=l*f+p*o,u=u*f+_*o,h=h*f+v*o}else{c=c*f+d*o,l=l*f+p*o,u=u*f+_*o,h=h*f+v*o;const T=1/Math.sqrt(c*c+l*l+u*u+h*h);c*=T,l*=T,u*=T,h*=T}}e[t]=c,e[t+1]=l,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,n,r,s,a){const o=n[r],c=n[r+1],l=n[r+2],u=n[r+3],h=s[a],d=s[a+1],p=s[a+2],_=s[a+3];return e[t]=o*_+u*h+c*p-l*d,e[t+1]=c*_+u*d+l*h-o*p,e[t+2]=l*_+u*p+o*d-c*h,e[t+3]=u*_-o*h-c*d-l*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,r=e._y,s=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),u=o(r/2),h=o(s/2),d=c(n/2),p=c(r/2),_=c(s/2);switch(a){case"XYZ":this._x=d*u*h+l*p*_,this._y=l*p*h-d*u*_,this._z=l*u*_+d*p*h,this._w=l*u*h-d*p*_;break;case"YXZ":this._x=d*u*h+l*p*_,this._y=l*p*h-d*u*_,this._z=l*u*_-d*p*h,this._w=l*u*h+d*p*_;break;case"ZXY":this._x=d*u*h-l*p*_,this._y=l*p*h+d*u*_,this._z=l*u*_+d*p*h,this._w=l*u*h-d*p*_;break;case"ZYX":this._x=d*u*h-l*p*_,this._y=l*p*h+d*u*_,this._z=l*u*_-d*p*h,this._w=l*u*h+d*p*_;break;case"YZX":this._x=d*u*h+l*p*_,this._y=l*p*h+d*u*_,this._z=l*u*_-d*p*h,this._w=l*u*h-d*p*_;break;case"XZY":this._x=d*u*h-l*p*_,this._y=l*p*h-d*u*_,this._z=l*u*_+d*p*h,this._w=l*u*h+d*p*_;break;default:Oe("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],r=t[4],s=t[8],a=t[1],o=t[5],c=t[9],l=t[2],u=t[6],h=t[10],d=n+o+h;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(u-c)*p,this._y=(s-l)*p,this._z=(a-r)*p}else if(n>o&&n>h){const p=2*Math.sqrt(1+n-o-h);this._w=(u-c)/p,this._x=.25*p,this._y=(r+a)/p,this._z=(s+l)/p}else if(o>h){const p=2*Math.sqrt(1+o-n-h);this._w=(s-l)/p,this._x=(r+a)/p,this._y=.25*p,this._z=(c+u)/p}else{const p=2*Math.sqrt(1+h-n-o);this._w=(a-r)/p,this._x=(s+l)/p,this._y=(c+u)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Xe(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,r=e._y,s=e._z,a=e._w,o=t._x,c=t._y,l=t._z,u=t._w;return this._x=n*u+a*o+r*l-s*c,this._y=r*u+a*c+s*o-n*l,this._z=s*u+a*l+n*c-r*o,this._w=a*u-n*o-r*c-s*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,r=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,s=-s,a=-a,o=-o);let c=1-t;if(o<.9995){const l=Math.acos(o),u=Math.sin(l);c=Math.sin(c*l)/u,t=Math.sin(t*l)/u,this._x=this._x*c+n*t,this._y=this._y*c+r*t,this._z=this._z*c+s*t,this._w=this._w*c+a*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+r*t,this._z=this._z*c+s*t,this._w=this._w*c+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class U{constructor(e=0,t=0,n=0){U.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(rs.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(rs.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*r,this.y=s[1]*t+s[4]*n+s[7]*r,this.z=s[2]*t+s[5]*n+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*r+s[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,r=this.z,s=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*r-o*n),u=2*(o*t-s*r),h=2*(s*n-a*t);return this.x=t+c*l+a*h-o*u,this.y=n+c*u+o*l-s*h,this.z=r+c*h+s*u-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r,this.y=s[1]*t+s[5]*n+s[9]*r,this.z=s[2]*t+s[6]*n+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Xe(this.x,e.x,t.x),this.y=Xe(this.y,e.y,t.y),this.z=Xe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Xe(this.x,e,t),this.y=Xe(this.y,e,t),this.z=Xe(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Xe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,r=e.y,s=e.z,a=t.x,o=t.y,c=t.z;return this.x=r*c-s*o,this.y=s*a-n*c,this.z=n*o-r*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return $i.copy(this).projectOnVector(e),this.sub($i)}reflect(e){return this.sub($i.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Xe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const $i=new U,rs=new li;class Ve{constructor(e,t,n,r,s,a,o,c,l){Ve.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,c,l)}set(e,t,n,r,s,a,o,c,l){const u=this.elements;return u[0]=e,u[1]=r,u[2]=o,u[3]=t,u[4]=s,u[5]=c,u[6]=n,u[7]=a,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],u=n[4],h=n[7],d=n[2],p=n[5],_=n[8],v=r[0],m=r[3],f=r[6],T=r[1],S=r[4],M=r[7],R=r[2],b=r[5],w=r[8];return s[0]=a*v+o*T+c*R,s[3]=a*m+o*S+c*b,s[6]=a*f+o*M+c*w,s[1]=l*v+u*T+h*R,s[4]=l*m+u*S+h*b,s[7]=l*f+u*M+h*w,s[2]=d*v+p*T+_*R,s[5]=d*m+p*S+_*b,s[8]=d*f+p*M+_*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],u=e[8];return t*a*u-t*o*l-n*s*u+n*o*c+r*s*l-r*a*c}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],u=e[8],h=u*a-o*l,d=o*c-u*s,p=l*s-a*c,_=t*h+n*d+r*p;if(_===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/_;return e[0]=h*v,e[1]=(r*l-u*n)*v,e[2]=(o*n-r*a)*v,e[3]=d*v,e[4]=(u*t-r*c)*v,e[5]=(r*s-o*t)*v,e[6]=p*v,e[7]=(n*c-l*t)*v,e[8]=(a*t-n*s)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,s,a,o){const c=Math.cos(s),l=Math.sin(s);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-r*l,r*c,-r*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ji.makeScale(e,t)),this}rotate(e){return this.premultiply(ji.makeRotation(-e)),this}translate(e,t){return this.premultiply(ji.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<9;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const ji=new Ve,ss=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),as=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Va(){const i={enabled:!0,workingColorSpace:Bn,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Qe&&(r.r=en(r.r),r.g=en(r.g),r.b=en(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Qe&&(r.r=On(r.r),r.g=On(r.g),r.b=On(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===cn?zi:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return ii("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return ii("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Bn]:{primaries:e,whitePoint:n,transfer:zi,toXYZ:ss,fromXYZ:as,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Ft},outputColorSpaceConfig:{drawingBufferColorSpace:Ft}},[Ft]:{primaries:e,whitePoint:n,transfer:Qe,toXYZ:ss,fromXYZ:as,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Ft}}}),i}const Ze=Va();function en(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function On(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Tn;class Ha{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Tn===void 0&&(Tn=Vi("canvas")),Tn.width=e.width,Tn.height=e.height;const r=Tn.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=Tn}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Vi("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const r=n.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a1),this.pmremVersion=0}get width(){return this.source.getSize(er).x}get height(){return this.source.getSize(er).y}get depth(){return this.source.getSize(er).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Oe(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){Oe(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case 1e3:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case 1e3:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}St.DEFAULT_IMAGE=null;St.DEFAULT_MAPPING=300;St.DEFAULT_ANISOTROPY=1;class ft{constructor(e=0,t=0,n=0,r=1){ft.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,s;const c=e.elements,l=c[0],u=c[4],h=c[8],d=c[1],p=c[5],_=c[9],v=c[2],m=c[6],f=c[10];if(Math.abs(u-d)<.01&&Math.abs(h-v)<.01&&Math.abs(_-m)<.01){if(Math.abs(u+d)<.1&&Math.abs(h+v)<.1&&Math.abs(_+m)<.1&&Math.abs(l+p+f-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const S=(l+1)/2,M=(p+1)/2,R=(f+1)/2,b=(u+d)/4,w=(h+v)/4,D=(_+m)/4;return S>M&&S>R?S<.01?(n=0,r=.707106781,s=.707106781):(n=Math.sqrt(S),r=b/n,s=w/n):M>R?M<.01?(n=.707106781,r=0,s=.707106781):(r=Math.sqrt(M),n=b/r,s=D/r):R<.01?(n=.707106781,r=.707106781,s=0):(s=Math.sqrt(R),n=w/s,r=D/s),this.set(n,r,s,t),this}let T=Math.sqrt((m-_)*(m-_)+(h-v)*(h-v)+(d-u)*(d-u));return Math.abs(T)<.001&&(T=1),this.x=(m-_)/T,this.y=(h-v)/T,this.z=(d-u)/T,this.w=Math.acos((l+p+f-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Xe(this.x,e.x,t.x),this.y=Xe(this.y,e.y,t.y),this.z=Xe(this.z,e.z,t.z),this.w=Xe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Xe(this.x,e,t),this.y=Xe(this.y,e,t),this.z=Xe(this.z,e,t),this.w=Xe(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Xe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Xa extends Vn{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new ft(0,0,e,t),this.scissorTest=!1,this.viewport=new ft(0,0,e,t);const r={width:e,height:t,depth:n.depth},s=new St(r);this.textures=[];const a=n.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ut),Ut.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Yn),pi.subVectors(this.max,Yn),An.subVectors(e.a,Yn),bn.subVectors(e.b,Yn),Rn.subVectors(e.c,Yn),nn.subVectors(bn,An),rn.subVectors(Rn,bn),dn.subVectors(An,Rn);let t=[0,-nn.z,nn.y,0,-rn.z,rn.y,0,-dn.z,dn.y,nn.z,0,-nn.x,rn.z,0,-rn.x,dn.z,0,-dn.x,-nn.y,nn.x,0,-rn.y,rn.x,0,-dn.y,dn.x,0];return!tr(t,An,bn,Rn,pi)||(t=[1,0,0,0,1,0,0,0,1],!tr(t,An,bn,Rn,pi))?!1:(mi.crossVectors(nn,rn),t=[mi.x,mi.y,mi.z],tr(t,An,bn,Rn,pi))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ut).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ut).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Zt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Zt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Zt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Zt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Zt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Zt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Zt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Zt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Zt),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Zt=[new U,new U,new U,new U,new U,new U,new U,new U],Ut=new U,di=new ci,An=new U,bn=new U,Rn=new U,nn=new U,rn=new U,dn=new U,Yn=new U,pi=new U,mi=new U,pn=new U;function tr(i,e,t,n,r){for(let s=0,a=i.length-3;s<=a;s+=3){pn.fromArray(i,s);const o=r.x*Math.abs(pn.x)+r.y*Math.abs(pn.y)+r.z*Math.abs(pn.z),c=e.dot(pn),l=t.dot(pn),u=n.dot(pn);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>o)return!1}return!0}const Ya=new ci,Zn=new U,nr=new U;class Hi{constructor(e=new U,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):Ya.setFromPoints(e).getCenter(n);let r=0;for(let s=0,a=e.length;sthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Zn.subVectors(e,this.center);const t=Zn.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),r=(n-this.radius)*.5;this.center.addScaledVector(Zn,r/n),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(nr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Zn.copy(e.center).add(nr)),this.expandByPoint(Zn.copy(e.center).sub(nr))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Jt=new U,ir=new U,gi=new U,sn=new U,rr=new U,_i=new U,sr=new U;class ta{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Jt)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Jt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Jt.copy(this.origin).addScaledVector(this.direction,t),Jt.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){ir.copy(e).add(t).multiplyScalar(.5),gi.copy(t).sub(e).normalize(),sn.copy(this.origin).sub(ir);const s=e.distanceTo(t)*.5,a=-this.direction.dot(gi),o=sn.dot(this.direction),c=-sn.dot(gi),l=sn.lengthSq(),u=Math.abs(1-a*a);let h,d,p,_;if(u>0)if(h=a*c-o,d=a*o-c,_=s*u,h>=0)if(d>=-_)if(d<=_){const v=1/u;h*=v,d*=v,p=h*(h+a*d+2*o)+d*(a*h+d+2*c)+l}else d=s,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*c)+l;else d=-s,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*c)+l;else d<=-_?(h=Math.max(0,-(-a*s+o)),d=h>0?-s:Math.min(Math.max(-s,-c),s),p=-h*h+d*(d+2*c)+l):d<=_?(h=0,d=Math.min(Math.max(-s,-c),s),p=d*(d+2*c)+l):(h=Math.max(0,-(a*s+o)),d=h>0?s:Math.min(Math.max(-s,-c),s),p=-h*h+d*(d+2*c)+l);else d=a>0?-s:s,h=Math.max(0,-(a*d+o)),p=-h*h+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),r&&r.copy(ir).addScaledVector(gi,d),p}intersectSphere(e,t){Jt.subVectors(e.center,this.origin);const n=Jt.dot(this.direction),r=Jt.dot(Jt)-n*n,s=e.radius*e.radius;if(r>s)return null;const a=Math.sqrt(s-r),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,s,a,o,c;const l=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,d=this.origin;return l>=0?(n=(e.min.x-d.x)*l,r=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,r=(e.min.x-d.x)*l),u>=0?(s=(e.min.y-d.y)*u,a=(e.max.y-d.y)*u):(s=(e.max.y-d.y)*u,a=(e.min.y-d.y)*u),n>a||s>r||((s>n||isNaN(n))&&(n=s),(a=0?(o=(e.min.z-d.z)*h,c=(e.max.z-d.z)*h):(o=(e.max.z-d.z)*h,c=(e.min.z-d.z)*h),n>c||o>r)||((o>n||n!==n)&&(n=o),(c=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Jt)!==null}intersectTriangle(e,t,n,r,s){rr.subVectors(t,e),_i.subVectors(n,e),sr.crossVectors(rr,_i);let a=this.direction.dot(sr),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;sn.subVectors(this.origin,e);const c=o*this.direction.dot(_i.crossVectors(sn,_i));if(c<0)return null;const l=o*this.direction.dot(rr.cross(sn));if(l<0||c+l>a)return null;const u=-o*sn.dot(sr);return u<0?null:this.at(u/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ot{constructor(e,t,n,r,s,a,o,c,l,u,h,d,p,_,v,m){ot.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,c,l,u,h,d,p,_,v,m)}set(e,t,n,r,s,a,o,c,l,u,h,d,p,_,v,m){const f=this.elements;return f[0]=e,f[4]=t,f[8]=n,f[12]=r,f[1]=s,f[5]=a,f[9]=o,f[13]=c,f[2]=l,f[6]=u,f[10]=h,f[14]=d,f[3]=p,f[7]=_,f[11]=v,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ot().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,r=1/Cn.setFromMatrixColumn(e,0).length(),s=1/Cn.setFromMatrixColumn(e,1).length(),a=1/Cn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,r=e.y,s=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(r),l=Math.sin(r),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const d=a*u,p=a*h,_=o*u,v=o*h;t[0]=c*u,t[4]=-c*h,t[8]=l,t[1]=p+_*l,t[5]=d-v*l,t[9]=-o*c,t[2]=v-d*l,t[6]=_+p*l,t[10]=a*c}else if(e.order==="YXZ"){const d=c*u,p=c*h,_=l*u,v=l*h;t[0]=d+v*o,t[4]=_*o-p,t[8]=a*l,t[1]=a*h,t[5]=a*u,t[9]=-o,t[2]=p*o-_,t[6]=v+d*o,t[10]=a*c}else if(e.order==="ZXY"){const d=c*u,p=c*h,_=l*u,v=l*h;t[0]=d-v*o,t[4]=-a*h,t[8]=_+p*o,t[1]=p+_*o,t[5]=a*u,t[9]=v-d*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const d=a*u,p=a*h,_=o*u,v=o*h;t[0]=c*u,t[4]=_*l-p,t[8]=d*l+v,t[1]=c*h,t[5]=v*l+d,t[9]=p*l-_,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const d=a*c,p=a*l,_=o*c,v=o*l;t[0]=c*u,t[4]=v-d*h,t[8]=_*h+p,t[1]=h,t[5]=a*u,t[9]=-o*u,t[2]=-l*u,t[6]=p*h+_,t[10]=d-v*h}else if(e.order==="XZY"){const d=a*c,p=a*l,_=o*c,v=o*l;t[0]=c*u,t[4]=-h,t[8]=l*u,t[1]=d*h+v,t[5]=a*u,t[9]=p*h-_,t[2]=_*h-p,t[6]=o*u,t[10]=v*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Za,e,Ja)}lookAt(e,t,n){const r=this.elements;return wt.subVectors(e,t),wt.lengthSq()===0&&(wt.z=1),wt.normalize(),an.crossVectors(n,wt),an.lengthSq()===0&&(Math.abs(n.z)===1?wt.x+=1e-4:wt.z+=1e-4,wt.normalize(),an.crossVectors(n,wt)),an.normalize(),xi.crossVectors(wt,an),r[0]=an.x,r[4]=xi.x,r[8]=wt.x,r[1]=an.y,r[5]=xi.y,r[9]=wt.y,r[2]=an.z,r[6]=xi.z,r[10]=wt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],u=n[1],h=n[5],d=n[9],p=n[13],_=n[2],v=n[6],m=n[10],f=n[14],T=n[3],S=n[7],M=n[11],R=n[15],b=r[0],w=r[4],D=r[8],x=r[12],E=r[1],P=r[5],O=r[9],B=r[13],k=r[2],q=r[6],z=r[10],H=r[14],j=r[3],de=r[7],ae=r[11],ce=r[15];return s[0]=a*b+o*E+c*k+l*j,s[4]=a*w+o*P+c*q+l*de,s[8]=a*D+o*O+c*z+l*ae,s[12]=a*x+o*B+c*H+l*ce,s[1]=u*b+h*E+d*k+p*j,s[5]=u*w+h*P+d*q+p*de,s[9]=u*D+h*O+d*z+p*ae,s[13]=u*x+h*B+d*H+p*ce,s[2]=_*b+v*E+m*k+f*j,s[6]=_*w+v*P+m*q+f*de,s[10]=_*D+v*O+m*z+f*ae,s[14]=_*x+v*B+m*H+f*ce,s[3]=T*b+S*E+M*k+R*j,s[7]=T*w+S*P+M*q+R*de,s[11]=T*D+S*O+M*z+R*ae,s[15]=T*x+S*B+M*H+R*ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],r=e[8],s=e[12],a=e[1],o=e[5],c=e[9],l=e[13],u=e[2],h=e[6],d=e[10],p=e[14],_=e[3],v=e[7],m=e[11],f=e[15],T=c*p-l*d,S=o*p-l*h,M=o*d-c*h,R=a*p-l*u,b=a*d-c*u,w=a*h-o*u;return t*(v*T-m*S+f*M)-n*(_*T-m*R+f*b)+r*(_*S-v*R+f*w)-s*(_*M-v*b+m*w)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],u=e[8],h=e[9],d=e[10],p=e[11],_=e[12],v=e[13],m=e[14],f=e[15],T=h*m*l-v*d*l+v*c*p-o*m*p-h*c*f+o*d*f,S=_*d*l-u*m*l-_*c*p+a*m*p+u*c*f-a*d*f,M=u*v*l-_*h*l+_*o*p-a*v*p-u*o*f+a*h*f,R=_*h*c-u*v*c-_*o*d+a*v*d+u*o*m-a*h*m,b=t*T+n*S+r*M+s*R;if(b===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/b;return e[0]=T*w,e[1]=(v*d*s-h*m*s-v*r*p+n*m*p+h*r*f-n*d*f)*w,e[2]=(o*m*s-v*c*s+v*r*l-n*m*l-o*r*f+n*c*f)*w,e[3]=(h*c*s-o*d*s-h*r*l+n*d*l+o*r*p-n*c*p)*w,e[4]=S*w,e[5]=(u*m*s-_*d*s+_*r*p-t*m*p-u*r*f+t*d*f)*w,e[6]=(_*c*s-a*m*s-_*r*l+t*m*l+a*r*f-t*c*f)*w,e[7]=(a*d*s-u*c*s+u*r*l-t*d*l-a*r*p+t*c*p)*w,e[8]=M*w,e[9]=(_*h*s-u*v*s-_*n*p+t*v*p+u*n*f-t*h*f)*w,e[10]=(a*v*s-_*o*s+_*n*l-t*v*l-a*n*f+t*o*f)*w,e[11]=(u*o*s-a*h*s-u*n*l+t*h*l+a*n*p-t*o*p)*w,e[12]=R*w,e[13]=(u*v*r-_*h*r+_*n*d-t*v*d-u*n*m+t*h*m)*w,e[14]=(_*o*r-a*v*r-_*n*c+t*v*c+a*n*m-t*o*m)*w,e[15]=(a*h*r-u*o*r+u*n*c-t*h*c-a*n*d+t*o*d)*w,this}scale(e){const t=this.elements,n=e.x,r=e.y,s=e.z;return t[0]*=n,t[4]*=r,t[8]*=s,t[1]*=n,t[5]*=r,t[9]*=s,t[2]*=n,t[6]*=r,t[10]*=s,t[3]*=n,t[7]*=r,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),r=Math.sin(t),s=1-n,a=e.x,o=e.y,c=e.z,l=s*a,u=s*o;return this.set(l*a+n,l*o-r*c,l*c+r*o,0,l*o+r*c,u*o+n,u*c-r*a,0,l*c-r*o,u*c+r*a,s*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,s,a){return this.set(1,n,s,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){const r=this.elements,s=t._x,a=t._y,o=t._z,c=t._w,l=s+s,u=a+a,h=o+o,d=s*l,p=s*u,_=s*h,v=a*u,m=a*h,f=o*h,T=c*l,S=c*u,M=c*h,R=n.x,b=n.y,w=n.z;return r[0]=(1-(v+f))*R,r[1]=(p+M)*R,r[2]=(_-S)*R,r[3]=0,r[4]=(p-M)*b,r[5]=(1-(d+f))*b,r[6]=(m+T)*b,r[7]=0,r[8]=(_+S)*w,r[9]=(m-T)*w,r[10]=(1-(d+v))*w,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){const r=this.elements;if(e.x=r[12],e.y=r[13],e.z=r[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let s=Cn.set(r[0],r[1],r[2]).length();const a=Cn.set(r[4],r[5],r[6]).length(),o=Cn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(s=-s),It.copy(this);const l=1/s,u=1/a,h=1/o;return It.elements[0]*=l,It.elements[1]*=l,It.elements[2]*=l,It.elements[4]*=u,It.elements[5]*=u,It.elements[6]*=u,It.elements[8]*=h,It.elements[9]*=h,It.elements[10]*=h,t.setFromRotationMatrix(It),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,r,s,a,o=2e3,c=!1){const l=this.elements,u=2*s/(t-e),h=2*s/(n-r),d=(t+e)/(t-e),p=(n+r)/(n-r);let _,v;if(c)_=s/(a-s),v=a*s/(a-s);else if(o===2e3)_=-(a+s)/(a-s),v=-2*a*s/(a-s);else if(o===2001)_=-a/(a-s),v=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=u,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=h,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=_,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,r,s,a,o=2e3,c=!1){const l=this.elements,u=2/(t-e),h=2/(n-r),d=-(t+e)/(t-e),p=-(n+r)/(n-r);let _,v;if(c)_=1/(a-s),v=a/(a-s);else if(o===2e3)_=-2/(a-s),v=-(a+s)/(a-s);else if(o===2001)_=-1/(a-s),v=-s/(a-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=u,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=h,l[9]=0,l[13]=p,l[2]=0,l[6]=0,l[10]=_,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<16;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const Cn=new U,It=new ot,Za=new U(0,0,0),Ja=new U(1,1,1),an=new U,xi=new U,wt=new U,os=new ot,ls=new li;class Wt{constructor(e=0,t=0,n=0,r=Wt.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const r=e.elements,s=r[0],a=r[4],o=r[8],c=r[1],l=r[5],u=r[9],h=r[2],d=r[6],p=r[10];switch(t){case"XYZ":this._y=Math.asin(Xe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Xe(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Xe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,p),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Xe(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(Xe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-Xe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-u,p),this._y=0);break;default:Oe("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return os.makeRotationFromQuaternion(e),this.setFromRotationMatrix(os,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ls.setFromEuler(this),this.setFromQuaternion(ls,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Wt.DEFAULT_ORDER="XYZ";class na{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,u=c.length;l0){r.children=[];for(let o=0;o0){r.animations=[];for(let o=0;o0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),u.length>0&&(n.images=u),h.length>0&&(n.shapes=h),d.length>0&&(n.skeletons=d),p.length>0&&(n.animations=p),_.length>0&&(n.nodes=_)}return n.object=r,n;function a(o){const c=[];for(const l in o){const u=o[l];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,n,r,s){Nt.subVectors(r,t),$t.subVectors(n,t),or.subVectors(e,t);const a=Nt.dot(Nt),o=Nt.dot($t),c=Nt.dot(or),l=$t.dot($t),u=$t.dot(or),h=a*l-o*o;if(h===0)return s.set(0,0,0),null;const d=1/h,p=(l*c-o*u)*d,_=(a*u-o*c)*d;return s.set(1-p-_,_,p)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,jt)===null?!1:jt.x>=0&&jt.y>=0&&jt.x+jt.y<=1}static getInterpolation(e,t,n,r,s,a,o,c){return this.getBarycoord(e,t,n,r,jt)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,jt.x),c.addScaledVector(a,jt.y),c.addScaledVector(o,jt.z),c)}static getInterpolatedAttribute(e,t,n,r,s,a){return hr.setScalar(0),fr.setScalar(0),dr.setScalar(0),hr.fromBufferAttribute(e,t),fr.fromBufferAttribute(e,n),dr.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(hr,s.x),a.addScaledVector(fr,s.y),a.addScaledVector(dr,s.z),a}static isFrontFacing(e,t,n,r){return Nt.subVectors(n,t),$t.subVectors(e,t),Nt.cross($t).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Nt.subVectors(this.c,this.b),$t.subVectors(this.a,this.b),Nt.cross($t).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Bt.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Bt.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,s){return Bt.getInterpolation(e,this.a,this.b,this.c,t,n,r,s)}containsPoint(e){return Bt.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Bt.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,r=this.b,s=this.c;let a,o;Dn.subVectors(r,n),Ln.subVectors(s,n),lr.subVectors(e,n);const c=Dn.dot(lr),l=Ln.dot(lr);if(c<=0&&l<=0)return t.copy(n);cr.subVectors(e,r);const u=Dn.dot(cr),h=Ln.dot(cr);if(u>=0&&h<=u)return t.copy(r);const d=c*h-u*l;if(d<=0&&c>=0&&u<=0)return a=c/(c-u),t.copy(n).addScaledVector(Dn,a);ur.subVectors(e,s);const p=Dn.dot(ur),_=Ln.dot(ur);if(_>=0&&p<=_)return t.copy(s);const v=p*l-c*_;if(v<=0&&l>=0&&_<=0)return o=l/(l-_),t.copy(n).addScaledVector(Ln,o);const m=u*_-p*h;if(m<=0&&h-u>=0&&p-_>=0)return ps.subVectors(s,r),o=(h-u)/(h-u+(p-_)),t.copy(r).addScaledVector(ps,o);const f=1/(m+v+d);return a=v*f,o=d*f,t.copy(n).addScaledVector(Dn,a).addScaledVector(Ln,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const ia={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},on={h:0,s:0,l:0},Si={h:0,s:0,l:0};function pr(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Je{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ft){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ze.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Ze.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ze.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Ze.workingColorSpace){if(e=za(e,1),t=Xe(t,0,1),n=Xe(n,0,1),t===0)this.r=this.g=this.b=n;else{const s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=pr(a,s,e+1/3),this.g=pr(a,s,e),this.b=pr(a,s,e-1/3)}return Ze.colorSpaceToWorking(this,r),this}setStyle(e,t=Ft){function n(s){s!==void 0&&parseFloat(s)<1&&Oe("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Oe("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);Oe("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ft){const n=ia[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Oe("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=en(e.r),this.g=en(e.g),this.b=en(e.b),this}copyLinearToSRGB(e){return this.r=On(e.r),this.g=On(e.g),this.b=On(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ft){return Ze.workingToColorSpace(vt.copy(this),e),Math.round(Xe(vt.r*255,0,255))*65536+Math.round(Xe(vt.g*255,0,255))*256+Math.round(Xe(vt.b*255,0,255))}getHexString(e=Ft){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ze.workingColorSpace){Ze.workingToColorSpace(vt.copy(this),t);const n=vt.r,r=vt.g,s=vt.b,a=Math.max(n,r,s),o=Math.min(n,r,s);let c,l;const u=(o+a)/2;if(o===a)c=0,l=0;else{const h=a-o;switch(l=u<=.5?h/(a+o):h/(2-a-o),a){case n:c=(r-s)/h+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Oe(`Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){Oe(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(s){const a=[];for(const o in s){const c=s[o];delete c.metadata,a.push(c)}return a}if(t){const s=r(e.textures),a=r(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const r=t.length;n=new Array(r);for(let s=0;s!==r;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class ra extends kn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Je(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Wt,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const dt=new U,Mi=new fe;let to=0;class kt{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:to++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,s=this.itemSize;rt.count&&Oe("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ci);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ye("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const r={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],u=[];for(let h=0,d=l.length;h0&&(r[c]=u,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const r=e.attributes;for(const l in r){const u=r[l];this.setAttribute(l,u.clone(t))}const s=e.morphAttributes;for(const l in s){const u=[],h=s[l];for(let d=0,p=h.length;d0){const r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s(e.far-e.near)**2))&&(ms.copy(s).invert(),mn.copy(e.ray).applyMatrix4(ms),!(n.boundingBox!==null&&mn.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,mn)))}_computeIntersections(e,t,n){let r;const s=this.geometry,a=this.material,o=s.index,c=s.attributes.position,l=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,d=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let _=0,v=d.length;_t.far?null:{distance:l,point:Ri.clone(),object:i}}function Ci(i,e,t,n,r,s,a,o,c,l){i.getVertexPosition(o,Ei),i.getVertexPosition(c,Ti),i.getVertexPosition(l,Ai);const u=io(i,e,t,n,Ei,Ti,Ai,_s);if(u){const h=new U;Bt.getBarycoord(_s,Ei,Ti,Ai,h),r&&(u.uv=Bt.getInterpolatedAttribute(r,o,c,l,h,new fe)),s&&(u.uv1=Bt.getInterpolatedAttribute(s,o,c,l,h,new fe)),a&&(u.normal=Bt.getInterpolatedAttribute(a,o,c,l,h,new U),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));const d={a:o,b:c,c:l,normal:new U,materialIndex:0};Bt.getNormal(Ei,Ti,Ai,d.normal),u.face=d,u.barycoord=h}return u}class ui extends Et{constructor(e=1,t=1,n=1,r=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:s,depthSegments:a};const o=this;r=Math.floor(r),s=Math.floor(s),a=Math.floor(a);const c=[],l=[],u=[],h=[];let d=0,p=0;_("z","y","x",-1,-1,n,t,e,a,s,0),_("z","y","x",1,-1,n,t,-e,a,s,1),_("x","z","y",1,1,e,n,t,r,a,2),_("x","z","y",1,-1,e,n,-t,r,a,3),_("x","y","z",1,-1,e,t,n,r,s,4),_("x","y","z",-1,-1,e,t,-n,r,s,5),this.setIndex(c),this.setAttribute("position",new ct(l,3)),this.setAttribute("normal",new ct(u,3)),this.setAttribute("uv",new ct(h,2));function _(v,m,f,T,S,M,R,b,w,D,x){const E=M/w,P=R/D,O=M/2,B=R/2,k=b/2,q=w+1,z=D+1;let H=0,j=0;const de=new U;for(let ae=0;ae0?1:-1,u.push(de.x,de.y,de.z),h.push(Ge/w),h.push(1-ae/D),H+=1}}for(let ae=0;ae0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const r in this.extensions)this.extensions[r]===!0&&(n[r]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class la extends _t{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ot,this.projectionMatrix=new ot,this.projectionMatrixInverse=new ot,this.coordinateSystem=2e3,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ln=new U,xs=new fe,vs=new fe;class Ot extends la{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=wr*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Ji*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return wr*2*Math.atan(Math.tan(Ji*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ln.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ln.x,ln.y).multiplyScalar(-e/ln.z),ln.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ln.x,ln.y).multiplyScalar(-e/ln.z)}getViewSize(e,t){return this.getViewBounds(e,xs,vs),t.subVectors(vs,xs)}setViewOffset(e,t,n,r,s,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Ji*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,s=-.5*r;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;s+=a.offsetX*r/c,t-=a.offsetY*n/l,r*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Un=-90,In=1;class lo extends _t{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new Ot(Un,In,e,t);r.layers=this.layers,this.add(r);const s=new Ot(Un,In,e,t);s.layers=this.layers,this.add(s);const a=new Ot(Un,In,e,t);a.layers=this.layers,this.add(a);const o=new Ot(Un,In,e,t);o.layers=this.layers,this.add(o);const c=new Ot(Un,In,e,t);c.layers=this.layers,this.add(c);const l=new Ot(Un,In,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,r,s,a,o,c]=t;for(const l of t)this.remove(l);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,a,o,c,l,u]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),_=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,s),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,c),e.setRenderTarget(n,4,r),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,r),e.render(t,u),e.setRenderTarget(h,d,p),e.xr.enabled=_,n.texture.needsPMREMUpdate=!0}}class ca extends St{constructor(e=[],t=301,n,r,s,a,o,c,l,u){super(e,t,n,r,s,a,o,c,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class ua extends Ht{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new ca(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new ui(5,5,5),s=new Xt({name:"CubemapFromEquirect",uniforms:Gn(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});s.uniforms.tEquirect.value=t;const a=new tn(r,s),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=1006),new lo(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){const s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,r);e.setRenderTarget(s)}}class wi extends _t{constructor(){super(),this.isGroup=!0,this.type="Group"}}const co={type:"move"};class _r{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new wi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new wi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new U,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new U),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new wi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new U,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new U),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,s=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),f=this._getHandJoint(l,v);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}const u=l.joints["index-finger-tip"],h=l.joints["thumb-tip"],d=u.position.distanceTo(h.position),p=.02,_=.005;l.inputState.pinching&&d>p+_?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=p-_&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(co)))}return o!==null&&(o.visible=r!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new wi;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class hd extends _t{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Wt,this.environmentIntensity=1,this.environmentRotation=new Wt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class uo extends St{constructor(e=null,t=1,n=1,r,s,a,o,c,l=1003,u=1003,h,d){super(null,a,o,c,l,u,r,s,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const xr=new U,ho=new U,fo=new Ve;class vn{constructor(e=new U(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const r=xr.subVectors(n,t).cross(ho.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(xr),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/r;return s<0||s>1?null:t.copy(e.start).addScaledVector(n,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||fo.getNormalMatrix(e),r=this.coplanarPoint(xr).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const gn=new Hi,po=new fe(.5,.5),Pi=new U;class Gr{constructor(e=new vn,t=new vn,n=new vn,r=new vn,s=new vn,a=new vn){this.planes=[e,t,n,r,s,a]}set(e,t,n,r,s,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){const r=this.planes,s=e.elements,a=s[0],o=s[1],c=s[2],l=s[3],u=s[4],h=s[5],d=s[6],p=s[7],_=s[8],v=s[9],m=s[10],f=s[11],T=s[12],S=s[13],M=s[14],R=s[15];if(r[0].setComponents(l-a,p-u,f-_,R-T).normalize(),r[1].setComponents(l+a,p+u,f+_,R+T).normalize(),r[2].setComponents(l+o,p+h,f+v,R+S).normalize(),r[3].setComponents(l-o,p-h,f-v,R-S).normalize(),n)r[4].setComponents(c,d,m,M).normalize(),r[5].setComponents(l-c,p-d,f-m,R-M).normalize();else if(r[4].setComponents(l-c,p-d,f-m,R-M).normalize(),t===2e3)r[5].setComponents(l+c,p+d,f+m,R+M).normalize();else if(t===2001)r[5].setComponents(c,d,m,M).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),gn.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),gn.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(gn)}intersectsSprite(e){gn.center.set(0,0,0);const t=po.distanceTo(e.center);return gn.radius=.7071067811865476+t,gn.applyMatrix4(e.matrixWorld),this.intersectsSphere(gn)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)0?e.max.x:e.min.x,Pi.y=r.normal.y>0?e.max.y:e.min.y,Pi.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Pi)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class mo extends kn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Je(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Ss=new ot,Pr=new ta,Di=new Hi,Li=new U;class fd extends _t{constructor(e=new Et,t=new mo){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,r=this.matrixWorld,s=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Di.copy(n.boundingSphere),Di.applyMatrix4(r),Di.radius+=s,e.ray.intersectsSphere(Di)===!1)return;Ss.copy(r).invert(),Pr.copy(e.ray).applyMatrix4(Ss);const o=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=o*o,l=n.index,h=n.attributes.position;if(l!==null){const d=Math.max(0,a.start),p=Math.min(l.count,a.start+a.count);for(let _=d,v=p;_0){const r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;sr.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class dd extends St{constructor(e,t,n,r,s,a,o,c,l){super(e,t,n,r,s,a,o,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class ri extends St{constructor(e,t,n=1014,r,s,a,o=1003,c=1003,l,u=1026,h=1){if(u!==1026&&u!==1027)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:h};super(d,r,s,a,o,c,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Br(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class go extends ri{constructor(e,t=1014,n=301,r,s,a=1003,o=1003,c,l=1026){const u={width:e,height:e,depth:1},h=[u,u,u,u,u,u];super(e,e,t,n,r,s,a,o,c,l),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class ha extends St{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class zr extends Et{constructor(e=1,t=1,n=1,r=32,s=1,a=!1,o=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:c};const l=this;r=Math.floor(r),s=Math.floor(s);const u=[],h=[],d=[],p=[];let _=0;const v=[],m=n/2;let f=0;T(),a===!1&&(e>0&&S(!0),t>0&&S(!1)),this.setIndex(u),this.setAttribute("position",new ct(h,3)),this.setAttribute("normal",new ct(d,3)),this.setAttribute("uv",new ct(p,2));function T(){const M=new U,R=new U;let b=0;const w=(t-e)/n;for(let D=0;D<=s;D++){const x=[],E=D/s,P=E*(t-e)+e;for(let O=0;O<=r;O++){const B=O/r,k=B*c+o,q=Math.sin(k),z=Math.cos(k);R.x=P*q,R.y=-E*n+m,R.z=P*z,h.push(R.x,R.y,R.z),M.set(q,w,z).normalize(),d.push(M.x,M.y,M.z),p.push(B,1-E),x.push(_++)}v.push(x)}for(let D=0;D0||x!==0)&&(u.push(E,P,B),b+=3),(t>0||x!==s-1)&&(u.push(P,O,B),b+=3)}l.addGroup(f,b,0),f+=b}function S(M){const R=_,b=new fe,w=new U;let D=0;const x=M===!0?e:t,E=M===!0?1:-1;for(let O=1;O<=r;O++)h.push(0,m*E,0),d.push(0,E,0),p.push(.5,.5),_++;const P=_;for(let O=0;O<=r;O++){const k=O/r*c+o,q=Math.cos(k),z=Math.sin(k);w.x=x*z,w.y=m*E,w.z=x*q,h.push(w.x,w.y,w.z),d.push(0,E,0),b.x=q*.5+.5,b.y=z*.5*E+.5,p.push(b.x,b.y),_++}for(let O=0;O.9&&w<.1&&(S<.2&&(a[T+0]+=1),M<.2&&(a[T+2]+=1),R<.2&&(a[T+4]+=1))}}function d(T){s.push(T.x,T.y,T.z)}function p(T,S){const M=T*3;S.x=e[M+0],S.y=e[M+1],S.z=e[M+2]}function _(){const T=new U,S=new U,M=new U,R=new U,b=new fe,w=new fe,D=new fe;for(let x=0,E=0;x0)c=r-1;else{c=r;break}if(r=c,n[r]===a)return r/(s-1);const u=n[r],d=n[r+1]-u,p=(a-u)/d;return(r+p)/(s-1)}getTangent(e,t){let r=e-1e-4,s=e+1e-4;r<0&&(r=0),s>1&&(s=1);const a=this.getPoint(r),o=this.getPoint(s),c=t||(a.isVector2?new fe:new U);return c.copy(o).sub(a).normalize(),c}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new U,r=[],s=[],a=[],o=new U,c=new ot;for(let p=0;p<=e;p++){const _=p/e;r[p]=this.getTangentAt(_,new U)}s[0]=new U,a[0]=new U;let l=Number.MAX_VALUE;const u=Math.abs(r[0].x),h=Math.abs(r[0].y),d=Math.abs(r[0].z);u<=l&&(l=u,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),d<=l&&n.set(0,0,1),o.crossVectors(r[0],n).normalize(),s[0].crossVectors(r[0],o),a[0].crossVectors(r[0],s[0]);for(let p=1;p<=e;p++){if(s[p]=s[p-1].clone(),a[p]=a[p-1].clone(),o.crossVectors(r[p-1],r[p]),o.length()>Number.EPSILON){o.normalize();const _=Math.acos(Xe(r[p-1].dot(r[p]),-1,1));s[p].applyMatrix4(c.makeRotationAxis(o,_))}a[p].crossVectors(r[p],s[p])}if(t===!0){let p=Math.acos(Xe(s[0].dot(s[e]),-1,1));p/=e,r[0].dot(o.crossVectors(s[0],s[e]))>0&&(p=-p);for(let _=1;_<=e;_++)s[_].applyMatrix4(c.makeRotationAxis(r[_],p*_)),a[_].crossVectors(r[_],s[_])}return{tangents:r,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Hr extends qt{constructor(e=0,t=0,n=1,r=1,s=0,a=Math.PI*2,o=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=c}getPoint(e,t=new fe){const n=t,r=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const a=Math.abs(s)r;)s-=r;s0?0:(Math.floor(Math.abs(o)/s)+1)*s:c===0&&o===s-1&&(o=s-2,c=1);let l,u;this.closed||o>0?l=r[(o-1)%s]:(Fi.subVectors(r[0],r[1]).add(r[0]),l=Fi);const h=r[o%s],d=r[(o+1)%s];if(this.closed||o+2r.length-2?r.length-1:a+1],h=r[a>r.length-3?r.length-1:a+2];return n.set(ys(o,c.x,l.x,u.x,h.x),ys(o,c.y,l.y,u.y,h.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){const a=r[s]-n,o=this.curves[s],c=o.getLength(),l=c===0?0:1-a/c;return o.getPointAt(l,t)}s++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let n=0,r=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const h=l.getPoint(0);h.equals(this.currentPoint)||this.lineTo(h.x,h.y)}this.curves.push(l);const u=l.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Bi extends Lr{constructor(e){super(e),this.uuid=Hn(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let n=0,r=this.holes.length;n80*t){o=i[0],c=i[1];let u=o,h=c;for(let d=t;du&&(u=p),_>h&&(h=_)}l=Math.max(u-o,h-c),l=l!==0?32767/l:0}return si(s,a,t,o,c,l,0),a}function _a(i,e,t,n,r){let s;if(r===qo(i,e,t,n)>0)for(let a=e;a=e;a-=n)s=Es(a/n|0,i[a],i[a+1],s);return s&&zn(s,s.next)&&(oi(s),s=s.next),s}function yn(i,e){if(!i)return i;e||(e=i);let t=i,n;do if(n=!1,!t.steiner&&(zn(t,t.next)||lt(t.prev,t,t.next)===0)){if(oi(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function si(i,e,t,n,r,s,a){if(!i)return;!a&&s&&zo(i,n,r,s);let o=i;for(;i.prev!==i.next;){const c=i.prev,l=i.next;if(s?Lo(i,n,r,s):Do(i)){e.push(c.i,i.i,l.i),oi(i),i=l.next,o=l.next;continue}if(i=l,i===o){a?a===1?(i=Fo(yn(i),e),si(i,e,t,n,r,s,2)):a===2&&Uo(i,e,t,n,r,s):si(yn(i),e,t,n,r,s,1);break}}}function Do(i){const e=i.prev,t=i,n=i.next;if(lt(e,t,n)>=0)return!1;const r=e.x,s=t.x,a=n.x,o=e.y,c=t.y,l=n.y,u=Math.min(r,s,a),h=Math.min(o,c,l),d=Math.max(r,s,a),p=Math.max(o,c,l);let _=n.next;for(;_!==e;){if(_.x>=u&&_.x<=d&&_.y>=h&&_.y<=p&&Qn(r,o,s,c,a,l,_.x,_.y)&<(_.prev,_,_.next)>=0)return!1;_=_.next}return!0}function Lo(i,e,t,n){const r=i.prev,s=i,a=i.next;if(lt(r,s,a)>=0)return!1;const o=r.x,c=s.x,l=a.x,u=r.y,h=s.y,d=a.y,p=Math.min(o,c,l),_=Math.min(u,h,d),v=Math.max(o,c,l),m=Math.max(u,h,d),f=Fr(p,_,e,t,n),T=Fr(v,m,e,t,n);let S=i.prevZ,M=i.nextZ;for(;S&&S.z>=f&&M&&M.z<=T;){if(S.x>=p&&S.x<=v&&S.y>=_&&S.y<=m&&S!==r&&S!==a&&Qn(o,u,c,h,l,d,S.x,S.y)&<(S.prev,S,S.next)>=0||(S=S.prevZ,M.x>=p&&M.x<=v&&M.y>=_&&M.y<=m&&M!==r&&M!==a&&Qn(o,u,c,h,l,d,M.x,M.y)&<(M.prev,M,M.next)>=0))return!1;M=M.nextZ}for(;S&&S.z>=f;){if(S.x>=p&&S.x<=v&&S.y>=_&&S.y<=m&&S!==r&&S!==a&&Qn(o,u,c,h,l,d,S.x,S.y)&<(S.prev,S,S.next)>=0)return!1;S=S.prevZ}for(;M&&M.z<=T;){if(M.x>=p&&M.x<=v&&M.y>=_&&M.y<=m&&M!==r&&M!==a&&Qn(o,u,c,h,l,d,M.x,M.y)&<(M.prev,M,M.next)>=0)return!1;M=M.nextZ}return!0}function Fo(i,e){let t=i;do{const n=t.prev,r=t.next.next;!zn(n,r)&&va(n,t,t.next,r)&&ai(n,r)&&ai(r,n)&&(e.push(n.i,t.i,r.i),oi(t),oi(t.next),t=i=r),t=t.next}while(t!==i);return yn(t)}function Uo(i,e,t,n,r,s){let a=i;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&ko(a,o)){let c=Sa(a,o);a=yn(a,a.next),c=yn(c,c.next),si(a,e,t,n,r,s,0),si(c,e,t,n,r,s,0);return}o=o.next}a=a.next}while(a!==i)}function Io(i,e,t,n){const r=[];for(let s=0,a=e.length;s=t.next.y&&t.next.y!==t.y){const h=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(h<=n&&h>s&&(s=h,a=t.x=t.x&&t.x>=c&&n!==t.x&&xa(ra.x||t.x===a.x&&Go(a,t)))&&(a=t,u=h)}t=t.next}while(t!==o);return a}function Go(i,e){return lt(i.prev,i,e.prev)<0&<(e.next,i,i.next)<0}function zo(i,e,t,n){let r=i;do r.z===0&&(r.z=Fr(r.x,r.y,e,t,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,Vo(r)}function Vo(i){let e,t=1;do{let n=i,r;i=null;let s=null;for(e=0;n;){e++;let a=n,o=0;for(let l=0;l0||c>0&&a;)o!==0&&(c===0||!a||n.z<=a.z)?(r=n,n=n.nextZ,o--):(r=a,a=a.nextZ,c--),s?s.nextZ=r:i=r,r.prevZ=s,s=r;n=a}s.nextZ=null,t*=2}while(e>1);return i}function Fr(i,e,t,n,r){return i=(i-t)*r|0,e=(e-n)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function Ho(i){let e=i,t=i;do(e.x=(i-a)*(s-o)&&(i-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(r-a)*(n-o)}function Qn(i,e,t,n,r,s,a,o){return!(i===a&&e===o)&&xa(i,e,t,n,r,s,a,o)}function ko(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!Wo(i,e)&&(ai(i,e)&&ai(e,i)&&Xo(i,e)&&(lt(i.prev,i,e.prev)||lt(i,e.prev,e))||zn(i,e)&<(i.prev,i,i.next)>0&<(e.prev,e,e.next)>0)}function lt(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function zn(i,e){return i.x===e.x&&i.y===e.y}function va(i,e,t,n){const r=Ii(lt(i,e,t)),s=Ii(lt(i,e,n)),a=Ii(lt(t,n,i)),o=Ii(lt(t,n,e));return!!(r!==s&&a!==o||r===0&&Ui(i,t,e)||s===0&&Ui(i,n,e)||a===0&&Ui(t,i,n)||o===0&&Ui(t,e,n))}function Ui(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function Ii(i){return i>0?1:i<0?-1:0}function Wo(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&va(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function ai(i,e){return lt(i.prev,i,i.next)<0?lt(i,e,i.next)>=0&<(i,i.prev,e)>=0:lt(i,e,i.prev)<0||lt(i,i.next,e)<0}function Xo(i,e){let t=i,n=!1;const r=(i.x+e.x)/2,s=(i.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&r<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==i);return n}function Sa(i,e){const t=Ur(i.i,i.x,i.y),n=Ur(e.i,e.x,e.y),r=i.next,s=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function Es(i,e,t,n){const r=Ur(i,e,t);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function oi(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function Ur(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function qo(i,e,t,n){let r=0;for(let s=e,a=t-n;s2&&i[e-1].equals(i[0])&&i.pop()}function As(i,e){for(let t=0;tNumber.EPSILON){const W=Math.sqrt(g),Z=Math.sqrt(re*re+A*A),X=te.x-Fe/W,be=te.y+xe/W,se=$.x-A/Z,Te=$.y+re/Z,Ue=((se-X)*A-(Te-be)*re)/(xe*A-Fe*re);me=X+xe*Ue-K.x,C=be+Fe*Ue-K.y;const ee=me*me+C*C;if(ee<=2)return new fe(me,C);we=Math.sqrt(ee/2)}else{let W=!1;xe>Number.EPSILON?re>Number.EPSILON&&(W=!0):xe<-Number.EPSILON?re<-Number.EPSILON&&(W=!0):Math.sign(Fe)===Math.sign(A)&&(W=!0),W?(me=-Fe,C=xe,we=Math.sqrt(g)):(me=xe,C=Fe,we=Math.sqrt(g/2))}return new fe(me/we,C/we)}const de=[];for(let K=0,te=q.length,$=te-1,me=K+1;K=0;K--){const te=K/m,$=p*Math.cos(te*Math.PI/2),me=_*Math.sin(te*Math.PI/2)+v;for(let C=0,we=q.length;C=0;){const me=$;let C=$-1;C<0&&(C=K.length-1);for(let we=0,xe=u+m*2;we0)&&p.push(S,M,b),(f!==n-1||c{t&&t(s),this.manager.itemEnd(e)},0),s;if(Qt[e]!==void 0){Qt[e].push({onLoad:t,onProgress:n,onError:r});return}Qt[e]=[],Qt[e].push({onLoad:t,onProgress:n,onError:r});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,c=this.responseType;fetch(a).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&Oe("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;const u=Qt[e],h=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),p=d?parseInt(d):0,_=p!==0;let v=0;const m=new ReadableStream({start(f){T();function T(){h.read().then(({done:S,value:M})=>{if(S)f.close();else{v+=M.byteLength;const R=new ProgressEvent("progress",{lengthComputable:_,loaded:v,total:p});for(let b=0,w=u.length;b{f.error(S)})}}});return new Response(m)}else throw new tl(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return l.json();default:if(o==="")return l.text();{const h=/charset="?([^;"\s]*)"?/i.exec(o),d=h&&h[1]?h[1].toLowerCase():void 0,p=new TextDecoder(d);return l.arrayBuffer().then(_=>p.decode(_))}}}).then(l=>{bs.add(`file:${e}`,l);const u=Qt[e];delete Qt[e];for(let h=0,d=u.length;h{const u=Qt[e];if(u===void 0)throw this.manager.itemError(e),l;delete Qt[e];for(let h=0,d=u.length;h{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class Ta extends _t{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Je(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}const yr=new ot,Rs=new U,Cs=new U;class il{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new fe(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new ot,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Gr,this._frameExtents=new fe(1,1),this._viewportCount=1,this._viewports=[new ft(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Rs.setFromMatrixPosition(e.matrixWorld),t.position.copy(Rs),Cs.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Cs),t.updateMatrixWorld(),yr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yr,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(yr)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class qr extends la{constructor(e=-1,t=1,n=1,r=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,s,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2;let s=n-e,a=n+e,o=r+t,c=r-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,a=s+l*this.view.width,o-=u*this.view.offsetY,c=o-u*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class rl extends il{constructor(){super(new qr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class md extends Ta{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(_t.DEFAULT_UP),this.updateMatrix(),this.target=new _t,this.shadow=new rl}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class gd extends Ta{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class sl extends Ot{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class al{constructor(){this.type="ShapePath",this.color=new Je,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Lr,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,r){return this.currentPath.quadraticCurveTo(e,t,n,r),this}bezierCurveTo(e,t,n,r,s,a){return this.currentPath.bezierCurveTo(e,t,n,r,s,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(f){const T=[];for(let S=0,M=f.length;SNumber.EPSILON){if(E<0&&(w=T[b],x=-x,D=T[R],E=-E),f.yD.y)continue;if(f.y===w.y){if(f.x===w.x)return!0}else{const P=E*(f.x-w.x)-x*(f.y-w.y);if(P===0)return!0;if(P<0)continue;M=!M}}else{if(f.y!==w.y)continue;if(D.x<=f.x&&f.x<=w.x||w.x<=f.x&&f.x<=D.x)return!0}}return M}const r=Mn.isClockWise,s=this.subPaths;if(s.length===0)return[];let a,o,c;const l=[];if(s.length===1)return o=s[0],c=new Bi,c.curves=o.curves,l.push(c),l;let u=!r(s[0].getPoints());u=e?!u:u;const h=[],d=[];let p=[],_=0,v;d[_]=void 0,p[_]=[];for(let f=0,T=s.length;f1){let f=!1,T=0;for(let S=0,M=d.length;S0&&f===!1&&(p=h)}let m;for(let f=0,T=d.length;fp.start-_.start);let d=0;for(let p=1;p 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Al=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,bl=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Rl=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Cl=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,wl=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Pl=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Dl=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Ll=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Fl=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Ul=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Il=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Nl=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Ol=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Bl=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Gl="gl_FragColor = linearToOutputTexel( gl_FragColor );",zl=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Vl=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Hl=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif +#endif`,kl=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Wl=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Xl=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,ql=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Yl=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Zl=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,Jl=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,Kl=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,$l=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,jl=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Ql=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,ec=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,tc=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,nc=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,ic=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,rc=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,sc=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,ac=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +material.metalness = metalnessFactor; +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = vec3( 0.04 ); + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,oc=`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + vec3 diffuseContribution; + vec3 specularColor; + vec3 specularColorBlended; + float roughness; + float metalness; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + vec3 iridescenceFresnelDielectric; + vec3 iridescenceFresnelMetallic; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return v; + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColorBlended; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float rInv = 1.0 / ( roughness + 0.1 ); + float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; + float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; + float DG = exp( a * dotNV + b ); + return saturate( DG ); +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; + vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; + vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; + vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; + float Ess_V = dfgV.x + dfgV.y; + float Ess_L = dfgL.x + dfgL.y; + float Ems_V = 1.0 - Ess_V; + float Ems_L = 1.0 - Ess_L; + vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; + vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); + float compensationFactor = Ems_V * Ems_L; + vec3 multiScatter = Fms * compensationFactor; + return singleScatter + multiScatter; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + + float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); + + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); + + irradiance *= sheenEnergyComp; + + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + diffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectDiffuse += diffuse; +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; + #endif + vec3 singleScatteringDielectric = vec3( 0.0 ); + vec3 multiScatteringDielectric = vec3( 0.0 ); + vec3 singleScatteringMetallic = vec3( 0.0 ); + vec3 multiScatteringMetallic = vec3( 0.0 ); + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #endif + vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); + vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); + vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; + vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + vec3 indirectSpecular = radiance * singleScattering; + indirectSpecular += multiScattering * cosineWeightedIrradiance; + vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + indirectSpecular *= sheenEnergyComp; + indirectDiffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectSpecular += indirectSpecular; + reflectedLight.indirectDiffuse += indirectDiffuse; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,lc=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); + material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,cc=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,uc=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,hc=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,fc=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,dc=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,pc=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,mc=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,gc=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,_c=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,xc=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,vc=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,Sc=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,Mc=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,yc=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,Ec=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Tc=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,Ac=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,bc=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,Rc=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Cc=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,wc=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Pc=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,Dc=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,Lc=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,Fc=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,Uc=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,Ic=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,Nc=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Oc=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,Bc=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Gc=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,zc=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Vc=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,Hc=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,kc=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,Wc=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #else + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #else + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #elif defined( SHADOWMAP_TYPE_BASIC ) + uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float interleavedGradientNoise( vec2 position ) { + return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); + } + vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { + const float goldenAngle = 2.399963229728653; + float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); + float theta = float( sampleIndex ) * goldenAngle + phi; + return vec2( cos( theta ), sin( theta ) ) * r; + } + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float radius = shadowRadius * texelSize.x; + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718; + shadow = ( + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_VSM ) + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; + float mean = distribution.x; + float variance = distribution.y * distribution.y; + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( mean, shadowCoord.z ); + #else + float hard_shadow = step( shadowCoord.z, mean ); + #endif + if ( hard_shadow == 1.0 ) { + shadow = 1.0; + } else { + variance = max( variance, 0.0000001 ); + float d = shadowCoord.z - mean; + float p_max = variance / ( variance + d * d ); + p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); + shadow = max( hard_shadow, p_max ); + } + } + return mix( 1.0, shadow, shadowIntensity ); + } + #else + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + float depth = texture2D( shadowMap, shadowCoord.xy ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadow = step( depth, shadowCoord.z ); + #else + shadow = step( shadowCoord.z, depth ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 bd3D = normalize( lightToPosition ); + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + float texelSize = shadowRadius / shadowMapSize.x; + vec3 absDir = abs( bd3D ); + vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); + tangent = normalize( cross( bd3D, tangent ) ); + vec3 bitangent = cross( bd3D, tangent ); + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718; + shadow = ( + texture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).y ) * texelSize, dp ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_BASIC ) + float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 bd3D = normalize( lightToPosition ); + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + float depth = textureCube( shadowMap, bd3D ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadow = step( depth, dp ); + #else + shadow = step( dp, depth ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #endif +#endif`,Xc=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,qc=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,Yc=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Zc=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,Jc=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,Kc=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,$c=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,jc=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,Qc=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,eu=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,tu=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,nu=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,iu=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,ru=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,su=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,au=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,ou=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const lu=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,cu=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,uu=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,hu=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,fu=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,du=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,pu=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,mu=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,gu=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,_u=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); +}`,xu=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,vu=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,Su=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Mu=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,yu=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Eu=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,Tu=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Au=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,bu=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Ru=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,Cu=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,wu=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,Pu=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Du=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Lu=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Fu=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + + outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; + + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Uu=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Iu=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,Nu=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,Ou=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Bu=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Gu=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,zu=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,Vu=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,He={alphahash_fragment:cl,alphahash_pars_fragment:ul,alphamap_fragment:hl,alphamap_pars_fragment:fl,alphatest_fragment:dl,alphatest_pars_fragment:pl,aomap_fragment:ml,aomap_pars_fragment:gl,batching_pars_vertex:_l,batching_vertex:xl,begin_vertex:vl,beginnormal_vertex:Sl,bsdfs:Ml,iridescence_fragment:yl,bumpmap_pars_fragment:El,clipping_planes_fragment:Tl,clipping_planes_pars_fragment:Al,clipping_planes_pars_vertex:bl,clipping_planes_vertex:Rl,color_fragment:Cl,color_pars_fragment:wl,color_pars_vertex:Pl,color_vertex:Dl,common:Ll,cube_uv_reflection_fragment:Fl,defaultnormal_vertex:Ul,displacementmap_pars_vertex:Il,displacementmap_vertex:Nl,emissivemap_fragment:Ol,emissivemap_pars_fragment:Bl,colorspace_fragment:Gl,colorspace_pars_fragment:zl,envmap_fragment:Vl,envmap_common_pars_fragment:Hl,envmap_pars_fragment:kl,envmap_pars_vertex:Wl,envmap_physical_pars_fragment:tc,envmap_vertex:Xl,fog_vertex:ql,fog_pars_vertex:Yl,fog_fragment:Zl,fog_pars_fragment:Jl,gradientmap_pars_fragment:Kl,lightmap_pars_fragment:$l,lights_lambert_fragment:jl,lights_lambert_pars_fragment:Ql,lights_pars_begin:ec,lights_toon_fragment:nc,lights_toon_pars_fragment:ic,lights_phong_fragment:rc,lights_phong_pars_fragment:sc,lights_physical_fragment:ac,lights_physical_pars_fragment:oc,lights_fragment_begin:lc,lights_fragment_maps:cc,lights_fragment_end:uc,logdepthbuf_fragment:hc,logdepthbuf_pars_fragment:fc,logdepthbuf_pars_vertex:dc,logdepthbuf_vertex:pc,map_fragment:mc,map_pars_fragment:gc,map_particle_fragment:_c,map_particle_pars_fragment:xc,metalnessmap_fragment:vc,metalnessmap_pars_fragment:Sc,morphinstance_vertex:Mc,morphcolor_vertex:yc,morphnormal_vertex:Ec,morphtarget_pars_vertex:Tc,morphtarget_vertex:Ac,normal_fragment_begin:bc,normal_fragment_maps:Rc,normal_pars_fragment:Cc,normal_pars_vertex:wc,normal_vertex:Pc,normalmap_pars_fragment:Dc,clearcoat_normal_fragment_begin:Lc,clearcoat_normal_fragment_maps:Fc,clearcoat_pars_fragment:Uc,iridescence_pars_fragment:Ic,opaque_fragment:Nc,packing:Oc,premultiplied_alpha_fragment:Bc,project_vertex:Gc,dithering_fragment:zc,dithering_pars_fragment:Vc,roughnessmap_fragment:Hc,roughnessmap_pars_fragment:kc,shadowmap_pars_fragment:Wc,shadowmap_pars_vertex:Xc,shadowmap_vertex:qc,shadowmask_pars_fragment:Yc,skinbase_vertex:Zc,skinning_pars_vertex:Jc,skinning_vertex:Kc,skinnormal_vertex:$c,specularmap_fragment:jc,specularmap_pars_fragment:Qc,tonemapping_fragment:eu,tonemapping_pars_fragment:tu,transmission_fragment:nu,transmission_pars_fragment:iu,uv_pars_fragment:ru,uv_pars_vertex:su,uv_vertex:au,worldpos_vertex:ou,background_vert:lu,background_frag:cu,backgroundCube_vert:uu,backgroundCube_frag:hu,cube_vert:fu,cube_frag:du,depth_vert:pu,depth_frag:mu,distance_vert:gu,distance_frag:_u,equirect_vert:xu,equirect_frag:vu,linedashed_vert:Su,linedashed_frag:Mu,meshbasic_vert:yu,meshbasic_frag:Eu,meshlambert_vert:Tu,meshlambert_frag:Au,meshmatcap_vert:bu,meshmatcap_frag:Ru,meshnormal_vert:Cu,meshnormal_frag:wu,meshphong_vert:Pu,meshphong_frag:Du,meshphysical_vert:Lu,meshphysical_frag:Fu,meshtoon_vert:Uu,meshtoon_frag:Iu,points_vert:Nu,points_frag:Ou,shadow_vert:Bu,shadow_frag:Gu,sprite_vert:zu,sprite_frag:Vu},pe={common:{diffuse:{value:new Je(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ve}},envmap:{envMap:{value:null},envMapRotation:{value:new Ve},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ve}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ve}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ve},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ve},normalScale:{value:new fe(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ve},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ve}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ve}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ve}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Je(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Je(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0},uvTransform:{value:new Ve}},sprite:{diffuse:{value:new Je(16777215)},opacity:{value:1},center:{value:new fe(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}}},Vt={basic:{uniforms:yt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:yt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,pe.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:yt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,pe.lights,{emissive:{value:new Je(0)},specular:{value:new Je(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:yt([pe.common,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.roughnessmap,pe.metalnessmap,pe.fog,pe.lights,{emissive:{value:new Je(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:yt([pe.common,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.gradientmap,pe.fog,pe.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:yt([pe.common,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:yt([pe.points,pe.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:yt([pe.common,pe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:yt([pe.common,pe.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:yt([pe.common,pe.bumpmap,pe.normalmap,pe.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:yt([pe.sprite,pe.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Ve},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ve}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:yt([pe.common,pe.displacementmap,{referencePosition:{value:new U},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:yt([pe.lights,pe.fog,{color:{value:new Je(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};Vt.physical={uniforms:yt([Vt.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ve},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ve},clearcoatNormalScale:{value:new fe(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ve},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ve},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ve},sheen:{value:0},sheenColor:{value:new Je(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ve},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ve},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ve},transmissionSamplerSize:{value:new fe},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ve},attenuationDistance:{value:0},attenuationColor:{value:new Je(0)},specularColor:{value:new Je(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ve},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ve},anisotropyVector:{value:new fe},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ve}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const Ni={r:0,b:0,g:0},_n=new Wt,Hu=new ot;function ku(i,e,t,n,r,s,a){const o=new Je(0);let c=s===!0?0:1,l,u,h=null,d=0,p=null;function _(S){let M=S.isScene===!0?S.background:null;return M&&M.isTexture&&(M=(S.backgroundBlurriness>0?t:e).get(M)),M}function v(S){let M=!1;const R=_(S);R===null?f(o,c):R&&R.isColor&&(f(R,1),M=!0);const b=i.xr.getEnvironmentBlendMode();b==="additive"?n.buffers.color.setClear(0,0,0,1,a):b==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||M)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(S,M){const R=_(M);R&&(R.isCubeTexture||R.mapping===306)?(u===void 0&&(u=new tn(new ui(1,1,1),new Xt({name:"BackgroundCubeMaterial",uniforms:Gn(Vt.backgroundCube.uniforms),vertexShader:Vt.backgroundCube.vertexShader,fragmentShader:Vt.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(b,w,D){this.matrixWorld.copyPosition(D.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(u)),_n.copy(M.backgroundRotation),_n.x*=-1,_n.y*=-1,_n.z*=-1,R.isCubeTexture&&R.isRenderTargetTexture===!1&&(_n.y*=-1,_n.z*=-1),u.material.uniforms.envMap.value=R,u.material.uniforms.flipEnvMap.value=R.isCubeTexture&&R.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=M.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(Hu.makeRotationFromEuler(_n)),u.material.toneMapped=Ze.getTransfer(R.colorSpace)!==Qe,(h!==R||d!==R.version||p!==i.toneMapping)&&(u.material.needsUpdate=!0,h=R,d=R.version,p=i.toneMapping),u.layers.enableAll(),S.unshift(u,u.geometry,u.material,0,0,null)):R&&R.isTexture&&(l===void 0&&(l=new tn(new ki(2,2),new Xt({name:"BackgroundMaterial",uniforms:Gn(Vt.background.uniforms),vertexShader:Vt.background.vertexShader,fragmentShader:Vt.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=R,l.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,l.material.toneMapped=Ze.getTransfer(R.colorSpace)!==Qe,R.matrixAutoUpdate===!0&&R.updateMatrix(),l.material.uniforms.uvTransform.value.copy(R.matrix),(h!==R||d!==R.version||p!==i.toneMapping)&&(l.material.needsUpdate=!0,h=R,d=R.version,p=i.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null))}function f(S,M){S.getRGB(Ni,oa(i)),n.buffers.color.setClear(Ni.r,Ni.g,Ni.b,M,a)}function T(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(S,M=1){o.set(S),c=M,f(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(S){c=S,f(o,c)},render:v,addToRenderList:m,dispose:T}}function Wu(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},r=d(null);let s=r,a=!1;function o(E,P,O,B,k){let q=!1;const z=h(B,O,P);s!==z&&(s=z,l(s.object)),q=p(E,B,O,k),q&&_(E,B,O,k),k!==null&&e.update(k,i.ELEMENT_ARRAY_BUFFER),(q||a)&&(a=!1,M(E,P,O,B),k!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(k).buffer))}function c(){return i.createVertexArray()}function l(E){return i.bindVertexArray(E)}function u(E){return i.deleteVertexArray(E)}function h(E,P,O){const B=O.wireframe===!0;let k=n[E.id];k===void 0&&(k={},n[E.id]=k);let q=k[P.id];q===void 0&&(q={},k[P.id]=q);let z=q[B];return z===void 0&&(z=d(c()),q[B]=z),z}function d(E){const P=[],O=[],B=[];for(let k=0;k=0){const ae=k[j];let ce=q[j];if(ce===void 0&&(j==="instanceMatrix"&&E.instanceMatrix&&(ce=E.instanceMatrix),j==="instanceColor"&&E.instanceColor&&(ce=E.instanceColor)),ae===void 0||ae.attribute!==ce||ce&&ae.data!==ce.data)return!0;z++}return s.attributesNum!==z||s.index!==B}function _(E,P,O,B){const k={},q=P.attributes;let z=0;const H=O.getAttributes();for(const j in H)if(H[j].location>=0){let ae=q[j];ae===void 0&&(j==="instanceMatrix"&&E.instanceMatrix&&(ae=E.instanceMatrix),j==="instanceColor"&&E.instanceColor&&(ae=E.instanceColor));const ce={};ce.attribute=ae,ae&&ae.data&&(ce.data=ae.data),k[j]=ce,z++}s.attributes=k,s.attributesNum=z,s.index=B}function v(){const E=s.newAttributes;for(let P=0,O=E.length;P=0){let de=k[H];if(de===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(de=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(de=E.instanceColor)),de!==void 0){const ae=de.normalized,ce=de.itemSize,Ge=e.get(de);if(Ge===void 0)continue;const Ne=Ge.buffer,et=Ge.type,tt=Ge.bytesPerElement,Y=et===i.INT||et===i.UNSIGNED_INT||de.gpuType===1013;if(de.isInterleavedBufferAttribute){const Q=de.data,Se=Q.stride,Le=de.offset;if(Q.isInstancedInterleavedBuffer){for(let ye=0;ye0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const u=c(l);u!==l&&(Oe("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u);const h=t.logarithmicDepthBuffer===!0,d=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),f=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),S=i.getParameter(i.MAX_VARYING_VECTORS),M=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),R=i.getParameter(i.MAX_SAMPLES),b=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:h,reversedDepthBuffer:d,maxTextures:p,maxVertexTextures:_,maxTextureSize:v,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:T,maxVaryings:S,maxFragmentUniforms:M,maxSamples:R,samples:b}}function Yu(i){const e=this;let t=null,n=0,r=!1,s=!1;const a=new vn,o=new Ve,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){const p=h.length!==0||d||n!==0||r;return r=d,n=h.length,p},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,d){t=u(h,d,0)},this.setState=function(h,d,p){const _=h.clippingPlanes,v=h.clipIntersection,m=h.clipShadows,f=i.get(h);if(!r||_===null||_.length===0||s&&!m)s?u(null):l();else{const T=s?0:n,S=T*4;let M=f.clippingState||null;c.value=M,M=u(_,d,S,p);for(let R=0;R!==S;++R)M[R]=t[R];f.clippingState=M,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=T}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function u(h,d,p,_){const v=h!==null?h.length:0;let m=null;if(v!==0){if(m=c.value,_!==!0||m===null){const f=p+v*4,T=d.matrixWorldInverse;o.getNormalMatrix(T),(m===null||m.length0){const l=new ua(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",r),t(l.texture,a.mapping)}else return null}}return a}function r(a){const o=a.target;o.removeEventListener("dispose",r);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function s(){e=new WeakMap}return{get:n,dispose:s}}const un=4,Ps=[.125,.215,.35,.446,.526,.582],Sn=20,Ju=256,$n=new qr,Ds=new Je;let Er=null,Tr=0,Ar=0,br=!1;const Ku=new U;class Ls{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,s={}){const{size:a=256,position:o=Ku}=s;Er=this._renderer.getRenderTarget(),Tr=this._renderer.getActiveCubeFace(),Ar=this._renderer.getActiveMipmapLevel(),br=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,r,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Is(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Us(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?R:0,R,R),h.setRenderTarget(r),f&&h.render(v,c),h.render(e,c)}h.toneMapping=p,h.autoClear=d,e.background=T}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Is()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Us());const s=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;const o=s.uniforms;o.envMap.value=e;const c=this._cubeSize;Nn(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,$n)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodMeshes.length;for(let s=1;s_-un?n-_+un:0),f=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=p,c.mipInt.value=_-t,Nn(s,m,f,3*v,2*v),r.setRenderTarget(s),r.render(o,$n),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=_-n,Nn(e,m,f,3*v,2*v),r.setRenderTarget(e),r.render(o,$n)}_blur(e,t,n,r,s){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,"latitudinal",s),this._halfBlur(a,e,n,n,r,"longitudinal",s)}_halfBlur(e,t,n,r,s,a,o){const c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&Ye("blur direction must be either latitudinal or longitudinal!");const u=3,h=this._lodMeshes[r];h.material=l;const d=l.uniforms,p=this._sizeLods[n]-1,_=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Sn-1),v=s/_,m=isFinite(s)?1+Math.floor(u*v):Sn;m>Sn&&Oe(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Sn}`);const f=[];let T=0;for(let w=0;wS-un?r-S+un:0),b=4*(this._cubeSize-M);Nn(t,R,b,3*M,2*M),c.setRenderTarget(t),c.render(h,$n)}}function $u(i){const e=[],t=[],n=[];let r=i;const s=i-un+1+Ps.length;for(let a=0;ai-un?c=Ps[a-i+un-1]:a===0&&(c=0),t.push(c);const l=1/(o-2),u=-l,h=1+l,d=[u,u,h,u,h,h,u,u,h,h,u,h],p=6,_=6,v=3,m=2,f=1,T=new Float32Array(v*_*p),S=new Float32Array(m*_*p),M=new Float32Array(f*_*p);for(let b=0;b2?0:-1,x=[w,D,0,w+2/3,D,0,w+2/3,D+1,0,w,D,0,w+2/3,D+1,0,w,D+1,0];T.set(x,v*_*b),S.set(d,m*_*b);const E=[b,b,b,b,b,b];M.set(E,f*_*b)}const R=new Et;R.setAttribute("position",new kt(T,v)),R.setAttribute("uv",new kt(S,m)),R.setAttribute("faceIndex",new kt(M,f)),n.push(new tn(R,null)),r>un&&r--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function Fs(i,e,t){const n=new Ht(i,e,t);return n.texture.mapping=306,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Nn(i,e,t,n,r){i.viewport.set(e,t,n,r),i.scissor.set(e,t,n,r)}function ju(i,e,t){return new Xt({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Ju,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Wi(),fragmentShader:` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float roughness; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 3.2: Transform view direction to hemisphere configuration + vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); + + // Section 4.1: Orthonormal basis + float lensq = Vh.x * Vh.x + Vh.y * Vh.y; + vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(Vh, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + Vh.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Qu(i,e,t){const n=new Float32Array(Sn),r=new U(0,1,0);return new Xt({name:"SphericalGaussianBlur",defines:{n:Sn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Wi(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Us(){return new Xt({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Wi(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Is(){return new Xt({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Wi(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Wi(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function eh(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===303||c===304,u=c===301||c===302;if(l||u){let h=e.get(o);const d=h!==void 0?h.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return t===null&&(t=new Ls(i)),h=l?t.fromEquirectangular(o,h):t.fromCubemap(o,h),h.texture.pmremVersion=o.pmremVersion,e.set(o,h),h.texture;if(h!==void 0)return h.texture;{const p=o.image;return l&&p&&p.height>0||u&&p&&r(p)?(t===null&&(t=new Ls(i)),h=l?t.fromEquirectangular(o):t.fromCubemap(o),h.texture.pmremVersion=o.pmremVersion,e.set(o,h),o.addEventListener("dispose",s),h.texture):null}}}return o}function r(o){let c=0;const l=6;for(let u=0;ue.maxTextureSize&&(R=Math.ceil(M/e.maxTextureSize),M=e.maxTextureSize);const b=new Float32Array(M*R*4*h),w=new ea(b,M,R,h);w.type=1015,w.needsUpdate=!0;const D=S*4;for(let E=0;E + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }`,depthTest:!1,depthWrite:!1}),l=new tn(o,c),u=new qr(-1,1,1,-1,0,1);let h=null,d=null,p=!1,_,v=null,m=[],f=!1;this.setSize=function(T,S){s.setSize(T,S),a.setSize(T,S);for(let M=0;M0&&m[0].isRenderPass===!0;const S=s.width,M=s.height;for(let R=0;R0)return i;const r=e*t;let s=Ns[r];if(s===void 0&&(s=new Float32Array(r),Ns[r]=s),e!==0){n.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(s,o)}return s}function pt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t0&&(this.seq=r.concat(s))}setValue(e,t,n,r){const s=this.map[t];s!==void 0&&s.setValue(e,n,r)}setOptional(e,t,n){const r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let s=0,a=t.length;s!==a;++s){const o=t[s],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,r)}}static seqWithValue(e,t){const n=[];for(let r=0,s=e.length;r!==s;++r){const a=e[r];a.id in t&&n.push(a)}return n}}function Hs(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const Qh=37297;let ef=0;function tf(i,e){const t=i.split(` +`),n=[],r=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let a=r;a":" "} ${o}: ${t[a]}`)}return n.join(` +`)}const ks=new Ve;function nf(i){Ze._getMatrix(ks,Ze.workingColorSpace,i);const e=`mat3( ${ks.elements.map(t=>t.toFixed(4))} )`;switch(Ze.getTransfer(i)){case zi:return[e,"LinearTransferOETF"];case Qe:return[e,"sRGBTransferOETF"];default:return Oe("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Ws(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),s=(i.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";const a=/ERROR: 0:(\d+)/.exec(s);if(a){const o=parseInt(a[1]);return t.toUpperCase()+` + +`+s+` + +`+tf(i.getShaderSource(e),o)}else return s}function rf(i,e){const t=nf(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` +`)}const sf={1:"Linear",2:"Reinhard",3:"Cineon",4:"ACESFilmic",6:"AgX",7:"Neutral",5:"Custom"};function af(i,e){const t=sf[e];return t===void 0?(Oe("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Oi=new U;function of(){Ze.getLuminanceCoefficients(Oi);const i=Oi.x.toFixed(4),e=Oi.y.toFixed(4),t=Oi.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function lf(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ei).join(` +`)}function cf(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` +`)}function uf(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Nr(i){return i.replace(hf,df)}const ff=new Map;function df(i,e){let t=He[e];if(t===void 0){const n=ff.get(e);if(n!==void 0)t=He[n],Oe('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Nr(t)}const pf=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Ys(i){return i.replace(pf,mf)}function mf(i,e,t,n){let r="";for(let s=parseInt(e);s0&&(m+=` +`),f=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_].filter(ei).join(` +`),f.length>0&&(f+=` +`)):(m=[Zs(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(ei).join(` +`),f=[Zs(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+u:"",t.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==0?"#define TONE_MAPPING":"",t.toneMapping!==0?He.tonemapping_pars_fragment:"",t.toneMapping!==0?af("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",He.colorspace_pars_fragment,rf("linearToOutputTexel",t.outputColorSpace),of(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(ei).join(` +`)),a=Nr(a),a=Xs(a,t),a=qs(a,t),o=Nr(o),o=Xs(o,t),o=qs(o,t),a=Ys(a),o=Ys(o),t.isRawShaderMaterial!==!0&&(T=`#version 300 es +`,m=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+m,f=["#define varying in",t.glslVersion===ts?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===ts?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+f);const S=T+m+a,M=T+f+o,R=Hs(r,r.VERTEX_SHADER,S),b=Hs(r,r.FRAGMENT_SHADER,M);r.attachShader(v,R),r.attachShader(v,b),t.index0AttributeName!==void 0?r.bindAttribLocation(v,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(v,0,"position"),r.linkProgram(v);function w(P){if(i.debug.checkShaderErrors){const O=r.getProgramInfoLog(v)||"",B=r.getShaderInfoLog(R)||"",k=r.getShaderInfoLog(b)||"",q=O.trim(),z=B.trim(),H=k.trim();let j=!0,de=!0;if(r.getProgramParameter(v,r.LINK_STATUS)===!1)if(j=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(r,v,R,b);else{const ae=Ws(r,R,"vertex"),ce=Ws(r,b,"fragment");Ye("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(v,r.VALIDATE_STATUS)+` + +Material Name: `+P.name+` +Material Type: `+P.type+` + +Program Info Log: `+q+` +`+ae+` +`+ce)}else q!==""?Oe("WebGLProgram: Program Info Log:",q):(z===""||H==="")&&(de=!1);de&&(P.diagnostics={runnable:j,programLog:q,vertexShader:{log:z,prefix:m},fragmentShader:{log:H,prefix:f}})}r.deleteShader(R),r.deleteShader(b),D=new Gi(r,v),x=uf(r,v)}let D;this.getUniforms=function(){return D===void 0&&w(this),D};let x;this.getAttributes=function(){return x===void 0&&w(this),x};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=r.getProgramParameter(v,Qh)),E},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=ef++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=R,this.fragmentShader=b,this}let bf=0;class Rf{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new Cf(e),t.set(e,n)),n}}class Cf{constructor(e){this.id=bf++,this.code=e,this.usedTimes=0}}function wf(i,e,t,n,r,s,a){const o=new na,c=new Rf,l=new Set,u=[],h=new Map,d=r.logarithmicDepthBuffer;let p=r.precision;const _={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(x){return l.add(x),x===0?"uv":`uv${x}`}function m(x,E,P,O,B){const k=O.fog,q=B.geometry,z=x.isMeshStandardMaterial?O.environment:null,H=(x.isMeshStandardMaterial?t:e).get(x.envMap||z),j=H&&H.mapping===306?H.image.height:null,de=_[x.type];x.precision!==null&&(p=r.getMaxPrecision(x.precision),p!==x.precision&&Oe("WebGLProgram.getParameters:",x.precision,"not supported, using",p,"instead."));const ae=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,ce=ae!==void 0?ae.length:0;let Ge=0;q.morphAttributes.position!==void 0&&(Ge=1),q.morphAttributes.normal!==void 0&&(Ge=2),q.morphAttributes.color!==void 0&&(Ge=3);let Ne,et,tt,Y;if(de){const $e=Vt[de];Ne=$e.vertexShader,et=$e.fragmentShader}else Ne=x.vertexShader,et=x.fragmentShader,c.update(x),tt=c.getVertexShaderID(x),Y=c.getFragmentShaderID(x);const Q=i.getRenderTarget(),Se=i.state.buffers.depth.getReversed(),Le=B.isInstancedMesh===!0,ye=B.isBatchedMesh===!0,qe=!!x.map,nt=!!x.matcap,ze=!!H,K=!!x.aoMap,te=!!x.lightMap,$=!!x.bumpMap,me=!!x.normalMap,C=!!x.displacementMap,we=!!x.emissiveMap,xe=!!x.metalnessMap,Fe=!!x.roughnessMap,re=x.anisotropy>0,A=x.clearcoat>0,g=x.dispersion>0,F=x.iridescence>0,W=x.sheen>0,Z=x.transmission>0,X=re&&!!x.anisotropyMap,be=A&&!!x.clearcoatMap,se=A&&!!x.clearcoatNormalMap,Te=A&&!!x.clearcoatRoughnessMap,Ue=F&&!!x.iridescenceMap,ee=F&&!!x.iridescenceThicknessMap,ue=W&&!!x.sheenColorMap,Ae=W&&!!x.sheenRoughnessMap,Re=!!x.specularMap,le=!!x.specularColorMap,ke=!!x.specularIntensityMap,L=Z&&!!x.transmissionMap,_e=Z&&!!x.thicknessMap,ie=!!x.gradientMap,ve=!!x.alphaMap,ne=x.alphaTest>0,J=!!x.alphaHash,oe=!!x.extensions;let Be=0;x.toneMapped&&(Q===null||Q.isXRRenderTarget===!0)&&(Be=i.toneMapping);const st={shaderID:de,shaderType:x.type,shaderName:x.name,vertexShader:Ne,fragmentShader:et,defines:x.defines,customVertexShaderID:tt,customFragmentShaderID:Y,isRawShaderMaterial:x.isRawShaderMaterial===!0,glslVersion:x.glslVersion,precision:p,batching:ye,batchingColor:ye&&B._colorsTexture!==null,instancing:Le,instancingColor:Le&&B.instanceColor!==null,instancingMorph:Le&&B.morphTexture!==null,outputColorSpace:Q===null?i.outputColorSpace:Q.isXRRenderTarget===!0?Q.texture.colorSpace:Bn,alphaToCoverage:!!x.alphaToCoverage,map:qe,matcap:nt,envMap:ze,envMapMode:ze&&H.mapping,envMapCubeUVHeight:j,aoMap:K,lightMap:te,bumpMap:$,normalMap:me,displacementMap:C,emissiveMap:we,normalMapObjectSpace:me&&x.normalMapType===1,normalMapTangentSpace:me&&x.normalMapType===0,metalnessMap:xe,roughnessMap:Fe,anisotropy:re,anisotropyMap:X,clearcoat:A,clearcoatMap:be,clearcoatNormalMap:se,clearcoatRoughnessMap:Te,dispersion:g,iridescence:F,iridescenceMap:Ue,iridescenceThicknessMap:ee,sheen:W,sheenColorMap:ue,sheenRoughnessMap:Ae,specularMap:Re,specularColorMap:le,specularIntensityMap:ke,transmission:Z,transmissionMap:L,thicknessMap:_e,gradientMap:ie,opaque:x.transparent===!1&&x.blending===1&&x.alphaToCoverage===!1,alphaMap:ve,alphaTest:ne,alphaHash:J,combine:x.combine,mapUv:qe&&v(x.map.channel),aoMapUv:K&&v(x.aoMap.channel),lightMapUv:te&&v(x.lightMap.channel),bumpMapUv:$&&v(x.bumpMap.channel),normalMapUv:me&&v(x.normalMap.channel),displacementMapUv:C&&v(x.displacementMap.channel),emissiveMapUv:we&&v(x.emissiveMap.channel),metalnessMapUv:xe&&v(x.metalnessMap.channel),roughnessMapUv:Fe&&v(x.roughnessMap.channel),anisotropyMapUv:X&&v(x.anisotropyMap.channel),clearcoatMapUv:be&&v(x.clearcoatMap.channel),clearcoatNormalMapUv:se&&v(x.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Te&&v(x.clearcoatRoughnessMap.channel),iridescenceMapUv:Ue&&v(x.iridescenceMap.channel),iridescenceThicknessMapUv:ee&&v(x.iridescenceThicknessMap.channel),sheenColorMapUv:ue&&v(x.sheenColorMap.channel),sheenRoughnessMapUv:Ae&&v(x.sheenRoughnessMap.channel),specularMapUv:Re&&v(x.specularMap.channel),specularColorMapUv:le&&v(x.specularColorMap.channel),specularIntensityMapUv:ke&&v(x.specularIntensityMap.channel),transmissionMapUv:L&&v(x.transmissionMap.channel),thicknessMapUv:_e&&v(x.thicknessMap.channel),alphaMapUv:ve&&v(x.alphaMap.channel),vertexTangents:!!q.attributes.tangent&&(me||re),vertexColors:x.vertexColors,vertexAlphas:x.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,pointsUvs:B.isPoints===!0&&!!q.attributes.uv&&(qe||ve),fog:!!k,useFog:x.fog===!0,fogExp2:!!k&&k.isFogExp2,flatShading:x.flatShading===!0&&x.wireframe===!1,sizeAttenuation:x.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Se,skinning:B.isSkinnedMesh===!0,morphTargets:q.morphAttributes.position!==void 0,morphNormals:q.morphAttributes.normal!==void 0,morphColors:q.morphAttributes.color!==void 0,morphTargetsCount:ce,morphTextureStride:Ge,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:x.dithering,shadowMapEnabled:i.shadowMap.enabled&&P.length>0,shadowMapType:i.shadowMap.type,toneMapping:Be,decodeVideoTexture:qe&&x.map.isVideoTexture===!0&&Ze.getTransfer(x.map.colorSpace)===Qe,decodeVideoTextureEmissive:we&&x.emissiveMap.isVideoTexture===!0&&Ze.getTransfer(x.emissiveMap.colorSpace)===Qe,premultipliedAlpha:x.premultipliedAlpha,doubleSided:x.side===2,flipSided:x.side===1,useDepthPacking:x.depthPacking>=0,depthPacking:x.depthPacking||0,index0AttributeName:x.index0AttributeName,extensionClipCullDistance:oe&&x.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(oe&&x.extensions.multiDraw===!0||ye)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:x.customProgramCacheKey()};return st.vertexUv1s=l.has(1),st.vertexUv2s=l.has(2),st.vertexUv3s=l.has(3),l.clear(),st}function f(x){const E=[];if(x.shaderID?E.push(x.shaderID):(E.push(x.customVertexShaderID),E.push(x.customFragmentShaderID)),x.defines!==void 0)for(const P in x.defines)E.push(P),E.push(x.defines[P]);return x.isRawShaderMaterial===!1&&(T(E,x),S(E,x),E.push(i.outputColorSpace)),E.push(x.customProgramCacheKey),E.join()}function T(x,E){x.push(E.precision),x.push(E.outputColorSpace),x.push(E.envMapMode),x.push(E.envMapCubeUVHeight),x.push(E.mapUv),x.push(E.alphaMapUv),x.push(E.lightMapUv),x.push(E.aoMapUv),x.push(E.bumpMapUv),x.push(E.normalMapUv),x.push(E.displacementMapUv),x.push(E.emissiveMapUv),x.push(E.metalnessMapUv),x.push(E.roughnessMapUv),x.push(E.anisotropyMapUv),x.push(E.clearcoatMapUv),x.push(E.clearcoatNormalMapUv),x.push(E.clearcoatRoughnessMapUv),x.push(E.iridescenceMapUv),x.push(E.iridescenceThicknessMapUv),x.push(E.sheenColorMapUv),x.push(E.sheenRoughnessMapUv),x.push(E.specularMapUv),x.push(E.specularColorMapUv),x.push(E.specularIntensityMapUv),x.push(E.transmissionMapUv),x.push(E.thicknessMapUv),x.push(E.combine),x.push(E.fogExp2),x.push(E.sizeAttenuation),x.push(E.morphTargetsCount),x.push(E.morphAttributeCount),x.push(E.numDirLights),x.push(E.numPointLights),x.push(E.numSpotLights),x.push(E.numSpotLightMaps),x.push(E.numHemiLights),x.push(E.numRectAreaLights),x.push(E.numDirLightShadows),x.push(E.numPointLightShadows),x.push(E.numSpotLightShadows),x.push(E.numSpotLightShadowsWithMaps),x.push(E.numLightProbes),x.push(E.shadowMapType),x.push(E.toneMapping),x.push(E.numClippingPlanes),x.push(E.numClipIntersection),x.push(E.depthPacking)}function S(x,E){o.disableAll(),E.instancing&&o.enable(0),E.instancingColor&&o.enable(1),E.instancingMorph&&o.enable(2),E.matcap&&o.enable(3),E.envMap&&o.enable(4),E.normalMapObjectSpace&&o.enable(5),E.normalMapTangentSpace&&o.enable(6),E.clearcoat&&o.enable(7),E.iridescence&&o.enable(8),E.alphaTest&&o.enable(9),E.vertexColors&&o.enable(10),E.vertexAlphas&&o.enable(11),E.vertexUv1s&&o.enable(12),E.vertexUv2s&&o.enable(13),E.vertexUv3s&&o.enable(14),E.vertexTangents&&o.enable(15),E.anisotropy&&o.enable(16),E.alphaHash&&o.enable(17),E.batching&&o.enable(18),E.dispersion&&o.enable(19),E.batchingColor&&o.enable(20),E.gradientMap&&o.enable(21),x.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),x.push(o.mask)}function M(x){const E=_[x.type];let P;if(E){const O=Vt[E];P=so.clone(O.uniforms)}else P=x.uniforms;return P}function R(x,E){let P=h.get(E);return P!==void 0?++P.usedTimes:(P=new Af(i,E,x,s),u.push(P),h.set(E,P)),P}function b(x){if(--x.usedTimes===0){const E=u.indexOf(x);u[E]=u[u.length-1],u.pop(),h.delete(x.cacheKey),x.destroy()}}function w(x){c.remove(x)}function D(){c.dispose()}return{getParameters:m,getProgramCacheKey:f,getUniforms:M,acquireProgram:R,releaseProgram:b,releaseShaderCache:w,programs:u,dispose:D}}function Pf(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function r(a,o,c){i.get(a)[o]=c}function s(){i=new WeakMap}return{has:e,get:t,remove:n,update:r,dispose:s}}function Df(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function Js(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Ks(){const i=[];let e=0;const t=[],n=[],r=[];function s(){e=0,t.length=0,n.length=0,r.length=0}function a(h,d,p,_,v,m){let f=i[e];return f===void 0?(f={id:h.id,object:h,geometry:d,material:p,groupOrder:_,renderOrder:h.renderOrder,z:v,group:m},i[e]=f):(f.id=h.id,f.object=h,f.geometry=d,f.material=p,f.groupOrder=_,f.renderOrder=h.renderOrder,f.z=v,f.group=m),e++,f}function o(h,d,p,_,v,m){const f=a(h,d,p,_,v,m);p.transmission>0?n.push(f):p.transparent===!0?r.push(f):t.push(f)}function c(h,d,p,_,v,m){const f=a(h,d,p,_,v,m);p.transmission>0?n.unshift(f):p.transparent===!0?r.unshift(f):t.unshift(f)}function l(h,d){t.length>1&&t.sort(h||Df),n.length>1&&n.sort(d||Js),r.length>1&&r.sort(d||Js)}function u(){for(let h=e,d=i.length;h=s.length?(a=new Ks,s.push(a)):a=s[r],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function Ff(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new U,color:new Je};break;case"SpotLight":t={position:new U,direction:new U,color:new Je,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new U,color:new Je,distance:0,decay:0};break;case"HemisphereLight":t={direction:new U,skyColor:new Je,groundColor:new Je};break;case"RectAreaLight":t={color:new Je,position:new U,halfWidth:new U,halfHeight:new U};break}return i[e.id]=t,t}}}function Uf(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fe};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fe};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fe,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let If=0;function Nf(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function Of(i){const e=new Ff,t=Uf(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new U);const r=new U,s=new ot,a=new ot;function o(l){let u=0,h=0,d=0;for(let x=0;x<9;x++)n.probe[x].set(0,0,0);let p=0,_=0,v=0,m=0,f=0,T=0,S=0,M=0,R=0,b=0,w=0;l.sort(Nf);for(let x=0,E=l.length;x0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=pe.LTC_FLOAT_1,n.rectAreaLTC2=pe.LTC_FLOAT_2):(n.rectAreaLTC1=pe.LTC_HALF_1,n.rectAreaLTC2=pe.LTC_HALF_2)),n.ambient[0]=u,n.ambient[1]=h,n.ambient[2]=d;const D=n.hash;(D.directionalLength!==p||D.pointLength!==_||D.spotLength!==v||D.rectAreaLength!==m||D.hemiLength!==f||D.numDirectionalShadows!==T||D.numPointShadows!==S||D.numSpotShadows!==M||D.numSpotMaps!==R||D.numLightProbes!==w)&&(n.directional.length=p,n.spot.length=v,n.rectArea.length=m,n.point.length=_,n.hemi.length=f,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=S,n.pointShadowMap.length=S,n.spotShadow.length=M,n.spotShadowMap.length=M,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=S,n.spotLightMatrix.length=M+R-b,n.spotLightMap.length=R,n.numSpotLightShadowsWithMaps=b,n.numLightProbes=w,D.directionalLength=p,D.pointLength=_,D.spotLength=v,D.rectAreaLength=m,D.hemiLength=f,D.numDirectionalShadows=T,D.numPointShadows=S,D.numSpotShadows=M,D.numSpotMaps=R,D.numLightProbes=w,n.version=If++)}function c(l,u){let h=0,d=0,p=0,_=0,v=0;const m=u.matrixWorldInverse;for(let f=0,T=l.length;f=a.length?(o=new $s(i),a.push(o)):o=a[s],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const Gf=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,zf=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); + gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); +}`,Vf=[new U(1,0,0),new U(-1,0,0),new U(0,1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1)],Hf=[new U(0,-1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1),new U(0,-1,0),new U(0,-1,0)],js=new ot,jn=new U,Cr=new U;function kf(i,e,t){let n=new Gr;const r=new fe,s=new fe,a=new ft,o=new $o,c=new jo,l={},u=t.maxTextureSize,h={0:1,1:0,2:2},d=new Xt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new fe},radius:{value:4}},vertexShader:Gf,fragmentShader:zf}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const _=new Et;_.setAttribute("position",new kt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new tn(_,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let f=this.type;this.render=function(b,w,D){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||b.length===0)return;b.type===2&&(Oe("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),b.type=1);const x=i.getRenderTarget(),E=i.getActiveCubeFace(),P=i.getActiveMipmapLevel(),O=i.state;O.setBlending(0),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const B=f!==this.type;B&&w.traverse(function(k){k.material&&(Array.isArray(k.material)?k.material.forEach(q=>q.needsUpdate=!0):k.material.needsUpdate=!0)});for(let k=0,q=b.length;ku||r.y>u)&&(r.x>u&&(s.x=Math.floor(u/j.x),r.x=s.x*j.x,H.mapSize.x=s.x),r.y>u&&(s.y=Math.floor(u/j.y),r.y=s.y*j.y,H.mapSize.y=s.y)),H.map===null||B===!0){if(H.map!==null&&(H.map.depthTexture!==null&&(H.map.depthTexture.dispose(),H.map.depthTexture=null),H.map.dispose()),this.type===3){if(z.isPointLight){Oe("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}H.map=new Ht(r.x,r.y,{format:1030,type:1016,minFilter:1006,magFilter:1006,generateMipmaps:!1}),H.map.texture.name=z.name+".shadowMap",H.map.depthTexture=new ri(r.x,r.y,1015),H.map.depthTexture.name=z.name+".shadowMapDepth",H.map.depthTexture.format=1026,H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=1003,H.map.depthTexture.magFilter=1003}else{z.isPointLight?(H.map=new ua(r.x),H.map.depthTexture=new go(r.x,1014)):(H.map=new Ht(r.x,r.y),H.map.depthTexture=new ri(r.x,r.y,1014)),H.map.depthTexture.name=z.name+".shadowMap",H.map.depthTexture.format=1026;const ae=i.state.buffers.depth.getReversed();this.type===1?(H.map.depthTexture.compareFunction=ae?518:515,H.map.depthTexture.minFilter=1006,H.map.depthTexture.magFilter=1006):(H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=1003,H.map.depthTexture.magFilter=1003)}H.camera.updateProjectionMatrix()}const de=H.map.isWebGLCubeRenderTarget?6:1;for(let ae=0;ae0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=E.uuid,B=w.uuid;let k=l[O];k===void 0&&(k={},l[O]=k);let q=k[B];q===void 0&&(q=E.clone(),k[B]=q,w.addEventListener("dispose",R)),E=q}if(E.visible=w.visible,E.wireframe=w.wireframe,x===3?E.side=w.shadowSide!==null?w.shadowSide:w.side:E.side=w.shadowSide!==null?w.shadowSide:h[w.side],E.alphaMap=w.alphaMap,E.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,E.map=w.map,E.clipShadows=w.clipShadows,E.clippingPlanes=w.clippingPlanes,E.clipIntersection=w.clipIntersection,E.displacementMap=w.displacementMap,E.displacementScale=w.displacementScale,E.displacementBias=w.displacementBias,E.wireframeLinewidth=w.wireframeLinewidth,E.linewidth=w.linewidth,D.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const O=i.properties.get(E);O.light=D}return E}function M(b,w,D,x,E){if(b.visible===!1)return;if(b.layers.test(w.layers)&&(b.isMesh||b.isLine||b.isPoints)&&(b.castShadow||b.receiveShadow&&E===3)&&(!b.frustumCulled||n.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(D.matrixWorldInverse,b.matrixWorld);const B=e.update(b),k=b.material;if(Array.isArray(k)){const q=B.groups;for(let z=0,H=q.length;z=1):j.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(j)[1]),z=H>=2);let de=null,ae={};const ce=i.getParameter(i.SCISSOR_BOX),Ge=i.getParameter(i.VIEWPORT),Ne=new ft().fromArray(ce),et=new ft().fromArray(Ge);function tt(L,_e,ie,ve){const ne=new Uint8Array(4),J=i.createTexture();i.bindTexture(L,J),i.texParameteri(L,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(L,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let oe=0;oe"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new fe,u=new WeakMap;let h;const d=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(A,g){return p?new OffscreenCanvas(A,g):Vi("canvas")}function v(A,g,F){let W=1;const Z=re(A);if((Z.width>F||Z.height>F)&&(W=F/Math.max(Z.width,Z.height)),W<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){const X=Math.floor(W*Z.width),be=Math.floor(W*Z.height);h===void 0&&(h=_(X,be));const se=g?_(X,be):h;return se.width=X,se.height=be,se.getContext("2d").drawImage(A,0,0,X,be),Oe("WebGLRenderer: Texture has been resized from ("+Z.width+"x"+Z.height+") to ("+X+"x"+be+")."),se}else return"data"in A&&Oe("WebGLRenderer: Image in DataTexture is too big ("+Z.width+"x"+Z.height+")."),A;return A}function m(A){return A.generateMipmaps}function f(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function S(A,g,F,W,Z=!1){if(A!==null){if(i[A]!==void 0)return i[A];Oe("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let X=g;if(g===i.RED&&(F===i.FLOAT&&(X=i.R32F),F===i.HALF_FLOAT&&(X=i.R16F),F===i.UNSIGNED_BYTE&&(X=i.R8)),g===i.RED_INTEGER&&(F===i.UNSIGNED_BYTE&&(X=i.R8UI),F===i.UNSIGNED_SHORT&&(X=i.R16UI),F===i.UNSIGNED_INT&&(X=i.R32UI),F===i.BYTE&&(X=i.R8I),F===i.SHORT&&(X=i.R16I),F===i.INT&&(X=i.R32I)),g===i.RG&&(F===i.FLOAT&&(X=i.RG32F),F===i.HALF_FLOAT&&(X=i.RG16F),F===i.UNSIGNED_BYTE&&(X=i.RG8)),g===i.RG_INTEGER&&(F===i.UNSIGNED_BYTE&&(X=i.RG8UI),F===i.UNSIGNED_SHORT&&(X=i.RG16UI),F===i.UNSIGNED_INT&&(X=i.RG32UI),F===i.BYTE&&(X=i.RG8I),F===i.SHORT&&(X=i.RG16I),F===i.INT&&(X=i.RG32I)),g===i.RGB_INTEGER&&(F===i.UNSIGNED_BYTE&&(X=i.RGB8UI),F===i.UNSIGNED_SHORT&&(X=i.RGB16UI),F===i.UNSIGNED_INT&&(X=i.RGB32UI),F===i.BYTE&&(X=i.RGB8I),F===i.SHORT&&(X=i.RGB16I),F===i.INT&&(X=i.RGB32I)),g===i.RGBA_INTEGER&&(F===i.UNSIGNED_BYTE&&(X=i.RGBA8UI),F===i.UNSIGNED_SHORT&&(X=i.RGBA16UI),F===i.UNSIGNED_INT&&(X=i.RGBA32UI),F===i.BYTE&&(X=i.RGBA8I),F===i.SHORT&&(X=i.RGBA16I),F===i.INT&&(X=i.RGBA32I)),g===i.RGB&&(F===i.UNSIGNED_INT_5_9_9_9_REV&&(X=i.RGB9_E5),F===i.UNSIGNED_INT_10F_11F_11F_REV&&(X=i.R11F_G11F_B10F)),g===i.RGBA){const be=Z?zi:Ze.getTransfer(W);F===i.FLOAT&&(X=i.RGBA32F),F===i.HALF_FLOAT&&(X=i.RGBA16F),F===i.UNSIGNED_BYTE&&(X=be===Qe?i.SRGB8_ALPHA8:i.RGBA8),F===i.UNSIGNED_SHORT_4_4_4_4&&(X=i.RGBA4),F===i.UNSIGNED_SHORT_5_5_5_1&&(X=i.RGB5_A1)}return(X===i.R16F||X===i.R32F||X===i.RG16F||X===i.RG32F||X===i.RGBA16F||X===i.RGBA32F)&&e.get("EXT_color_buffer_float"),X}function M(A,g){let F;return A?g===null||g===1014||g===1020?F=i.DEPTH24_STENCIL8:g===1015?F=i.DEPTH32F_STENCIL8:g===1012&&(F=i.DEPTH24_STENCIL8,Oe("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):g===null||g===1014||g===1020?F=i.DEPTH_COMPONENT24:g===1015?F=i.DEPTH_COMPONENT32F:g===1012&&(F=i.DEPTH_COMPONENT16),F}function R(A,g){return m(A)===!0||A.isFramebufferTexture&&A.minFilter!==1003&&A.minFilter!==1006?Math.log2(Math.max(g.width,g.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?g.mipmaps.length:1}function b(A){const g=A.target;g.removeEventListener("dispose",b),D(g),g.isVideoTexture&&u.delete(g)}function w(A){const g=A.target;g.removeEventListener("dispose",w),E(g)}function D(A){const g=n.get(A);if(g.__webglInit===void 0)return;const F=A.source,W=d.get(F);if(W){const Z=W[g.__cacheKey];Z.usedTimes--,Z.usedTimes===0&&x(A),Object.keys(W).length===0&&d.delete(F)}n.remove(A)}function x(A){const g=n.get(A);i.deleteTexture(g.__webglTexture);const F=A.source,W=d.get(F);delete W[g.__cacheKey],a.memory.textures--}function E(A){const g=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let W=0;W<6;W++){if(Array.isArray(g.__webglFramebuffer[W]))for(let Z=0;Z=r.maxTextures&&Oe("WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+r.maxTextures),P+=1,A}function k(A){const g=[];return g.push(A.wrapS),g.push(A.wrapT),g.push(A.wrapR||0),g.push(A.magFilter),g.push(A.minFilter),g.push(A.anisotropy),g.push(A.internalFormat),g.push(A.format),g.push(A.type),g.push(A.generateMipmaps),g.push(A.premultiplyAlpha),g.push(A.flipY),g.push(A.unpackAlignment),g.push(A.colorSpace),g.join()}function q(A,g){const F=n.get(A);if(A.isVideoTexture&&xe(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&F.__version!==A.version){const W=A.image;if(W===null)Oe("WebGLRenderer: Texture marked for update but no image data found.");else if(W.complete===!1)Oe("WebGLRenderer: Texture marked for update but image is incomplete");else{Y(F,A,g);return}}else A.isExternalTexture&&(F.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,F.__webglTexture,i.TEXTURE0+g)}function z(A,g){const F=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&F.__version!==A.version){Y(F,A,g);return}else A.isExternalTexture&&(F.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,F.__webglTexture,i.TEXTURE0+g)}function H(A,g){const F=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&F.__version!==A.version){Y(F,A,g);return}t.bindTexture(i.TEXTURE_3D,F.__webglTexture,i.TEXTURE0+g)}function j(A,g){const F=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&F.__version!==A.version){Q(F,A,g);return}t.bindTexture(i.TEXTURE_CUBE_MAP,F.__webglTexture,i.TEXTURE0+g)}const de={1e3:i.REPEAT,1001:i.CLAMP_TO_EDGE,1002:i.MIRRORED_REPEAT},ae={1003:i.NEAREST,1004:i.NEAREST_MIPMAP_NEAREST,1005:i.NEAREST_MIPMAP_LINEAR,1006:i.LINEAR,1007:i.LINEAR_MIPMAP_NEAREST,1008:i.LINEAR_MIPMAP_LINEAR},ce={512:i.NEVER,519:i.ALWAYS,513:i.LESS,515:i.LEQUAL,514:i.EQUAL,518:i.GEQUAL,516:i.GREATER,517:i.NOTEQUAL};function Ge(A,g){if(g.type===1015&&e.has("OES_texture_float_linear")===!1&&(g.magFilter===1006||g.magFilter===1007||g.magFilter===1005||g.magFilter===1008||g.minFilter===1006||g.minFilter===1007||g.minFilter===1005||g.minFilter===1008)&&Oe("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,de[g.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,de[g.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,de[g.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,ae[g.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,ae[g.minFilter]),g.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,ce[g.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(g.magFilter===1003||g.minFilter!==1005&&g.minFilter!==1008||g.type===1015&&e.has("OES_texture_float_linear")===!1)return;if(g.anisotropy>1||n.get(g).__currentAnisotropy){const F=e.get("EXT_texture_filter_anisotropic");i.texParameterf(A,F.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,r.getMaxAnisotropy())),n.get(g).__currentAnisotropy=g.anisotropy}}}function Ne(A,g){let F=!1;A.__webglInit===void 0&&(A.__webglInit=!0,g.addEventListener("dispose",b));const W=g.source;let Z=d.get(W);Z===void 0&&(Z={},d.set(W,Z));const X=k(g);if(X!==A.__cacheKey){Z[X]===void 0&&(Z[X]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,F=!0),Z[X].usedTimes++;const be=Z[A.__cacheKey];be!==void 0&&(Z[A.__cacheKey].usedTimes--,be.usedTimes===0&&x(g)),A.__cacheKey=X,A.__webglTexture=Z[X].texture}return F}function et(A,g,F){return Math.floor(Math.floor(A/F)/g)}function tt(A,g,F,W){const X=A.updateRanges;if(X.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,g.width,g.height,F,W,g.data);else{X.sort((ee,ue)=>ee.start-ue.start);let be=0;for(let ee=1;ee0){L&&_e&&t.texStorage2D(i.TEXTURE_2D,ve,Re,ke[0].width,ke[0].height);for(let ne=0,J=ke.length;ne0){const oe=ws(le.width,le.height,g.format,g.type);for(const Be of g.layerUpdates){const st=le.data.subarray(Be*oe/le.data.BYTES_PER_ELEMENT,(Be+1)*oe/le.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ne,0,0,Be,le.width,le.height,1,ue,st)}g.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ne,0,0,0,le.width,le.height,ee.depth,ue,le.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,ne,Re,le.width,le.height,ee.depth,0,le.data,0,0);else Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else L?ie&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,ne,0,0,0,le.width,le.height,ee.depth,ue,Ae,le.data):t.texImage3D(i.TEXTURE_2D_ARRAY,ne,Re,le.width,le.height,ee.depth,0,ue,Ae,le.data)}else{L&&_e&&t.texStorage2D(i.TEXTURE_2D,ve,Re,ke[0].width,ke[0].height);for(let ne=0,J=ke.length;ne0){const ne=ws(ee.width,ee.height,g.format,g.type);for(const J of g.layerUpdates){const oe=ee.data.subarray(J*ne/ee.data.BYTES_PER_ELEMENT,(J+1)*ne/ee.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,J,ee.width,ee.height,1,ue,Ae,oe)}g.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,ee.width,ee.height,ee.depth,ue,Ae,ee.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Re,ee.width,ee.height,ee.depth,0,ue,Ae,ee.data);else if(g.isData3DTexture)L?(_e&&t.texStorage3D(i.TEXTURE_3D,ve,Re,ee.width,ee.height,ee.depth),ie&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,ee.width,ee.height,ee.depth,ue,Ae,ee.data)):t.texImage3D(i.TEXTURE_3D,0,Re,ee.width,ee.height,ee.depth,0,ue,Ae,ee.data);else if(g.isFramebufferTexture){if(_e)if(L)t.texStorage2D(i.TEXTURE_2D,ve,Re,ee.width,ee.height);else{let ne=ee.width,J=ee.height;for(let oe=0;oe>=1,J>>=1}}else if(ke.length>0){if(L&&_e){const ne=re(ke[0]);t.texStorage2D(i.TEXTURE_2D,ve,Re,ne.width,ne.height)}for(let ne=0,J=ke.length;ne0&&ve++;const J=re(ue[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,ve,ke,J.width,J.height)}for(let J=0;J<6;J++)if(ee){L?ie&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+J,0,0,0,ue[J].width,ue[J].height,Re,le,ue[J].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+J,0,ke,ue[J].width,ue[J].height,0,Re,le,ue[J].data);for(let oe=0;oe>X),Ae=Math.max(1,g.height>>X);Z===i.TEXTURE_3D||Z===i.TEXTURE_2D_ARRAY?t.texImage3D(Z,X,Te,ue,Ae,g.depth,0,be,se,null):t.texImage2D(Z,X,Te,ue,Ae,0,be,se,null)}t.bindFramebuffer(i.FRAMEBUFFER,A),we(g)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,W,Z,ee.__webglTexture,0,C(g)):(Z===i.TEXTURE_2D||Z>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&Z<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,W,Z,ee.__webglTexture,X),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Le(A,g,F){if(i.bindRenderbuffer(i.RENDERBUFFER,A),g.depthBuffer){const W=g.depthTexture,Z=W&&W.isDepthTexture?W.type:null,X=M(g.stencilBuffer,Z),be=g.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;we(g)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,C(g),X,g.width,g.height):F?i.renderbufferStorageMultisample(i.RENDERBUFFER,C(g),X,g.width,g.height):i.renderbufferStorage(i.RENDERBUFFER,X,g.width,g.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,be,i.RENDERBUFFER,A)}else{const W=g.textures;for(let Z=0;Z{delete g.__boundDepthTexture,delete g.__depthDisposeCallback,W.removeEventListener("dispose",Z)};W.addEventListener("dispose",Z),g.__depthDisposeCallback=Z}g.__boundDepthTexture=W}if(A.depthTexture&&!g.__autoAllocateDepthBuffer)if(F)for(let W=0;W<6;W++)ye(g.__webglFramebuffer[W],A,W);else{const W=A.texture.mipmaps;W&&W.length>0?ye(g.__webglFramebuffer[0],A,0):ye(g.__webglFramebuffer,A,0)}else if(F){g.__webglDepthbuffer=[];for(let W=0;W<6;W++)if(t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[W]),g.__webglDepthbuffer[W]===void 0)g.__webglDepthbuffer[W]=i.createRenderbuffer(),Le(g.__webglDepthbuffer[W],A,!1);else{const Z=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,X=g.__webglDepthbuffer[W];i.bindRenderbuffer(i.RENDERBUFFER,X),i.framebufferRenderbuffer(i.FRAMEBUFFER,Z,i.RENDERBUFFER,X)}}else{const W=A.texture.mipmaps;if(W&&W.length>0?t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer),g.__webglDepthbuffer===void 0)g.__webglDepthbuffer=i.createRenderbuffer(),Le(g.__webglDepthbuffer,A,!1);else{const Z=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,X=g.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,X),i.framebufferRenderbuffer(i.FRAMEBUFFER,Z,i.RENDERBUFFER,X)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function nt(A,g,F){const W=n.get(A);g!==void 0&&Se(W.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),F!==void 0&&qe(A)}function ze(A){const g=A.texture,F=n.get(A),W=n.get(g);A.addEventListener("dispose",w);const Z=A.textures,X=A.isWebGLCubeRenderTarget===!0,be=Z.length>1;if(be||(W.__webglTexture===void 0&&(W.__webglTexture=i.createTexture()),W.__version=g.version,a.memory.textures++),X){F.__webglFramebuffer=[];for(let se=0;se<6;se++)if(g.mipmaps&&g.mipmaps.length>0){F.__webglFramebuffer[se]=[];for(let Te=0;Te0){F.__webglFramebuffer=[];for(let se=0;se0&&we(A)===!1){F.__webglMultisampledFramebuffer=i.createFramebuffer(),F.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,F.__webglMultisampledFramebuffer);for(let se=0;se0)for(let Te=0;Te0)for(let Te=0;Te0){if(we(A)===!1){const g=A.textures,F=A.width,W=A.height;let Z=i.COLOR_BUFFER_BIT;const X=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,be=n.get(A),se=g.length>1;if(se)for(let Ue=0;Ue0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,be.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,be.__webglFramebuffer);for(let Ue=0;Ue0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&g.__useRenderToTexture!==!1}function xe(A){const g=a.render.frame;u.get(A)!==g&&(u.set(A,g),A.update())}function Fe(A,g){const F=A.colorSpace,W=A.format,Z=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||F!==Bn&&F!==cn&&(Ze.getTransfer(F)===Qe?(W!==1023||Z!==1009)&&Oe("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ye("WebGLTextures: Unsupported texture color space:",F)),g}function re(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=B,this.resetTextureUnits=O,this.setTexture2D=q,this.setTexture2DArray=z,this.setTexture3D=H,this.setTextureCube=j,this.rebindTextures=nt,this.setupRenderTarget=ze,this.updateRenderTargetMipmap=K,this.updateMultisampleRenderTarget=me,this.setupDepthRenderbuffer=qe,this.setupFrameBufferTexture=Se,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function Yf(i,e){function t(n,r=cn){let s;const a=Ze.getTransfer(r);if(n===1009)return i.UNSIGNED_BYTE;if(n===1017)return i.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return i.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return i.BYTE;if(n===1011)return i.SHORT;if(n===1012)return i.UNSIGNED_SHORT;if(n===1013)return i.INT;if(n===1014)return i.UNSIGNED_INT;if(n===1015)return i.FLOAT;if(n===1016)return i.HALF_FLOAT;if(n===1021)return i.ALPHA;if(n===1022)return i.RGB;if(n===1023)return i.RGBA;if(n===1026)return i.DEPTH_COMPONENT;if(n===1027)return i.DEPTH_STENCIL;if(n===1028)return i.RED;if(n===1029)return i.RED_INTEGER;if(n===1030)return i.RG;if(n===1031)return i.RG_INTEGER;if(n===1033)return i.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===Qe)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===33776)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===33776)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===35840)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===36196||n===37492)return a===Qe?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===37496)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return s.COMPRESSED_R11_EAC;if(n===37489)return s.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return s.COMPRESSED_RG11_EAC;if(n===37491)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===37808)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===Qe?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===36492)return a===Qe?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===36283)return s.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const Zf=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,Jf=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class Kf{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new ha(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Xt({vertexShader:Zf,fragmentShader:Jf,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new tn(new ki(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class $f extends Vn{constructor(e,t){super();const n=this;let r=null,s=1,a=null,o="local-floor",c=1,l=null,u=null,h=null,d=null,p=null,_=null;const v=typeof XRWebGLBinding<"u",m=new Kf,f={},T=t.getContextAttributes();let S=null,M=null;const R=[],b=[],w=new fe;let D=null;const x=new Ot;x.viewport=new ft;const E=new Ot;E.viewport=new ft;const P=[x,E],O=new sl;let B=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let Q=R[Y];return Q===void 0&&(Q=new _r,R[Y]=Q),Q.getTargetRaySpace()},this.getControllerGrip=function(Y){let Q=R[Y];return Q===void 0&&(Q=new _r,R[Y]=Q),Q.getGripSpace()},this.getHand=function(Y){let Q=R[Y];return Q===void 0&&(Q=new _r,R[Y]=Q),Q.getHandSpace()};function q(Y){const Q=b.indexOf(Y.inputSource);if(Q===-1)return;const Se=R[Q];Se!==void 0&&(Se.update(Y.inputSource,Y.frame,l||a),Se.dispatchEvent({type:Y.type,data:Y.inputSource}))}function z(){r.removeEventListener("select",q),r.removeEventListener("selectstart",q),r.removeEventListener("selectend",q),r.removeEventListener("squeeze",q),r.removeEventListener("squeezestart",q),r.removeEventListener("squeezeend",q),r.removeEventListener("end",z),r.removeEventListener("inputsourceschange",H);for(let Y=0;Y=0&&(b[Le]=null,R[Le].disconnect(Se))}for(let Q=0;Q=b.length){b.push(Se),Le=qe;break}else if(b[qe]===null){b[qe]=Se,Le=qe;break}if(Le===-1)break}const ye=R[Le];ye&&ye.connect(Se)}}const j=new U,de=new U;function ae(Y,Q,Se){j.setFromMatrixPosition(Q.matrixWorld),de.setFromMatrixPosition(Se.matrixWorld);const Le=j.distanceTo(de),ye=Q.projectionMatrix.elements,qe=Se.projectionMatrix.elements,nt=ye[14]/(ye[10]-1),ze=ye[14]/(ye[10]+1),K=(ye[9]+1)/ye[5],te=(ye[9]-1)/ye[5],$=(ye[8]-1)/ye[0],me=(qe[8]+1)/qe[0],C=nt*$,we=nt*me,xe=Le/(-$+me),Fe=xe*-$;if(Q.matrixWorld.decompose(Y.position,Y.quaternion,Y.scale),Y.translateX(Fe),Y.translateZ(xe),Y.matrixWorld.compose(Y.position,Y.quaternion,Y.scale),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),ye[10]===-1)Y.projectionMatrix.copy(Q.projectionMatrix),Y.projectionMatrixInverse.copy(Q.projectionMatrixInverse);else{const re=nt+xe,A=ze+xe,g=C-Fe,F=we+(Le-Fe),W=K*ze/A*re,Z=te*ze/A*re;Y.projectionMatrix.makePerspective(g,F,W,Z,re,A),Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert()}}function ce(Y,Q){Q===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices(Q.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(r===null)return;let Q=Y.near,Se=Y.far;m.texture!==null&&(m.depthNear>0&&(Q=m.depthNear),m.depthFar>0&&(Se=m.depthFar)),O.near=E.near=x.near=Q,O.far=E.far=x.far=Se,(B!==O.near||k!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),B=O.near,k=O.far),O.layers.mask=Y.layers.mask|6,x.layers.mask=O.layers.mask&3,E.layers.mask=O.layers.mask&5;const Le=Y.parent,ye=O.cameras;ce(O,Le);for(let qe=0;qe0&&(m.alphaTest.value=f.alphaTest);const T=e.get(f),S=T.envMap,M=T.envMapRotation;S&&(m.envMap.value=S,xn.copy(M),xn.x*=-1,xn.y*=-1,xn.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(xn.y*=-1,xn.z*=-1),m.envMapRotation.value.setFromMatrix4(jf.makeRotationFromEuler(xn)),m.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,t(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,t(f.aoMap,m.aoMapTransform))}function a(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform))}function o(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function c(m,f,T,S){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*T,m.scale.value=S*.5,f.map&&(m.map.value=f.map,t(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function l(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function u(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function h(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function d(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,t(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,t(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,T){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,t(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,t(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,t(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,t(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,t(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===1&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,t(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,t(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=T.texture,m.transmissionSamplerSize.value.set(T.width,T.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,t(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,t(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,t(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,t(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,t(f.specularIntensityMap,m.specularIntensityMapTransform))}function _(m,f){f.matcap&&(m.matcap.value=f.matcap)}function v(m,f){const T=e.get(f).light;m.referencePosition.value.setFromMatrixPosition(T.matrixWorld),m.nearDistance.value=T.shadow.camera.near,m.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function ed(i,e,t,n){let r={},s={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(T,S){const M=S.program;n.uniformBlockBinding(T,M)}function l(T,S){let M=r[T.id];M===void 0&&(_(T),M=u(T),r[T.id]=M,T.addEventListener("dispose",m));const R=S.program;n.updateUBOMapping(T,R);const b=e.render.frame;s[T.id]!==b&&(d(T),s[T.id]=b)}function u(T){const S=h();T.__bindingPointIndex=S;const M=i.createBuffer(),R=T.__size,b=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,M),i.bufferData(i.UNIFORM_BUFFER,R,b),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,S,M),M}function h(){for(let T=0;T0&&(M+=R-b),T.__size=M,T.__cache={},this}function v(T){const S={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(S.boundary=4,S.storage=4):T.isVector2?(S.boundary=8,S.storage=8):T.isVector3||T.isColor?(S.boundary=16,S.storage=12):T.isVector4?(S.boundary=16,S.storage=16):T.isMatrix3?(S.boundary=48,S.storage=48):T.isMatrix4?(S.boundary=64,S.storage=64):T.isTexture?Oe("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Oe("WebGLRenderer: Unsupported uniform value type.",T),S}function m(T){const S=T.target;S.removeEventListener("dispose",m);const M=a.indexOf(S.__bindingPointIndex);a.splice(M,1),i.deleteBuffer(r[S.id]),delete r[S.id],delete s[S.id]}function f(){for(const T in r)i.deleteBuffer(r[T]);a=[],r={},s={}}return{bind:c,update:l,dispose:f}}const td=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let zt=null;function nd(){return zt===null&&(zt=new uo(td,16,16,1030,1016),zt.name="DFG_LUT",zt.minFilter=1006,zt.magFilter=1006,zt.wrapS=1001,zt.wrapT=1001,zt.generateMipmaps=!1,zt.needsUpdate=!0),zt}class _d{constructor(e={}){const{canvas:t=Ba(),context:n=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:p=1009}=e;this.isWebGLRenderer=!0;let _;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");_=n.getContextAttributes().alpha}else _=a;const v=p,m=new Set([1033,1031,1029]),f=new Set([1009,1014,1012,1020,1017,1018]),T=new Uint32Array(4),S=new Int32Array(4);let M=null,R=null;const b=[],w=[];let D=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const x=this;let E=!1;this._outputColorSpace=Ft;let P=0,O=0,B=null,k=-1,q=null;const z=new ft,H=new ft;let j=null;const de=new Je(0);let ae=0,ce=t.width,Ge=t.height,Ne=1,et=null,tt=null;const Y=new ft(0,0,ce,Ge),Q=new ft(0,0,ce,Ge);let Se=!1;const Le=new Gr;let ye=!1,qe=!1;const nt=new ot,ze=new U,K=new ft,te={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let $=!1;function me(){return B===null?Ne:1}let C=n;function we(y,I){return t.getContext(y,I)}try{const y={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Or}`),t.addEventListener("webglcontextlost",Be,!1),t.addEventListener("webglcontextrestored",st,!1),t.addEventListener("webglcontextcreationerror",$e,!1),C===null){const I="webgl2";if(C=we(I,y),C===null)throw we(I)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(y){throw Ye("WebGLRenderer: "+y.message),y}let xe,Fe,re,A,g,F,W,Z,X,be,se,Te,Ue,ee,ue,Ae,Re,le,ke,L,_e,ie,ve,ne;function J(){xe=new th(C),xe.init(),ie=new Yf(C,xe),Fe=new qu(C,xe,e,ie),re=new Xf(C,xe),Fe.reversedDepthBuffer&&d&&re.buffers.depth.setReversed(!0),A=new rh(C),g=new Pf,F=new qf(C,xe,re,g,Fe,ie,A),W=new Zu(x),Z=new eh(x),X=new ll(C),ve=new Wu(C,X),be=new nh(C,X,A,ve),se=new ah(C,be,X,A),ke=new sh(C,Fe,F),Ae=new Yu(g),Te=new wf(x,W,Z,xe,Fe,ve,Ae),Ue=new Qf(x,g),ee=new Lf,ue=new Bf(xe),le=new ku(x,W,Z,re,se,_,c),Re=new kf(x,se,Fe),ne=new ed(C,A,Fe,re),L=new Xu(C,xe,A),_e=new ih(C,xe,A),A.programs=Te.programs,x.capabilities=Fe,x.extensions=xe,x.properties=g,x.renderLists=ee,x.shadowMap=Re,x.state=re,x.info=A}J(),v!==1009&&(D=new lh(v,t.width,t.height,r,s));const oe=new $f(x,C);this.xr=oe,this.getContext=function(){return C},this.getContextAttributes=function(){return C.getContextAttributes()},this.forceContextLoss=function(){const y=xe.get("WEBGL_lose_context");y&&y.loseContext()},this.forceContextRestore=function(){const y=xe.get("WEBGL_lose_context");y&&y.restoreContext()},this.getPixelRatio=function(){return Ne},this.setPixelRatio=function(y){y!==void 0&&(Ne=y,this.setSize(ce,Ge,!1))},this.getSize=function(y){return y.set(ce,Ge)},this.setSize=function(y,I,V=!0){if(oe.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}ce=y,Ge=I,t.width=Math.floor(y*Ne),t.height=Math.floor(I*Ne),V===!0&&(t.style.width=y+"px",t.style.height=I+"px"),D!==null&&D.setSize(t.width,t.height),this.setViewport(0,0,y,I)},this.getDrawingBufferSize=function(y){return y.set(ce*Ne,Ge*Ne).floor()},this.setDrawingBufferSize=function(y,I,V){ce=y,Ge=I,Ne=V,t.width=Math.floor(y*V),t.height=Math.floor(I*V),this.setViewport(0,0,y,I)},this.setEffects=function(y){if(v===1009){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(y){for(let I=0;I{function he(){if(G.forEach(function(Me){g.get(Me).currentProgram.isReady()&&G.delete(Me)}),G.size===0){N(y);return}setTimeout(he,10)}xe.get("KHR_parallel_shader_compile")!==null?he():setTimeout(he,10)})};let qi=null;function Da(y){qi&&qi(y)}function Zr(){hn.stop()}function Jr(){hn.start()}const hn=new Aa;hn.setAnimationLoop(Da),typeof self<"u"&&hn.setContext(self),this.setAnimationLoop=function(y){qi=y,oe.setAnimationLoop(y),y===null?hn.stop():hn.start()},oe.addEventListener("sessionstart",Zr),oe.addEventListener("sessionend",Jr),this.render=function(y,I){if(I!==void 0&&I.isCamera!==!0){Ye("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(E===!0)return;const V=oe.enabled===!0&&oe.isPresenting===!0,G=D!==null&&(B===null||V)&&D.begin(x,B);if(y.matrixWorldAutoUpdate===!0&&y.updateMatrixWorld(),I.parent===null&&I.matrixWorldAutoUpdate===!0&&I.updateMatrixWorld(),oe.enabled===!0&&oe.isPresenting===!0&&(D===null||D.isCompositing()===!1)&&(oe.cameraAutoUpdate===!0&&oe.updateCamera(I),I=oe.getCamera()),y.isScene===!0&&y.onBeforeRender(x,y,I,B),R=ue.get(y,w.length),R.init(I),w.push(R),nt.multiplyMatrices(I.projectionMatrix,I.matrixWorldInverse),Le.setFromProjectionMatrix(nt,2e3,I.reversedDepth),qe=this.localClippingEnabled,ye=Ae.init(this.clippingPlanes,qe),M=ee.get(y,b.length),M.init(),b.push(M),oe.enabled===!0&&oe.isPresenting===!0){const Me=x.xr.getDepthSensingMesh();Me!==null&&Yi(Me,I,-1/0,x.sortObjects)}Yi(y,I,0,x.sortObjects),M.finish(),x.sortObjects===!0&&M.sort(et,tt),$=oe.enabled===!1||oe.isPresenting===!1||oe.hasDepthSensing()===!1,$&&le.addToRenderList(M,y),this.info.render.frame++,ye===!0&&Ae.beginShadows();const N=R.state.shadowsArray;if(Re.render(N,y,I),ye===!0&&Ae.endShadows(),this.info.autoReset===!0&&this.info.reset(),(G&&D.hasRenderPass())===!1){const Me=M.opaque,ge=M.transmissive;if(R.setupLights(),I.isArrayCamera){const Ee=I.cameras;if(ge.length>0)for(let Ce=0,Ie=Ee.length;Ce0&&$r(Me,ge,y,I),$&&le.render(y),Kr(M,y,I)}B!==null&&O===0&&(F.updateMultisampleRenderTarget(B),F.updateRenderTargetMipmap(B)),G&&D.end(x),y.isScene===!0&&y.onAfterRender(x,y,I),ve.resetDefaultState(),k=-1,q=null,w.pop(),w.length>0?(R=w[w.length-1],ye===!0&&Ae.setGlobalState(x.clippingPlanes,R.state.camera)):R=null,b.pop(),b.length>0?M=b[b.length-1]:M=null};function Yi(y,I,V,G){if(y.visible===!1)return;if(y.layers.test(I.layers)){if(y.isGroup)V=y.renderOrder;else if(y.isLOD)y.autoUpdate===!0&&y.update(I);else if(y.isLight)R.pushLight(y),y.castShadow&&R.pushShadow(y);else if(y.isSprite){if(!y.frustumCulled||Le.intersectsSprite(y)){G&&K.setFromMatrixPosition(y.matrixWorld).applyMatrix4(nt);const Me=se.update(y),ge=y.material;ge.visible&&M.push(y,Me,ge,V,K.z,null)}}else if((y.isMesh||y.isLine||y.isPoints)&&(!y.frustumCulled||Le.intersectsObject(y))){const Me=se.update(y),ge=y.material;if(G&&(y.boundingSphere!==void 0?(y.boundingSphere===null&&y.computeBoundingSphere(),K.copy(y.boundingSphere.center)):(Me.boundingSphere===null&&Me.computeBoundingSphere(),K.copy(Me.boundingSphere.center)),K.applyMatrix4(y.matrixWorld).applyMatrix4(nt)),Array.isArray(ge)){const Ee=Me.groups;for(let Ce=0,Ie=Ee.length;Ce0&&hi(N,I,V),he.length>0&&hi(he,I,V),Me.length>0&&hi(Me,I,V),re.buffers.depth.setTest(!0),re.buffers.depth.setMask(!0),re.buffers.color.setMask(!0),re.setPolygonOffset(!1)}function $r(y,I,V,G){if((V.isScene===!0?V.overrideMaterial:null)!==null)return;if(R.state.transmissionRenderTarget[G.id]===void 0){const We=xe.has("EXT_color_buffer_half_float")||xe.has("EXT_color_buffer_float");R.state.transmissionRenderTarget[G.id]=new Ht(1,1,{generateMipmaps:!0,type:We?1016:1009,minFilter:1008,samples:Fe.samples,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ze.workingColorSpace})}const he=R.state.transmissionRenderTarget[G.id],Me=G.viewport||z;he.setSize(Me.z*x.transmissionResolutionScale,Me.w*x.transmissionResolutionScale);const ge=x.getRenderTarget(),Ee=x.getActiveCubeFace(),Ce=x.getActiveMipmapLevel();x.setRenderTarget(he),x.getClearColor(de),ae=x.getClearAlpha(),ae<1&&x.setClearColor(16777215,.5),x.clear(),$&&le.render(V);const Ie=x.toneMapping;x.toneMapping=0;const Pe=G.viewport;if(G.viewport!==void 0&&(G.viewport=void 0),R.setupLightsView(G),ye===!0&&Ae.setGlobalState(x.clippingPlanes,G),hi(y,V,G),F.updateMultisampleRenderTarget(he),F.updateRenderTargetMipmap(he),xe.has("WEBGL_multisampled_render_to_texture")===!1){let We=!1;for(let it=0,ut=I.length;it0),Pe=!!V.morphAttributes.position,We=!!V.morphAttributes.normal,it=!!V.morphAttributes.color;let ut=0;G.toneMapped&&(B===null||B.isXRRenderTarget===!0)&&(ut=x.toneMapping);const ht=V.morphAttributes.position||V.morphAttributes.normal||V.morphAttributes.color,rt=ht!==void 0?ht.length:0,De=g.get(G),je=R.state.lights;if(ye===!0&&(qe===!0||y!==q)){const Mt=y===q&&G.id===k;Ae.setState(G,y,Mt)}let Ke=!1;G.version===De.__version?(De.needsLights&&De.lightsStateVersion!==je.state.version||De.outputColorSpace!==ge||N.isBatchedMesh&&De.batching===!1||!N.isBatchedMesh&&De.batching===!0||N.isBatchedMesh&&De.batchingColor===!0&&N.colorTexture===null||N.isBatchedMesh&&De.batchingColor===!1&&N.colorTexture!==null||N.isInstancedMesh&&De.instancing===!1||!N.isInstancedMesh&&De.instancing===!0||N.isSkinnedMesh&&De.skinning===!1||!N.isSkinnedMesh&&De.skinning===!0||N.isInstancedMesh&&De.instancingColor===!0&&N.instanceColor===null||N.isInstancedMesh&&De.instancingColor===!1&&N.instanceColor!==null||N.isInstancedMesh&&De.instancingMorph===!0&&N.morphTexture===null||N.isInstancedMesh&&De.instancingMorph===!1&&N.morphTexture!==null||De.envMap!==Ee||G.fog===!0&&De.fog!==he||De.numClippingPlanes!==void 0&&(De.numClippingPlanes!==Ae.numPlanes||De.numIntersection!==Ae.numIntersection)||De.vertexAlphas!==Ce||De.vertexTangents!==Ie||De.morphTargets!==Pe||De.morphNormals!==We||De.morphColors!==it||De.toneMapping!==ut||De.morphTargetsCount!==rt)&&(Ke=!0):(Ke=!0,De.__version=G.version);let Rt=De.currentProgram;Ke===!0&&(Rt=fi(G,I,N));let En=!1,Ct=!1,Xn=!1;const at=Rt.getUniforms(),Tt=De.uniforms;if(re.useProgram(Rt.program)&&(En=!0,Ct=!0,Xn=!0),G.id!==k&&(k=G.id,Ct=!0),En||q!==y){re.buffers.depth.getReversed()&&y.reversedDepth!==!0&&(y._reversedDepth=!0,y.updateProjectionMatrix()),at.setValue(C,"projectionMatrix",y.projectionMatrix),at.setValue(C,"viewMatrix",y.matrixWorldInverse);const At=at.map.cameraPosition;At!==void 0&&At.setValue(C,ze.setFromMatrixPosition(y.matrixWorld)),Fe.logarithmicDepthBuffer&&at.setValue(C,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2)),(G.isMeshPhongMaterial||G.isMeshToonMaterial||G.isMeshLambertMaterial||G.isMeshBasicMaterial||G.isMeshStandardMaterial||G.isShaderMaterial)&&at.setValue(C,"isOrthographic",y.isOrthographicCamera===!0),q!==y&&(q=y,Ct=!0,Xn=!0)}if(De.needsLights&&(je.state.directionalShadowMap.length>0&&at.setValue(C,"directionalShadowMap",je.state.directionalShadowMap,F),je.state.spotShadowMap.length>0&&at.setValue(C,"spotShadowMap",je.state.spotShadowMap,F),je.state.pointShadowMap.length>0&&at.setValue(C,"pointShadowMap",je.state.pointShadowMap,F)),N.isSkinnedMesh){at.setOptional(C,N,"bindMatrix"),at.setOptional(C,N,"bindMatrixInverse");const Mt=N.skeleton;Mt&&(Mt.boneTexture===null&&Mt.computeBoneTexture(),at.setValue(C,"boneTexture",Mt.boneTexture,F))}N.isBatchedMesh&&(at.setOptional(C,N,"batchingTexture"),at.setValue(C,"batchingTexture",N._matricesTexture,F),at.setOptional(C,N,"batchingIdTexture"),at.setValue(C,"batchingIdTexture",N._indirectTexture,F),at.setOptional(C,N,"batchingColorTexture"),N._colorsTexture!==null&&at.setValue(C,"batchingColorTexture",N._colorsTexture,F));const Dt=V.morphAttributes;if((Dt.position!==void 0||Dt.normal!==void 0||Dt.color!==void 0)&&ke.update(N,V,Rt),(Ct||De.receiveShadow!==N.receiveShadow)&&(De.receiveShadow=N.receiveShadow,at.setValue(C,"receiveShadow",N.receiveShadow)),G.isMeshGouraudMaterial&&G.envMap!==null&&(Tt.envMap.value=Ee,Tt.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),G.isMeshStandardMaterial&&G.envMap===null&&I.environment!==null&&(Tt.envMapIntensity.value=I.environmentIntensity),Tt.dfgLUT!==void 0&&(Tt.dfgLUT.value=nd()),Ct&&(at.setValue(C,"toneMappingExposure",x.toneMappingExposure),De.needsLights&&Fa(Tt,Xn),he&&G.fog===!0&&Ue.refreshFogUniforms(Tt,he),Ue.refreshMaterialUniforms(Tt,G,Ne,Ge,R.state.transmissionRenderTarget[y.id]),Gi.upload(C,Qr(De),Tt,F)),G.isShaderMaterial&&G.uniformsNeedUpdate===!0&&(Gi.upload(C,Qr(De),Tt,F),G.uniformsNeedUpdate=!1),G.isSpriteMaterial&&at.setValue(C,"center",N.center),at.setValue(C,"modelViewMatrix",N.modelViewMatrix),at.setValue(C,"normalMatrix",N.normalMatrix),at.setValue(C,"modelMatrix",N.matrixWorld),G.isShaderMaterial||G.isRawShaderMaterial){const Mt=G.uniformsGroups;for(let At=0,Zi=Mt.length;At0&&F.useMultisampledRTT(y)===!1?G=g.get(y).__webglMultisampledFramebuffer:Array.isArray(Ce)?G=Ce[V]:G=Ce,z.copy(y.viewport),H.copy(y.scissor),j=y.scissorTest}else z.copy(Y).multiplyScalar(Ne).floor(),H.copy(Q).multiplyScalar(Ne).floor(),j=Se;if(V!==0&&(G=Ia),re.bindFramebuffer(C.FRAMEBUFFER,G)&&re.drawBuffers(y,G),re.viewport(z),re.scissor(H),re.setScissorTest(j),N){const ge=g.get(y.texture);C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_CUBE_MAP_POSITIVE_X+I,ge.__webglTexture,V)}else if(he){const ge=I;for(let Ee=0;Ee=0&&I<=y.width-G&&V>=0&&V<=y.height-N&&(y.textures.length>1&&C.readBuffer(C.COLOR_ATTACHMENT0+ge),C.readPixels(I,V,G,N,ie.convert(Ie),ie.convert(Pe),he))}finally{const Ce=B!==null?g.get(B).__webglFramebuffer:null;re.bindFramebuffer(C.FRAMEBUFFER,Ce)}}},this.readRenderTargetPixelsAsync=async function(y,I,V,G,N,he,Me,ge=0){if(!(y&&y.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=g.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&Me!==void 0&&(Ee=Ee[Me]),Ee)if(I>=0&&I<=y.width-G&&V>=0&&V<=y.height-N){re.bindFramebuffer(C.FRAMEBUFFER,Ee);const Ce=y.textures[ge],Ie=Ce.format,Pe=Ce.type;if(!Fe.textureFormatReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Fe.textureTypeReadable(Pe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const We=C.createBuffer();C.bindBuffer(C.PIXEL_PACK_BUFFER,We),C.bufferData(C.PIXEL_PACK_BUFFER,he.byteLength,C.STREAM_READ),y.textures.length>1&&C.readBuffer(C.COLOR_ATTACHMENT0+ge),C.readPixels(I,V,G,N,ie.convert(Ie),ie.convert(Pe),0);const it=B!==null?g.get(B).__webglFramebuffer:null;re.bindFramebuffer(C.FRAMEBUFFER,it);const ut=C.fenceSync(C.SYNC_GPU_COMMANDS_COMPLETE,0);return C.flush(),await Ga(C,ut,4),C.bindBuffer(C.PIXEL_PACK_BUFFER,We),C.getBufferSubData(C.PIXEL_PACK_BUFFER,0,he),C.deleteBuffer(We),C.deleteSync(ut),he}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(y,I=null,V=0){const G=Math.pow(2,-V),N=Math.floor(y.image.width*G),he=Math.floor(y.image.height*G),Me=I!==null?I.x:0,ge=I!==null?I.y:0;F.setTexture2D(y,0),C.copyTexSubImage2D(C.TEXTURE_2D,V,0,0,Me,ge,N,he),re.unbindTexture()};const Na=C.createFramebuffer(),Oa=C.createFramebuffer();this.copyTextureToTexture=function(y,I,V=null,G=null,N=0,he=null){he===null&&(N!==0?(ii("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),he=N,N=0):he=0);let Me,ge,Ee,Ce,Ie,Pe,We,it,ut;const ht=y.isCompressedTexture?y.mipmaps[he]:y.image;if(V!==null)Me=V.max.x-V.min.x,ge=V.max.y-V.min.y,Ee=V.isBox3?V.max.z-V.min.z:1,Ce=V.min.x,Ie=V.min.y,Pe=V.isBox3?V.min.z:0;else{const Dt=Math.pow(2,-N);Me=Math.floor(ht.width*Dt),ge=Math.floor(ht.height*Dt),y.isDataArrayTexture?Ee=ht.depth:y.isData3DTexture?Ee=Math.floor(ht.depth*Dt):Ee=1,Ce=0,Ie=0,Pe=0}G!==null?(We=G.x,it=G.y,ut=G.z):(We=0,it=0,ut=0);const rt=ie.convert(I.format),De=ie.convert(I.type);let je;I.isData3DTexture?(F.setTexture3D(I,0),je=C.TEXTURE_3D):I.isDataArrayTexture||I.isCompressedArrayTexture?(F.setTexture2DArray(I,0),je=C.TEXTURE_2D_ARRAY):(F.setTexture2D(I,0),je=C.TEXTURE_2D),C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,I.flipY),C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,I.premultiplyAlpha),C.pixelStorei(C.UNPACK_ALIGNMENT,I.unpackAlignment);const Ke=C.getParameter(C.UNPACK_ROW_LENGTH),Rt=C.getParameter(C.UNPACK_IMAGE_HEIGHT),En=C.getParameter(C.UNPACK_SKIP_PIXELS),Ct=C.getParameter(C.UNPACK_SKIP_ROWS),Xn=C.getParameter(C.UNPACK_SKIP_IMAGES);C.pixelStorei(C.UNPACK_ROW_LENGTH,ht.width),C.pixelStorei(C.UNPACK_IMAGE_HEIGHT,ht.height),C.pixelStorei(C.UNPACK_SKIP_PIXELS,Ce),C.pixelStorei(C.UNPACK_SKIP_ROWS,Ie),C.pixelStorei(C.UNPACK_SKIP_IMAGES,Pe);const at=y.isDataArrayTexture||y.isData3DTexture,Tt=I.isDataArrayTexture||I.isData3DTexture;if(y.isDepthTexture){const Dt=g.get(y),Mt=g.get(I),At=g.get(Dt.__renderTarget),Zi=g.get(Mt.__renderTarget);re.bindFramebuffer(C.READ_FRAMEBUFFER,At.__webglFramebuffer),re.bindFramebuffer(C.DRAW_FRAMEBUFFER,Zi.__webglFramebuffer);for(let fn=0;fn, + @location(0) texCoord: vec2, +}; + +struct LayerUniforms { + opacity: f32, + padding: vec3, +}; + +@group(0) @binding(0) var layer: LayerUniforms; +@group(1) @binding(0) var textureSampler: sampler; +@group(1) @binding(1) var layerTexture: texture_2d; + +@vertex +fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput { + var output: VertexOutput; + let x = f32(i32(vertexIndex & 1u) * 4 - 1); + let y = f32(i32(vertexIndex >> 1u) * 4 - 1); + output.position = vec4(x, y, 0.0, 1.0); + output.texCoord = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5); + return output; +} + +@fragment +fn fragmentMain(input: VertexOutput) -> @location(0) vec4 { + let texColor = textureSample(layerTexture, textureSampler, input.texCoord); + return vec4(texColor.rgb, texColor.a * layer.opacity); +} +`,U=` +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) texCoord: vec2, +}; + +struct TransformUniforms { + matrix: mat4x4, + opacity: f32, + borderRadius: f32, + cropX: f32, + cropY: f32, + cropWidth: f32, + cropHeight: f32, + padding: vec2, +}; + +@group(0) @binding(0) var transform: TransformUniforms; +@group(1) @binding(0) var textureSampler: sampler; +@group(1) @binding(1) var layerTexture: texture_2d; + +@vertex +fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput { + var output: VertexOutput; + var positions = array, 6>( + vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0), + vec2(-1.0, 1.0), vec2(1.0, -1.0), vec2(1.0, 1.0) + ); + var texCoords = array, 6>( + vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(0.0, 0.0), + vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0) + ); + let pos = positions[vertexIndex]; + output.position = transform.matrix * vec4(pos, 0.0, 1.0); + output.texCoord = texCoords[vertexIndex]; + return output; +} + +@fragment +fn fragmentMain(input: VertexOutput) -> @location(0) vec4 { + let croppedUV = vec2( + transform.cropX + input.texCoord.x * transform.cropWidth, + transform.cropY + input.texCoord.y * transform.cropHeight + ); + let texColor = textureSample(layerTexture, textureSampler, croppedUV); + return vec4(texColor.rgb, texColor.a * transform.opacity); +} +`,C=` +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) texCoord: vec2, + @location(1) localPos: vec2, +}; + +struct BorderRadiusUniforms { + matrix: mat4x4, + opacity: f32, + radius: f32, + aspectRatio: f32, + smoothness: f32, +}; + +@group(0) @binding(0) var uniforms: BorderRadiusUniforms; +@group(1) @binding(0) var textureSampler: sampler; +@group(1) @binding(1) var layerTexture: texture_2d; + +@vertex +fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput { + var output: VertexOutput; + var positions = array, 6>( + vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0), + vec2(-1.0, 1.0), vec2(1.0, -1.0), vec2(1.0, 1.0) + ); + var texCoords = array, 6>( + vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(0.0, 0.0), + vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0) + ); + let pos = positions[vertexIndex]; + output.position = uniforms.matrix * vec4(pos, 0.0, 1.0); + output.texCoord = texCoords[vertexIndex]; + output.localPos = pos; + return output; +} + +fn sdRoundedRect(p: vec2, b: vec2, r: f32) -> f32 { + let q = abs(p) - b + vec2(r); + return min(max(q.x, q.y), 0.0) + length(max(q, vec2(0.0))) - r; +} + +@fragment +fn fragmentMain(input: VertexOutput) -> @location(0) vec4 { + let texColor = textureSample(layerTexture, textureSampler, input.texCoord); + let halfSize = vec2(1.0, 1.0); + let clampedRadius = clamp(uniforms.radius, 0.0, 0.5); + let dist = sdRoundedRect(input.localPos, halfSize, clampedRadius * 2.0); + let alpha = 1.0 - smoothstep(-uniforms.smoothness, uniforms.smoothness, dist); + return vec4(texColor.rgb, texColor.a * uniforms.opacity * alpha); +} +`;function w(u){const e=new Float32Array(8);return e[0]=u,e}function R(u,e,t,r){const i=new Float32Array(24);return i.set(u,0),i[16]=e,i[17]=t,i[18]=r?.x??0,i[19]=r?.y??0,i[20]=r?.width??1,i[21]=r?.height??1,i}function x(u,e,t,r,i,a){const s=new Float32Array(16),f=u.x/i*2,o=u.y/a*2,n=Math.cos(t),c=Math.sin(t),h=(r.x-.5)*2,l=(r.y-.5)*2;s[0]=e.x*n,s[1]=e.x*c,s[2]=0,s[3]=0,s[4]=-e.y*c,s[5]=e.y*n,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0;const d=f+h*(1-e.x*n)+l*e.y*c,p=o+l*(1-e.y*n)-h*e.x*c;return s[12]=d,s[13]=p,s[14]=0,s[15]=1,s}const S=` +// Effect parameters uniform buffer +struct EffectUniforms { + brightness: f32, // -1 to 1 + contrast: f32, + saturation: f32, + hue: f32, // 0 to 360 degrees + temperature: f32, // -1 to 1 (cool to warm) + tint: f32, // -1 to 1 (green to magenta) + shadows: f32, // -1 to 1 + highlights: f32, // -1 to 1 +}; + +// Image dimensions +struct Dimensions { + width: u32, + height: u32, + padding: vec2, +}; + +@group(0) @binding(0) var inputTexture: texture_2d; +@group(0) @binding(1) var outputTexture: texture_storage_2d; +@group(0) @binding(2) var effects: EffectUniforms; +@group(0) @binding(3) var dimensions: Dimensions; +fn rgb2hsv(rgb: vec3) -> vec3 { + let r = rgb.r; + let g = rgb.g; + let b = rgb.b; + + let maxC = max(max(r, g), b); + let minC = min(min(r, g), b); + let delta = maxC - minC; + + var h: f32 = 0.0; + var s: f32 = 0.0; + let v: f32 = maxC; + + if (delta > 0.00001) { + s = delta / maxC; + + if (maxC == r) { + h = (g - b) / delta; + if (g < b) { + h = h + 6.0; + } + } else if (maxC == g) { + h = 2.0 + (b - r) / delta; + } else { + h = 4.0 + (r - g) / delta; + } + h = h / 6.0; + } + + return vec3(h, s, v); +} +fn hsv2rgb(hsv: vec3) -> vec3 { + let h = hsv.x * 6.0; + let s = hsv.y; + let v = hsv.z; + + let i = floor(h); + let f = h - i; + let p = v * (1.0 - s); + let q = v * (1.0 - s * f); + let t = v * (1.0 - s * (1.0 - f)); + + let idx = i32(i) % 6; + + if (idx == 0) { + return vec3(v, t, p); + } else if (idx == 1) { + return vec3(q, v, p); + } else if (idx == 2) { + return vec3(p, v, t); + } else if (idx == 3) { + return vec3(p, q, v); + } else if (idx == 4) { + return vec3(t, p, v); + } else { + return vec3(v, p, q); + } +} +fn applyBrightness(color: vec3, brightness: f32) -> vec3 { + return clamp(color + vec3(brightness), vec3(0.0), vec3(1.0)); +} +fn applyContrast(color: vec3, contrast: f32) -> vec3 { + return clamp((color - 0.5) * contrast + 0.5, vec3(0.0), vec3(1.0)); +} +fn applySaturation(color: vec3, saturation: f32) -> vec3 { + let luminance = dot(color, vec3(0.299, 0.587, 0.114)); + return clamp(mix(vec3(luminance), color, saturation), vec3(0.0), vec3(1.0)); +} +fn applyHueRotation(color: vec3, hueShift: f32) -> vec3 { + var hsv = rgb2hsv(color); + hsv.x = fract(hsv.x + hueShift / 360.0); + return hsv2rgb(hsv); +} +fn applyTemperature(color: vec3, temperature: f32) -> vec3 { + var result = color; + if (temperature > 0.0) { + result.r = min(1.0, result.r + temperature * 0.2); + result.g = min(1.0, result.g + temperature * 0.1); + result.b = max(0.0, result.b - temperature * 0.2); + } else { + result.r = max(0.0, result.r + temperature * 0.2); + result.g = max(0.0, result.g + temperature * 0.05); + result.b = min(1.0, result.b - temperature * 0.2); + } + return result; +} +fn applyTint(color: vec3, tint: f32) -> vec3 { + var result = color; + result.r = clamp(result.r + tint * 0.1, 0.0, 1.0); + result.g = clamp(result.g - tint * 0.2, 0.0, 1.0); + result.b = clamp(result.b + tint * 0.1, 0.0, 1.0); + return result; +} +fn smoothstepCustom(edge0: f32, edge1: f32, x: f32) -> f32 { + let t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} +fn applyShadowsHighlights(color: vec3, shadows: f32, highlights: f32) -> vec3 { + let luminance = dot(color, vec3(0.299, 0.587, 0.114)); + let shadowWeight = 1.0 - smoothstepCustom(0.0, 0.33, luminance); + let highlightWeight = smoothstepCustom(0.66, 1.0, luminance); + let adjustment = shadows * shadowWeight * 0.3 + highlights * highlightWeight * 0.3; + return clamp(color + vec3(adjustment), vec3(0.0), vec3(1.0)); +} + +// Main compute shader entry point +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let x = global_id.x; + let y = global_id.y; + + if (x >= dimensions.width || y >= dimensions.height) { + return; + } + + let coords = vec2(i32(x), i32(y)); + var color = textureLoad(inputTexture, coords, 0); + var rgb = color.rgb; + if (abs(effects.brightness) > 0.001) { + rgb = applyBrightness(rgb, effects.brightness); + } + if (abs(effects.contrast - 1.0) > 0.001) { + rgb = applyContrast(rgb, effects.contrast); + } + if (abs(effects.saturation - 1.0) > 0.001) { + rgb = applySaturation(rgb, effects.saturation); + } + if (abs(effects.hue) > 0.001) { + rgb = applyHueRotation(rgb, effects.hue); + } + if (abs(effects.temperature) > 0.001) { + rgb = applyTemperature(rgb, effects.temperature); + } + if (abs(effects.tint) > 0.001) { + rgb = applyTint(rgb, effects.tint); + } + if (abs(effects.shadows) > 0.001 || abs(effects.highlights) > 0.001) { + rgb = applyShadowsHighlights(rgb, effects.shadows, effects.highlights); + } + + textureStore(outputTexture, coords, vec4(rgb, color.a)); +} +`,G=` +// Blur parameters +struct BlurUniforms { + radius: f32, + sigma: f32, + direction: vec2, +}; + +struct Dimensions { + width: u32, + height: u32, + padding: vec2, +}; + +@group(0) @binding(0) var inputTexture: texture_2d; +@group(0) @binding(1) var outputTexture: texture_storage_2d; +@group(0) @binding(2) var blur: BlurUniforms; +@group(0) @binding(3) var dimensions: Dimensions; + +fn gaussianWeight(offset: f32, sigma: f32) -> f32 { + let sigma2 = sigma * sigma; + return exp(-(offset * offset) / (2.0 * sigma2)) / (sqrt(2.0 * 3.14159265) * sigma); +} + +@compute @workgroup_size(16, 16, 1) +fn main(@builtin(global_invocation_id) global_id: vec3) { + let x = global_id.x; + let y = global_id.y; + + if (x >= dimensions.width || y >= dimensions.height) { + return; + } + + let coords = vec2(i32(x), i32(y)); + + if (blur.radius < 0.5) { + let color = textureLoad(inputTexture, coords, 0); + textureStore(outputTexture, coords, color); + return; + } + + let kernelRadius = i32(min(blur.radius, 20.0)); + let sigma = max(blur.sigma, blur.radius / 3.0); + + var colorSum = vec4(0.0); + var weightSum: f32 = 0.0; + + for (var i = -kernelRadius; i <= kernelRadius; i = i + 1) { + let offset = vec2(i32(blur.direction.x * f32(i)), i32(blur.direction.y * f32(i))); + let sampleCoords = coords + offset; + let clampedCoords = vec2( + clamp(sampleCoords.x, 0, i32(dimensions.width) - 1), + clamp(sampleCoords.y, 0, i32(dimensions.height) - 1) + ); + let weight = gaussianWeight(f32(i), sigma); + colorSum = colorSum + textureLoad(inputTexture, clampedCoords, 0) * weight; + weightSum = weightSum + weight; + } + + let finalColor = colorSum / weightSum; + textureStore(outputTexture, coords, finalColor); +} +`;function L(u=0,e=1,t=1,r=0,i=0,a=0,s=0,f=0){const o=new Float32Array(8);return o[0]=u,o[1]=e,o[2]=t,o[3]=r,o[4]=i,o[5]=a,o[6]=s,o[7]=f,o}function M(u=0,e=0,t=1,r=0){const i=new Float32Array(4);return i[0]=u,i[1]=e>0?e:u/3,i[2]=t,i[3]=r,i}function y(u,e){const t=new Uint32Array(4);return t[0]=u,t[1]=e,t[2]=0,t[3]=0,t}class E{device;width;height;effectsPipeline=null;blurPipeline=null;effectsBindGroupLayout=null;blurBindGroupLayout=null;effectsUniformBuffer=null;blurUniformBuffer=null;dimensionsBuffer=null;intermediateTextures=[];currentTextureIndex=0;effectsChangeCallbacks=[];lastEffectsHash=new Map;pendingReRenders=new Map;lastProcessingTime=0;constructor(e){this.device=e.device,this.width=e.width,this.height=e.height}async initialize(){try{return this.createBindGroupLayouts(),await this.createPipelines(),this.createUniformBuffers(),this.createIntermediateTextures(),!0}catch(e){return console.error("[WebGPUEffectsProcessor] Initialization failed:",e),!1}}createBindGroupLayouts(){this.effectsBindGroupLayout=this.device.createBindGroupLayout({label:"Effects Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.blurBindGroupLayout=this.device.createBindGroupLayout({label:"Blur Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]})}async createPipelines(){const e=this.device.createShaderModule({label:"Effects Compute Shader",code:S});this.effectsPipeline=this.device.createComputePipeline({label:"Effects Compute Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.effectsBindGroupLayout]}),compute:{module:e,entryPoint:"main"}});const t=this.device.createShaderModule({label:"Blur Compute Shader",code:G});this.blurPipeline=this.device.createComputePipeline({label:"Blur Compute Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.blurBindGroupLayout]}),compute:{module:t,entryPoint:"main"}})}createUniformBuffers(){this.effectsUniformBuffer=this.device.createBuffer({label:"Effects Uniform Buffer",size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.blurUniformBuffer=this.device.createBuffer({label:"Blur Uniform Buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.dimensionsBuffer=this.device.createBuffer({label:"Dimensions Buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});const e=y(this.width,this.height);this.device.queue.writeBuffer(this.dimensionsBuffer,0,e.buffer)}createIntermediateTextures(){for(const e of this.intermediateTextures)e.destroy();this.intermediateTextures=[];for(let e=0;e<2;e++){const t=this.device.createTexture({label:`Intermediate Texture ${e}`,size:{width:this.width,height:this.height},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST});this.intermediateTextures.push(t)}}processEffects(e,t){const r=performance.now(),i=t.filter(n=>n.enabled);if(i.length===0)return this.lastProcessingTime=performance.now()-r,e;const a=this.aggregateEffectParams(i),s=i.some(n=>n.type==="blur"),f=i.find(n=>n.type==="blur"),o=this.device.createCommandEncoder({label:"Effects Processing"});if(o.copyTextureToTexture({texture:e},{texture:this.intermediateTextures[0]},{width:this.width,height:this.height}),this.currentTextureIndex=0,this.hasColorEffects(a)&&this.applyColorEffects(o,a),s&&f){const n=f.params;this.applyBlur(o,{radius:n.radius??0,sigma:n.sigma})}return this.device.queue.submit([o.finish()]),this.lastProcessingTime=performance.now()-r,this.intermediateTextures[this.currentTextureIndex]}aggregateEffectParams(e){const t={brightness:0,contrast:1,saturation:1,hue:0,temperature:0,tint:0,shadows:0,highlights:0};for(const r of e){const i=r.params;switch(r.type){case"brightness":t.brightness+=i.value??0;break;case"contrast":t.contrast*=i.value??1;break;case"saturation":t.saturation*=i.value??1;break;case"hue":t.hue+=i.rotation??0;break;case"temperature":t.temperature+=i.value??0;break;case"tint":t.tint+=i.value??0;break;case"tonal":t.shadows+=i.shadows??0,t.highlights+=i.highlights??0;break}}return t.brightness=Math.max(-1,Math.min(1,t.brightness)),t.contrast=Math.max(0,Math.min(4,t.contrast)),t.saturation=Math.max(0,Math.min(4,t.saturation)),t.hue=t.hue%360,t.temperature=Math.max(-1,Math.min(1,t.temperature)),t.tint=Math.max(-1,Math.min(1,t.tint)),t.shadows=Math.max(-1,Math.min(1,t.shadows)),t.highlights=Math.max(-1,Math.min(1,t.highlights)),t}hasColorEffects(e){return Math.abs(e.brightness)>.001||Math.abs(e.contrast-1)>.001||Math.abs(e.saturation-1)>.001||Math.abs(e.hue)>.001||Math.abs(e.temperature)>.001||Math.abs(e.tint)>.001||Math.abs(e.shadows)>.001||Math.abs(e.highlights)>.001}applyColorEffects(e,t){const r=L(t.brightness,t.contrast,t.saturation,t.hue,t.temperature,t.tint,t.shadows,t.highlights);this.device.queue.writeBuffer(this.effectsUniformBuffer,0,r.buffer);const i=this.intermediateTextures[this.currentTextureIndex],a=1-this.currentTextureIndex,s=this.intermediateTextures[a],f=this.device.createBindGroup({label:"Effects Bind Group",layout:this.effectsBindGroupLayout,entries:[{binding:0,resource:i.createView()},{binding:1,resource:s.createView()},{binding:2,resource:{buffer:this.effectsUniformBuffer}},{binding:3,resource:{buffer:this.dimensionsBuffer}}]}),o=e.beginComputePass({label:"Effects Compute Pass"});o.setPipeline(this.effectsPipeline),o.setBindGroup(0,f);const n=Math.ceil(this.width/16),c=Math.ceil(this.height/16);o.dispatchWorkgroups(n,c,1),o.end(),this.currentTextureIndex=a}applyBlur(e,t){t.radius<.5||(this.applyBlurPass(e,t,1,0),this.applyBlurPass(e,t,0,1))}applyBlurPass(e,t,r,i){const a=M(t.radius,t.sigma??t.radius/3,r,i);this.device.queue.writeBuffer(this.blurUniformBuffer,0,a.buffer);const s=this.intermediateTextures[this.currentTextureIndex],f=1-this.currentTextureIndex,o=this.intermediateTextures[f],n=this.device.createBindGroup({label:`Blur Bind Group (${r},${i})`,layout:this.blurBindGroupLayout,entries:[{binding:0,resource:s.createView()},{binding:1,resource:o.createView()},{binding:2,resource:{buffer:this.blurUniformBuffer}},{binding:3,resource:{buffer:this.dimensionsBuffer}}]}),c=e.beginComputePass({label:`Blur Compute Pass (${r},${i})`});c.setPipeline(this.blurPipeline),c.setBindGroup(0,n);const h=Math.ceil(this.width/16),l=Math.ceil(this.height/16);c.dispatchWorkgroups(h,l,1),c.end(),this.currentTextureIndex=f}onEffectsChange(e){this.effectsChangeCallbacks.push(e)}notifyEffectsChanged(e,t){const r=this.calculateEffectsHash(t),i=this.lastEffectsHash.get(e);if(r===i)return;this.lastEffectsHash.set(e,r);const a=this.pendingReRenders.get(e);a&&clearTimeout(a);const s=setTimeout(()=>{this.pendingReRenders.delete(e);for(const f of this.effectsChangeCallbacks)f(e,t)},16);this.pendingReRenders.set(e,s)}calculateEffectsHash(e){return e.filter(t=>t.enabled).map(t=>`${t.id}:${t.type}:${JSON.stringify(t.params)}`).join("|")}getLastProcessingTime(){return this.lastProcessingTime}resize(e,t){if(this.width=e,this.height=t,this.dimensionsBuffer){const r=y(e,t);this.device.queue.writeBuffer(this.dimensionsBuffer,0,r.buffer)}this.createIntermediateTextures()}dispose(){for(const e of this.pendingReRenders.values())clearTimeout(e);this.pendingReRenders.clear();for(const e of this.intermediateTextures)e.destroy();this.intermediateTextures=[],this.effectsUniformBuffer?.destroy(),this.blurUniformBuffer?.destroy(),this.dimensionsBuffer?.destroy(),this.effectsUniformBuffer=null,this.blurUniformBuffer=null,this.dimensionsBuffer=null,this.effectsChangeCallbacks=[],this.lastEffectsHash.clear()}}const F=500*1024*1024;function g(u,e){return`${u}:${e.toFixed(6)}`}class D{cache=new Map;maxSize;currentSize=0;onEvict;constructor(e={}){this.maxSize=e.maxSize??F,this.onEvict=e.onEvict}get(e,t){const r=g(e,t),i=this.cache.get(r);return i?(i.lastUsed=Date.now(),i.texture):null}set(e,t,r,i){const a=g(e,t);for(this.cache.has(a)&&this.evictKey(a);this.currentSize+i>this.maxSize&&this.cache.size>0;)this.evictLRU();const s={texture:r,lastUsed:Date.now(),size:i,clipId:e,frameTime:t};this.cache.set(a,s),this.currentSize+=i}evict(e){const t=[];for(const[r,i]of this.cache.entries())i.clipId===e&&t.push(r);for(const r of t)this.evictKey(r)}evictLRU(){if(this.cache.size===0)return;let e=null,t=1/0;for(const[r,i]of this.cache.entries())i.lastUsed{this.triggerReRender(t,r)}),this.frameCache=new D({maxSize:this._maxTextureCache,onEvict:t=>{console.debug(`[WebGPURenderer] Evicted frame cache entry: ${t.clipId}:${t.frameTime}`)}}),!0}catch(e){return console.error("[WebGPURenderer] Initialization failed:",e),!1}}setupDeviceLossHandling(){this.device&&this.device.lost.then(e=>{console.warn(`[WebGPURenderer] Device lost: ${e.reason}`,e.message),this.isDeviceLost=!0;for(const t of this.deviceLostCallbacks)t();this.deviceRecreationInProgress||this.attemptDeviceRecreation().catch(t=>{console.error("[WebGPURenderer] Device recreation failed:",t)})})}async attemptDeviceRecreation(){this.deviceRecreationInProgress=!0;const e=3,t=1e3;for(let r=1;r<=e;r++)if(await new Promise(a=>setTimeout(a,t)),await this.recreateDevice()){this.deviceRecreationInProgress=!1;return}console.error("[WebGPURenderer] Failed to recreate device after multiple attempts"),this.deviceRecreationInProgress=!1}createFrameBuffers(){if(this.device){for(const e of this.frameBuffers)e.destroy();this.frameBuffers=[];for(let e=0;e<2;e++){const t=this.device.createTexture({size:{width:this.width,height:this.height},format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});this.frameBuffers.push(t)}}}createBindGroupLayouts(){this.device&&(this.compositeUniformLayout=this.device.createBindGroupLayout({label:"Composite Uniform Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.compositeTextureLayout=this.device.createBindGroupLayout({label:"Composite Texture Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.transformUniformLayout=this.device.createBindGroupLayout({label:"Transform Uniform Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.transformTextureLayout=this.compositeTextureLayout,this.borderRadiusUniformLayout=this.device.createBindGroupLayout({label:"Border Radius Uniform Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.borderRadiusTextureLayout=this.compositeTextureLayout,this.bindGroupLayoutRef=this.compositeUniformLayout)}createUniformBuffers(){this.device&&(this.layerUniformBuffer=this.device.createBuffer({label:"Layer Uniform Buffer",size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.transformUniformBuffer=this.device.createBuffer({label:"Transform Uniform Buffer",size:96,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.borderRadiusUniformBuffer=this.device.createBuffer({label:"Border Radius Uniform Buffer",size:80,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}))}createTextureSampler(){this.device&&(this.textureSampler=this.device.createSampler({label:"Texture Sampler",magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}))}async initializePipelines(){if(!this.device)return;const e=navigator.gpu.getPreferredCanvasFormat();await this.createCompositePipeline(e),await this.createTransformPipeline("rgba8unorm"),await this.createBorderRadiusPipeline("rgba8unorm"),this.renderPipelineRef=this.compositePipeline}async createCompositePipeline(e){if(!this.device||!this.compositeUniformLayout||!this.compositeTextureLayout)return;const t=this.device.createShaderModule({label:"Composite Shader",code:B});this.compositePipeline=this.device.createRenderPipeline({label:"Composite Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.compositeUniformLayout,this.compositeTextureLayout]}),vertex:{module:t,entryPoint:"vertexMain"},fragment:{module:t,entryPoint:"fragmentMain",targets:[{format:e,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}})}async createTransformPipeline(e){if(!this.device||!this.transformUniformLayout||!this.transformTextureLayout)return;const t=this.device.createShaderModule({label:"Transform Shader",code:U});this.transformPipeline=this.device.createRenderPipeline({label:"Transform Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.transformUniformLayout,this.transformTextureLayout]}),vertex:{module:t,entryPoint:"vertexMain"},fragment:{module:t,entryPoint:"fragmentMain",targets:[{format:e,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}})}async createBorderRadiusPipeline(e){if(!this.device||!this.borderRadiusUniformLayout||!this.borderRadiusTextureLayout)return;const t=this.device.createShaderModule({label:"Border Radius Shader",code:C});this.borderRadiusPipeline=this.device.createRenderPipeline({label:"Border Radius Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.borderRadiusUniformLayout,this.borderRadiusTextureLayout]}),vertex:{module:t,entryPoint:"vertexMain"},fragment:{module:t,entryPoint:"fragmentMain",targets:[{format:e,blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}})}isSupported(){return typeof navigator<"u"&&"gpu"in navigator}destroy(){this.effectsProcessor&&(this.effectsProcessor.dispose(),this.effectsProcessor=null),this.frameCache&&(this.frameCache.clear(),this.frameCache=null);for(const e of this.frameBuffers)e.destroy();this.frameBuffers=[],this.currentFrameTexture&&(this.currentFrameTexture.destroy(),this.currentFrameTexture=null),this.layerUniformBuffer?.destroy(),this.transformUniformBuffer?.destroy(),this.borderRadiusUniformBuffer?.destroy(),this.layerUniformBuffer=null,this.transformUniformBuffer=null,this.borderRadiusUniformBuffer=null,this.compositePipeline=null,this.transformPipeline=null,this.borderRadiusPipeline=null,this.renderPipelineRef=null,this.compositeUniformLayout=null,this.compositeTextureLayout=null,this.transformUniformLayout=null,this.transformTextureLayout=null,this.borderRadiusUniformLayout=null,this.borderRadiusTextureLayout=null,this.bindGroupLayoutRef=null,this.textureSampler=null,this.device&&(this.device.destroy(),this.device=null),this.adapter=null,this.context=null,this.deviceLostCallbacks=[],this.effectsChangeCallbacks=[],this.layers=[],this.frameCacheHits=0,this.frameCacheMisses=0}beginFrame(){!this.device||this.isDeviceLost||(this.layers=[],this.currentFrameBuffer=1-this.currentFrameBuffer)}renderLayer(e){this.layers.push(e)}async endFrame(){if(!this.device||!this.context||this.isDeviceLost)throw new Error("WebGPU device not available");const e=performance.now(),t=this.context.getCurrentTexture(),r=this.device.createCommandEncoder({label:"Frame Command Encoder"}),i=this.frameBuffers[this.currentFrameBuffer],a=r.beginRenderPass({label:"Frame Buffer Render Pass",colorAttachments:[{view:i.createView(),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});this.renderLayersToPass(a),a.end();const s=r.beginRenderPass({label:"Present Render Pass",colorAttachments:[{view:t.createView(),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});this.renderFrameBufferToScreen(s),s.end();const f=r.finish();this.device.queue.submit([f]);const o=Math.ceil(this.width*4/256)*256,n=this.device.createBuffer({size:o*this.height,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),c=this.device.createCommandEncoder();c.copyTextureToBuffer({texture:i},{buffer:n,bytesPerRow:o},{width:this.width,height:this.height}),this.device.queue.submit([c.finish()]),await n.mapAsync(1);const h=n.getMappedRange(),l=new Uint8ClampedArray(h),d=new Uint8ClampedArray(this.width*this.height*4),p=o,b=this.width*4;for(let m=0;m0;let a=r;t.effects.length>0&&this.effectsProcessor&&(a=this.effectsProcessor.processEffects(r,t.effects)),i&&this.borderRadiusPipeline?this.renderLayerWithBorderRadius(e,a,t):this.transformPipeline&&this.renderLayerWithTransform(e,a,t)}}renderLayerWithTransform(e,t,r){if(!this.device||!this.transformPipeline||!this.transformUniformBuffer||!this.transformUniformLayout||!this.transformTextureLayout||!this.textureSampler)return;const i=x(r.transform.position,r.transform.scale,r.transform.rotation,r.transform.anchor,this.width,this.height),a=R(i,r.opacity*r.transform.opacity,r.borderRadius,r.transform.crop);this.device.queue.writeBuffer(this.transformUniformBuffer,0,a.buffer);const s=this.device.createBindGroup({label:"Transform Uniform Bind Group",layout:this.transformUniformLayout,entries:[{binding:0,resource:{buffer:this.transformUniformBuffer}}]}),f=this.device.createBindGroup({label:"Transform Texture Bind Group",layout:this.transformTextureLayout,entries:[{binding:0,resource:this.textureSampler},{binding:1,resource:t.createView()}]});e.setPipeline(this.transformPipeline),e.setBindGroup(0,s),e.setBindGroup(1,f),e.draw(6)}renderLayerWithBorderRadius(e,t,r){if(!this.device||!this.borderRadiusPipeline||!this.borderRadiusUniformBuffer||!this.borderRadiusUniformLayout||!this.borderRadiusTextureLayout||!this.textureSampler)return;const i=x(r.transform.position,r.transform.scale,r.transform.rotation,r.transform.anchor,this.width,this.height),a=Math.min(r.borderRadius/100,.5),s=new Float32Array(20);s.set(i,0),s[16]=r.opacity*r.transform.opacity,s[17]=a,s[18]=this.width/this.height,s[19]=.01,this.device.queue.writeBuffer(this.borderRadiusUniformBuffer,0,s.buffer);const f=this.device.createBindGroup({label:"Border Radius Uniform Bind Group",layout:this.borderRadiusUniformLayout,entries:[{binding:0,resource:{buffer:this.borderRadiusUniformBuffer}}]}),o=this.device.createBindGroup({label:"Border Radius Texture Bind Group",layout:this.borderRadiusTextureLayout,entries:[{binding:0,resource:this.textureSampler},{binding:1,resource:t.createView()}]});e.setPipeline(this.borderRadiusPipeline),e.setBindGroup(0,f),e.setBindGroup(1,o),e.draw(6)}renderFrameBufferToScreen(e){if(!this.device||!this.compositePipeline||!this.layerUniformBuffer||!this.compositeUniformLayout||!this.compositeTextureLayout||!this.textureSampler)return;const t=this.frameBuffers[this.currentFrameBuffer],r=w(1);this.device.queue.writeBuffer(this.layerUniformBuffer,0,r.buffer);const i=this.device.createBindGroup({label:"Composite Uniform Bind Group",layout:this.compositeUniformLayout,entries:[{binding:0,resource:{buffer:this.layerUniformBuffer}}]}),a=this.device.createBindGroup({label:"Composite Texture Bind Group",layout:this.compositeTextureLayout,entries:[{binding:0,resource:this.textureSampler},{binding:1,resource:t.createView()}]});e.setPipeline(this.compositePipeline),e.setBindGroup(0,i),e.setBindGroup(1,a),e.draw(3)}createTextureFromImage(e){if(!this.device)throw new Error("WebGPU device not initialized");const t=this.device.createTexture({size:{width:e.width,height:e.height},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});return this.device.queue.copyExternalImageToTexture({source:e},{texture:t},{width:e.width,height:e.height}),t}releaseTexture(e){e&&"destroy"in e&&e.destroy()}applyEffects(e,t){return!this.effectsProcessor||!e||!("destroy"in e&&"createView"in e)?e:this.effectsProcessor.processEffects(e,t)}notifyEffectsChanged(e,t){this.effectsProcessor&&this.effectsProcessor.notifyEffectsChanged(e,t)}onEffectsReRender(e){this.effectsChangeCallbacks.push(e)}triggerReRender(e,t){const r=performance.now();for(const i of this.effectsChangeCallbacks)i(e,t);this.lastRenderTime=performance.now()-r,this.lastRenderTime>100&&console.warn(`[WebGPURenderer] Re-render took ${this.lastRenderTime.toFixed(2)}ms, exceeds 100ms target`)}getLastRenderTime(){return this.lastRenderTime}getEffectsProcessingTime(){return this.effectsProcessor?.getLastProcessingTime()??0}onDeviceLost(e){this.deviceLostCallbacks.push(e)}async recreateDevice(){return this.isDeviceLost=!1,this.destroy(),this.initialize()}resize(e,t){if(this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.context&&this.device){const r=navigator.gpu.getPreferredCanvasFormat();this.context.configure({device:this.device,format:r,alphaMode:"premultiplied"}),this.createFrameBuffers(),this.effectsProcessor&&this.effectsProcessor.resize(e,t)}}getMemoryUsage(){return this.width*this.height*4*2}getDevice(){return this.device}isLost(){return this.isDeviceLost}getCachedFrame(e,t){if(!this.frameCache)return null;const r=this.frameCache.get(e,t);return r?(this.frameCacheHits++,r):(this.frameCacheMisses++,null)}cacheFrame(e,t,r){if(!this.device)throw new Error("WebGPU device not initialized");const i=this.getCachedFrame(e,t);if(i)return i;const a=this.createTextureFromImage(r),s=_(r.width,r.height,"rgba8unorm");return this.frameCache&&this.frameCache.set(e,t,a,s),a}hasFrameCached(e,t){return this.frameCache?.has(e,t)??!1}evictClipFrames(e){this.frameCache?.evict(e)}getFrameCacheStats(){const e=this.frameCacheHits+this.frameCacheMisses;return{hits:this.frameCacheHits,misses:this.frameCacheMisses,hitRate:e>0?this.frameCacheHits/e:0,memoryUsage:this.frameCache?.getMemoryUsage()??0,maxSize:this.frameCache?.getMaxSize()??0,entryCount:this.frameCache?.getCount()??0}}clearFrameCache(){this.frameCache?.clear(),this.frameCacheHits=0,this.frameCacheMisses=0}getRenderPipeline(){return this.compositePipeline}getTransformPipeline(){return this.transformPipeline}getBorderRadiusPipeline(){return this.borderRadiusPipeline}arePipelinesInitialized(){return this.compositePipeline!==null&&this.transformPipeline!==null&&this.borderRadiusPipeline!==null}}const I=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:z},Symbol.toStringTag,{value:"Module"}));export{D as T,z as W,E as a,B as b,_ as c,C as d,w as e,R as f,x as g,S as h,G as i,L as j,M as k,y as l,U as t,I as w}; diff --git a/resources/video-editor/assets/worker-DYSz7Krg.js b/resources/video-editor/assets/worker-DYSz7Krg.js new file mode 100644 index 00000000..6f874d61 --- /dev/null +++ b/resources/video-editor/assets/worker-DYSz7Krg.js @@ -0,0 +1 @@ +const f="0.12.9",R=`https://unpkg.com/@ffmpeg/core@${f}/dist/umd/ffmpeg-core.js`;var E;(function(t){t.LOAD="LOAD",t.EXEC="EXEC",t.FFPROBE="FFPROBE",t.WRITE_FILE="WRITE_FILE",t.READ_FILE="READ_FILE",t.DELETE_FILE="DELETE_FILE",t.RENAME="RENAME",t.CREATE_DIR="CREATE_DIR",t.LIST_DIR="LIST_DIR",t.DELETE_DIR="DELETE_DIR",t.ERROR="ERROR",t.DOWNLOAD="DOWNLOAD",t.PROGRESS="PROGRESS",t.LOG="LOG",t.MOUNT="MOUNT",t.UNMOUNT="UNMOUNT"})(E||(E={}));const u=new Error("unknown message type"),O=new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),m=new Error("failed to import ffmpeg-core.js");let r;const l=async({coreURL:t,wasmURL:n,workerURL:e})=>{const o=!r;try{t||(t=R),importScripts(t)}catch{if((!t||t===R)&&(t=R.replace("/umd/","/esm/")),self.createFFmpegCore=(await import(t)).default,!self.createFFmpegCore)throw m}const s=t,c=n||t.replace(/.js$/g,".wasm"),a=e||t.replace(/.js$/g,".worker.js");return r=await self.createFFmpegCore({mainScriptUrlOrBlob:`${s}#${btoa(JSON.stringify({wasmURL:c,workerURL:a}))}`}),r.setLogger(i=>self.postMessage({type:E.LOG,data:i})),r.setProgress(i=>self.postMessage({type:E.PROGRESS,data:i})),o},D=({args:t,timeout:n=-1})=>{r.setTimeout(n),r.exec(...t);const e=r.ret;return r.reset(),e},S=({args:t,timeout:n=-1})=>{r.setTimeout(n),r.ffprobe(...t);const e=r.ret;return r.reset(),e},I=({path:t,data:n})=>(r.FS.writeFile(t,n),!0),L=({path:t,encoding:n})=>r.FS.readFile(t,{encoding:n}),N=({path:t})=>(r.FS.unlink(t),!0),A=({oldPath:t,newPath:n})=>(r.FS.rename(t,n),!0),k=({path:t})=>(r.FS.mkdir(t),!0),w=({path:t})=>{const n=r.FS.readdir(t),e=[];for(const o of n){const s=r.FS.stat(`${t}/${o}`),c=r.FS.isDir(s.mode);e.push({name:o,isDir:c})}return e},b=({path:t})=>(r.FS.rmdir(t),!0),p=({fsType:t,options:n,mountPoint:e})=>{const o=t,s=r.FS.filesystems[o];return s?(r.FS.mount(s,n,e),!0):!1},d=({mountPoint:t})=>(r.FS.unmount(t),!0);self.onmessage=async({data:{id:t,type:n,data:e}})=>{const o=[];let s;try{if(n!==E.LOAD&&!r)throw O;switch(n){case E.LOAD:s=await l(e);break;case E.EXEC:s=D(e);break;case E.FFPROBE:s=S(e);break;case E.WRITE_FILE:s=I(e);break;case E.READ_FILE:s=L(e);break;case E.DELETE_FILE:s=N(e);break;case E.RENAME:s=A(e);break;case E.CREATE_DIR:s=k(e);break;case E.LIST_DIR:s=w(e);break;case E.DELETE_DIR:s=b(e);break;case E.MOUNT:s=p(e);break;case E.UNMOUNT:s=d(e);break;default:throw u}}catch(c){self.postMessage({id:t,type:E.ERROR,data:c.toString()});return}s instanceof Uint8Array&&o.push(s.buffer),self.postMessage({id:t,type:n,data:s},o)}; diff --git a/resources/video-editor/assets/zustand-CnPgS7xu.js b/resources/video-editor/assets/zustand-CnPgS7xu.js new file mode 100644 index 00000000..a43b07bc --- /dev/null +++ b/resources/video-editor/assets/zustand-CnPgS7xu.js @@ -0,0 +1,17 @@ +import{r as D,g as P,d as T}from"./react-kyfdMflE.js";const W={},w=e=>{let r;const n=new Set,o=(m,S)=>{const y=typeof m=="function"?m(r):m;if(!Object.is(y,r)){const l=r;r=S??(typeof y!="object"||y===null)?y:Object.assign({},r,y),n.forEach(h=>h(r,l))}},s=()=>r,v={setState:o,getState:s,getInitialState:()=>c,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(W?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=r=e(o,s,v);return v},A=e=>e?w(e):w;var j={exports:{}},z={},H={exports:{}},x={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var p=D;function J(e,r){return e===r&&(e!==0||1/e===1/r)||e!==e&&r!==r}var N=typeof Object.is=="function"?Object.is:J,U=p.useState,k=p.useEffect,L=p.useLayoutEffect,M=p.useDebugValue;function G(e,r){var n=r(),o=U({inst:{value:n,getSnapshot:r}}),s=o[0].inst,t=o[1];return L(function(){s.value=n,s.getSnapshot=r,I(s)&&t({inst:s})},[e,n,r]),k(function(){return I(s)&&t({inst:s}),e(function(){I(s)&&t({inst:s})})},[e]),M(n),n}function I(e){var r=e.getSnapshot;e=e.value;try{var n=r();return!N(e,n)}catch{return!0}}function B(e,r){return r()}var q=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?B:G;x.useSyncExternalStore=p.useSyncExternalStore!==void 0?p.useSyncExternalStore:q;H.exports=x;var K=H.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var _=D,Q=K;function X(e,r){return e===r&&(e!==0||1/e===1/r)||e!==e&&r!==r}var Y=typeof Object.is=="function"?Object.is:X,Z=Q.useSyncExternalStore,V=_.useRef,ee=_.useEffect,te=_.useMemo,re=_.useDebugValue;z.useSyncExternalStoreWithSelector=function(e,r,n,o,s){var t=V(null);if(t.current===null){var d={hasValue:!1,value:null};t.current=d}else d=t.current;t=te(function(){function v(l){if(!c){if(c=!0,m=l,l=o(l),s!==void 0&&d.hasValue){var h=d.value;if(s(h,l))return S=h}return S=l}if(h=S,Y(m,l))return h;var u=o(l);return s!==void 0&&s(h,u)?(m=l,h):(m=l,S=u)}var c=!1,m,S,y=n===void 0?null:n;return[function(){return v(r())},y===null?void 0:function(){return v(y())}]},[r,n,o,s]);var f=Z(e,t[0],t[1]);return ee(function(){d.hasValue=!0,d.value=f},[f]),re(f),f};j.exports=z;var ne=j.exports;const oe=P(ne),F={},{useDebugValue:se}=T,{useSyncExternalStoreWithSelector:ie}=oe;let R=!1;const ae=e=>e;function ue(e,r=ae,n){(F?"production":void 0)!=="production"&&n&&!R&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),R=!0);const o=ie(e.subscribe,e.getState,e.getServerState||e.getInitialState,r,n);return se(o),o}const $=e=>{(F?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const r=typeof e=="function"?A(e):e,n=(o,s)=>ue(r,o,s);return Object.assign(n,r),n},he=e=>e?$(e):$,ce={},le=e=>(r,n,o)=>{const s=o.subscribe;return o.subscribe=(d,f,v)=>{let c=d;if(f){const m=v?.equalityFn||Object.is;let S=d(o.getState());c=y=>{const l=d(y);if(!m(S,l)){const h=S;f(S=l,h)}},v?.fireImmediately&&f(S,S)}return s(c)},e(r,n,o)},ye=le;function de(e,r){let n;try{n=e()}catch{return}return{getItem:s=>{var t;const d=v=>v===null?null:JSON.parse(v,void 0),f=(t=n.getItem(s))!=null?t:null;return f instanceof Promise?f.then(d):d(f)},setItem:(s,t)=>n.setItem(s,JSON.stringify(t,void 0)),removeItem:s=>n.removeItem(s)}}const E=e=>r=>{try{const n=e(r);return n instanceof Promise?n:{then(o){return E(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return E(o)(n)}}}},fe=(e,r)=>(n,o,s)=>{let t={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:a=>a,version:0,merge:(a,g)=>({...g,...a}),...r},d=!1;const f=new Set,v=new Set;let c;try{c=t.getStorage()}catch{}if(!c)return e((...a)=>{console.warn(`[zustand persist middleware] Unable to update item '${t.name}', the given storage is currently unavailable.`),n(...a)},o,s);const m=E(t.serialize),S=()=>{const a=t.partialize({...o()});let g;const i=m({state:a,version:t.version}).then(b=>c.setItem(t.name,b)).catch(b=>{g=b});if(g)throw g;return i},y=s.setState;s.setState=(a,g)=>{y(a,g),S()};const l=e((...a)=>{n(...a),S()},o,s);let h;const u=()=>{var a;if(!c)return;d=!1,f.forEach(i=>i(o()));const g=((a=t.onRehydrateStorage)==null?void 0:a.call(t,o()))||void 0;return E(c.getItem.bind(c))(t.name).then(i=>{if(i)return t.deserialize(i)}).then(i=>{if(i)if(typeof i.version=="number"&&i.version!==t.version){if(t.migrate)return t.migrate(i.state,i.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return i.state}).then(i=>{var b;return h=t.merge(i,(b=o())!=null?b:l),n(h,!0),S()}).then(()=>{g?.(h,void 0),d=!0,v.forEach(i=>i(h))}).catch(i=>{g?.(void 0,i)})};return s.persist={setOptions:a=>{t={...t,...a},a.getStorage&&(c=a.getStorage())},clearStorage:()=>{c?.removeItem(t.name)},getOptions:()=>t,rehydrate:()=>u(),hasHydrated:()=>d,onHydrate:a=>(f.add(a),()=>{f.delete(a)}),onFinishHydration:a=>(v.add(a),()=>{v.delete(a)})},u(),h||l},ve=(e,r)=>(n,o,s)=>{let t={storage:de(()=>localStorage),partialize:u=>u,version:0,merge:(u,a)=>({...a,...u}),...r},d=!1;const f=new Set,v=new Set;let c=t.storage;if(!c)return e((...u)=>{console.warn(`[zustand persist middleware] Unable to update item '${t.name}', the given storage is currently unavailable.`),n(...u)},o,s);const m=()=>{const u=t.partialize({...o()});return c.setItem(t.name,{state:u,version:t.version})},S=s.setState;s.setState=(u,a)=>{S(u,a),m()};const y=e((...u)=>{n(...u),m()},o,s);s.getInitialState=()=>y;let l;const h=()=>{var u,a;if(!c)return;d=!1,f.forEach(i=>{var b;return i((b=o())!=null?b:y)});const g=((a=t.onRehydrateStorage)==null?void 0:a.call(t,(u=o())!=null?u:y))||void 0;return E(c.getItem.bind(c))(t.name).then(i=>{if(i)if(typeof i.version=="number"&&i.version!==t.version){if(t.migrate)return[!0,t.migrate(i.state,i.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,i.state];return[!1,void 0]}).then(i=>{var b;const[O,C]=i;if(l=t.merge(C,(b=o())!=null?b:y),n(l,!0),O)return m()}).then(()=>{g?.(l,void 0),l=o(),d=!0,v.forEach(i=>i(l))}).catch(i=>{g?.(void 0,i)})};return s.persist={setOptions:u=>{t={...t,...u},u.storage&&(c=u.storage)},clearStorage:()=>{c?.removeItem(t.name)},getOptions:()=>t,rehydrate:()=>h(),hasHydrated:()=>d,onHydrate:u=>(f.add(u),()=>{f.delete(u)}),onFinishHydration:u=>(v.add(u),()=>{v.delete(u)})},t.skipHydration||h(),l||y},me=(e,r)=>"getStorage"in r||"serialize"in r||"deserialize"in r?((ce?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),fe(e,r)):ve(e,r),ge=me;export{he as c,ge as p,ye as s}; diff --git a/resources/video-editor/favicon.svg b/resources/video-editor/favicon.svg new file mode 100644 index 00000000..7b6da5b8 --- /dev/null +++ b/resources/video-editor/favicon.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/resources/video-editor/fonts/helvetiker_bold.typeface.json b/resources/video-editor/fonts/helvetiker_bold.typeface.json new file mode 100644 index 00000000..872ce447 --- /dev/null +++ b/resources/video-editor/fonts/helvetiker_bold.typeface.json @@ -0,0 +1 @@ +{"glyphs":{"ο":{"x_min":0,"x_max":764,"ha":863,"o":"m 380 -25 q 105 87 211 -25 q 0 372 0 200 q 104 660 0 545 q 380 775 209 775 q 658 659 552 775 q 764 372 764 544 q 658 87 764 200 q 380 -25 552 -25 m 379 142 q 515 216 466 142 q 557 373 557 280 q 515 530 557 465 q 379 607 466 607 q 245 530 294 607 q 204 373 204 465 q 245 218 204 283 q 379 142 294 142 "},"S":{"x_min":0,"x_max":826,"ha":915,"o":"m 826 306 q 701 55 826 148 q 423 -29 587 -29 q 138 60 255 -29 q 0 318 13 154 l 208 318 q 288 192 216 238 q 437 152 352 152 q 559 181 506 152 q 623 282 623 217 q 466 411 623 372 q 176 487 197 478 q 18 719 18 557 q 136 958 18 869 q 399 1040 244 1040 q 670 956 561 1040 q 791 713 791 864 l 591 713 q 526 826 583 786 q 393 866 469 866 q 277 838 326 866 q 218 742 218 804 q 374 617 218 655 q 667 542 646 552 q 826 306 826 471 "},"¦":{"x_min":0,"x_max":143,"ha":240,"o":"m 143 462 l 0 462 l 0 984 l 143 984 l 143 462 m 143 -242 l 0 -242 l 0 280 l 143 280 l 143 -242 "},"/":{"x_min":196.109375,"x_max":632.5625,"ha":828,"o":"m 632 1040 l 289 -128 l 196 -128 l 538 1040 l 632 1040 "},"Τ":{"x_min":-0.609375,"x_max":808,"ha":878,"o":"m 808 831 l 508 831 l 508 0 l 298 0 l 298 831 l 0 831 l 0 1013 l 808 1013 l 808 831 "},"y":{"x_min":0,"x_max":738.890625,"ha":828,"o":"m 738 749 l 444 -107 q 361 -238 413 -199 q 213 -277 308 -277 q 156 -275 176 -277 q 120 -271 131 -271 l 120 -110 q 147 -113 134 -111 q 179 -116 161 -116 q 247 -91 226 -116 q 269 -17 269 -67 q 206 173 269 -4 q 84 515 162 301 q 0 749 41 632 l 218 749 l 376 207 l 529 749 l 738 749 "},"Π":{"x_min":0,"x_max":809,"ha":922,"o":"m 809 0 l 598 0 l 598 836 l 208 836 l 208 0 l 0 0 l 0 1012 l 809 1012 l 809 0 "},"ΐ":{"x_min":-162,"x_max":364,"ha":364,"o":"m 364 810 l 235 810 l 235 952 l 364 952 l 364 810 m 301 1064 l 86 810 l -12 810 l 123 1064 l 301 1064 m -33 810 l -162 810 l -162 952 l -33 952 l -33 810 m 200 0 l 0 0 l 0 748 l 200 748 l 200 0 "},"g":{"x_min":0,"x_max":724,"ha":839,"o":"m 724 48 q 637 -223 724 -142 q 357 -304 551 -304 q 140 -253 226 -304 q 23 -72 36 -192 l 243 -72 q 290 -127 255 -110 q 368 -144 324 -144 q 504 -82 470 -144 q 530 71 530 -38 l 530 105 q 441 25 496 51 q 319 0 386 0 q 79 115 166 0 q 0 377 0 219 q 77 647 0 534 q 317 775 166 775 q 534 656 456 775 l 534 748 l 724 748 l 724 48 m 368 167 q 492 237 447 167 q 530 382 530 297 q 490 529 530 466 q 364 603 444 603 q 240 532 284 603 q 201 386 201 471 q 240 239 201 300 q 368 167 286 167 "},"²":{"x_min":0,"x_max":463,"ha":560,"o":"m 463 791 q 365 627 463 706 q 151 483 258 555 l 455 483 l 455 382 l 0 382 q 84 565 0 488 q 244 672 97 576 q 331 784 331 727 q 299 850 331 824 q 228 876 268 876 q 159 848 187 876 q 132 762 132 820 l 10 762 q 78 924 10 866 q 228 976 137 976 q 392 925 322 976 q 463 791 463 874 "},"–":{"x_min":0,"x_max":704.171875,"ha":801,"o":"m 704 297 l 0 297 l 0 450 l 704 450 l 704 297 "},"Κ":{"x_min":0,"x_max":899.671875,"ha":969,"o":"m 899 0 l 646 0 l 316 462 l 208 355 l 208 0 l 0 0 l 0 1013 l 208 1013 l 208 596 l 603 1013 l 863 1013 l 460 603 l 899 0 "},"ƒ":{"x_min":-46,"x_max":440,"ha":525,"o":"m 440 609 l 316 609 l 149 -277 l -46 -277 l 121 609 l 14 609 l 14 749 l 121 749 q 159 949 121 894 q 344 1019 208 1019 l 440 1015 l 440 855 l 377 855 q 326 841 338 855 q 314 797 314 827 q 314 773 314 786 q 314 749 314 761 l 440 749 l 440 609 "},"e":{"x_min":0,"x_max":708,"ha":808,"o":"m 708 321 l 207 321 q 254 186 207 236 q 362 141 298 141 q 501 227 453 141 l 700 227 q 566 36 662 104 q 362 -26 477 -26 q 112 72 213 -26 q 0 369 0 182 q 95 683 0 573 q 358 793 191 793 q 619 677 531 793 q 708 321 708 561 m 501 453 q 460 571 501 531 q 353 612 420 612 q 247 570 287 612 q 207 453 207 529 l 501 453 "},"ό":{"x_min":0,"x_max":764,"ha":863,"o":"m 380 -25 q 105 87 211 -25 q 0 372 0 200 q 104 660 0 545 q 380 775 209 775 q 658 659 552 775 q 764 372 764 544 q 658 87 764 200 q 380 -25 552 -25 m 379 142 q 515 216 466 142 q 557 373 557 280 q 515 530 557 465 q 379 607 466 607 q 245 530 294 607 q 204 373 204 465 q 245 218 204 283 q 379 142 294 142 m 593 1039 l 391 823 l 293 823 l 415 1039 l 593 1039 "},"J":{"x_min":0,"x_max":649,"ha":760,"o":"m 649 294 q 573 48 649 125 q 327 -29 497 -29 q 61 82 136 -29 q 0 375 0 173 l 200 375 l 199 309 q 219 194 199 230 q 321 145 249 145 q 418 193 390 145 q 441 307 441 232 l 441 1013 l 649 1013 l 649 294 "},"»":{"x_min":-0.234375,"x_max":526,"ha":624,"o":"m 526 286 l 297 87 l 296 250 l 437 373 l 297 495 l 297 660 l 526 461 l 526 286 m 229 286 l 0 87 l 0 250 l 140 373 l 0 495 l 0 660 l 229 461 l 229 286 "},"©":{"x_min":3,"x_max":1007,"ha":1104,"o":"m 507 -6 q 129 153 269 -6 q 3 506 3 298 q 127 857 3 713 q 502 1017 266 1017 q 880 855 740 1017 q 1007 502 1007 711 q 882 152 1007 295 q 507 -6 743 -6 m 502 934 q 184 800 302 934 q 79 505 79 680 q 184 210 79 331 q 501 76 302 76 q 819 210 701 76 q 925 507 925 331 q 820 800 925 682 q 502 934 704 934 m 758 410 q 676 255 748 313 q 506 197 605 197 q 298 291 374 197 q 229 499 229 377 q 297 713 229 624 q 494 811 372 811 q 666 760 593 811 q 752 616 739 710 l 621 616 q 587 688 621 658 q 509 719 554 719 q 404 658 441 719 q 368 511 368 598 q 403 362 368 427 q 498 298 438 298 q 624 410 606 298 l 758 410 "},"ώ":{"x_min":0,"x_max":945,"ha":1051,"o":"m 566 528 l 372 528 l 372 323 q 372 298 372 311 q 373 271 372 285 q 360 183 373 211 q 292 142 342 142 q 219 222 243 142 q 203 365 203 279 q 241 565 203 461 q 334 748 273 650 l 130 748 q 36 552 68 650 q 0 337 0 444 q 69 96 0 204 q 276 -29 149 -29 q 390 0 337 -29 q 470 78 444 28 q 551 0 495 30 q 668 -29 608 -29 q 874 96 793 -29 q 945 337 945 205 q 910 547 945 444 q 814 748 876 650 l 610 748 q 703 565 671 650 q 742 365 742 462 q 718 189 742 237 q 651 142 694 142 q 577 190 597 142 q 565 289 565 221 l 565 323 l 566 528 m 718 1039 l 516 823 l 417 823 l 540 1039 l 718 1039 "},"^":{"x_min":197.21875,"x_max":630.5625,"ha":828,"o":"m 630 836 l 536 836 l 413 987 l 294 836 l 197 836 l 331 1090 l 493 1090 l 630 836 "},"«":{"x_min":0,"x_max":526.546875,"ha":624,"o":"m 526 87 l 297 286 l 297 461 l 526 660 l 526 495 l 385 373 l 526 250 l 526 87 m 229 87 l 0 286 l 0 461 l 229 660 l 229 495 l 88 373 l 229 250 l 229 87 "},"D":{"x_min":0,"x_max":864,"ha":968,"o":"m 400 1013 q 736 874 608 1013 q 864 523 864 735 q 717 146 864 293 q 340 0 570 0 l 0 0 l 0 1013 l 400 1013 m 398 837 l 206 837 l 206 182 l 372 182 q 584 276 507 182 q 657 504 657 365 q 594 727 657 632 q 398 837 522 837 "},"∙":{"x_min":0,"x_max":207,"ha":304,"o":"m 207 528 l 0 528 l 0 735 l 207 735 l 207 528 "},"ÿ":{"x_min":0,"x_max":47,"ha":125,"o":"m 47 3 q 37 -7 47 -7 q 28 0 30 -7 q 39 -4 32 -4 q 45 3 45 -1 l 37 0 q 28 9 28 0 q 39 19 28 19 l 47 16 l 47 19 l 47 3 m 37 1 q 44 8 44 1 q 37 16 44 16 q 30 8 30 16 q 37 1 30 1 m 26 1 l 23 22 l 14 0 l 3 22 l 3 3 l 0 25 l 13 1 l 22 25 l 26 1 "},"w":{"x_min":0,"x_max":1056.953125,"ha":1150,"o":"m 1056 749 l 848 0 l 647 0 l 527 536 l 412 0 l 211 0 l 0 749 l 202 749 l 325 226 l 429 748 l 633 748 l 740 229 l 864 749 l 1056 749 "},"$":{"x_min":0,"x_max":704,"ha":800,"o":"m 682 693 l 495 693 q 468 782 491 749 q 391 831 441 824 l 391 579 q 633 462 562 534 q 704 259 704 389 q 616 57 704 136 q 391 -22 528 -22 l 391 -156 l 308 -156 l 308 -22 q 76 69 152 -7 q 0 300 0 147 l 183 300 q 215 191 190 230 q 308 128 245 143 l 308 414 q 84 505 157 432 q 12 700 12 578 q 89 902 12 824 q 308 981 166 981 l 308 1069 l 391 1069 l 391 981 q 595 905 521 981 q 682 693 670 829 m 308 599 l 308 831 q 228 796 256 831 q 200 712 200 762 q 225 642 200 668 q 308 599 251 617 m 391 128 q 476 174 449 140 q 504 258 504 207 q 391 388 504 354 l 391 128 "},"\\":{"x_min":-0.03125,"x_max":434.765625,"ha":532,"o":"m 434 -128 l 341 -128 l 0 1039 l 91 1040 l 434 -128 "},"µ":{"x_min":0,"x_max":647,"ha":754,"o":"m 647 0 l 478 0 l 478 68 q 412 9 448 30 q 330 -11 375 -11 q 261 3 296 -11 q 199 43 226 18 l 199 -277 l 0 -277 l 0 749 l 199 749 l 199 358 q 216 221 199 267 q 322 151 244 151 q 435 240 410 151 q 448 401 448 283 l 448 749 l 647 749 l 647 0 "},"Ι":{"x_min":42,"x_max":250,"ha":413,"o":"m 250 0 l 42 0 l 42 1013 l 250 1013 l 250 0 "},"Ύ":{"x_min":0,"x_max":1211.15625,"ha":1289,"o":"m 1211 1012 l 907 376 l 907 0 l 697 0 l 697 376 l 374 1012 l 583 1012 l 802 576 l 1001 1012 l 1211 1012 m 313 1035 l 98 780 l 0 780 l 136 1035 l 313 1035 "},"’":{"x_min":0,"x_max":192,"ha":289,"o":"m 192 834 q 137 692 192 751 q 0 626 83 634 l 0 697 q 101 831 101 723 l 0 831 l 0 1013 l 192 1013 l 192 834 "},"Ν":{"x_min":0,"x_max":833,"ha":946,"o":"m 833 0 l 617 0 l 206 696 l 206 0 l 0 0 l 0 1013 l 216 1013 l 629 315 l 629 1013 l 833 1013 l 833 0 "},"-":{"x_min":27.78125,"x_max":413.890625,"ha":525,"o":"m 413 279 l 27 279 l 27 468 l 413 468 l 413 279 "},"Q":{"x_min":0,"x_max":995.59375,"ha":1096,"o":"m 995 49 l 885 -70 l 762 42 q 641 -12 709 4 q 497 -29 572 -29 q 135 123 271 -29 q 0 504 0 276 q 131 881 0 731 q 497 1040 270 1040 q 859 883 719 1040 q 994 506 994 731 q 966 321 994 413 q 884 152 938 229 l 995 49 m 730 299 q 767 395 755 344 q 779 504 779 446 q 713 743 779 644 q 505 857 638 857 q 284 745 366 857 q 210 501 210 644 q 279 265 210 361 q 492 157 357 157 q 615 181 557 157 l 508 287 l 620 405 l 730 299 "},"ς":{"x_min":0,"x_max":731.78125,"ha":768,"o":"m 731 448 l 547 448 q 485 571 531 533 q 369 610 440 610 q 245 537 292 610 q 204 394 204 473 q 322 186 204 238 q 540 133 430 159 q 659 -15 659 98 q 643 -141 659 -80 q 595 -278 627 -202 l 423 -278 q 458 -186 448 -215 q 474 -88 474 -133 q 352 0 474 -27 q 123 80 181 38 q 0 382 0 170 q 98 660 0 549 q 367 777 202 777 q 622 683 513 777 q 731 448 731 589 "},"M":{"x_min":0,"x_max":1019,"ha":1135,"o":"m 1019 0 l 823 0 l 823 819 l 618 0 l 402 0 l 194 818 l 194 0 l 0 0 l 0 1013 l 309 1012 l 510 241 l 707 1013 l 1019 1013 l 1019 0 "},"Ψ":{"x_min":0,"x_max":995,"ha":1085,"o":"m 995 698 q 924 340 995 437 q 590 200 841 227 l 590 0 l 404 0 l 404 200 q 70 340 152 227 q 0 698 0 437 l 0 1013 l 188 1013 l 188 694 q 212 472 188 525 q 404 383 254 383 l 404 1013 l 590 1013 l 590 383 q 781 472 740 383 q 807 694 807 525 l 807 1013 l 995 1013 l 995 698 "},"C":{"x_min":0,"x_max":970.828125,"ha":1043,"o":"m 970 345 q 802 70 933 169 q 490 -29 672 -29 q 130 130 268 -29 q 0 506 0 281 q 134 885 0 737 q 502 1040 275 1040 q 802 939 668 1040 q 965 679 936 838 l 745 679 q 649 809 716 761 q 495 857 582 857 q 283 747 361 857 q 214 508 214 648 q 282 267 214 367 q 493 154 359 154 q 651 204 584 154 q 752 345 718 255 l 970 345 "},"!":{"x_min":0,"x_max":204,"ha":307,"o":"m 204 739 q 182 515 204 686 q 152 282 167 398 l 52 282 q 13 589 27 473 q 0 739 0 704 l 0 1013 l 204 1013 l 204 739 m 204 0 l 0 0 l 0 203 l 204 203 l 204 0 "},"{":{"x_min":0,"x_max":501.390625,"ha":599,"o":"m 501 -285 q 229 -209 301 -285 q 176 -35 176 -155 q 182 47 176 -8 q 189 126 189 103 q 156 245 189 209 q 0 294 112 294 l 0 438 q 154 485 111 438 q 189 603 189 522 q 186 666 189 636 q 176 783 176 772 q 231 945 176 894 q 501 1015 306 1015 l 501 872 q 370 833 408 872 q 340 737 340 801 q 342 677 340 705 q 353 569 353 579 q 326 451 353 496 q 207 366 291 393 q 327 289 294 346 q 353 164 353 246 q 348 79 353 132 q 344 17 344 26 q 372 -95 344 -58 q 501 -141 408 -141 l 501 -285 "},"X":{"x_min":0,"x_max":894.453125,"ha":999,"o":"m 894 0 l 654 0 l 445 351 l 238 0 l 0 0 l 316 516 l 0 1013 l 238 1013 l 445 659 l 652 1013 l 894 1013 l 577 519 l 894 0 "},"#":{"x_min":0,"x_max":1019.453125,"ha":1117,"o":"m 1019 722 l 969 582 l 776 581 l 717 417 l 919 417 l 868 279 l 668 278 l 566 -6 l 413 -5 l 516 279 l 348 279 l 247 -6 l 94 -6 l 196 278 l 0 279 l 49 417 l 245 417 l 304 581 l 98 582 l 150 722 l 354 721 l 455 1006 l 606 1006 l 507 721 l 673 722 l 776 1006 l 927 1006 l 826 721 l 1019 722 m 627 581 l 454 581 l 394 417 l 567 417 l 627 581 "},"ι":{"x_min":42,"x_max":242,"ha":389,"o":"m 242 0 l 42 0 l 42 749 l 242 749 l 242 0 "},"Ά":{"x_min":0,"x_max":995.828125,"ha":1072,"o":"m 313 1035 l 98 780 l 0 780 l 136 1035 l 313 1035 m 995 0 l 776 0 l 708 208 l 315 208 l 247 0 l 29 0 l 390 1012 l 629 1012 l 995 0 m 652 376 l 509 809 l 369 376 l 652 376 "},")":{"x_min":0,"x_max":389,"ha":486,"o":"m 389 357 q 319 14 389 187 q 145 -293 259 -134 l 0 -293 q 139 22 90 -142 q 189 358 189 187 q 139 689 189 525 q 0 1013 90 853 l 145 1013 q 319 703 258 857 q 389 357 389 528 "},"ε":{"x_min":16.671875,"x_max":652.78125,"ha":742,"o":"m 652 259 q 565 49 652 123 q 340 -25 479 -25 q 102 39 188 -25 q 16 197 16 104 q 45 299 16 249 q 134 390 75 348 q 58 456 86 419 q 25 552 25 502 q 120 717 25 653 q 322 776 208 776 q 537 710 456 776 q 625 508 625 639 l 445 508 q 415 585 445 563 q 327 608 386 608 q 254 590 293 608 q 215 544 215 573 q 252 469 215 490 q 336 453 280 453 q 369 455 347 453 q 400 456 391 456 l 400 308 l 329 308 q 247 291 280 308 q 204 223 204 269 q 255 154 204 172 q 345 143 286 143 q 426 174 398 143 q 454 259 454 206 l 652 259 "},"Δ":{"x_min":0,"x_max":981.953125,"ha":1057,"o":"m 981 0 l 0 0 l 386 1013 l 594 1013 l 981 0 m 715 175 l 490 765 l 266 175 l 715 175 "},"}":{"x_min":0,"x_max":500,"ha":597,"o":"m 500 294 q 348 246 390 294 q 315 128 315 209 q 320 42 315 101 q 326 -48 326 -17 q 270 -214 326 -161 q 0 -285 196 -285 l 0 -141 q 126 -97 90 -141 q 154 8 154 -64 q 150 91 154 37 q 146 157 146 145 q 172 281 146 235 q 294 366 206 339 q 173 451 208 390 q 146 576 146 500 q 150 655 146 603 q 154 731 154 708 q 126 831 154 799 q 0 872 90 872 l 0 1015 q 270 944 196 1015 q 326 777 326 891 q 322 707 326 747 q 313 593 313 612 q 347 482 313 518 q 500 438 390 438 l 500 294 "},"‰":{"x_min":0,"x_max":1681,"ha":1775,"o":"m 861 484 q 1048 404 979 484 q 1111 228 1111 332 q 1048 51 1111 123 q 859 -29 979 -29 q 672 50 740 -29 q 610 227 610 122 q 672 403 610 331 q 861 484 741 484 m 861 120 q 939 151 911 120 q 967 226 967 183 q 942 299 967 270 q 861 333 912 333 q 783 301 811 333 q 756 226 756 269 q 783 151 756 182 q 861 120 810 120 m 904 984 l 316 -28 l 205 -29 l 793 983 l 904 984 m 250 984 q 436 904 366 984 q 499 730 499 832 q 436 552 499 626 q 248 472 366 472 q 62 552 132 472 q 0 728 0 624 q 62 903 0 831 q 250 984 132 984 m 249 835 q 169 801 198 835 q 140 725 140 768 q 167 652 140 683 q 247 621 195 621 q 327 654 298 621 q 357 730 357 687 q 329 803 357 772 q 249 835 301 835 m 1430 484 q 1618 404 1548 484 q 1681 228 1681 332 q 1618 51 1681 123 q 1429 -29 1548 -29 q 1241 50 1309 -29 q 1179 227 1179 122 q 1241 403 1179 331 q 1430 484 1311 484 m 1431 120 q 1509 151 1481 120 q 1537 226 1537 183 q 1511 299 1537 270 q 1431 333 1482 333 q 1352 301 1380 333 q 1325 226 1325 269 q 1352 151 1325 182 q 1431 120 1379 120 "},"a":{"x_min":0,"x_max":700,"ha":786,"o":"m 700 0 l 488 0 q 465 93 469 45 q 365 5 427 37 q 233 -26 303 -26 q 65 37 130 -26 q 0 205 0 101 q 120 409 0 355 q 343 452 168 431 q 465 522 465 468 q 424 588 465 565 q 337 611 384 611 q 250 581 285 611 q 215 503 215 552 l 26 503 q 113 707 26 633 q 328 775 194 775 q 538 723 444 775 q 657 554 657 659 l 657 137 q 666 73 657 101 q 700 33 675 45 l 700 0 m 465 297 l 465 367 q 299 322 358 340 q 193 217 193 287 q 223 150 193 174 q 298 127 254 127 q 417 175 370 127 q 465 297 465 224 "},"—":{"x_min":0,"x_max":941.671875,"ha":1039,"o":"m 941 297 l 0 297 l 0 450 l 941 450 l 941 297 "},"=":{"x_min":29.171875,"x_max":798.609375,"ha":828,"o":"m 798 502 l 29 502 l 29 635 l 798 635 l 798 502 m 798 204 l 29 204 l 29 339 l 798 339 l 798 204 "},"N":{"x_min":0,"x_max":833,"ha":949,"o":"m 833 0 l 617 0 l 206 695 l 206 0 l 0 0 l 0 1013 l 216 1013 l 629 315 l 629 1013 l 833 1013 l 833 0 "},"ρ":{"x_min":0,"x_max":722,"ha":810,"o":"m 364 -17 q 271 0 313 -17 q 194 48 230 16 l 194 -278 l 0 -278 l 0 370 q 87 656 0 548 q 358 775 183 775 q 626 655 524 775 q 722 372 722 541 q 621 95 722 208 q 364 -17 520 -17 m 360 607 q 237 529 280 607 q 201 377 201 463 q 234 229 201 292 q 355 147 277 147 q 467 210 419 147 q 515 374 515 273 q 471 537 515 468 q 360 607 428 607 "},"2":{"x_min":64,"x_max":764,"ha":828,"o":"m 764 685 q 675 452 764 541 q 484 325 637 415 q 307 168 357 250 l 754 168 l 754 0 l 64 0 q 193 301 64 175 q 433 480 202 311 q 564 673 564 576 q 519 780 564 737 q 416 824 475 824 q 318 780 358 824 q 262 633 270 730 l 80 633 q 184 903 80 807 q 415 988 276 988 q 654 907 552 988 q 764 685 764 819 "},"¯":{"x_min":0,"x_max":775,"ha":771,"o":"m 775 958 l 0 958 l 0 1111 l 775 1111 l 775 958 "},"Z":{"x_min":0,"x_max":804.171875,"ha":906,"o":"m 804 836 l 251 182 l 793 182 l 793 0 l 0 0 l 0 176 l 551 830 l 11 830 l 11 1013 l 804 1013 l 804 836 "},"u":{"x_min":0,"x_max":668,"ha":782,"o":"m 668 0 l 474 0 l 474 89 q 363 9 425 37 q 233 -19 301 -19 q 61 53 123 -19 q 0 239 0 126 l 0 749 l 199 749 l 199 296 q 225 193 199 233 q 316 146 257 146 q 424 193 380 146 q 469 304 469 240 l 469 749 l 668 749 l 668 0 "},"k":{"x_min":0,"x_max":688.890625,"ha":771,"o":"m 688 0 l 450 0 l 270 316 l 196 237 l 196 0 l 0 0 l 0 1013 l 196 1013 l 196 483 l 433 748 l 675 748 l 413 469 l 688 0 "},"Η":{"x_min":0,"x_max":837,"ha":950,"o":"m 837 0 l 627 0 l 627 450 l 210 450 l 210 0 l 0 0 l 0 1013 l 210 1013 l 210 635 l 627 635 l 627 1013 l 837 1013 l 837 0 "},"Α":{"x_min":0,"x_max":966.671875,"ha":1043,"o":"m 966 0 l 747 0 l 679 208 l 286 208 l 218 0 l 0 0 l 361 1013 l 600 1013 l 966 0 m 623 376 l 480 809 l 340 376 l 623 376 "},"s":{"x_min":0,"x_max":681,"ha":775,"o":"m 681 229 q 568 33 681 105 q 340 -29 471 -29 q 107 39 202 -29 q 0 245 0 114 l 201 245 q 252 155 201 189 q 358 128 295 128 q 436 144 401 128 q 482 205 482 166 q 363 284 482 255 q 143 348 181 329 q 25 533 25 408 q 129 716 25 647 q 340 778 220 778 q 554 710 465 778 q 658 522 643 643 l 463 522 q 419 596 458 570 q 327 622 380 622 q 255 606 290 622 q 221 556 221 590 q 339 473 221 506 q 561 404 528 420 q 681 229 681 344 "},"B":{"x_min":0,"x_max":835,"ha":938,"o":"m 674 547 q 791 450 747 518 q 835 304 835 383 q 718 75 835 158 q 461 0 612 0 l 0 0 l 0 1013 l 477 1013 q 697 951 609 1013 q 797 754 797 880 q 765 630 797 686 q 674 547 734 575 m 438 621 q 538 646 495 621 q 590 730 590 676 q 537 814 590 785 q 436 838 494 838 l 199 838 l 199 621 l 438 621 m 445 182 q 561 211 513 182 q 618 311 618 247 q 565 410 618 375 q 444 446 512 446 l 199 446 l 199 182 l 445 182 "},"…":{"x_min":0,"x_max":819,"ha":963,"o":"m 206 0 l 0 0 l 0 207 l 206 207 l 206 0 m 512 0 l 306 0 l 306 207 l 512 207 l 512 0 m 819 0 l 613 0 l 613 207 l 819 207 l 819 0 "},"?":{"x_min":1,"x_max":687,"ha":785,"o":"m 687 734 q 621 563 687 634 q 501 454 560 508 q 436 293 436 386 l 251 293 l 251 391 q 363 557 251 462 q 476 724 476 653 q 432 827 476 788 q 332 866 389 866 q 238 827 275 866 q 195 699 195 781 l 1 699 q 110 955 1 861 q 352 1040 210 1040 q 582 963 489 1040 q 687 734 687 878 m 446 0 l 243 0 l 243 203 l 446 203 l 446 0 "},"H":{"x_min":0,"x_max":838,"ha":953,"o":"m 838 0 l 628 0 l 628 450 l 210 450 l 210 0 l 0 0 l 0 1013 l 210 1013 l 210 635 l 628 635 l 628 1013 l 838 1013 l 838 0 "},"ν":{"x_min":0,"x_max":740.28125,"ha":828,"o":"m 740 749 l 473 0 l 266 0 l 0 749 l 222 749 l 373 211 l 529 749 l 740 749 "},"c":{"x_min":0,"x_max":751.390625,"ha":828,"o":"m 751 282 q 625 58 725 142 q 384 -26 526 -26 q 107 84 215 -26 q 0 366 0 195 q 98 651 0 536 q 370 774 204 774 q 616 700 518 774 q 751 486 715 626 l 536 486 q 477 570 516 538 q 380 607 434 607 q 248 533 298 607 q 204 378 204 466 q 242 219 204 285 q 377 139 290 139 q 483 179 438 139 q 543 282 527 220 l 751 282 "},"¶":{"x_min":0,"x_max":566.671875,"ha":678,"o":"m 21 892 l 52 892 l 98 761 l 145 892 l 176 892 l 178 741 l 157 741 l 157 867 l 108 741 l 88 741 l 40 871 l 40 741 l 21 741 l 21 892 m 308 854 l 308 731 q 252 691 308 691 q 227 691 240 691 q 207 696 213 695 l 207 712 l 253 706 q 288 733 288 706 l 288 763 q 244 741 279 741 q 193 797 193 741 q 261 860 193 860 q 287 860 273 860 q 308 854 302 855 m 288 842 l 263 843 q 213 796 213 843 q 248 756 213 756 q 288 796 288 756 l 288 842 m 566 988 l 502 988 l 502 -1 l 439 -1 l 439 988 l 317 988 l 317 -1 l 252 -1 l 252 602 q 81 653 155 602 q 0 805 0 711 q 101 989 0 918 q 309 1053 194 1053 l 566 1053 l 566 988 "},"β":{"x_min":0,"x_max":703,"ha":789,"o":"m 510 539 q 651 429 600 501 q 703 262 703 357 q 617 53 703 136 q 404 -29 532 -29 q 199 51 279 -29 l 199 -278 l 0 -278 l 0 627 q 77 911 0 812 q 343 1021 163 1021 q 551 957 464 1021 q 649 769 649 886 q 613 638 649 697 q 510 539 577 579 m 344 136 q 452 181 408 136 q 497 291 497 227 q 435 409 497 369 q 299 444 381 444 l 299 600 q 407 634 363 600 q 452 731 452 669 q 417 820 452 784 q 329 857 382 857 q 217 775 246 857 q 199 622 199 725 l 199 393 q 221 226 199 284 q 344 136 254 136 "},"Μ":{"x_min":0,"x_max":1019,"ha":1132,"o":"m 1019 0 l 823 0 l 823 818 l 617 0 l 402 0 l 194 818 l 194 0 l 0 0 l 0 1013 l 309 1013 l 509 241 l 708 1013 l 1019 1013 l 1019 0 "},"Ό":{"x_min":0.15625,"x_max":1174,"ha":1271,"o":"m 676 -29 q 312 127 451 -29 q 179 505 179 277 q 311 883 179 733 q 676 1040 449 1040 q 1040 883 901 1040 q 1174 505 1174 733 q 1041 127 1174 277 q 676 -29 903 -29 m 676 154 q 890 266 811 154 q 961 506 961 366 q 891 745 961 648 q 676 857 812 857 q 462 747 541 857 q 392 506 392 648 q 461 266 392 365 q 676 154 540 154 m 314 1034 l 98 779 l 0 779 l 136 1034 l 314 1034 "},"Ή":{"x_min":0,"x_max":1248,"ha":1361,"o":"m 1248 0 l 1038 0 l 1038 450 l 621 450 l 621 0 l 411 0 l 411 1012 l 621 1012 l 621 635 l 1038 635 l 1038 1012 l 1248 1012 l 1248 0 m 313 1035 l 98 780 l 0 780 l 136 1035 l 313 1035 "},"•":{"x_min":-27.78125,"x_max":691.671875,"ha":775,"o":"m 691 508 q 588 252 691 358 q 331 147 486 147 q 77 251 183 147 q -27 508 -27 355 q 75 761 -27 655 q 331 868 179 868 q 585 763 479 868 q 691 508 691 658 "},"¥":{"x_min":0,"x_max":836,"ha":931,"o":"m 195 625 l 0 1013 l 208 1013 l 427 576 l 626 1013 l 836 1013 l 650 625 l 777 625 l 777 472 l 578 472 l 538 389 l 777 389 l 777 236 l 532 236 l 532 0 l 322 0 l 322 236 l 79 236 l 79 389 l 315 389 l 273 472 l 79 472 l 79 625 l 195 625 "},"(":{"x_min":0,"x_max":388.890625,"ha":486,"o":"m 388 -293 l 243 -293 q 70 14 130 -134 q 0 357 0 189 q 69 703 0 526 q 243 1013 129 856 l 388 1013 q 248 695 297 860 q 200 358 200 530 q 248 24 200 187 q 388 -293 297 -138 "},"U":{"x_min":0,"x_max":813,"ha":926,"o":"m 813 362 q 697 79 813 187 q 405 -29 582 -29 q 114 78 229 -29 q 0 362 0 186 l 0 1013 l 210 1013 l 210 387 q 260 226 210 291 q 408 154 315 154 q 554 226 500 154 q 603 387 603 291 l 603 1013 l 813 1013 l 813 362 "},"γ":{"x_min":0.0625,"x_max":729.234375,"ha":815,"o":"m 729 749 l 457 37 l 457 -278 l 257 -278 l 257 37 q 218 155 243 95 q 170 275 194 215 l 0 749 l 207 749 l 363 284 l 522 749 l 729 749 "},"α":{"x_min":-1,"x_max":722,"ha":835,"o":"m 722 0 l 531 0 l 530 101 q 433 8 491 41 q 304 -25 375 -25 q 72 104 157 -25 q -1 372 -1 216 q 72 643 -1 530 q 308 775 158 775 q 433 744 375 775 q 528 656 491 713 l 528 749 l 722 749 l 722 0 m 361 601 q 233 527 277 601 q 196 375 196 464 q 232 224 196 288 q 358 144 277 144 q 487 217 441 144 q 528 370 528 281 q 489 523 528 457 q 361 601 443 601 "},"F":{"x_min":0,"x_max":706.953125,"ha":778,"o":"m 706 837 l 206 837 l 206 606 l 645 606 l 645 431 l 206 431 l 206 0 l 0 0 l 0 1013 l 706 1013 l 706 837 "},"­":{"x_min":0,"x_max":704.171875,"ha":801,"o":"m 704 297 l 0 297 l 0 450 l 704 450 l 704 297 "},":":{"x_min":0,"x_max":207,"ha":304,"o":"m 207 528 l 0 528 l 0 735 l 207 735 l 207 528 m 207 0 l 0 0 l 0 207 l 207 207 l 207 0 "},"Χ":{"x_min":0,"x_max":894.453125,"ha":978,"o":"m 894 0 l 654 0 l 445 351 l 238 0 l 0 0 l 316 516 l 0 1013 l 238 1013 l 445 660 l 652 1013 l 894 1013 l 577 519 l 894 0 "},"*":{"x_min":115,"x_max":713,"ha":828,"o":"m 713 740 l 518 688 l 651 525 l 531 438 l 412 612 l 290 439 l 173 523 l 308 688 l 115 741 l 159 880 l 342 816 l 343 1013 l 482 1013 l 481 816 l 664 880 l 713 740 "},"†":{"x_min":0,"x_max":809,"ha":894,"o":"m 509 804 l 809 804 l 809 621 l 509 621 l 509 0 l 299 0 l 299 621 l 0 621 l 0 804 l 299 804 l 299 1011 l 509 1011 l 509 804 "},"°":{"x_min":-1,"x_max":363,"ha":460,"o":"m 181 808 q 46 862 94 808 q -1 992 -1 917 q 44 1118 -1 1066 q 181 1175 96 1175 q 317 1118 265 1175 q 363 991 363 1066 q 315 862 363 917 q 181 808 267 808 m 181 908 q 240 933 218 908 q 263 992 263 958 q 242 1051 263 1027 q 181 1075 221 1075 q 120 1050 142 1075 q 99 991 99 1026 q 120 933 99 958 q 181 908 142 908 "},"V":{"x_min":0,"x_max":895.828125,"ha":997,"o":"m 895 1013 l 550 0 l 347 0 l 0 1013 l 231 1013 l 447 256 l 666 1013 l 895 1013 "},"Ξ":{"x_min":0,"x_max":751.390625,"ha":800,"o":"m 733 826 l 5 826 l 5 1012 l 733 1012 l 733 826 m 681 432 l 65 432 l 65 617 l 681 617 l 681 432 m 751 0 l 0 0 l 0 183 l 751 183 l 751 0 "}," ":{"x_min":0,"x_max":0,"ha":853},"Ϋ":{"x_min":-0.21875,"x_max":836.171875,"ha":914,"o":"m 610 1046 l 454 1046 l 454 1215 l 610 1215 l 610 1046 m 369 1046 l 212 1046 l 212 1215 l 369 1215 l 369 1046 m 836 1012 l 532 376 l 532 0 l 322 0 l 322 376 l 0 1012 l 208 1012 l 427 576 l 626 1012 l 836 1012 "},"0":{"x_min":51,"x_max":779,"ha":828,"o":"m 415 -26 q 142 129 242 -26 q 51 476 51 271 q 141 825 51 683 q 415 984 242 984 q 687 825 585 984 q 779 476 779 682 q 688 131 779 271 q 415 -26 587 -26 m 415 137 q 529 242 485 137 q 568 477 568 338 q 530 713 568 619 q 415 821 488 821 q 303 718 344 821 q 262 477 262 616 q 301 237 262 337 q 415 137 341 137 "},"”":{"x_min":0,"x_max":469,"ha":567,"o":"m 192 834 q 137 692 192 751 q 0 626 83 634 l 0 697 q 101 831 101 723 l 0 831 l 0 1013 l 192 1013 l 192 834 m 469 834 q 414 692 469 751 q 277 626 360 634 l 277 697 q 379 831 379 723 l 277 831 l 277 1013 l 469 1013 l 469 834 "},"@":{"x_min":0,"x_max":1276,"ha":1374,"o":"m 1115 -52 q 895 -170 1015 -130 q 647 -211 776 -211 q 158 -34 334 -211 q 0 360 0 123 q 179 810 0 621 q 698 1019 377 1019 q 1138 859 981 1019 q 1276 514 1276 720 q 1173 210 1276 335 q 884 75 1062 75 q 784 90 810 75 q 737 186 749 112 q 647 104 698 133 q 532 75 596 75 q 360 144 420 75 q 308 308 308 205 q 398 568 308 451 q 638 696 497 696 q 731 671 690 696 q 805 604 772 647 l 840 673 l 964 673 q 886 373 915 490 q 856 239 856 257 q 876 201 856 214 q 920 188 895 188 q 1084 284 1019 188 q 1150 511 1150 380 q 1051 779 1150 672 q 715 905 934 905 q 272 734 439 905 q 121 363 121 580 q 250 41 121 170 q 647 -103 394 -103 q 863 -67 751 -103 q 1061 26 975 -32 l 1115 -52 m 769 483 q 770 500 770 489 q 733 567 770 539 q 651 596 695 596 q 508 504 566 596 q 457 322 457 422 q 483 215 457 256 q 561 175 509 175 q 671 221 625 175 q 733 333 718 268 l 769 483 "},"Ί":{"x_min":0,"x_max":619,"ha":732,"o":"m 313 1035 l 98 780 l 0 780 l 136 1035 l 313 1035 m 619 0 l 411 0 l 411 1012 l 619 1012 l 619 0 "},"i":{"x_min":14,"x_max":214,"ha":326,"o":"m 214 830 l 14 830 l 14 1013 l 214 1013 l 214 830 m 214 0 l 14 0 l 14 748 l 214 748 l 214 0 "},"Β":{"x_min":0,"x_max":835,"ha":961,"o":"m 675 547 q 791 450 747 518 q 835 304 835 383 q 718 75 835 158 q 461 0 612 0 l 0 0 l 0 1013 l 477 1013 q 697 951 609 1013 q 797 754 797 880 q 766 630 797 686 q 675 547 734 575 m 439 621 q 539 646 496 621 q 590 730 590 676 q 537 814 590 785 q 436 838 494 838 l 199 838 l 199 621 l 439 621 m 445 182 q 561 211 513 182 q 618 311 618 247 q 565 410 618 375 q 444 446 512 446 l 199 446 l 199 182 l 445 182 "},"υ":{"x_min":0,"x_max":656,"ha":767,"o":"m 656 416 q 568 55 656 145 q 326 -25 490 -25 q 59 97 137 -25 q 0 369 0 191 l 0 749 l 200 749 l 200 369 q 216 222 200 268 q 326 142 245 142 q 440 247 411 142 q 456 422 456 304 l 456 749 l 656 749 l 656 416 "},"]":{"x_min":0,"x_max":349,"ha":446,"o":"m 349 -300 l 0 -300 l 0 -154 l 163 -154 l 163 866 l 0 866 l 0 1013 l 349 1013 l 349 -300 "},"m":{"x_min":0,"x_max":1065,"ha":1174,"o":"m 1065 0 l 866 0 l 866 483 q 836 564 866 532 q 759 596 807 596 q 663 555 700 596 q 627 454 627 514 l 627 0 l 433 0 l 433 481 q 403 563 433 531 q 323 596 374 596 q 231 554 265 596 q 197 453 197 513 l 197 0 l 0 0 l 0 748 l 189 748 l 189 665 q 279 745 226 715 q 392 775 333 775 q 509 744 455 775 q 606 659 563 713 q 695 744 640 713 q 814 775 749 775 q 992 702 920 775 q 1065 523 1065 630 l 1065 0 "},"χ":{"x_min":0,"x_max":759.71875,"ha":847,"o":"m 759 -299 l 548 -299 l 379 66 l 215 -299 l 0 -299 l 261 233 l 13 749 l 230 749 l 379 400 l 527 749 l 738 749 l 500 238 l 759 -299 "},"8":{"x_min":57,"x_max":770,"ha":828,"o":"m 625 516 q 733 416 697 477 q 770 284 770 355 q 675 69 770 161 q 415 -29 574 -29 q 145 65 244 -29 q 57 273 57 150 q 93 413 57 350 q 204 516 130 477 q 112 609 142 556 q 83 718 83 662 q 177 905 83 824 q 414 986 272 986 q 650 904 555 986 q 745 715 745 822 q 716 608 745 658 q 625 516 688 558 m 414 590 q 516 624 479 590 q 553 706 553 659 q 516 791 553 755 q 414 828 480 828 q 311 792 348 828 q 275 706 275 757 q 310 624 275 658 q 414 590 345 590 m 413 135 q 527 179 487 135 q 564 279 564 218 q 525 386 564 341 q 411 436 482 436 q 298 387 341 436 q 261 282 261 344 q 300 178 261 222 q 413 135 340 135 "},"ί":{"x_min":42,"x_max":371.171875,"ha":389,"o":"m 242 0 l 42 0 l 42 748 l 242 748 l 242 0 m 371 1039 l 169 823 l 71 823 l 193 1039 l 371 1039 "},"Ζ":{"x_min":0,"x_max":804.171875,"ha":886,"o":"m 804 835 l 251 182 l 793 182 l 793 0 l 0 0 l 0 176 l 551 829 l 11 829 l 11 1012 l 804 1012 l 804 835 "},"R":{"x_min":0,"x_max":836.109375,"ha":947,"o":"m 836 0 l 608 0 q 588 53 596 20 q 581 144 581 86 q 581 179 581 162 q 581 215 581 197 q 553 345 581 306 q 428 393 518 393 l 208 393 l 208 0 l 0 0 l 0 1013 l 491 1013 q 720 944 630 1013 q 819 734 819 869 q 778 584 819 654 q 664 485 738 513 q 757 415 727 463 q 794 231 794 358 l 794 170 q 800 84 794 116 q 836 31 806 51 l 836 0 m 462 838 l 208 838 l 208 572 l 452 572 q 562 604 517 572 q 612 704 612 640 q 568 801 612 765 q 462 838 525 838 "},"o":{"x_min":0,"x_max":764,"ha":871,"o":"m 380 -26 q 105 86 211 -26 q 0 371 0 199 q 104 660 0 545 q 380 775 209 775 q 658 659 552 775 q 764 371 764 544 q 658 86 764 199 q 380 -26 552 -26 m 379 141 q 515 216 466 141 q 557 373 557 280 q 515 530 557 465 q 379 607 466 607 q 245 530 294 607 q 204 373 204 465 q 245 217 204 282 q 379 141 294 141 "},"5":{"x_min":59,"x_max":767,"ha":828,"o":"m 767 319 q 644 59 767 158 q 382 -29 533 -29 q 158 43 247 -29 q 59 264 59 123 l 252 264 q 295 165 252 201 q 400 129 339 129 q 512 172 466 129 q 564 308 564 220 q 514 437 564 387 q 398 488 464 488 q 329 472 361 488 q 271 420 297 456 l 93 428 l 157 958 l 722 958 l 722 790 l 295 790 l 271 593 q 348 635 306 621 q 431 649 389 649 q 663 551 560 649 q 767 319 767 453 "},"7":{"x_min":65.28125,"x_max":762.5,"ha":828,"o":"m 762 808 q 521 435 604 626 q 409 0 438 244 l 205 0 q 313 422 227 234 q 548 789 387 583 l 65 789 l 65 958 l 762 958 l 762 808 "},"K":{"x_min":0,"x_max":900,"ha":996,"o":"m 900 0 l 647 0 l 316 462 l 208 355 l 208 0 l 0 0 l 0 1013 l 208 1013 l 208 595 l 604 1013 l 863 1013 l 461 603 l 900 0 "},",":{"x_min":0,"x_max":206,"ha":303,"o":"m 206 5 q 150 -151 206 -88 q 0 -238 94 -213 l 0 -159 q 84 -100 56 -137 q 111 -2 111 -62 l 0 -2 l 0 205 l 206 205 l 206 5 "},"d":{"x_min":0,"x_max":722,"ha":836,"o":"m 722 0 l 530 0 l 530 101 q 303 -26 449 -26 q 72 103 155 -26 q 0 373 0 214 q 72 642 0 528 q 305 775 156 775 q 433 743 373 775 q 530 656 492 712 l 530 1013 l 722 1013 l 722 0 m 361 600 q 234 523 280 600 q 196 372 196 458 q 233 220 196 286 q 358 143 278 143 q 489 216 442 143 q 530 369 530 280 q 491 522 530 456 q 361 600 443 600 "},"¨":{"x_min":212,"x_max":609,"ha":933,"o":"m 609 1046 l 453 1046 l 453 1216 l 609 1216 l 609 1046 m 369 1046 l 212 1046 l 212 1216 l 369 1216 l 369 1046 "},"E":{"x_min":0,"x_max":761.109375,"ha":824,"o":"m 761 0 l 0 0 l 0 1013 l 734 1013 l 734 837 l 206 837 l 206 621 l 690 621 l 690 446 l 206 446 l 206 186 l 761 186 l 761 0 "},"Y":{"x_min":0,"x_max":836,"ha":931,"o":"m 836 1013 l 532 376 l 532 0 l 322 0 l 322 376 l 0 1013 l 208 1013 l 427 576 l 626 1013 l 836 1013 "},"\"":{"x_min":0,"x_max":357,"ha":454,"o":"m 357 604 l 225 604 l 225 988 l 357 988 l 357 604 m 132 604 l 0 604 l 0 988 l 132 988 l 132 604 "},"‹":{"x_min":35.984375,"x_max":791.671875,"ha":828,"o":"m 791 17 l 36 352 l 35 487 l 791 823 l 791 672 l 229 421 l 791 168 l 791 17 "},"„":{"x_min":0,"x_max":483,"ha":588,"o":"m 206 5 q 150 -151 206 -88 q 0 -238 94 -213 l 0 -159 q 84 -100 56 -137 q 111 -2 111 -62 l 0 -2 l 0 205 l 206 205 l 206 5 m 483 5 q 427 -151 483 -88 q 277 -238 371 -213 l 277 -159 q 361 -100 334 -137 q 388 -2 388 -62 l 277 -2 l 277 205 l 483 205 l 483 5 "},"δ":{"x_min":6,"x_max":732,"ha":835,"o":"m 732 352 q 630 76 732 177 q 354 -25 529 -25 q 101 74 197 -25 q 6 333 6 174 q 89 581 6 480 q 323 690 178 690 q 66 864 201 787 l 66 1013 l 669 1013 l 669 856 l 348 856 q 532 729 461 789 q 673 566 625 651 q 732 352 732 465 m 419 551 q 259 496 321 551 q 198 344 198 441 q 238 208 198 267 q 357 140 283 140 q 484 203 437 140 q 526 344 526 260 q 499 466 526 410 q 419 551 473 521 "},"έ":{"x_min":16.671875,"x_max":652.78125,"ha":742,"o":"m 652 259 q 565 49 652 123 q 340 -25 479 -25 q 102 39 188 -25 q 16 197 16 104 q 45 299 16 250 q 134 390 75 348 q 58 456 86 419 q 25 552 25 502 q 120 717 25 653 q 322 776 208 776 q 537 710 456 776 q 625 508 625 639 l 445 508 q 415 585 445 563 q 327 608 386 608 q 254 590 293 608 q 215 544 215 573 q 252 469 215 490 q 336 453 280 453 q 369 455 347 453 q 400 456 391 456 l 400 308 l 329 308 q 247 291 280 308 q 204 223 204 269 q 255 154 204 172 q 345 143 286 143 q 426 174 398 143 q 454 259 454 206 l 652 259 m 579 1039 l 377 823 l 279 823 l 401 1039 l 579 1039 "},"ω":{"x_min":0,"x_max":945,"ha":1051,"o":"m 565 323 l 565 289 q 577 190 565 221 q 651 142 597 142 q 718 189 694 142 q 742 365 742 237 q 703 565 742 462 q 610 749 671 650 l 814 749 q 910 547 876 650 q 945 337 945 444 q 874 96 945 205 q 668 -29 793 -29 q 551 0 608 -29 q 470 78 495 30 q 390 0 444 28 q 276 -29 337 -29 q 69 96 149 -29 q 0 337 0 204 q 36 553 0 444 q 130 749 68 650 l 334 749 q 241 565 273 650 q 203 365 203 461 q 219 222 203 279 q 292 142 243 142 q 360 183 342 142 q 373 271 373 211 q 372 298 372 285 q 372 323 372 311 l 372 528 l 566 528 l 565 323 "},"´":{"x_min":0,"x_max":132,"ha":299,"o":"m 132 604 l 0 604 l 0 988 l 132 988 l 132 604 "},"±":{"x_min":29,"x_max":798,"ha":828,"o":"m 798 480 l 484 480 l 484 254 l 344 254 l 344 480 l 29 480 l 29 615 l 344 615 l 344 842 l 484 842 l 484 615 l 798 615 l 798 480 m 798 0 l 29 0 l 29 136 l 798 136 l 798 0 "},"|":{"x_min":0,"x_max":143,"ha":240,"o":"m 143 462 l 0 462 l 0 984 l 143 984 l 143 462 m 143 -242 l 0 -242 l 0 280 l 143 280 l 143 -242 "},"ϋ":{"x_min":0,"x_max":656,"ha":767,"o":"m 535 810 l 406 810 l 406 952 l 535 952 l 535 810 m 271 810 l 142 810 l 142 952 l 271 952 l 271 810 m 656 417 q 568 55 656 146 q 326 -25 490 -25 q 59 97 137 -25 q 0 369 0 192 l 0 748 l 200 748 l 200 369 q 216 222 200 268 q 326 142 245 142 q 440 247 411 142 q 456 422 456 304 l 456 748 l 656 748 l 656 417 "},"§":{"x_min":0,"x_max":633,"ha":731,"o":"m 633 469 q 601 356 633 406 q 512 274 569 305 q 570 197 548 242 q 593 105 593 152 q 501 -76 593 -5 q 301 -142 416 -142 q 122 -82 193 -142 q 43 108 43 -15 l 212 108 q 251 27 220 53 q 321 1 283 1 q 389 23 360 1 q 419 83 419 46 q 310 194 419 139 q 108 297 111 295 q 0 476 0 372 q 33 584 0 537 q 120 659 62 626 q 72 720 91 686 q 53 790 53 755 q 133 978 53 908 q 312 1042 207 1042 q 483 984 412 1042 q 574 807 562 921 l 409 807 q 379 875 409 851 q 307 900 349 900 q 244 881 270 900 q 218 829 218 862 q 324 731 218 781 q 524 636 506 647 q 633 469 633 565 m 419 334 q 473 411 473 372 q 451 459 473 436 q 390 502 430 481 l 209 595 q 167 557 182 577 q 153 520 153 537 q 187 461 153 491 q 263 413 212 440 l 419 334 "},"b":{"x_min":0,"x_max":722,"ha":822,"o":"m 416 -26 q 289 6 346 -26 q 192 101 232 39 l 192 0 l 0 0 l 0 1013 l 192 1013 l 192 656 q 286 743 226 712 q 415 775 346 775 q 649 644 564 775 q 722 374 722 533 q 649 106 722 218 q 416 -26 565 -26 m 361 600 q 232 524 279 600 q 192 371 192 459 q 229 221 192 284 q 357 145 275 145 q 487 221 441 145 q 526 374 526 285 q 488 523 526 460 q 361 600 442 600 "},"q":{"x_min":0,"x_max":722,"ha":833,"o":"m 722 -298 l 530 -298 l 530 97 q 306 -25 449 -25 q 73 104 159 -25 q 0 372 0 216 q 72 643 0 529 q 305 775 156 775 q 430 742 371 775 q 530 654 488 709 l 530 750 l 722 750 l 722 -298 m 360 601 q 234 527 278 601 q 197 378 197 466 q 233 225 197 291 q 357 144 277 144 q 488 217 441 144 q 530 370 530 282 q 491 523 530 459 q 360 601 443 601 "},"Ω":{"x_min":-0.03125,"x_max":1008.53125,"ha":1108,"o":"m 1008 0 l 589 0 l 589 199 q 717 368 670 265 q 764 580 764 471 q 698 778 764 706 q 504 855 629 855 q 311 773 380 855 q 243 563 243 691 q 289 360 243 458 q 419 199 336 262 l 419 0 l 0 0 l 0 176 l 202 176 q 77 355 123 251 q 32 569 32 459 q 165 908 32 776 q 505 1040 298 1040 q 844 912 711 1040 q 977 578 977 785 q 931 362 977 467 q 805 176 886 256 l 1008 176 l 1008 0 "},"ύ":{"x_min":0,"x_max":656,"ha":767,"o":"m 656 417 q 568 55 656 146 q 326 -25 490 -25 q 59 97 137 -25 q 0 369 0 192 l 0 748 l 200 748 l 201 369 q 218 222 201 269 q 326 142 245 142 q 440 247 411 142 q 456 422 456 304 l 456 748 l 656 748 l 656 417 m 579 1039 l 378 823 l 279 823 l 401 1039 l 579 1039 "},"z":{"x_min":0,"x_max":663.890625,"ha":753,"o":"m 663 0 l 0 0 l 0 154 l 411 591 l 25 591 l 25 749 l 650 749 l 650 584 l 245 165 l 663 165 l 663 0 "},"™":{"x_min":0,"x_max":951,"ha":1063,"o":"m 405 921 l 255 921 l 255 506 l 149 506 l 149 921 l 0 921 l 0 1013 l 405 1013 l 405 921 m 951 506 l 852 506 l 852 916 l 750 506 l 643 506 l 539 915 l 539 506 l 442 506 l 442 1013 l 595 1012 l 695 625 l 794 1013 l 951 1013 l 951 506 "},"ή":{"x_min":0,"x_max":669,"ha":779,"o":"m 669 -278 l 469 -278 l 469 390 q 448 526 469 473 q 348 606 417 606 q 244 553 288 606 q 201 441 201 501 l 201 0 l 0 0 l 0 749 l 201 749 l 201 665 q 301 744 244 715 q 423 774 359 774 q 606 685 538 774 q 669 484 669 603 l 669 -278 m 495 1039 l 293 823 l 195 823 l 317 1039 l 495 1039 "},"Θ":{"x_min":0,"x_max":993,"ha":1092,"o":"m 497 -29 q 133 127 272 -29 q 0 505 0 277 q 133 883 0 733 q 497 1040 272 1040 q 861 883 722 1040 q 993 505 993 733 q 861 127 993 277 q 497 -29 722 -29 m 497 154 q 711 266 631 154 q 782 506 782 367 q 712 746 782 648 q 497 858 634 858 q 281 746 361 858 q 211 506 211 648 q 280 266 211 365 q 497 154 359 154 m 676 430 l 316 430 l 316 593 l 676 593 l 676 430 "},"®":{"x_min":3,"x_max":1007,"ha":1104,"o":"m 507 -6 q 129 153 269 -6 q 3 506 3 298 q 127 857 3 713 q 502 1017 266 1017 q 880 855 740 1017 q 1007 502 1007 711 q 882 152 1007 295 q 507 -6 743 -6 m 502 934 q 184 800 302 934 q 79 505 79 680 q 184 210 79 331 q 501 76 302 76 q 819 210 701 76 q 925 507 925 331 q 820 800 925 682 q 502 934 704 934 m 782 190 l 639 190 q 627 225 632 202 q 623 285 623 248 l 623 326 q 603 411 623 384 q 527 439 584 439 l 388 439 l 388 190 l 257 190 l 257 829 l 566 829 q 709 787 654 829 q 772 654 772 740 q 746 559 772 604 q 675 497 720 514 q 735 451 714 483 q 756 341 756 419 l 756 299 q 760 244 756 265 q 782 212 764 223 l 782 190 m 546 718 l 388 718 l 388 552 l 541 552 q 612 572 584 552 q 641 635 641 593 q 614 695 641 672 q 546 718 587 718 "},"~":{"x_min":0,"x_max":851,"ha":949,"o":"m 851 968 q 795 750 851 831 q 599 656 730 656 q 406 744 506 656 q 259 832 305 832 q 162 775 193 832 q 139 656 139 730 l 0 656 q 58 871 0 787 q 251 968 124 968 q 442 879 341 968 q 596 791 544 791 q 691 849 663 791 q 712 968 712 892 l 851 968 "},"Ε":{"x_min":0,"x_max":761.546875,"ha":824,"o":"m 761 0 l 0 0 l 0 1012 l 735 1012 l 735 836 l 206 836 l 206 621 l 690 621 l 690 446 l 206 446 l 206 186 l 761 186 l 761 0 "},"³":{"x_min":0,"x_max":467,"ha":564,"o":"m 467 555 q 393 413 467 466 q 229 365 325 365 q 70 413 134 365 q 0 565 0 467 l 123 565 q 163 484 131 512 q 229 461 190 461 q 299 486 269 461 q 329 553 329 512 q 281 627 329 607 q 187 641 248 641 l 187 722 q 268 737 237 722 q 312 804 312 758 q 285 859 312 837 q 224 882 259 882 q 165 858 189 882 q 135 783 140 834 l 12 783 q 86 930 20 878 q 230 976 145 976 q 379 931 314 976 q 444 813 444 887 q 423 744 444 773 q 365 695 402 716 q 439 640 412 676 q 467 555 467 605 "},"[":{"x_min":0,"x_max":347.21875,"ha":444,"o":"m 347 -300 l 0 -300 l 0 1013 l 347 1013 l 347 866 l 188 866 l 188 -154 l 347 -154 l 347 -300 "},"L":{"x_min":0,"x_max":704.171875,"ha":763,"o":"m 704 0 l 0 0 l 0 1013 l 208 1013 l 208 186 l 704 186 l 704 0 "},"σ":{"x_min":0,"x_max":851.3125,"ha":940,"o":"m 851 594 l 712 594 q 761 369 761 485 q 658 83 761 191 q 379 -25 555 -25 q 104 87 208 -25 q 0 372 0 200 q 103 659 0 544 q 378 775 207 775 q 464 762 407 775 q 549 750 521 750 l 851 750 l 851 594 m 379 142 q 515 216 466 142 q 557 373 557 280 q 515 530 557 465 q 379 608 465 608 q 244 530 293 608 q 203 373 203 465 q 244 218 203 283 q 379 142 293 142 "},"ζ":{"x_min":0,"x_max":622,"ha":701,"o":"m 622 -32 q 604 -158 622 -98 q 551 -278 587 -218 l 373 -278 q 426 -180 406 -229 q 446 -80 446 -131 q 421 -22 446 -37 q 354 -8 397 -8 q 316 -9 341 -8 q 280 -11 291 -11 q 75 69 150 -11 q 0 283 0 150 q 87 596 0 437 q 291 856 162 730 l 47 856 l 47 1013 l 592 1013 l 592 904 q 317 660 422 800 q 197 318 197 497 q 306 141 197 169 q 510 123 408 131 q 622 -32 622 102 "},"θ":{"x_min":0,"x_max":714,"ha":817,"o":"m 357 1022 q 633 833 534 1022 q 714 486 714 679 q 634 148 714 288 q 354 -25 536 -25 q 79 147 175 -25 q 0 481 0 288 q 79 831 0 679 q 357 1022 177 1022 m 510 590 q 475 763 510 687 q 351 862 430 862 q 233 763 272 862 q 204 590 204 689 l 510 590 m 510 440 l 204 440 q 233 251 204 337 q 355 131 274 131 q 478 248 434 131 q 510 440 510 337 "},"Ο":{"x_min":0,"x_max":995,"ha":1092,"o":"m 497 -29 q 133 127 272 -29 q 0 505 0 277 q 132 883 0 733 q 497 1040 270 1040 q 861 883 722 1040 q 995 505 995 733 q 862 127 995 277 q 497 -29 724 -29 m 497 154 q 711 266 632 154 q 781 506 781 365 q 711 745 781 647 q 497 857 632 857 q 283 747 361 857 q 213 506 213 647 q 282 266 213 365 q 497 154 361 154 "},"Γ":{"x_min":0,"x_max":703.84375,"ha":742,"o":"m 703 836 l 208 836 l 208 0 l 0 0 l 0 1012 l 703 1012 l 703 836 "}," ":{"x_min":0,"x_max":0,"ha":375},"%":{"x_min":0,"x_max":1111,"ha":1213,"o":"m 861 484 q 1048 404 979 484 q 1111 228 1111 332 q 1048 51 1111 123 q 859 -29 979 -29 q 672 50 740 -29 q 610 227 610 122 q 672 403 610 331 q 861 484 741 484 m 861 120 q 939 151 911 120 q 967 226 967 183 q 942 299 967 270 q 861 333 912 333 q 783 301 811 333 q 756 226 756 269 q 783 151 756 182 q 861 120 810 120 m 904 984 l 316 -28 l 205 -29 l 793 983 l 904 984 m 250 984 q 436 904 366 984 q 499 730 499 832 q 436 552 499 626 q 248 472 366 472 q 62 552 132 472 q 0 728 0 624 q 62 903 0 831 q 250 984 132 984 m 249 835 q 169 801 198 835 q 140 725 140 768 q 167 652 140 683 q 247 621 195 621 q 327 654 298 621 q 357 730 357 687 q 329 803 357 772 q 249 835 301 835 "},"P":{"x_min":0,"x_max":771,"ha":838,"o":"m 208 361 l 208 0 l 0 0 l 0 1013 l 450 1013 q 682 919 593 1013 q 771 682 771 826 q 687 452 771 544 q 466 361 604 361 l 208 361 m 421 837 l 208 837 l 208 544 l 410 544 q 525 579 480 544 q 571 683 571 615 q 527 792 571 747 q 421 837 484 837 "},"Έ":{"x_min":0,"x_max":1172.546875,"ha":1235,"o":"m 1172 0 l 411 0 l 411 1012 l 1146 1012 l 1146 836 l 617 836 l 617 621 l 1101 621 l 1101 446 l 617 446 l 617 186 l 1172 186 l 1172 0 m 313 1035 l 98 780 l 0 780 l 136 1035 l 313 1035 "},"Ώ":{"x_min":0.4375,"x_max":1189.546875,"ha":1289,"o":"m 1189 0 l 770 0 l 770 199 q 897 369 849 263 q 945 580 945 474 q 879 778 945 706 q 685 855 810 855 q 492 773 561 855 q 424 563 424 691 q 470 360 424 458 q 600 199 517 262 l 600 0 l 180 0 l 180 176 l 383 176 q 258 355 304 251 q 213 569 213 459 q 346 908 213 776 q 686 1040 479 1040 q 1025 912 892 1040 q 1158 578 1158 785 q 1112 362 1158 467 q 986 176 1067 256 l 1189 176 l 1189 0 m 314 1092 l 99 837 l 0 837 l 136 1092 l 314 1092 "},"_":{"x_min":61.109375,"x_max":766.671875,"ha":828,"o":"m 766 -333 l 61 -333 l 61 -190 l 766 -190 l 766 -333 "},"Ϊ":{"x_min":-56,"x_max":342,"ha":503,"o":"m 342 1046 l 186 1046 l 186 1215 l 342 1215 l 342 1046 m 101 1046 l -56 1046 l -56 1215 l 101 1215 l 101 1046 m 249 0 l 41 0 l 41 1012 l 249 1012 l 249 0 "},"+":{"x_min":43,"x_max":784,"ha":828,"o":"m 784 353 l 483 353 l 483 0 l 343 0 l 343 353 l 43 353 l 43 489 l 343 489 l 343 840 l 483 840 l 483 489 l 784 489 l 784 353 "},"½":{"x_min":0,"x_max":1090,"ha":1188,"o":"m 1090 380 q 992 230 1090 301 q 779 101 886 165 q 822 94 784 95 q 924 93 859 93 l 951 93 l 973 93 l 992 93 l 1009 93 q 1046 93 1027 93 q 1085 93 1066 93 l 1085 0 l 650 0 l 654 38 q 815 233 665 137 q 965 376 965 330 q 936 436 965 412 q 869 461 908 461 q 806 435 831 461 q 774 354 780 409 l 659 354 q 724 505 659 451 q 870 554 783 554 q 1024 506 958 554 q 1090 380 1090 459 m 868 998 l 268 -28 l 154 -27 l 757 999 l 868 998 m 272 422 l 147 422 l 147 799 l 0 799 l 0 875 q 126 900 91 875 q 170 973 162 926 l 272 973 l 272 422 "},"Ρ":{"x_min":0,"x_max":771,"ha":838,"o":"m 208 361 l 208 0 l 0 0 l 0 1012 l 450 1012 q 682 919 593 1012 q 771 681 771 826 q 687 452 771 544 q 466 361 604 361 l 208 361 m 422 836 l 209 836 l 209 544 l 410 544 q 525 579 480 544 q 571 683 571 614 q 527 791 571 747 q 422 836 484 836 "},"'":{"x_min":0,"x_max":192,"ha":289,"o":"m 192 834 q 137 692 192 751 q 0 626 82 632 l 0 697 q 101 830 101 726 l 0 830 l 0 1013 l 192 1013 l 192 834 "},"ª":{"x_min":0,"x_max":350,"ha":393,"o":"m 350 625 l 245 625 q 237 648 241 636 q 233 672 233 661 q 117 611 192 611 q 33 643 66 611 q 0 727 0 675 q 116 846 0 828 q 233 886 233 864 q 211 919 233 907 q 168 931 190 931 q 108 877 108 931 l 14 877 q 56 977 14 942 q 165 1013 98 1013 q 270 987 224 1013 q 329 903 329 955 l 329 694 q 332 661 329 675 q 350 641 336 648 l 350 625 m 233 774 l 233 809 q 151 786 180 796 q 97 733 97 768 q 111 700 97 712 q 149 689 126 689 q 210 713 187 689 q 233 774 233 737 "},"΅":{"x_min":57,"x_max":584,"ha":753,"o":"m 584 810 l 455 810 l 455 952 l 584 952 l 584 810 m 521 1064 l 305 810 l 207 810 l 343 1064 l 521 1064 m 186 810 l 57 810 l 57 952 l 186 952 l 186 810 "},"T":{"x_min":0,"x_max":809,"ha":894,"o":"m 809 831 l 509 831 l 509 0 l 299 0 l 299 831 l 0 831 l 0 1013 l 809 1013 l 809 831 "},"Φ":{"x_min":0,"x_max":949,"ha":1032,"o":"m 566 0 l 385 0 l 385 121 q 111 230 222 121 q 0 508 0 340 q 112 775 0 669 q 385 892 219 875 l 385 1013 l 566 1013 l 566 892 q 836 776 732 875 q 949 507 949 671 q 838 231 949 341 q 566 121 728 121 l 566 0 m 566 285 q 701 352 650 285 q 753 508 753 419 q 703 658 753 597 q 566 729 653 720 l 566 285 m 385 285 l 385 729 q 245 661 297 717 q 193 516 193 604 q 246 356 193 427 q 385 285 300 285 "},"j":{"x_min":-45.828125,"x_max":242,"ha":361,"o":"m 242 830 l 42 830 l 42 1013 l 242 1013 l 242 830 m 242 -119 q 180 -267 242 -221 q 20 -308 127 -308 l -45 -308 l -45 -140 l -24 -140 q 25 -130 8 -140 q 42 -88 42 -120 l 42 748 l 242 748 l 242 -119 "},"Σ":{"x_min":0,"x_max":772.21875,"ha":849,"o":"m 772 0 l 0 0 l 0 140 l 368 526 l 18 862 l 18 1012 l 740 1012 l 740 836 l 315 836 l 619 523 l 298 175 l 772 175 l 772 0 "},"1":{"x_min":197.609375,"x_max":628,"ha":828,"o":"m 628 0 l 434 0 l 434 674 l 197 674 l 197 810 q 373 837 318 810 q 468 984 450 876 l 628 984 l 628 0 "},"›":{"x_min":36.109375,"x_max":792,"ha":828,"o":"m 792 352 l 36 17 l 36 168 l 594 420 l 36 672 l 36 823 l 792 487 l 792 352 "},"<":{"x_min":35.984375,"x_max":791.671875,"ha":828,"o":"m 791 17 l 36 352 l 35 487 l 791 823 l 791 672 l 229 421 l 791 168 l 791 17 "},"£":{"x_min":0,"x_max":716.546875,"ha":814,"o":"m 716 38 q 603 -9 658 5 q 502 -24 548 -24 q 398 -10 451 -24 q 239 25 266 25 q 161 12 200 25 q 77 -29 122 0 l 0 113 q 110 211 81 174 q 151 315 151 259 q 117 440 151 365 l 0 440 l 0 515 l 73 515 q 35 610 52 560 q 15 710 15 671 q 119 910 15 831 q 349 984 216 984 q 570 910 480 984 q 693 668 674 826 l 501 668 q 455 791 501 746 q 353 830 414 830 q 256 795 298 830 q 215 705 215 760 q 249 583 215 655 q 283 515 266 548 l 479 515 l 479 440 l 309 440 q 316 394 313 413 q 319 355 319 374 q 287 241 319 291 q 188 135 263 205 q 262 160 225 152 q 332 168 298 168 q 455 151 368 168 q 523 143 500 143 q 588 152 558 143 q 654 189 617 162 l 716 38 "},"t":{"x_min":0,"x_max":412,"ha":511,"o":"m 412 -6 q 349 -8 391 -6 q 287 -11 307 -11 q 137 38 177 -11 q 97 203 97 87 l 97 609 l 0 609 l 0 749 l 97 749 l 97 951 l 297 951 l 297 749 l 412 749 l 412 609 l 297 609 l 297 191 q 315 152 297 162 q 366 143 334 143 q 389 143 378 143 q 412 143 400 143 l 412 -6 "},"¬":{"x_min":0,"x_max":704,"ha":801,"o":"m 704 93 l 551 93 l 551 297 l 0 297 l 0 450 l 704 450 l 704 93 "},"λ":{"x_min":0,"x_max":701.390625,"ha":775,"o":"m 701 0 l 491 0 l 345 444 l 195 0 l 0 0 l 238 697 l 131 1013 l 334 1013 l 701 0 "},"W":{"x_min":0,"x_max":1291.671875,"ha":1399,"o":"m 1291 1013 l 1002 0 l 802 0 l 645 777 l 490 0 l 288 0 l 0 1013 l 215 1013 l 388 298 l 534 1012 l 757 1013 l 904 299 l 1076 1013 l 1291 1013 "},">":{"x_min":36.109375,"x_max":792,"ha":828,"o":"m 792 352 l 36 17 l 36 168 l 594 420 l 36 672 l 36 823 l 792 487 l 792 352 "},"v":{"x_min":0,"x_max":740.28125,"ha":828,"o":"m 740 749 l 473 0 l 266 0 l 0 749 l 222 749 l 373 211 l 529 749 l 740 749 "},"τ":{"x_min":0.28125,"x_max":618.734375,"ha":699,"o":"m 618 593 l 409 593 l 409 0 l 210 0 l 210 593 l 0 593 l 0 749 l 618 749 l 618 593 "},"ξ":{"x_min":0,"x_max":640,"ha":715,"o":"m 640 -14 q 619 -157 640 -84 q 563 -299 599 -230 l 399 -299 q 442 -194 433 -223 q 468 -85 468 -126 q 440 -25 468 -41 q 368 -10 412 -10 q 333 -11 355 -10 q 302 -13 311 -13 q 91 60 179 -13 q 0 259 0 138 q 56 426 0 354 q 201 530 109 493 q 106 594 144 553 q 65 699 65 642 q 94 787 65 747 q 169 856 123 828 l 22 856 l 22 1013 l 597 1013 l 597 856 l 497 857 q 345 840 398 857 q 257 736 257 812 q 366 614 257 642 q 552 602 416 602 l 552 446 l 513 446 q 313 425 379 446 q 199 284 199 389 q 312 162 199 184 q 524 136 418 148 q 640 -14 640 105 "},"&":{"x_min":-1,"x_max":910.109375,"ha":1007,"o":"m 910 -1 l 676 -1 l 607 83 q 291 -47 439 -47 q 50 100 135 -47 q -1 273 -1 190 q 51 431 -1 357 q 218 568 104 505 q 151 661 169 629 q 120 769 120 717 q 201 951 120 885 q 382 1013 276 1013 q 555 957 485 1013 q 635 789 635 894 q 584 644 635 709 q 468 539 548 597 l 615 359 q 664 527 654 440 l 844 527 q 725 223 824 359 l 910 -1 m 461 787 q 436 848 461 826 q 381 870 412 870 q 325 849 349 870 q 301 792 301 829 q 324 719 301 757 q 372 660 335 703 q 430 714 405 680 q 461 787 461 753 m 500 214 l 318 441 q 198 286 198 363 q 225 204 198 248 q 347 135 268 135 q 425 153 388 135 q 500 214 462 172 "},"Λ":{"x_min":0,"x_max":894.453125,"ha":974,"o":"m 894 0 l 666 0 l 447 757 l 225 0 l 0 0 l 344 1013 l 547 1013 l 894 0 "},"I":{"x_min":41,"x_max":249,"ha":365,"o":"m 249 0 l 41 0 l 41 1013 l 249 1013 l 249 0 "},"G":{"x_min":0,"x_max":971,"ha":1057,"o":"m 971 -1 l 829 -1 l 805 118 q 479 -29 670 -29 q 126 133 261 -29 q 0 509 0 286 q 130 884 0 737 q 493 1040 268 1040 q 790 948 659 1040 q 961 698 920 857 l 736 698 q 643 813 709 769 q 500 857 578 857 q 285 746 364 857 q 213 504 213 644 q 285 263 213 361 q 505 154 365 154 q 667 217 598 154 q 761 374 736 280 l 548 374 l 548 548 l 971 548 l 971 -1 "},"ΰ":{"x_min":0,"x_max":655,"ha":767,"o":"m 583 810 l 454 810 l 454 952 l 583 952 l 583 810 m 186 810 l 57 809 l 57 952 l 186 952 l 186 810 m 516 1039 l 315 823 l 216 823 l 338 1039 l 516 1039 m 655 417 q 567 55 655 146 q 326 -25 489 -25 q 59 97 137 -25 q 0 369 0 192 l 0 748 l 200 748 l 201 369 q 218 222 201 269 q 326 142 245 142 q 439 247 410 142 q 455 422 455 304 l 455 748 l 655 748 l 655 417 "},"`":{"x_min":0,"x_max":190,"ha":288,"o":"m 190 654 l 0 654 l 0 830 q 55 970 0 909 q 190 1040 110 1031 l 190 969 q 111 922 134 952 q 88 836 88 892 l 190 836 l 190 654 "},"·":{"x_min":0,"x_max":207,"ha":304,"o":"m 207 528 l 0 528 l 0 735 l 207 735 l 207 528 "},"Υ":{"x_min":-0.21875,"x_max":836.171875,"ha":914,"o":"m 836 1013 l 532 376 l 532 0 l 322 0 l 322 376 l 0 1013 l 208 1013 l 427 576 l 626 1013 l 836 1013 "},"r":{"x_min":0,"x_max":431.9375,"ha":513,"o":"m 431 564 q 269 536 320 564 q 200 395 200 498 l 200 0 l 0 0 l 0 748 l 183 748 l 183 618 q 285 731 224 694 q 431 768 345 768 l 431 564 "},"x":{"x_min":0,"x_max":738.890625,"ha":826,"o":"m 738 0 l 504 0 l 366 238 l 230 0 l 0 0 l 252 382 l 11 749 l 238 749 l 372 522 l 502 749 l 725 749 l 488 384 l 738 0 "},"μ":{"x_min":0,"x_max":647,"ha":754,"o":"m 647 0 l 477 0 l 477 68 q 411 9 448 30 q 330 -11 374 -11 q 261 3 295 -11 q 199 43 226 18 l 199 -278 l 0 -278 l 0 749 l 199 749 l 199 358 q 216 222 199 268 q 322 152 244 152 q 435 240 410 152 q 448 401 448 283 l 448 749 l 647 749 l 647 0 "},"h":{"x_min":0,"x_max":669,"ha":782,"o":"m 669 0 l 469 0 l 469 390 q 449 526 469 472 q 353 607 420 607 q 248 554 295 607 q 201 441 201 501 l 201 0 l 0 0 l 0 1013 l 201 1013 l 201 665 q 303 743 245 715 q 425 772 362 772 q 609 684 542 772 q 669 484 669 605 l 669 0 "},".":{"x_min":0,"x_max":206,"ha":303,"o":"m 206 0 l 0 0 l 0 207 l 206 207 l 206 0 "},"φ":{"x_min":-1,"x_max":921,"ha":990,"o":"m 542 -278 l 367 -278 l 367 -22 q 99 92 200 -22 q -1 376 -1 206 q 72 627 -1 520 q 288 769 151 742 l 288 581 q 222 495 243 550 q 202 378 202 439 q 240 228 202 291 q 367 145 285 157 l 367 776 l 515 776 q 807 667 694 776 q 921 379 921 558 q 815 93 921 209 q 542 -22 709 -22 l 542 -278 m 542 145 q 672 225 625 145 q 713 381 713 291 q 671 536 713 470 q 542 611 624 611 l 542 145 "},";":{"x_min":0,"x_max":208,"ha":306,"o":"m 208 528 l 0 528 l 0 735 l 208 735 l 208 528 m 208 6 q 152 -151 208 -89 q 0 -238 96 -212 l 0 -158 q 87 -100 61 -136 q 113 0 113 -65 l 0 0 l 0 207 l 208 207 l 208 6 "},"f":{"x_min":0,"x_max":424,"ha":525,"o":"m 424 609 l 300 609 l 300 0 l 107 0 l 107 609 l 0 609 l 0 749 l 107 749 q 145 949 107 894 q 328 1019 193 1019 l 424 1015 l 424 855 l 362 855 q 312 841 324 855 q 300 797 300 827 q 300 773 300 786 q 300 749 300 761 l 424 749 l 424 609 "},"“":{"x_min":0,"x_max":468,"ha":567,"o":"m 190 631 l 0 631 l 0 807 q 55 947 0 885 q 190 1017 110 1010 l 190 947 q 88 813 88 921 l 190 813 l 190 631 m 468 631 l 278 631 l 278 807 q 333 947 278 885 q 468 1017 388 1010 l 468 947 q 366 813 366 921 l 468 813 l 468 631 "},"A":{"x_min":0,"x_max":966.671875,"ha":1069,"o":"m 966 0 l 747 0 l 679 208 l 286 208 l 218 0 l 0 0 l 361 1013 l 600 1013 l 966 0 m 623 376 l 480 810 l 340 376 l 623 376 "},"6":{"x_min":57,"x_max":771,"ha":828,"o":"m 744 734 l 544 734 q 500 802 533 776 q 425 828 466 828 q 315 769 359 828 q 264 571 264 701 q 451 638 343 638 q 691 537 602 638 q 771 315 771 449 q 683 79 771 176 q 420 -29 586 -29 q 134 123 227 -29 q 57 455 57 250 q 184 865 57 721 q 452 988 293 988 q 657 916 570 988 q 744 734 744 845 m 426 128 q 538 178 498 128 q 578 300 578 229 q 538 422 578 372 q 415 479 493 479 q 303 430 342 479 q 264 313 264 381 q 308 184 264 240 q 426 128 352 128 "},"‘":{"x_min":0,"x_max":190,"ha":289,"o":"m 190 631 l 0 631 l 0 807 q 55 947 0 885 q 190 1017 110 1010 l 190 947 q 88 813 88 921 l 190 813 l 190 631 "},"ϊ":{"x_min":-55,"x_max":337,"ha":389,"o":"m 337 810 l 208 810 l 208 952 l 337 952 l 337 810 m 74 810 l -55 810 l -55 952 l 74 952 l 74 810 m 242 0 l 42 0 l 42 748 l 242 748 l 242 0 "},"π":{"x_min":0.5,"x_max":838.890625,"ha":938,"o":"m 838 593 l 750 593 l 750 0 l 549 0 l 549 593 l 287 593 l 287 0 l 88 0 l 88 593 l 0 593 l 0 749 l 838 749 l 838 593 "},"ά":{"x_min":-1,"x_max":722,"ha":835,"o":"m 722 0 l 531 0 l 530 101 q 433 8 491 41 q 304 -25 375 -25 q 72 104 157 -25 q -1 372 -1 216 q 72 643 -1 530 q 308 775 158 775 q 433 744 375 775 q 528 656 491 713 l 528 749 l 722 749 l 722 0 m 361 601 q 233 527 277 601 q 196 375 196 464 q 232 224 196 288 q 358 144 277 144 q 487 217 441 144 q 528 370 528 281 q 489 523 528 457 q 361 601 443 601 m 579 1039 l 377 823 l 279 823 l 401 1039 l 579 1039 "},"O":{"x_min":0,"x_max":994,"ha":1094,"o":"m 497 -29 q 133 127 272 -29 q 0 505 0 277 q 131 883 0 733 q 497 1040 270 1040 q 860 883 721 1040 q 994 505 994 733 q 862 127 994 277 q 497 -29 723 -29 m 497 154 q 710 266 631 154 q 780 506 780 365 q 710 745 780 647 q 497 857 631 857 q 283 747 361 857 q 213 506 213 647 q 282 266 213 365 q 497 154 361 154 "},"n":{"x_min":0,"x_max":669,"ha":782,"o":"m 669 0 l 469 0 l 469 452 q 442 553 469 513 q 352 601 412 601 q 245 553 290 601 q 200 441 200 505 l 200 0 l 0 0 l 0 748 l 194 748 l 194 659 q 289 744 230 713 q 416 775 349 775 q 600 700 531 775 q 669 509 669 626 l 669 0 "},"3":{"x_min":61,"x_max":767,"ha":828,"o":"m 767 290 q 653 51 767 143 q 402 -32 548 -32 q 168 48 262 -32 q 61 300 61 140 l 250 300 q 298 173 250 219 q 405 132 343 132 q 514 169 471 132 q 563 282 563 211 q 491 405 563 369 q 343 432 439 432 l 343 568 q 472 592 425 568 q 534 701 534 626 q 493 793 534 758 q 398 829 453 829 q 306 789 344 829 q 268 669 268 749 l 80 669 q 182 909 80 823 q 410 986 274 986 q 633 916 540 986 q 735 719 735 840 q 703 608 735 656 q 615 522 672 561 q 727 427 687 486 q 767 290 767 369 "},"9":{"x_min":58,"x_max":769,"ha":828,"o":"m 769 492 q 646 90 769 232 q 384 -33 539 -33 q 187 35 271 -33 q 83 224 98 107 l 282 224 q 323 154 286 182 q 404 127 359 127 q 513 182 471 127 q 563 384 563 248 q 475 335 532 355 q 372 315 418 315 q 137 416 224 315 q 58 642 58 507 q 144 877 58 781 q 407 984 239 984 q 694 827 602 984 q 769 492 769 699 m 416 476 q 525 521 488 476 q 563 632 563 566 q 521 764 563 709 q 403 826 474 826 q 297 773 337 826 q 258 649 258 720 q 295 530 258 577 q 416 476 339 476 "},"l":{"x_min":41,"x_max":240,"ha":363,"o":"m 240 0 l 41 0 l 41 1013 l 240 1013 l 240 0 "},"¤":{"x_min":40.265625,"x_max":727.203125,"ha":825,"o":"m 727 792 l 594 659 q 620 552 620 609 q 598 459 620 504 l 725 331 l 620 224 l 491 352 q 382 331 443 331 q 273 352 322 331 l 144 224 l 40 330 l 167 459 q 147 552 147 501 q 172 658 147 608 l 40 794 l 147 898 l 283 759 q 383 776 330 776 q 482 759 434 776 l 620 898 l 727 792 m 383 644 q 308 617 334 644 q 283 551 283 590 q 309 489 283 517 q 381 462 335 462 q 456 488 430 462 q 482 554 482 515 q 455 616 482 588 q 383 644 429 644 "},"κ":{"x_min":0,"x_max":691.84375,"ha":779,"o":"m 691 0 l 479 0 l 284 343 l 196 252 l 196 0 l 0 0 l 0 749 l 196 749 l 196 490 l 440 749 l 677 749 l 416 479 l 691 0 "},"4":{"x_min":53,"x_max":775.21875,"ha":828,"o":"m 775 213 l 660 213 l 660 0 l 470 0 l 470 213 l 53 213 l 53 384 l 416 958 l 660 958 l 660 370 l 775 370 l 775 213 m 474 364 l 474 786 l 204 363 l 474 364 "},"p":{"x_min":0,"x_max":722,"ha":824,"o":"m 415 -26 q 287 4 346 -26 q 192 92 228 34 l 192 -298 l 0 -298 l 0 750 l 192 750 l 192 647 q 289 740 230 706 q 416 775 347 775 q 649 645 566 775 q 722 375 722 534 q 649 106 722 218 q 415 -26 564 -26 m 363 603 q 232 529 278 603 q 192 375 192 465 q 230 222 192 286 q 360 146 276 146 q 487 221 441 146 q 526 371 526 285 q 488 523 526 458 q 363 603 443 603 "},"‡":{"x_min":0,"x_max":809,"ha":894,"o":"m 299 621 l 0 621 l 0 804 l 299 804 l 299 1011 l 509 1011 l 509 804 l 809 804 l 809 621 l 509 621 l 509 387 l 809 387 l 809 205 l 509 205 l 509 0 l 299 0 l 299 205 l 0 205 l 0 387 l 299 387 l 299 621 "},"ψ":{"x_min":0,"x_max":875,"ha":979,"o":"m 522 142 q 657 274 620 163 q 671 352 671 316 l 671 748 l 875 748 l 875 402 q 806 134 875 240 q 525 -22 719 -1 l 525 -278 l 349 -278 l 349 -22 q 65 135 152 -1 q 0 402 0 238 l 0 748 l 204 748 l 204 352 q 231 240 204 295 q 353 142 272 159 l 353 922 l 524 922 l 522 142 "},"η":{"x_min":0,"x_max":669,"ha":779,"o":"m 669 -278 l 469 -278 l 469 390 q 448 526 469 473 q 348 606 417 606 q 244 553 288 606 q 201 441 201 501 l 201 0 l 0 0 l 0 749 l 201 749 l 201 665 q 301 744 244 715 q 423 774 359 774 q 606 685 538 774 q 669 484 669 603 l 669 -278 "}},"cssFontWeight":"bold","ascender":1216,"underlinePosition":-100,"cssFontStyle":"normal","boundingBox":{"yMin":-333,"xMin":-162,"yMax":1216,"xMax":1681},"resolution":1000,"original_font_information":{"postscript_name":"Helvetiker-Bold","version_string":"Version 1.00 2004 initial release","vendor_url":"http://www.magenta.gr","full_font_name":"Helvetiker Bold","font_family_name":"Helvetiker","copyright":"Copyright (c) Magenta ltd, 2004.","description":"","trademark":"","designer":"","designer_url":"","unique_font_identifier":"Magenta ltd:Helvetiker Bold:22-10-104","license_url":"http://www.ellak.gr/fonts/MgOpen/license.html","license_description":"Copyright (c) 2004 by MAGENTA Ltd. All Rights Reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license (\"Fonts\") and associated documentation files (the \"Font Software\"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: \r\n\r\nThe above copyright and this permission notice shall be included in all copies of one or more of the Font Software typefaces.\r\n\r\nThe Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing the word \"MgOpen\", or if the modifications are accepted for inclusion in the Font Software itself by the each appointed Administrator.\r\n\r\nThis License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the \"MgOpen\" name.\r\n\r\nThe Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. \r\n\r\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL MAGENTA OR PERSONS OR BODIES IN CHARGE OF ADMINISTRATION AND MAINTENANCE OF THE FONT SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.","manufacturer_name":"Magenta ltd","font_sub_family_name":"Bold"},"descender":-334,"familyName":"Helvetiker","lineHeight":1549,"underlineThickness":50} \ No newline at end of file diff --git a/resources/video-editor/fonts/helvetiker_regular.typeface.json b/resources/video-editor/fonts/helvetiker_regular.typeface.json new file mode 100644 index 00000000..d19293b4 --- /dev/null +++ b/resources/video-editor/fonts/helvetiker_regular.typeface.json @@ -0,0 +1 @@ +{"glyphs":{"ο":{"x_min":0,"x_max":712,"ha":815,"o":"m 356 -25 q 96 88 192 -25 q 0 368 0 201 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 "},"S":{"x_min":0,"x_max":788,"ha":890,"o":"m 788 291 q 662 54 788 144 q 397 -26 550 -26 q 116 68 226 -26 q 0 337 0 168 l 131 337 q 200 152 131 220 q 384 85 269 85 q 557 129 479 85 q 650 270 650 183 q 490 429 650 379 q 194 513 341 470 q 33 739 33 584 q 142 964 33 881 q 388 1041 242 1041 q 644 957 543 1041 q 756 716 756 867 l 625 716 q 561 874 625 816 q 395 933 497 933 q 243 891 309 933 q 164 759 164 841 q 325 609 164 656 q 625 526 475 568 q 788 291 788 454 "},"¦":{"x_min":343,"x_max":449,"ha":792,"o":"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"/":{"x_min":183.25,"x_max":608.328125,"ha":792,"o":"m 608 1041 l 266 -129 l 183 -129 l 520 1041 l 608 1041 "},"Τ":{"x_min":-0.4375,"x_max":777.453125,"ha":839,"o":"m 777 893 l 458 893 l 458 0 l 319 0 l 319 892 l 0 892 l 0 1013 l 777 1013 l 777 893 "},"y":{"x_min":0,"x_max":684.78125,"ha":771,"o":"m 684 738 l 388 -83 q 311 -216 356 -167 q 173 -279 252 -279 q 97 -266 133 -279 l 97 -149 q 132 -155 109 -151 q 168 -160 155 -160 q 240 -114 213 -160 q 274 -26 248 -98 l 0 738 l 137 737 l 341 139 l 548 737 l 684 738 "},"Π":{"x_min":0,"x_max":803,"ha":917,"o":"m 803 0 l 667 0 l 667 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 803 1012 l 803 0 "},"ΐ":{"x_min":-111,"x_max":339,"ha":361,"o":"m 339 800 l 229 800 l 229 925 l 339 925 l 339 800 m -1 800 l -111 800 l -111 925 l -1 925 l -1 800 m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 m 302 1040 l 113 819 l 30 819 l 165 1040 l 302 1040 "},"g":{"x_min":0,"x_max":686,"ha":838,"o":"m 686 34 q 586 -213 686 -121 q 331 -306 487 -306 q 131 -252 216 -306 q 31 -84 31 -190 l 155 -84 q 228 -174 166 -138 q 345 -207 284 -207 q 514 -109 454 -207 q 564 89 564 -27 q 461 6 521 36 q 335 -23 401 -23 q 88 100 184 -23 q 0 370 0 215 q 87 634 0 522 q 330 758 183 758 q 457 728 398 758 q 564 644 515 699 l 564 737 l 686 737 l 686 34 m 582 367 q 529 560 582 481 q 358 652 468 652 q 189 561 250 652 q 135 369 135 482 q 189 176 135 255 q 361 85 251 85 q 529 176 468 85 q 582 367 582 255 "},"²":{"x_min":0,"x_max":442,"ha":539,"o":"m 442 383 l 0 383 q 91 566 0 492 q 260 668 176 617 q 354 798 354 727 q 315 875 354 845 q 227 905 277 905 q 136 869 173 905 q 99 761 99 833 l 14 761 q 82 922 14 864 q 232 974 141 974 q 379 926 316 974 q 442 797 442 878 q 351 635 442 704 q 183 539 321 611 q 92 455 92 491 l 442 455 l 442 383 "},"–":{"x_min":0,"x_max":705.5625,"ha":803,"o":"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},"Κ":{"x_min":0,"x_max":819.5625,"ha":893,"o":"m 819 0 l 650 0 l 294 509 l 139 356 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},"ƒ":{"x_min":-46.265625,"x_max":392,"ha":513,"o":"m 392 651 l 259 651 l 79 -279 l -46 -278 l 134 651 l 14 651 l 14 751 l 135 751 q 151 948 135 900 q 304 1041 185 1041 q 334 1040 319 1041 q 392 1034 348 1039 l 392 922 q 337 931 360 931 q 271 883 287 931 q 260 793 260 853 l 260 751 l 392 751 l 392 651 "},"e":{"x_min":0,"x_max":714,"ha":813,"o":"m 714 326 l 140 326 q 200 157 140 227 q 359 87 260 87 q 488 130 431 87 q 561 245 545 174 l 697 245 q 577 48 670 123 q 358 -26 484 -26 q 97 85 195 -26 q 0 363 0 197 q 94 642 0 529 q 358 765 195 765 q 626 627 529 765 q 714 326 714 503 m 576 429 q 507 583 564 522 q 355 650 445 650 q 206 583 266 650 q 140 429 152 522 l 576 429 "},"ό":{"x_min":0,"x_max":712,"ha":815,"o":"m 356 -25 q 94 91 194 -25 q 0 368 0 202 q 92 642 0 533 q 356 761 192 761 q 617 644 517 761 q 712 368 712 533 q 619 91 712 201 q 356 -25 520 -25 m 356 85 q 527 175 465 85 q 583 369 583 255 q 528 562 583 484 q 356 651 466 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 356 85 250 85 m 576 1040 l 387 819 l 303 819 l 438 1040 l 576 1040 "},"J":{"x_min":0,"x_max":588,"ha":699,"o":"m 588 279 q 287 -26 588 -26 q 58 73 126 -26 q 0 327 0 158 l 133 327 q 160 172 133 227 q 288 96 198 96 q 426 171 391 96 q 449 336 449 219 l 449 1013 l 588 1013 l 588 279 "},"»":{"x_min":-1,"x_max":503,"ha":601,"o":"m 503 302 l 280 136 l 281 256 l 429 373 l 281 486 l 280 608 l 503 440 l 503 302 m 221 302 l 0 136 l 0 255 l 145 372 l 0 486 l -1 608 l 221 440 l 221 302 "},"©":{"x_min":-3,"x_max":1008,"ha":1106,"o":"m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 741 394 q 661 246 731 302 q 496 190 591 190 q 294 285 369 190 q 228 497 228 370 q 295 714 228 625 q 499 813 370 813 q 656 762 588 813 q 733 625 724 711 l 634 625 q 589 704 629 673 q 498 735 550 735 q 377 666 421 735 q 334 504 334 597 q 374 340 334 408 q 490 272 415 272 q 589 304 549 272 q 638 394 628 337 l 741 394 "},"ώ":{"x_min":0,"x_max":922,"ha":1030,"o":"m 687 1040 l 498 819 l 415 819 l 549 1040 l 687 1040 m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 338 0 202 q 45 551 0 444 q 161 737 84 643 l 302 737 q 175 552 219 647 q 124 336 124 446 q 155 179 124 248 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 341 797 257 q 745 555 797 450 q 619 737 705 637 l 760 737 q 874 551 835 640 q 922 339 922 444 "},"^":{"x_min":193.0625,"x_max":598.609375,"ha":792,"o":"m 598 772 l 515 772 l 395 931 l 277 772 l 193 772 l 326 1013 l 462 1013 l 598 772 "},"«":{"x_min":0,"x_max":507.203125,"ha":604,"o":"m 506 136 l 284 302 l 284 440 l 506 608 l 507 485 l 360 371 l 506 255 l 506 136 m 222 136 l 0 302 l 0 440 l 222 608 l 221 486 l 73 373 l 222 256 l 222 136 "},"D":{"x_min":0,"x_max":828,"ha":935,"o":"m 389 1013 q 714 867 593 1013 q 828 521 828 729 q 712 161 828 309 q 382 0 587 0 l 0 0 l 0 1013 l 389 1013 m 376 124 q 607 247 523 124 q 681 510 681 355 q 607 771 681 662 q 376 896 522 896 l 139 896 l 139 124 l 376 124 "},"∙":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"ÿ":{"x_min":0,"x_max":47,"ha":125,"o":"m 47 3 q 37 -7 47 -7 q 28 0 30 -7 q 39 -4 32 -4 q 45 3 45 -1 l 37 0 q 28 9 28 0 q 39 19 28 19 l 47 16 l 47 19 l 47 3 m 37 1 q 44 8 44 1 q 37 16 44 16 q 30 8 30 16 q 37 1 30 1 m 26 1 l 23 22 l 14 0 l 3 22 l 3 3 l 0 25 l 13 1 l 22 25 l 26 1 "},"w":{"x_min":0,"x_max":1009.71875,"ha":1100,"o":"m 1009 738 l 783 0 l 658 0 l 501 567 l 345 0 l 222 0 l 0 738 l 130 738 l 284 174 l 432 737 l 576 738 l 721 173 l 881 737 l 1009 738 "},"$":{"x_min":0,"x_max":700,"ha":793,"o":"m 664 717 l 542 717 q 490 825 531 785 q 381 872 450 865 l 381 551 q 620 446 540 522 q 700 241 700 370 q 618 45 700 116 q 381 -25 536 -25 l 381 -152 l 307 -152 l 307 -25 q 81 62 162 -25 q 0 297 0 149 l 124 297 q 169 146 124 204 q 307 81 215 89 l 307 441 q 80 536 148 469 q 13 725 13 603 q 96 910 13 839 q 307 982 180 982 l 307 1077 l 381 1077 l 381 982 q 574 917 494 982 q 664 717 664 845 m 307 565 l 307 872 q 187 831 233 872 q 142 724 142 791 q 180 618 142 656 q 307 565 218 580 m 381 76 q 562 237 562 96 q 517 361 562 313 q 381 423 472 409 l 381 76 "},"\\":{"x_min":-0.015625,"x_max":425.0625,"ha":522,"o":"m 425 -129 l 337 -129 l 0 1041 l 83 1041 l 425 -129 "},"µ":{"x_min":0,"x_max":697.21875,"ha":747,"o":"m 697 -4 q 629 -14 658 -14 q 498 97 513 -14 q 422 9 470 41 q 313 -23 374 -23 q 207 4 258 -23 q 119 81 156 32 l 119 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 173 124 246 q 308 83 216 83 q 452 178 402 83 q 493 359 493 255 l 493 738 l 617 738 l 617 214 q 623 136 617 160 q 673 92 637 92 q 697 96 684 92 l 697 -4 "},"Ι":{"x_min":42,"x_max":181,"ha":297,"o":"m 181 0 l 42 0 l 42 1013 l 181 1013 l 181 0 "},"Ύ":{"x_min":0,"x_max":1144.5,"ha":1214,"o":"m 1144 1012 l 807 416 l 807 0 l 667 0 l 667 416 l 325 1012 l 465 1012 l 736 533 l 1004 1012 l 1144 1012 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"’":{"x_min":0,"x_max":139,"ha":236,"o":"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"Ν":{"x_min":0,"x_max":801,"ha":915,"o":"m 801 0 l 651 0 l 131 822 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 191 l 670 1013 l 801 1013 l 801 0 "},"-":{"x_min":8.71875,"x_max":350.390625,"ha":478,"o":"m 350 317 l 8 317 l 8 428 l 350 428 l 350 317 "},"Q":{"x_min":0,"x_max":968,"ha":1072,"o":"m 954 5 l 887 -79 l 744 35 q 622 -11 687 2 q 483 -26 556 -26 q 127 130 262 -26 q 0 504 0 279 q 127 880 0 728 q 484 1041 262 1041 q 841 884 708 1041 q 968 507 968 735 q 933 293 968 398 q 832 104 899 188 l 954 5 m 723 191 q 802 330 777 248 q 828 499 828 412 q 744 790 828 673 q 483 922 650 922 q 228 791 322 922 q 142 505 142 673 q 227 221 142 337 q 487 91 323 91 q 632 123 566 91 l 520 215 l 587 301 l 723 191 "},"ς":{"x_min":1,"x_max":676.28125,"ha":740,"o":"m 676 460 l 551 460 q 498 595 542 546 q 365 651 448 651 q 199 578 263 651 q 136 401 136 505 q 266 178 136 241 q 508 106 387 142 q 640 -50 640 62 q 625 -158 640 -105 q 583 -278 611 -211 l 465 -278 q 498 -182 490 -211 q 515 -80 515 -126 q 381 12 515 -15 q 134 91 197 51 q 1 388 1 179 q 100 651 1 542 q 354 761 199 761 q 587 680 498 761 q 676 460 676 599 "},"M":{"x_min":0,"x_max":954,"ha":1067,"o":"m 954 0 l 819 0 l 819 869 l 537 0 l 405 0 l 128 866 l 128 0 l 0 0 l 0 1013 l 200 1013 l 472 160 l 757 1013 l 954 1013 l 954 0 "},"Ψ":{"x_min":0,"x_max":1006,"ha":1094,"o":"m 1006 678 q 914 319 1006 429 q 571 200 814 200 l 571 0 l 433 0 l 433 200 q 92 319 194 200 q 0 678 0 429 l 0 1013 l 139 1013 l 139 679 q 191 417 139 492 q 433 326 255 326 l 433 1013 l 571 1013 l 571 326 l 580 326 q 813 423 747 326 q 868 679 868 502 l 868 1013 l 1006 1013 l 1006 678 "},"C":{"x_min":0,"x_max":886,"ha":944,"o":"m 886 379 q 760 87 886 201 q 455 -26 634 -26 q 112 136 236 -26 q 0 509 0 283 q 118 882 0 737 q 469 1041 245 1041 q 748 955 630 1041 q 879 708 879 859 l 745 708 q 649 862 724 805 q 473 920 573 920 q 219 791 312 920 q 136 509 136 675 q 217 229 136 344 q 470 99 311 99 q 672 179 591 99 q 753 379 753 259 l 886 379 "},"!":{"x_min":0,"x_max":138,"ha":236,"o":"m 138 684 q 116 409 138 629 q 105 244 105 299 l 33 244 q 16 465 33 313 q 0 684 0 616 l 0 1013 l 138 1013 l 138 684 m 138 0 l 0 0 l 0 151 l 138 151 l 138 0 "},"{":{"x_min":0,"x_max":480.5625,"ha":578,"o":"m 480 -286 q 237 -213 303 -286 q 187 -45 187 -159 q 194 48 187 -15 q 201 141 201 112 q 164 264 201 225 q 0 314 118 314 l 0 417 q 164 471 119 417 q 201 605 201 514 q 199 665 201 644 q 193 772 193 769 q 241 941 193 887 q 480 1015 308 1015 l 480 915 q 336 866 375 915 q 306 742 306 828 q 310 662 306 717 q 314 577 314 606 q 288 452 314 500 q 176 365 256 391 q 289 275 257 337 q 314 143 314 226 q 313 84 314 107 q 310 -11 310 -5 q 339 -131 310 -94 q 480 -182 377 -182 l 480 -286 "},"X":{"x_min":-0.015625,"x_max":854.15625,"ha":940,"o":"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 428 637 l 675 1013 l 836 1013 l 504 520 l 854 0 "},"#":{"x_min":0,"x_max":963.890625,"ha":1061,"o":"m 963 690 l 927 590 l 719 590 l 655 410 l 876 410 l 840 310 l 618 310 l 508 -3 l 393 -2 l 506 309 l 329 310 l 215 -2 l 102 -3 l 212 310 l 0 310 l 36 410 l 248 409 l 312 590 l 86 590 l 120 690 l 347 690 l 459 1006 l 573 1006 l 462 690 l 640 690 l 751 1006 l 865 1006 l 754 690 l 963 690 m 606 590 l 425 590 l 362 410 l 543 410 l 606 590 "},"ι":{"x_min":42,"x_max":284,"ha":361,"o":"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 738 l 167 738 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 103 239 101 q 284 112 257 104 l 284 3 "},"Ά":{"x_min":0,"x_max":906.953125,"ha":982,"o":"m 283 1040 l 88 799 l 5 799 l 145 1040 l 283 1040 m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1012 l 529 1012 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},")":{"x_min":0,"x_max":318,"ha":415,"o":"m 318 365 q 257 25 318 191 q 87 -290 197 -141 l 0 -290 q 140 21 93 -128 q 193 360 193 189 q 141 704 193 537 q 0 1024 97 850 l 87 1024 q 257 706 197 871 q 318 365 318 542 "},"ε":{"x_min":0,"x_max":634.71875,"ha":714,"o":"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 314 0 265 q 128 390 67 353 q 56 460 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 "},"Δ":{"x_min":0,"x_max":952.78125,"ha":1028,"o":"m 952 0 l 0 0 l 400 1013 l 551 1013 l 952 0 m 762 124 l 476 867 l 187 124 l 762 124 "},"}":{"x_min":0,"x_max":481,"ha":578,"o":"m 481 314 q 318 262 364 314 q 282 136 282 222 q 284 65 282 97 q 293 -58 293 -48 q 241 -217 293 -166 q 0 -286 174 -286 l 0 -182 q 143 -130 105 -182 q 171 -2 171 -93 q 168 81 171 22 q 165 144 165 140 q 188 275 165 229 q 306 365 220 339 q 191 455 224 391 q 165 588 165 505 q 168 681 165 624 q 171 742 171 737 q 141 865 171 827 q 0 915 102 915 l 0 1015 q 243 942 176 1015 q 293 773 293 888 q 287 675 293 741 q 282 590 282 608 q 318 466 282 505 q 481 417 364 417 l 481 314 "},"‰":{"x_min":-3,"x_max":1672,"ha":1821,"o":"m 846 0 q 664 76 732 0 q 603 244 603 145 q 662 412 603 344 q 846 489 729 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 846 0 962 0 m 845 103 q 945 143 910 103 q 981 243 981 184 q 947 340 981 301 q 845 385 910 385 q 745 342 782 385 q 709 243 709 300 q 742 147 709 186 q 845 103 781 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 m 1428 0 q 1246 76 1314 0 q 1185 244 1185 145 q 1244 412 1185 344 q 1428 489 1311 489 q 1610 412 1542 489 q 1672 244 1672 343 q 1612 76 1672 144 q 1428 0 1545 0 m 1427 103 q 1528 143 1492 103 q 1564 243 1564 184 q 1530 340 1564 301 q 1427 385 1492 385 q 1327 342 1364 385 q 1291 243 1291 300 q 1324 147 1291 186 q 1427 103 1363 103 "},"a":{"x_min":0,"x_max":698.609375,"ha":794,"o":"m 698 0 q 661 -12 679 -7 q 615 -17 643 -17 q 536 12 564 -17 q 500 96 508 41 q 384 6 456 37 q 236 -25 312 -25 q 65 31 130 -25 q 0 194 0 88 q 118 390 0 334 q 328 435 180 420 q 488 483 476 451 q 495 523 495 504 q 442 619 495 584 q 325 654 389 654 q 209 617 257 654 q 152 513 161 580 l 33 513 q 123 705 33 633 q 332 772 207 772 q 528 712 448 772 q 617 531 617 645 l 617 163 q 624 108 617 126 q 664 90 632 90 l 698 94 l 698 0 m 491 262 l 491 372 q 272 329 350 347 q 128 201 128 294 q 166 113 128 144 q 264 83 205 83 q 414 130 346 83 q 491 262 491 183 "},"—":{"x_min":0,"x_max":941.671875,"ha":1039,"o":"m 941 334 l 0 334 l 0 410 l 941 410 l 941 334 "},"=":{"x_min":8.71875,"x_max":780.953125,"ha":792,"o":"m 780 510 l 8 510 l 8 606 l 780 606 l 780 510 m 780 235 l 8 235 l 8 332 l 780 332 l 780 235 "},"N":{"x_min":0,"x_max":801,"ha":914,"o":"m 801 0 l 651 0 l 131 823 l 131 0 l 0 0 l 0 1013 l 151 1013 l 670 193 l 670 1013 l 801 1013 l 801 0 "},"ρ":{"x_min":0,"x_max":712,"ha":797,"o":"m 712 369 q 620 94 712 207 q 362 -26 521 -26 q 230 2 292 -26 q 119 83 167 30 l 119 -278 l 0 -278 l 0 362 q 91 643 0 531 q 355 764 190 764 q 617 647 517 764 q 712 369 712 536 m 583 366 q 530 559 583 480 q 359 651 469 651 q 190 562 252 651 q 135 370 135 483 q 189 176 135 257 q 359 85 250 85 q 528 175 466 85 q 583 366 583 254 "},"2":{"x_min":59,"x_max":731,"ha":792,"o":"m 731 0 l 59 0 q 197 314 59 188 q 457 487 199 315 q 598 691 598 580 q 543 819 598 772 q 411 867 488 867 q 272 811 328 867 q 209 630 209 747 l 81 630 q 182 901 81 805 q 408 986 271 986 q 629 909 536 986 q 731 694 731 826 q 613 449 731 541 q 378 316 495 383 q 201 122 235 234 l 731 122 l 731 0 "},"¯":{"x_min":0,"x_max":941.671875,"ha":938,"o":"m 941 1033 l 0 1033 l 0 1109 l 941 1109 l 941 1033 "},"Z":{"x_min":0,"x_max":779,"ha":849,"o":"m 779 0 l 0 0 l 0 113 l 621 896 l 40 896 l 40 1013 l 779 1013 l 778 887 l 171 124 l 779 124 l 779 0 "},"u":{"x_min":0,"x_max":617,"ha":729,"o":"m 617 0 l 499 0 l 499 110 q 391 10 460 45 q 246 -25 322 -25 q 61 58 127 -25 q 0 258 0 136 l 0 738 l 125 738 l 125 284 q 156 148 125 202 q 273 82 197 82 q 433 165 369 82 q 493 340 493 243 l 493 738 l 617 738 l 617 0 "},"k":{"x_min":0,"x_max":612.484375,"ha":697,"o":"m 612 738 l 338 465 l 608 0 l 469 0 l 251 382 l 121 251 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 402 l 456 738 l 612 738 "},"Η":{"x_min":0,"x_max":803,"ha":917,"o":"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"Α":{"x_min":0,"x_max":906.953125,"ha":985,"o":"m 906 0 l 756 0 l 650 303 l 251 303 l 143 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 609 421 l 452 866 l 293 421 l 609 421 "},"s":{"x_min":0,"x_max":604,"ha":697,"o":"m 604 217 q 501 36 604 104 q 292 -23 411 -23 q 86 43 166 -23 q 0 238 0 114 l 121 237 q 175 122 121 164 q 300 85 223 85 q 415 112 363 85 q 479 207 479 147 q 361 309 479 276 q 140 372 141 370 q 21 544 21 426 q 111 708 21 647 q 298 761 190 761 q 492 705 413 761 q 583 531 583 643 l 462 531 q 412 625 462 594 q 298 657 363 657 q 199 636 242 657 q 143 558 143 608 q 262 454 143 486 q 484 394 479 397 q 604 217 604 341 "},"B":{"x_min":0,"x_max":778,"ha":876,"o":"m 580 546 q 724 469 670 535 q 778 311 778 403 q 673 83 778 171 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 892 q 691 633 732 693 q 580 546 650 572 m 393 899 l 139 899 l 139 588 l 379 588 q 521 624 462 588 q 592 744 592 667 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 303 635 219 q 559 436 635 389 q 402 477 494 477 l 139 477 l 139 124 l 419 124 "},"…":{"x_min":0,"x_max":614,"ha":708,"o":"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 m 378 0 l 236 0 l 236 151 l 378 151 l 378 0 m 614 0 l 472 0 l 472 151 l 614 151 l 614 0 "},"?":{"x_min":0,"x_max":607,"ha":704,"o":"m 607 777 q 543 599 607 674 q 422 474 482 537 q 357 272 357 391 l 236 272 q 297 487 236 395 q 411 619 298 490 q 474 762 474 691 q 422 885 474 838 q 301 933 371 933 q 179 880 228 933 q 124 706 124 819 l 0 706 q 94 963 0 872 q 302 1044 177 1044 q 511 973 423 1044 q 607 777 607 895 m 370 0 l 230 0 l 230 151 l 370 151 l 370 0 "},"H":{"x_min":0,"x_max":803,"ha":915,"o":"m 803 0 l 667 0 l 667 475 l 140 475 l 140 0 l 0 0 l 0 1013 l 140 1013 l 140 599 l 667 599 l 667 1013 l 803 1013 l 803 0 "},"ν":{"x_min":0,"x_max":675,"ha":761,"o":"m 675 738 l 404 0 l 272 0 l 0 738 l 133 738 l 340 147 l 541 738 l 675 738 "},"c":{"x_min":1,"x_max":701.390625,"ha":775,"o":"m 701 264 q 584 53 681 133 q 353 -26 487 -26 q 91 91 188 -26 q 1 370 1 201 q 92 645 1 537 q 353 761 190 761 q 572 688 479 761 q 690 493 666 615 l 556 493 q 487 606 545 562 q 356 650 428 650 q 186 563 246 650 q 134 372 134 487 q 188 179 134 258 q 359 88 250 88 q 492 136 437 88 q 566 264 548 185 l 701 264 "},"¶":{"x_min":0,"x_max":566.671875,"ha":678,"o":"m 21 892 l 52 892 l 98 761 l 145 892 l 176 892 l 178 741 l 157 741 l 157 867 l 108 741 l 88 741 l 40 871 l 40 741 l 21 741 l 21 892 m 308 854 l 308 731 q 252 691 308 691 q 227 691 240 691 q 207 696 213 695 l 207 712 l 253 706 q 288 733 288 706 l 288 763 q 244 741 279 741 q 193 797 193 741 q 261 860 193 860 q 287 860 273 860 q 308 854 302 855 m 288 842 l 263 843 q 213 796 213 843 q 248 756 213 756 q 288 796 288 756 l 288 842 m 566 988 l 502 988 l 502 -1 l 439 -1 l 439 988 l 317 988 l 317 -1 l 252 -1 l 252 602 q 81 653 155 602 q 0 805 0 711 q 101 989 0 918 q 309 1053 194 1053 l 566 1053 l 566 988 "},"β":{"x_min":0,"x_max":660,"ha":745,"o":"m 471 550 q 610 450 561 522 q 660 280 660 378 q 578 64 660 151 q 367 -22 497 -22 q 239 5 299 -22 q 126 82 178 32 l 126 -278 l 0 -278 l 0 593 q 54 903 0 801 q 318 1042 127 1042 q 519 964 436 1042 q 603 771 603 887 q 567 644 603 701 q 471 550 532 586 m 337 79 q 476 138 418 79 q 535 279 535 198 q 427 437 535 386 q 226 477 344 477 l 226 583 q 398 620 329 583 q 486 762 486 668 q 435 884 486 833 q 312 935 384 935 q 169 861 219 935 q 126 698 126 797 l 126 362 q 170 169 126 242 q 337 79 224 79 "},"Μ":{"x_min":0,"x_max":954,"ha":1068,"o":"m 954 0 l 819 0 l 819 868 l 537 0 l 405 0 l 128 865 l 128 0 l 0 0 l 0 1013 l 199 1013 l 472 158 l 758 1013 l 954 1013 l 954 0 "},"Ό":{"x_min":0.109375,"x_max":1120,"ha":1217,"o":"m 1120 505 q 994 132 1120 282 q 642 -29 861 -29 q 290 130 422 -29 q 167 505 167 280 q 294 883 167 730 q 650 1046 430 1046 q 999 882 868 1046 q 1120 505 1120 730 m 977 504 q 896 784 977 669 q 644 915 804 915 q 391 785 484 915 q 307 504 307 669 q 391 224 307 339 q 644 95 486 95 q 894 224 803 95 q 977 504 977 339 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Ή":{"x_min":0,"x_max":1158,"ha":1275,"o":"m 1158 0 l 1022 0 l 1022 475 l 496 475 l 496 0 l 356 0 l 356 1012 l 496 1012 l 496 599 l 1022 599 l 1022 1012 l 1158 1012 l 1158 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"•":{"x_min":0,"x_max":663.890625,"ha":775,"o":"m 663 529 q 566 293 663 391 q 331 196 469 196 q 97 294 194 196 q 0 529 0 393 q 96 763 0 665 q 331 861 193 861 q 566 763 469 861 q 663 529 663 665 "},"¥":{"x_min":0.1875,"x_max":819.546875,"ha":886,"o":"m 563 561 l 697 561 l 696 487 l 520 487 l 482 416 l 482 380 l 697 380 l 695 308 l 482 308 l 482 0 l 342 0 l 342 308 l 125 308 l 125 380 l 342 380 l 342 417 l 303 487 l 125 487 l 125 561 l 258 561 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 l 563 561 "},"(":{"x_min":0,"x_max":318.0625,"ha":415,"o":"m 318 -290 l 230 -290 q 61 23 122 -142 q 0 365 0 190 q 62 712 0 540 q 230 1024 119 869 l 318 1024 q 175 705 219 853 q 125 360 125 542 q 176 22 125 187 q 318 -290 223 -127 "},"U":{"x_min":0,"x_max":796,"ha":904,"o":"m 796 393 q 681 93 796 212 q 386 -25 566 -25 q 101 95 208 -25 q 0 393 0 211 l 0 1013 l 138 1013 l 138 391 q 204 191 138 270 q 394 107 276 107 q 586 191 512 107 q 656 391 656 270 l 656 1013 l 796 1013 l 796 393 "},"γ":{"x_min":0.5,"x_max":744.953125,"ha":822,"o":"m 744 737 l 463 54 l 463 -278 l 338 -278 l 338 54 l 154 495 q 104 597 124 569 q 13 651 67 651 l 0 651 l 0 751 l 39 753 q 168 711 121 753 q 242 594 207 676 l 403 208 l 617 737 l 744 737 "},"α":{"x_min":0,"x_max":765.5625,"ha":809,"o":"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 728 407 760 q 563 637 524 696 l 563 739 l 685 739 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 96 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 "},"F":{"x_min":0,"x_max":683.328125,"ha":717,"o":"m 683 888 l 140 888 l 140 583 l 613 583 l 613 458 l 140 458 l 140 0 l 0 0 l 0 1013 l 683 1013 l 683 888 "},"­":{"x_min":0,"x_max":705.5625,"ha":803,"o":"m 705 334 l 0 334 l 0 410 l 705 410 l 705 334 "},":":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"Χ":{"x_min":0,"x_max":854.171875,"ha":935,"o":"m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 427 637 l 675 1013 l 836 1013 l 504 521 l 854 0 "},"*":{"x_min":116,"x_max":674,"ha":792,"o":"m 674 768 l 475 713 l 610 544 l 517 477 l 394 652 l 272 478 l 178 544 l 314 713 l 116 766 l 153 876 l 341 812 l 342 1013 l 446 1013 l 446 811 l 635 874 l 674 768 "},"†":{"x_min":0,"x_max":777,"ha":835,"o":"m 458 804 l 777 804 l 777 683 l 458 683 l 458 0 l 319 0 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 "},"°":{"x_min":0,"x_max":347,"ha":444,"o":"m 173 802 q 43 856 91 802 q 0 977 0 905 q 45 1101 0 1049 q 173 1153 90 1153 q 303 1098 255 1153 q 347 977 347 1049 q 303 856 347 905 q 173 802 256 802 m 173 884 q 238 910 214 884 q 262 973 262 937 q 239 1038 262 1012 q 173 1064 217 1064 q 108 1037 132 1064 q 85 973 85 1010 q 108 910 85 937 q 173 884 132 884 "},"V":{"x_min":0,"x_max":862.71875,"ha":940,"o":"m 862 1013 l 505 0 l 361 0 l 0 1013 l 143 1013 l 434 165 l 718 1012 l 862 1013 "},"Ξ":{"x_min":0,"x_max":734.71875,"ha":763,"o":"m 723 889 l 9 889 l 9 1013 l 723 1013 l 723 889 m 673 463 l 61 463 l 61 589 l 673 589 l 673 463 m 734 0 l 0 0 l 0 124 l 734 124 l 734 0 "}," ":{"x_min":0,"x_max":0,"ha":853},"Ϋ":{"x_min":0.328125,"x_max":819.515625,"ha":889,"o":"m 588 1046 l 460 1046 l 460 1189 l 588 1189 l 588 1046 m 360 1046 l 232 1046 l 232 1189 l 360 1189 l 360 1046 m 819 1012 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1012 l 140 1012 l 411 533 l 679 1012 l 819 1012 "},"0":{"x_min":73,"x_max":715,"ha":792,"o":"m 394 -29 q 153 129 242 -29 q 73 479 73 272 q 152 829 73 687 q 394 989 241 989 q 634 829 545 989 q 715 479 715 684 q 635 129 715 270 q 394 -29 546 -29 m 394 89 q 546 211 489 89 q 598 479 598 322 q 548 748 598 640 q 394 871 491 871 q 241 748 298 871 q 190 479 190 637 q 239 211 190 319 q 394 89 296 89 "},"”":{"x_min":0,"x_max":347,"ha":454,"o":"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 m 347 851 q 310 737 347 784 q 208 669 273 690 l 208 734 q 267 787 250 741 q 280 873 280 821 l 208 873 l 208 1013 l 347 1013 l 347 851 "},"@":{"x_min":0,"x_max":1260,"ha":1357,"o":"m 1098 -45 q 877 -160 1001 -117 q 633 -203 752 -203 q 155 -29 327 -203 q 0 360 0 127 q 176 802 0 616 q 687 1008 372 1008 q 1123 854 969 1008 q 1260 517 1260 718 q 1155 216 1260 341 q 868 82 1044 82 q 772 106 801 82 q 737 202 737 135 q 647 113 700 144 q 527 82 594 82 q 367 147 420 82 q 314 312 314 212 q 401 565 314 452 q 639 690 498 690 q 810 588 760 690 l 849 668 l 938 668 q 877 441 900 532 q 833 226 833 268 q 853 182 833 198 q 902 167 873 167 q 1088 272 1012 167 q 1159 512 1159 372 q 1051 793 1159 681 q 687 925 925 925 q 248 747 415 925 q 97 361 97 586 q 226 26 97 159 q 627 -122 370 -122 q 856 -87 737 -122 q 1061 8 976 -53 l 1098 -45 m 786 488 q 738 580 777 545 q 643 615 700 615 q 483 517 548 615 q 425 322 425 430 q 457 203 425 250 q 552 156 490 156 q 722 273 665 156 q 786 488 738 309 "},"Ί":{"x_min":0,"x_max":499,"ha":613,"o":"m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 m 499 0 l 360 0 l 360 1012 l 499 1012 l 499 0 "},"i":{"x_min":14,"x_max":136,"ha":275,"o":"m 136 873 l 14 873 l 14 1013 l 136 1013 l 136 873 m 136 0 l 14 0 l 14 737 l 136 737 l 136 0 "},"Β":{"x_min":0,"x_max":778,"ha":877,"o":"m 580 545 q 724 468 671 534 q 778 310 778 402 q 673 83 778 170 q 432 0 575 0 l 0 0 l 0 1013 l 411 1013 q 629 957 541 1013 q 732 768 732 891 q 691 632 732 692 q 580 545 650 571 m 393 899 l 139 899 l 139 587 l 379 587 q 521 623 462 587 q 592 744 592 666 q 531 859 592 819 q 393 899 471 899 m 419 124 q 566 169 504 124 q 635 302 635 219 q 559 435 635 388 q 402 476 494 476 l 139 476 l 139 124 l 419 124 "},"υ":{"x_min":0,"x_max":617,"ha":725,"o":"m 617 352 q 540 94 617 199 q 308 -24 455 -24 q 76 94 161 -24 q 0 352 0 199 l 0 739 l 126 739 l 126 355 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 355 492 257 l 492 739 l 617 739 l 617 352 "},"]":{"x_min":0,"x_max":275,"ha":372,"o":"m 275 -281 l 0 -281 l 0 -187 l 151 -187 l 151 920 l 0 920 l 0 1013 l 275 1013 l 275 -281 "},"m":{"x_min":0,"x_max":1019,"ha":1128,"o":"m 1019 0 l 897 0 l 897 454 q 860 591 897 536 q 739 660 816 660 q 613 586 659 660 q 573 436 573 522 l 573 0 l 447 0 l 447 455 q 412 591 447 535 q 294 657 372 657 q 165 586 213 657 q 122 437 122 521 l 122 0 l 0 0 l 0 738 l 117 738 l 117 640 q 202 730 150 697 q 316 763 254 763 q 437 730 381 763 q 525 642 494 697 q 621 731 559 700 q 753 763 682 763 q 943 694 867 763 q 1019 512 1019 625 l 1019 0 "},"χ":{"x_min":8.328125,"x_max":780.5625,"ha":815,"o":"m 780 -278 q 715 -294 747 -294 q 616 -257 663 -294 q 548 -175 576 -227 l 379 133 l 143 -277 l 9 -277 l 313 254 l 163 522 q 127 586 131 580 q 36 640 91 640 q 8 637 27 640 l 8 752 l 52 757 q 162 719 113 757 q 236 627 200 690 l 383 372 l 594 737 l 726 737 l 448 250 l 625 -69 q 670 -153 647 -110 q 743 -188 695 -188 q 780 -184 759 -188 l 780 -278 "},"8":{"x_min":55,"x_max":736,"ha":792,"o":"m 571 527 q 694 424 652 491 q 736 280 736 358 q 648 71 736 158 q 395 -26 551 -26 q 142 69 238 -26 q 55 279 55 157 q 96 425 55 359 q 220 527 138 491 q 120 615 153 562 q 88 726 88 668 q 171 904 88 827 q 395 986 261 986 q 618 905 529 986 q 702 727 702 830 q 670 616 702 667 q 571 527 638 565 m 394 565 q 519 610 475 565 q 563 717 563 655 q 521 823 563 781 q 392 872 474 872 q 265 824 312 872 q 224 720 224 783 q 265 613 224 656 q 394 565 312 565 m 395 91 q 545 150 488 91 q 597 280 597 204 q 546 408 597 355 q 395 465 492 465 q 244 408 299 465 q 194 280 194 356 q 244 150 194 203 q 395 91 299 91 "},"ί":{"x_min":42,"x_max":326.71875,"ha":361,"o":"m 284 3 q 233 -10 258 -5 q 182 -15 207 -15 q 85 26 119 -15 q 42 200 42 79 l 42 737 l 167 737 l 168 215 q 172 141 168 157 q 226 101 183 101 q 248 102 239 101 q 284 112 257 104 l 284 3 m 326 1040 l 137 819 l 54 819 l 189 1040 l 326 1040 "},"Ζ":{"x_min":0,"x_max":779.171875,"ha":850,"o":"m 779 0 l 0 0 l 0 113 l 620 896 l 40 896 l 40 1013 l 779 1013 l 779 887 l 170 124 l 779 124 l 779 0 "},"R":{"x_min":0,"x_max":781.953125,"ha":907,"o":"m 781 0 l 623 0 q 587 242 590 52 q 407 433 585 433 l 138 433 l 138 0 l 0 0 l 0 1013 l 396 1013 q 636 946 539 1013 q 749 731 749 868 q 711 597 749 659 q 608 502 674 534 q 718 370 696 474 q 729 207 722 352 q 781 26 736 62 l 781 0 m 373 551 q 533 594 465 551 q 614 731 614 645 q 532 859 614 815 q 373 896 465 896 l 138 896 l 138 551 l 373 551 "},"o":{"x_min":0,"x_max":713,"ha":821,"o":"m 357 -25 q 94 91 194 -25 q 0 368 0 202 q 93 642 0 533 q 357 761 193 761 q 618 644 518 761 q 713 368 713 533 q 619 91 713 201 q 357 -25 521 -25 m 357 85 q 528 175 465 85 q 584 369 584 255 q 529 562 584 484 q 357 651 467 651 q 189 560 250 651 q 135 369 135 481 q 187 177 135 257 q 357 85 250 85 "},"5":{"x_min":54.171875,"x_max":738,"ha":792,"o":"m 738 314 q 626 60 738 153 q 382 -23 526 -23 q 155 47 248 -23 q 54 256 54 125 l 183 256 q 259 132 204 174 q 382 91 314 91 q 533 149 471 91 q 602 314 602 213 q 538 469 602 411 q 386 528 475 528 q 284 506 332 528 q 197 439 237 484 l 81 439 l 159 958 l 684 958 l 684 840 l 254 840 l 214 579 q 306 627 258 612 q 407 643 354 643 q 636 552 540 643 q 738 314 738 457 "},"7":{"x_min":58.71875,"x_max":730.953125,"ha":792,"o":"m 730 839 q 469 448 560 641 q 335 0 378 255 l 192 0 q 328 441 235 252 q 593 830 421 630 l 58 830 l 58 958 l 730 958 l 730 839 "},"K":{"x_min":0,"x_max":819.46875,"ha":906,"o":"m 819 0 l 649 0 l 294 509 l 139 355 l 139 0 l 0 0 l 0 1013 l 139 1013 l 139 526 l 626 1013 l 809 1013 l 395 600 l 819 0 "},",":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 -12 q 105 -132 142 -82 q 0 -205 68 -182 l 0 -138 q 57 -82 40 -124 q 70 0 70 -51 l 0 0 l 0 151 l 142 151 l 142 -12 "},"d":{"x_min":0,"x_max":683,"ha":796,"o":"m 683 0 l 564 0 l 564 93 q 456 6 516 38 q 327 -25 395 -25 q 87 100 181 -25 q 0 365 0 215 q 90 639 0 525 q 343 763 187 763 q 564 647 486 763 l 564 1013 l 683 1013 l 683 0 m 582 373 q 529 562 582 484 q 361 653 468 653 q 190 561 253 653 q 135 365 135 479 q 189 175 135 254 q 358 85 251 85 q 529 178 468 85 q 582 373 582 258 "},"¨":{"x_min":-109,"x_max":247,"ha":232,"o":"m 247 1046 l 119 1046 l 119 1189 l 247 1189 l 247 1046 m 19 1046 l -109 1046 l -109 1189 l 19 1189 l 19 1046 "},"E":{"x_min":0,"x_max":736.109375,"ha":789,"o":"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},"Y":{"x_min":0,"x_max":820,"ha":886,"o":"m 820 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 534 l 679 1012 l 820 1013 "},"\"":{"x_min":0,"x_max":299,"ha":396,"o":"m 299 606 l 203 606 l 203 988 l 299 988 l 299 606 m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"‹":{"x_min":17.984375,"x_max":773.609375,"ha":792,"o":"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"„":{"x_min":0,"x_max":364,"ha":467,"o":"m 141 -12 q 104 -132 141 -82 q 0 -205 67 -182 l 0 -138 q 56 -82 40 -124 q 69 0 69 -51 l 0 0 l 0 151 l 141 151 l 141 -12 m 364 -12 q 327 -132 364 -82 q 222 -205 290 -182 l 222 -138 q 279 -82 262 -124 q 292 0 292 -51 l 222 0 l 222 151 l 364 151 l 364 -12 "},"δ":{"x_min":1,"x_max":710,"ha":810,"o":"m 710 360 q 616 87 710 196 q 356 -28 518 -28 q 99 82 197 -28 q 1 356 1 192 q 100 606 1 509 q 355 703 199 703 q 180 829 288 754 q 70 903 124 866 l 70 1012 l 643 1012 l 643 901 l 258 901 q 462 763 422 794 q 636 592 577 677 q 710 360 710 485 m 584 365 q 552 501 584 447 q 451 602 521 555 q 372 611 411 611 q 197 541 258 611 q 136 355 136 472 q 190 171 136 245 q 358 85 252 85 q 528 173 465 85 q 584 365 584 252 "},"έ":{"x_min":0,"x_max":634.71875,"ha":714,"o":"m 634 234 q 527 38 634 110 q 300 -25 433 -25 q 98 29 183 -25 q 0 204 0 93 q 37 313 0 265 q 128 390 67 352 q 56 459 82 419 q 26 555 26 505 q 114 712 26 654 q 295 763 191 763 q 499 700 416 763 q 589 515 589 631 l 478 515 q 419 618 464 580 q 307 657 374 657 q 207 630 253 657 q 151 547 151 598 q 238 445 151 469 q 389 434 280 434 l 389 331 l 349 331 q 206 315 255 331 q 125 210 125 287 q 183 107 125 145 q 302 76 233 76 q 436 117 379 76 q 509 234 493 159 l 634 234 m 520 1040 l 331 819 l 248 819 l 383 1040 l 520 1040 "},"ω":{"x_min":0,"x_max":922,"ha":1031,"o":"m 922 339 q 856 97 922 203 q 650 -26 780 -26 q 538 9 587 -26 q 461 103 489 44 q 387 12 436 46 q 277 -22 339 -22 q 69 97 147 -22 q 0 339 0 203 q 45 551 0 444 q 161 738 84 643 l 302 738 q 175 553 219 647 q 124 336 124 446 q 155 179 124 249 q 275 88 197 88 q 375 163 341 88 q 400 294 400 219 l 400 572 l 524 572 l 524 294 q 561 135 524 192 q 643 88 591 88 q 762 182 719 88 q 797 342 797 257 q 745 556 797 450 q 619 738 705 638 l 760 738 q 874 551 835 640 q 922 339 922 444 "},"´":{"x_min":0,"x_max":96,"ha":251,"o":"m 96 606 l 0 606 l 0 988 l 96 988 l 96 606 "},"±":{"x_min":11,"x_max":781,"ha":792,"o":"m 781 490 l 446 490 l 446 255 l 349 255 l 349 490 l 11 490 l 11 586 l 349 586 l 349 819 l 446 819 l 446 586 l 781 586 l 781 490 m 781 21 l 11 21 l 11 115 l 781 115 l 781 21 "},"|":{"x_min":343,"x_max":449,"ha":792,"o":"m 449 462 l 343 462 l 343 986 l 449 986 l 449 462 m 449 -242 l 343 -242 l 343 280 l 449 280 l 449 -242 "},"ϋ":{"x_min":0,"x_max":617,"ha":725,"o":"m 482 800 l 372 800 l 372 925 l 482 925 l 482 800 m 239 800 l 129 800 l 129 925 l 239 925 l 239 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 "},"§":{"x_min":0,"x_max":593,"ha":690,"o":"m 593 425 q 554 312 593 369 q 467 233 516 254 q 537 83 537 172 q 459 -74 537 -12 q 288 -133 387 -133 q 115 -69 184 -133 q 47 96 47 -6 l 166 96 q 199 7 166 40 q 288 -26 232 -26 q 371 -5 332 -26 q 420 60 420 21 q 311 201 420 139 q 108 309 210 255 q 0 490 0 383 q 33 602 0 551 q 124 687 66 654 q 75 743 93 712 q 58 812 58 773 q 133 984 58 920 q 300 1043 201 1043 q 458 987 394 1043 q 529 814 529 925 l 411 814 q 370 908 404 877 q 289 939 336 939 q 213 911 246 939 q 180 841 180 883 q 286 720 180 779 q 484 612 480 615 q 593 425 593 534 m 467 409 q 355 544 467 473 q 196 630 228 612 q 146 587 162 609 q 124 525 124 558 q 239 387 124 462 q 398 298 369 315 q 448 345 429 316 q 467 409 467 375 "},"b":{"x_min":0,"x_max":685,"ha":783,"o":"m 685 372 q 597 99 685 213 q 347 -25 501 -25 q 219 5 277 -25 q 121 93 161 36 l 121 0 l 0 0 l 0 1013 l 121 1013 l 121 634 q 214 723 157 692 q 341 754 272 754 q 591 637 493 754 q 685 372 685 526 m 554 356 q 499 550 554 470 q 328 644 437 644 q 162 556 223 644 q 108 369 108 478 q 160 176 108 256 q 330 83 221 83 q 498 169 435 83 q 554 356 554 245 "},"q":{"x_min":0,"x_max":683,"ha":876,"o":"m 683 -278 l 564 -278 l 564 97 q 474 8 533 39 q 345 -23 415 -23 q 91 93 188 -23 q 0 364 0 203 q 87 635 0 522 q 337 760 184 760 q 466 727 408 760 q 564 637 523 695 l 564 737 l 683 737 l 683 -278 m 582 375 q 527 564 582 488 q 358 652 466 652 q 190 565 253 652 q 135 377 135 488 q 189 179 135 261 q 361 84 251 84 q 530 179 469 84 q 582 375 582 260 "},"Ω":{"x_min":-0.171875,"x_max":969.5625,"ha":1068,"o":"m 969 0 l 555 0 l 555 123 q 744 308 675 194 q 814 558 814 423 q 726 812 814 709 q 484 922 633 922 q 244 820 334 922 q 154 567 154 719 q 223 316 154 433 q 412 123 292 199 l 412 0 l 0 0 l 0 124 l 217 124 q 68 327 122 210 q 15 572 15 444 q 144 911 15 781 q 484 1041 274 1041 q 822 909 691 1041 q 953 569 953 777 q 899 326 953 443 q 750 124 846 210 l 969 124 l 969 0 "},"ύ":{"x_min":0,"x_max":617,"ha":725,"o":"m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 535 1040 l 346 819 l 262 819 l 397 1040 l 535 1040 "},"z":{"x_min":-0.015625,"x_max":613.890625,"ha":697,"o":"m 613 0 l 0 0 l 0 100 l 433 630 l 20 630 l 20 738 l 594 738 l 593 636 l 163 110 l 613 110 l 613 0 "},"™":{"x_min":0,"x_max":894,"ha":1000,"o":"m 389 951 l 229 951 l 229 503 l 160 503 l 160 951 l 0 951 l 0 1011 l 389 1011 l 389 951 m 894 503 l 827 503 l 827 939 l 685 503 l 620 503 l 481 937 l 481 503 l 417 503 l 417 1011 l 517 1011 l 653 580 l 796 1010 l 894 1011 l 894 503 "},"ή":{"x_min":0.78125,"x_max":697,"ha":810,"o":"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 721 124 755 q 200 630 193 687 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 m 479 1040 l 290 819 l 207 819 l 341 1040 l 479 1040 "},"Θ":{"x_min":0,"x_max":960,"ha":1056,"o":"m 960 507 q 833 129 960 280 q 476 -32 698 -32 q 123 129 255 -32 q 0 507 0 280 q 123 883 0 732 q 476 1045 255 1045 q 832 883 696 1045 q 960 507 960 732 m 817 500 q 733 789 817 669 q 476 924 639 924 q 223 792 317 924 q 142 507 142 675 q 222 222 142 339 q 476 89 315 89 q 730 218 636 89 q 817 500 817 334 m 716 449 l 243 449 l 243 571 l 716 571 l 716 449 "},"®":{"x_min":-3,"x_max":1008,"ha":1106,"o":"m 503 532 q 614 562 566 532 q 672 658 672 598 q 614 747 672 716 q 503 772 569 772 l 338 772 l 338 532 l 503 532 m 502 -7 q 123 151 263 -7 q -3 501 -3 294 q 123 851 -3 706 q 502 1011 263 1011 q 881 851 739 1011 q 1008 501 1008 708 q 883 151 1008 292 q 502 -7 744 -7 m 502 60 q 830 197 709 60 q 940 501 940 322 q 831 805 940 681 q 502 944 709 944 q 174 805 296 944 q 65 501 65 680 q 173 197 65 320 q 502 60 294 60 m 788 146 l 678 146 q 653 316 655 183 q 527 449 652 449 l 338 449 l 338 146 l 241 146 l 241 854 l 518 854 q 688 808 621 854 q 766 658 766 755 q 739 563 766 607 q 668 497 713 519 q 751 331 747 472 q 788 164 756 190 l 788 146 "},"~":{"x_min":0,"x_max":833,"ha":931,"o":"m 833 958 q 778 753 833 831 q 594 665 716 665 q 402 761 502 665 q 240 857 302 857 q 131 795 166 857 q 104 665 104 745 l 0 665 q 54 867 0 789 q 237 958 116 958 q 429 861 331 958 q 594 765 527 765 q 704 827 670 765 q 729 958 729 874 l 833 958 "},"Ε":{"x_min":0,"x_max":736.21875,"ha":778,"o":"m 736 0 l 0 0 l 0 1013 l 725 1013 l 725 889 l 139 889 l 139 585 l 677 585 l 677 467 l 139 467 l 139 125 l 736 125 l 736 0 "},"³":{"x_min":0,"x_max":450,"ha":547,"o":"m 450 552 q 379 413 450 464 q 220 366 313 366 q 69 414 130 366 q 0 567 0 470 l 85 567 q 126 470 85 504 q 225 437 168 437 q 320 467 280 437 q 360 552 360 498 q 318 632 360 608 q 213 657 276 657 q 195 657 203 657 q 176 657 181 657 l 176 722 q 279 733 249 722 q 334 815 334 752 q 300 881 334 856 q 220 907 267 907 q 133 875 169 907 q 97 781 97 844 l 15 781 q 78 926 15 875 q 220 972 135 972 q 364 930 303 972 q 426 817 426 888 q 344 697 426 733 q 421 642 392 681 q 450 552 450 603 "},"[":{"x_min":0,"x_max":273.609375,"ha":371,"o":"m 273 -281 l 0 -281 l 0 1013 l 273 1013 l 273 920 l 124 920 l 124 -187 l 273 -187 l 273 -281 "},"L":{"x_min":0,"x_max":645.828125,"ha":696,"o":"m 645 0 l 0 0 l 0 1013 l 140 1013 l 140 126 l 645 126 l 645 0 "},"σ":{"x_min":0,"x_max":803.390625,"ha":894,"o":"m 803 628 l 633 628 q 713 368 713 512 q 618 93 713 204 q 357 -25 518 -25 q 94 91 194 -25 q 0 368 0 201 q 94 644 0 533 q 356 761 194 761 q 481 750 398 761 q 608 739 564 739 l 803 739 l 803 628 m 360 85 q 529 180 467 85 q 584 374 584 262 q 527 566 584 490 q 352 651 463 651 q 187 559 247 651 q 135 368 135 478 q 189 175 135 254 q 360 85 251 85 "},"ζ":{"x_min":0,"x_max":573,"ha":642,"o":"m 573 -40 q 553 -162 573 -97 q 510 -278 543 -193 l 400 -278 q 441 -187 428 -219 q 462 -90 462 -132 q 378 -14 462 -14 q 108 45 197 -14 q 0 290 0 117 q 108 631 0 462 q 353 901 194 767 l 55 901 l 55 1012 l 561 1012 l 561 924 q 261 669 382 831 q 128 301 128 489 q 243 117 128 149 q 458 98 350 108 q 573 -40 573 80 "},"θ":{"x_min":0,"x_max":674,"ha":778,"o":"m 674 496 q 601 160 674 304 q 336 -26 508 -26 q 73 153 165 -26 q 0 485 0 296 q 72 840 0 683 q 343 1045 166 1045 q 605 844 516 1045 q 674 496 674 692 m 546 579 q 498 798 546 691 q 336 935 437 935 q 178 798 237 935 q 126 579 137 701 l 546 579 m 546 475 l 126 475 q 170 233 126 348 q 338 80 230 80 q 504 233 447 80 q 546 475 546 346 "},"Ο":{"x_min":0,"x_max":958,"ha":1054,"o":"m 485 1042 q 834 883 703 1042 q 958 511 958 735 q 834 136 958 287 q 481 -26 701 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 729 q 485 1042 263 1042 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 670 q 480 913 640 913 q 226 785 321 913 q 142 504 142 671 q 226 224 142 339 q 480 98 319 98 "},"Γ":{"x_min":0,"x_max":705.28125,"ha":749,"o":"m 705 886 l 140 886 l 140 0 l 0 0 l 0 1012 l 705 1012 l 705 886 "}," ":{"x_min":0,"x_max":0,"ha":375},"%":{"x_min":-3,"x_max":1089,"ha":1186,"o":"m 845 0 q 663 76 731 0 q 602 244 602 145 q 661 412 602 344 q 845 489 728 489 q 1027 412 959 489 q 1089 244 1089 343 q 1029 76 1089 144 q 845 0 962 0 m 844 103 q 945 143 909 103 q 981 243 981 184 q 947 340 981 301 q 844 385 909 385 q 744 342 781 385 q 708 243 708 300 q 741 147 708 186 q 844 103 780 103 m 888 986 l 284 -25 l 199 -25 l 803 986 l 888 986 m 241 468 q 58 545 126 468 q -3 715 -3 615 q 56 881 -3 813 q 238 958 124 958 q 421 881 353 958 q 483 712 483 813 q 423 544 483 612 q 241 468 356 468 m 241 855 q 137 811 175 855 q 100 710 100 768 q 136 612 100 653 q 240 572 172 572 q 344 614 306 572 q 382 713 382 656 q 347 810 382 771 q 241 855 308 855 "},"P":{"x_min":0,"x_max":726,"ha":806,"o":"m 424 1013 q 640 931 555 1013 q 726 719 726 850 q 637 506 726 587 q 413 426 548 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 379 889 l 140 889 l 140 548 l 372 548 q 522 589 459 548 q 593 720 593 637 q 528 845 593 801 q 379 889 463 889 "},"Έ":{"x_min":0,"x_max":1078.21875,"ha":1118,"o":"m 1078 0 l 342 0 l 342 1013 l 1067 1013 l 1067 889 l 481 889 l 481 585 l 1019 585 l 1019 467 l 481 467 l 481 125 l 1078 125 l 1078 0 m 277 1040 l 83 799 l 0 799 l 140 1040 l 277 1040 "},"Ώ":{"x_min":0.125,"x_max":1136.546875,"ha":1235,"o":"m 1136 0 l 722 0 l 722 123 q 911 309 842 194 q 981 558 981 423 q 893 813 981 710 q 651 923 800 923 q 411 821 501 923 q 321 568 321 720 q 390 316 321 433 q 579 123 459 200 l 579 0 l 166 0 l 166 124 l 384 124 q 235 327 289 210 q 182 572 182 444 q 311 912 182 782 q 651 1042 441 1042 q 989 910 858 1042 q 1120 569 1120 778 q 1066 326 1120 443 q 917 124 1013 210 l 1136 124 l 1136 0 m 277 1040 l 83 800 l 0 800 l 140 1041 l 277 1040 "},"_":{"x_min":0,"x_max":705.5625,"ha":803,"o":"m 705 -334 l 0 -334 l 0 -234 l 705 -234 l 705 -334 "},"Ϊ":{"x_min":-110,"x_max":246,"ha":275,"o":"m 246 1046 l 118 1046 l 118 1189 l 246 1189 l 246 1046 m 18 1046 l -110 1046 l -110 1189 l 18 1189 l 18 1046 m 136 0 l 0 0 l 0 1012 l 136 1012 l 136 0 "},"+":{"x_min":23,"x_max":768,"ha":792,"o":"m 768 372 l 444 372 l 444 0 l 347 0 l 347 372 l 23 372 l 23 468 l 347 468 l 347 840 l 444 840 l 444 468 l 768 468 l 768 372 "},"½":{"x_min":0,"x_max":1050,"ha":1149,"o":"m 1050 0 l 625 0 q 712 178 625 108 q 878 277 722 187 q 967 385 967 328 q 932 456 967 429 q 850 484 897 484 q 759 450 798 484 q 721 352 721 416 l 640 352 q 706 502 640 448 q 851 551 766 551 q 987 509 931 551 q 1050 385 1050 462 q 976 251 1050 301 q 829 179 902 215 q 717 68 740 133 l 1050 68 l 1050 0 m 834 985 l 215 -28 l 130 -28 l 750 984 l 834 985 m 224 422 l 142 422 l 142 811 l 0 811 l 0 867 q 104 889 62 867 q 164 973 157 916 l 224 973 l 224 422 "},"Ρ":{"x_min":0,"x_max":720,"ha":783,"o":"m 424 1013 q 637 933 554 1013 q 720 723 720 853 q 633 508 720 591 q 413 426 546 426 l 140 426 l 140 0 l 0 0 l 0 1013 l 424 1013 m 378 889 l 140 889 l 140 548 l 371 548 q 521 589 458 548 q 592 720 592 637 q 527 845 592 801 q 378 889 463 889 "},"'":{"x_min":0,"x_max":139,"ha":236,"o":"m 139 851 q 102 737 139 784 q 0 669 65 690 l 0 734 q 59 787 42 741 q 72 873 72 821 l 0 873 l 0 1013 l 139 1013 l 139 851 "},"ª":{"x_min":0,"x_max":350,"ha":397,"o":"m 350 625 q 307 616 328 616 q 266 631 281 616 q 247 673 251 645 q 190 628 225 644 q 116 613 156 613 q 32 641 64 613 q 0 722 0 669 q 72 826 0 800 q 247 866 159 846 l 247 887 q 220 934 247 916 q 162 953 194 953 q 104 934 129 953 q 76 882 80 915 l 16 882 q 60 976 16 941 q 166 1011 104 1011 q 266 979 224 1011 q 308 891 308 948 l 308 706 q 311 679 308 688 q 331 670 315 670 l 350 672 l 350 625 m 247 757 l 247 811 q 136 790 175 798 q 64 726 64 773 q 83 682 64 697 q 132 667 103 667 q 207 690 174 667 q 247 757 247 718 "},"΅":{"x_min":0,"x_max":450,"ha":553,"o":"m 450 800 l 340 800 l 340 925 l 450 925 l 450 800 m 406 1040 l 212 800 l 129 800 l 269 1040 l 406 1040 m 110 800 l 0 800 l 0 925 l 110 925 l 110 800 "},"T":{"x_min":0,"x_max":777,"ha":835,"o":"m 777 894 l 458 894 l 458 0 l 319 0 l 319 894 l 0 894 l 0 1013 l 777 1013 l 777 894 "},"Φ":{"x_min":0,"x_max":915,"ha":997,"o":"m 527 0 l 389 0 l 389 122 q 110 231 220 122 q 0 509 0 340 q 110 785 0 677 q 389 893 220 893 l 389 1013 l 527 1013 l 527 893 q 804 786 693 893 q 915 509 915 679 q 805 231 915 341 q 527 122 696 122 l 527 0 m 527 226 q 712 310 641 226 q 779 507 779 389 q 712 705 779 627 q 527 787 641 787 l 527 226 m 389 226 l 389 787 q 205 698 275 775 q 136 505 136 620 q 206 308 136 391 q 389 226 276 226 "},"⁋":{"x_min":0,"x_max":0,"ha":694},"j":{"x_min":-77.78125,"x_max":167,"ha":349,"o":"m 167 871 l 42 871 l 42 1013 l 167 1013 l 167 871 m 167 -80 q 121 -231 167 -184 q -26 -278 76 -278 l -77 -278 l -77 -164 l -41 -164 q 26 -143 11 -164 q 42 -65 42 -122 l 42 737 l 167 737 l 167 -80 "},"Σ":{"x_min":0,"x_max":756.953125,"ha":819,"o":"m 756 0 l 0 0 l 0 107 l 395 523 l 22 904 l 22 1013 l 745 1013 l 745 889 l 209 889 l 566 523 l 187 125 l 756 125 l 756 0 "},"1":{"x_min":215.671875,"x_max":574,"ha":792,"o":"m 574 0 l 442 0 l 442 697 l 215 697 l 215 796 q 386 833 330 796 q 475 986 447 875 l 574 986 l 574 0 "},"›":{"x_min":18.0625,"x_max":774,"ha":792,"o":"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},"<":{"x_min":17.984375,"x_max":773.609375,"ha":792,"o":"m 773 40 l 18 376 l 17 465 l 773 799 l 773 692 l 159 420 l 773 149 l 773 40 "},"£":{"x_min":0,"x_max":704.484375,"ha":801,"o":"m 704 41 q 623 -10 664 5 q 543 -26 583 -26 q 359 15 501 -26 q 243 36 288 36 q 158 23 197 36 q 73 -21 119 10 l 6 76 q 125 195 90 150 q 175 331 175 262 q 147 443 175 383 l 0 443 l 0 512 l 108 512 q 43 734 43 623 q 120 929 43 854 q 358 1010 204 1010 q 579 936 487 1010 q 678 729 678 857 l 678 684 l 552 684 q 504 838 552 780 q 362 896 457 896 q 216 852 263 896 q 176 747 176 815 q 199 627 176 697 q 248 512 217 574 l 468 512 l 468 443 l 279 443 q 297 356 297 398 q 230 194 297 279 q 153 107 211 170 q 227 133 190 125 q 293 142 264 142 q 410 119 339 142 q 516 96 482 96 q 579 105 550 96 q 648 142 608 115 l 704 41 "},"t":{"x_min":0,"x_max":367,"ha":458,"o":"m 367 0 q 312 -5 339 -2 q 262 -8 284 -8 q 145 28 183 -8 q 108 143 108 64 l 108 638 l 0 638 l 0 738 l 108 738 l 108 944 l 232 944 l 232 738 l 367 738 l 367 638 l 232 638 l 232 185 q 248 121 232 140 q 307 102 264 102 q 345 104 330 102 q 367 107 360 107 l 367 0 "},"¬":{"x_min":0,"x_max":706,"ha":803,"o":"m 706 411 l 706 158 l 630 158 l 630 335 l 0 335 l 0 411 l 706 411 "},"λ":{"x_min":0,"x_max":750,"ha":803,"o":"m 750 -7 q 679 -15 716 -15 q 538 59 591 -15 q 466 214 512 97 l 336 551 l 126 0 l 0 0 l 270 705 q 223 837 247 770 q 116 899 190 899 q 90 898 100 899 l 90 1004 q 152 1011 125 1011 q 298 938 244 1011 q 373 783 326 901 l 605 192 q 649 115 629 136 q 716 95 669 95 l 736 95 q 750 97 745 97 l 750 -7 "},"W":{"x_min":0,"x_max":1263.890625,"ha":1351,"o":"m 1263 1013 l 995 0 l 859 0 l 627 837 l 405 0 l 265 0 l 0 1013 l 136 1013 l 342 202 l 556 1013 l 701 1013 l 921 207 l 1133 1012 l 1263 1013 "},">":{"x_min":18.0625,"x_max":774,"ha":792,"o":"m 774 376 l 18 40 l 18 149 l 631 421 l 18 692 l 18 799 l 774 465 l 774 376 "},"v":{"x_min":0,"x_max":675.15625,"ha":761,"o":"m 675 738 l 404 0 l 272 0 l 0 738 l 133 737 l 340 147 l 541 737 l 675 738 "},"τ":{"x_min":0.28125,"x_max":644.5,"ha":703,"o":"m 644 628 l 382 628 l 382 179 q 388 120 382 137 q 436 91 401 91 q 474 94 447 91 q 504 97 501 97 l 504 0 q 454 -9 482 -5 q 401 -14 426 -14 q 278 67 308 -14 q 260 233 260 118 l 260 628 l 0 628 l 0 739 l 644 739 l 644 628 "},"ξ":{"x_min":0,"x_max":624.9375,"ha":699,"o":"m 624 -37 q 608 -153 624 -96 q 563 -278 593 -211 l 454 -278 q 491 -183 486 -200 q 511 -83 511 -126 q 484 -23 511 -44 q 370 1 452 1 q 323 0 354 1 q 283 -1 293 -1 q 84 76 169 -1 q 0 266 0 154 q 56 431 0 358 q 197 538 108 498 q 94 613 134 562 q 54 730 54 665 q 77 823 54 780 q 143 901 101 867 l 27 901 l 27 1012 l 576 1012 l 576 901 l 380 901 q 244 863 303 901 q 178 745 178 820 q 312 600 178 636 q 532 582 380 582 l 532 479 q 276 455 361 479 q 118 281 118 410 q 165 173 118 217 q 274 120 208 133 q 494 101 384 110 q 624 -37 624 76 "},"&":{"x_min":-3,"x_max":894.25,"ha":992,"o":"m 894 0 l 725 0 l 624 123 q 471 0 553 40 q 306 -41 390 -41 q 168 -7 231 -41 q 62 92 105 26 q 14 187 31 139 q -3 276 -3 235 q 55 433 -3 358 q 248 581 114 508 q 170 689 196 640 q 137 817 137 751 q 214 985 137 922 q 384 1041 284 1041 q 548 988 483 1041 q 622 824 622 928 q 563 666 622 739 q 431 556 516 608 l 621 326 q 649 407 639 361 q 663 493 653 426 l 781 493 q 703 229 781 352 l 894 0 m 504 818 q 468 908 504 877 q 384 940 433 940 q 293 907 331 940 q 255 818 255 875 q 289 714 255 767 q 363 628 313 678 q 477 729 446 682 q 504 818 504 771 m 556 209 l 314 499 q 179 395 223 449 q 135 283 135 341 q 146 222 135 253 q 183 158 158 192 q 333 80 241 80 q 556 209 448 80 "},"Λ":{"x_min":0,"x_max":862.5,"ha":942,"o":"m 862 0 l 719 0 l 426 847 l 143 0 l 0 0 l 356 1013 l 501 1013 l 862 0 "},"I":{"x_min":41,"x_max":180,"ha":293,"o":"m 180 0 l 41 0 l 41 1013 l 180 1013 l 180 0 "},"G":{"x_min":0,"x_max":921,"ha":1011,"o":"m 921 0 l 832 0 l 801 136 q 655 15 741 58 q 470 -28 568 -28 q 126 133 259 -28 q 0 499 0 284 q 125 881 0 731 q 486 1043 259 1043 q 763 957 647 1043 q 905 709 890 864 l 772 709 q 668 866 747 807 q 486 926 589 926 q 228 795 322 926 q 142 507 142 677 q 228 224 142 342 q 483 94 323 94 q 712 195 625 94 q 796 435 796 291 l 477 435 l 477 549 l 921 549 l 921 0 "},"ΰ":{"x_min":0,"x_max":617,"ha":725,"o":"m 524 800 l 414 800 l 414 925 l 524 925 l 524 800 m 183 800 l 73 800 l 73 925 l 183 925 l 183 800 m 617 352 q 540 93 617 199 q 308 -24 455 -24 q 76 93 161 -24 q 0 352 0 199 l 0 738 l 126 738 l 126 354 q 169 185 126 257 q 312 98 220 98 q 451 185 402 98 q 492 354 492 257 l 492 738 l 617 738 l 617 352 m 489 1040 l 300 819 l 216 819 l 351 1040 l 489 1040 "},"`":{"x_min":0,"x_max":138.890625,"ha":236,"o":"m 138 699 l 0 699 l 0 861 q 36 974 0 929 q 138 1041 72 1020 l 138 977 q 82 931 95 969 q 69 839 69 893 l 138 839 l 138 699 "},"·":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 "},"Υ":{"x_min":0.328125,"x_max":819.515625,"ha":889,"o":"m 819 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 533 l 679 1013 l 819 1013 "},"r":{"x_min":0,"x_max":355.5625,"ha":432,"o":"m 355 621 l 343 621 q 179 569 236 621 q 122 411 122 518 l 122 0 l 0 0 l 0 737 l 117 737 l 117 604 q 204 719 146 686 q 355 753 262 753 l 355 621 "},"x":{"x_min":0,"x_max":675,"ha":764,"o":"m 675 0 l 525 0 l 331 286 l 144 0 l 0 0 l 256 379 l 12 738 l 157 737 l 336 473 l 516 738 l 661 738 l 412 380 l 675 0 "},"μ":{"x_min":0,"x_max":696.609375,"ha":747,"o":"m 696 -4 q 628 -14 657 -14 q 498 97 513 -14 q 422 8 470 41 q 313 -24 374 -24 q 207 3 258 -24 q 120 80 157 31 l 120 -278 l 0 -278 l 0 738 l 124 738 l 124 343 q 165 172 124 246 q 308 82 216 82 q 451 177 402 82 q 492 358 492 254 l 492 738 l 616 738 l 616 214 q 623 136 616 160 q 673 92 636 92 q 696 95 684 92 l 696 -4 "},"h":{"x_min":0,"x_max":615,"ha":724,"o":"m 615 472 l 615 0 l 490 0 l 490 454 q 456 590 490 535 q 338 654 416 654 q 186 588 251 654 q 122 436 122 522 l 122 0 l 0 0 l 0 1013 l 122 1013 l 122 633 q 218 727 149 694 q 362 760 287 760 q 552 676 484 760 q 615 472 615 600 "},".":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "},"φ":{"x_min":-2,"x_max":878,"ha":974,"o":"m 496 -279 l 378 -279 l 378 -17 q 101 88 204 -17 q -2 367 -2 194 q 68 626 -2 510 q 283 758 151 758 l 283 646 q 167 537 209 626 q 133 373 133 462 q 192 177 133 254 q 378 93 259 93 l 378 758 q 445 764 426 763 q 476 765 464 765 q 765 659 653 765 q 878 377 878 553 q 771 96 878 209 q 496 -17 665 -17 l 496 -279 m 496 93 l 514 93 q 687 183 623 93 q 746 380 746 265 q 691 569 746 491 q 522 658 629 658 l 496 656 l 496 93 "},";":{"x_min":0,"x_max":142,"ha":239,"o":"m 142 585 l 0 585 l 0 738 l 142 738 l 142 585 m 142 -12 q 105 -132 142 -82 q 0 -206 68 -182 l 0 -138 q 58 -82 43 -123 q 68 0 68 -56 l 0 0 l 0 151 l 142 151 l 142 -12 "},"f":{"x_min":0,"x_max":378,"ha":472,"o":"m 378 638 l 246 638 l 246 0 l 121 0 l 121 638 l 0 638 l 0 738 l 121 738 q 137 935 121 887 q 290 1028 171 1028 q 320 1027 305 1028 q 378 1021 334 1026 l 378 908 q 323 918 346 918 q 257 870 273 918 q 246 780 246 840 l 246 738 l 378 738 l 378 638 "},"“":{"x_min":1,"x_max":348.21875,"ha":454,"o":"m 140 670 l 1 670 l 1 830 q 37 943 1 897 q 140 1011 74 990 l 140 947 q 82 900 97 940 q 68 810 68 861 l 140 810 l 140 670 m 348 670 l 209 670 l 209 830 q 245 943 209 897 q 348 1011 282 990 l 348 947 q 290 900 305 940 q 276 810 276 861 l 348 810 l 348 670 "},"A":{"x_min":0.03125,"x_max":906.953125,"ha":1008,"o":"m 906 0 l 756 0 l 648 303 l 251 303 l 142 0 l 0 0 l 376 1013 l 529 1013 l 906 0 m 610 421 l 452 867 l 293 421 l 610 421 "},"6":{"x_min":53,"x_max":739,"ha":792,"o":"m 739 312 q 633 62 739 162 q 400 -31 534 -31 q 162 78 257 -31 q 53 439 53 206 q 178 859 53 712 q 441 986 284 986 q 643 912 559 986 q 732 713 732 833 l 601 713 q 544 830 594 786 q 426 875 494 875 q 268 793 331 875 q 193 517 193 697 q 301 597 240 570 q 427 624 362 624 q 643 540 552 624 q 739 312 739 451 m 603 298 q 540 461 603 400 q 404 516 484 516 q 268 461 323 516 q 207 300 207 401 q 269 137 207 198 q 405 83 325 83 q 541 137 486 83 q 603 298 603 197 "},"‘":{"x_min":1,"x_max":139.890625,"ha":236,"o":"m 139 670 l 1 670 l 1 830 q 37 943 1 897 q 139 1011 74 990 l 139 947 q 82 900 97 940 q 68 810 68 861 l 139 810 l 139 670 "},"ϊ":{"x_min":-70,"x_max":283,"ha":361,"o":"m 283 800 l 173 800 l 173 925 l 283 925 l 283 800 m 40 800 l -70 800 l -70 925 l 40 925 l 40 800 m 283 3 q 232 -10 257 -5 q 181 -15 206 -15 q 84 26 118 -15 q 41 200 41 79 l 41 737 l 166 737 l 167 215 q 171 141 167 157 q 225 101 182 101 q 247 103 238 101 q 283 112 256 104 l 283 3 "},"π":{"x_min":-0.21875,"x_max":773.21875,"ha":857,"o":"m 773 -7 l 707 -11 q 575 40 607 -11 q 552 174 552 77 l 552 226 l 552 626 l 222 626 l 222 0 l 97 0 l 97 626 l 0 626 l 0 737 l 773 737 l 773 626 l 676 626 l 676 171 q 695 103 676 117 q 773 90 714 90 l 773 -7 "},"ά":{"x_min":0,"x_max":765.5625,"ha":809,"o":"m 765 -4 q 698 -14 726 -14 q 564 97 586 -14 q 466 7 525 40 q 337 -26 407 -26 q 88 98 186 -26 q 0 369 0 212 q 88 637 0 525 q 337 760 184 760 q 465 727 407 760 q 563 637 524 695 l 563 738 l 685 738 l 685 222 q 693 141 685 168 q 748 94 708 94 q 765 95 760 94 l 765 -4 m 584 371 q 531 562 584 485 q 360 653 470 653 q 192 566 254 653 q 135 379 135 489 q 186 181 135 261 q 358 84 247 84 q 528 176 465 84 q 584 371 584 260 m 604 1040 l 415 819 l 332 819 l 466 1040 l 604 1040 "},"O":{"x_min":0,"x_max":958,"ha":1057,"o":"m 485 1041 q 834 882 702 1041 q 958 512 958 734 q 834 136 958 287 q 481 -26 702 -26 q 126 130 261 -26 q 0 504 0 279 q 127 880 0 728 q 485 1041 263 1041 m 480 98 q 731 225 638 98 q 815 504 815 340 q 733 783 815 669 q 480 912 640 912 q 226 784 321 912 q 142 504 142 670 q 226 224 142 339 q 480 98 319 98 "},"n":{"x_min":0,"x_max":615,"ha":724,"o":"m 615 463 l 615 0 l 490 0 l 490 454 q 453 592 490 537 q 331 656 410 656 q 178 585 240 656 q 117 421 117 514 l 117 0 l 0 0 l 0 738 l 117 738 l 117 630 q 218 728 150 693 q 359 764 286 764 q 552 675 484 764 q 615 463 615 593 "},"3":{"x_min":54,"x_max":737,"ha":792,"o":"m 737 284 q 635 55 737 141 q 399 -25 541 -25 q 156 52 248 -25 q 54 308 54 140 l 185 308 q 245 147 185 202 q 395 96 302 96 q 539 140 484 96 q 602 280 602 190 q 510 429 602 390 q 324 454 451 454 l 324 565 q 487 584 441 565 q 565 719 565 617 q 515 835 565 791 q 395 879 466 879 q 255 824 307 879 q 203 661 203 769 l 78 661 q 166 909 78 822 q 387 992 250 992 q 603 921 513 992 q 701 723 701 844 q 669 607 701 656 q 578 524 637 558 q 696 434 655 499 q 737 284 737 369 "},"9":{"x_min":53,"x_max":739,"ha":792,"o":"m 739 524 q 619 94 739 241 q 362 -32 516 -32 q 150 47 242 -32 q 59 244 59 126 l 191 244 q 246 129 191 176 q 373 82 301 82 q 526 161 466 82 q 597 440 597 255 q 363 334 501 334 q 130 432 216 334 q 53 650 53 521 q 134 880 53 786 q 383 986 226 986 q 659 841 566 986 q 739 524 739 719 m 388 449 q 535 514 480 449 q 585 658 585 573 q 535 805 585 744 q 388 873 480 873 q 242 809 294 873 q 191 658 191 745 q 239 514 191 572 q 388 449 292 449 "},"l":{"x_min":41,"x_max":166,"ha":279,"o":"m 166 0 l 41 0 l 41 1013 l 166 1013 l 166 0 "},"¤":{"x_min":40.09375,"x_max":728.796875,"ha":825,"o":"m 728 304 l 649 224 l 512 363 q 383 331 458 331 q 256 363 310 331 l 119 224 l 40 304 l 177 441 q 150 553 150 493 q 184 673 150 621 l 40 818 l 119 898 l 267 749 q 321 766 291 759 q 384 773 351 773 q 447 766 417 773 q 501 749 477 759 l 649 898 l 728 818 l 585 675 q 612 618 604 648 q 621 553 621 587 q 591 441 621 491 l 728 304 m 384 682 q 280 643 318 682 q 243 551 243 604 q 279 461 243 499 q 383 423 316 423 q 487 461 449 423 q 525 553 525 500 q 490 641 525 605 q 384 682 451 682 "},"κ":{"x_min":0,"x_max":632.328125,"ha":679,"o":"m 632 0 l 482 0 l 225 384 l 124 288 l 124 0 l 0 0 l 0 738 l 124 738 l 124 446 l 433 738 l 596 738 l 312 466 l 632 0 "},"4":{"x_min":48,"x_max":742.453125,"ha":792,"o":"m 742 243 l 602 243 l 602 0 l 476 0 l 476 243 l 48 243 l 48 368 l 476 958 l 602 958 l 602 354 l 742 354 l 742 243 m 476 354 l 476 792 l 162 354 l 476 354 "},"p":{"x_min":0,"x_max":685,"ha":786,"o":"m 685 364 q 598 96 685 205 q 350 -23 504 -23 q 121 89 205 -23 l 121 -278 l 0 -278 l 0 738 l 121 738 l 121 633 q 220 726 159 691 q 351 761 280 761 q 598 636 504 761 q 685 364 685 522 m 557 371 q 501 560 557 481 q 330 651 437 651 q 162 559 223 651 q 108 366 108 479 q 162 177 108 254 q 333 87 224 87 q 502 178 441 87 q 557 371 557 258 "},"‡":{"x_min":0,"x_max":777,"ha":835,"o":"m 458 238 l 458 0 l 319 0 l 319 238 l 0 238 l 0 360 l 319 360 l 319 681 l 0 683 l 0 804 l 319 804 l 319 1015 l 458 1013 l 458 804 l 777 804 l 777 683 l 458 683 l 458 360 l 777 360 l 777 238 l 458 238 "},"ψ":{"x_min":0,"x_max":808,"ha":907,"o":"m 465 -278 l 341 -278 l 341 -15 q 87 102 180 -15 q 0 378 0 210 l 0 739 l 133 739 l 133 379 q 182 195 133 275 q 341 98 242 98 l 341 922 l 465 922 l 465 98 q 623 195 563 98 q 675 382 675 278 l 675 742 l 808 742 l 808 381 q 720 104 808 213 q 466 -13 627 -13 l 465 -278 "},"η":{"x_min":0.78125,"x_max":697,"ha":810,"o":"m 697 -278 l 572 -278 l 572 454 q 540 587 572 536 q 425 650 501 650 q 271 579 337 650 q 206 420 206 509 l 206 0 l 81 0 l 81 489 q 73 588 81 562 q 0 644 56 644 l 0 741 q 68 755 38 755 q 158 720 124 755 q 200 630 193 686 q 297 726 234 692 q 434 761 359 761 q 620 692 544 761 q 697 516 697 624 l 697 -278 "}},"cssFontWeight":"normal","ascender":1189,"underlinePosition":-100,"cssFontStyle":"normal","boundingBox":{"yMin":-334,"xMin":-111,"yMax":1189,"xMax":1672},"resolution":1000,"original_font_information":{"postscript_name":"Helvetiker-Regular","version_string":"Version 1.00 2004 initial release","vendor_url":"http://www.magenta.gr/","full_font_name":"Helvetiker","font_family_name":"Helvetiker","copyright":"Copyright (c) Μagenta ltd, 2004","description":"","trademark":"","designer":"","designer_url":"","unique_font_identifier":"Μagenta ltd:Helvetiker:22-10-104","license_url":"http://www.ellak.gr/fonts/MgOpen/license.html","license_description":"Copyright (c) 2004 by MAGENTA Ltd. All Rights Reserved.\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license (\"Fonts\") and associated documentation files (the \"Font Software\"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: \r\n\r\nThe above copyright and this permission notice shall be included in all copies of one or more of the Font Software typefaces.\r\n\r\nThe Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing the word \"MgOpen\", or if the modifications are accepted for inclusion in the Font Software itself by the each appointed Administrator.\r\n\r\nThis License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the \"MgOpen\" name.\r\n\r\nThe Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. \r\n\r\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL MAGENTA OR PERSONS OR BODIES IN CHARGE OF ADMINISTRATION AND MAINTENANCE OF THE FONT SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.","manufacturer_name":"Μagenta ltd","font_sub_family_name":"Regular"},"descender":-334,"familyName":"Helvetiker","lineHeight":1522,"underlineThickness":50} \ No newline at end of file diff --git a/resources/video-editor/index.html b/resources/video-editor/index.html new file mode 100644 index 00000000..37084008 --- /dev/null +++ b/resources/video-editor/index.html @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + OpenReel Video - Professional Video Editor + + + + + + + +
+ + diff --git a/resources/video-editor/manifest.json b/resources/video-editor/manifest.json new file mode 100644 index 00000000..2facf46e --- /dev/null +++ b/resources/video-editor/manifest.json @@ -0,0 +1,24 @@ +{ + "name": "OpenReel", + "short_name": "OpenReel", + "description": "Professional browser-based video, audio, and photo editing application", + "start_url": "/", + "display": "standalone", + "background_color": "#0f172a", + "theme_color": "#3b82f6", + "orientation": "landscape", + "icons": [ + { + "src": "/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "categories": ["productivity", "utilities"], + "prefer_related_applications": false +} diff --git a/resources/video-editor/sw.js b/resources/video-editor/sw.js new file mode 100644 index 00000000..311affd5 --- /dev/null +++ b/resources/video-editor/sw.js @@ -0,0 +1,316 @@ +/** + * OpenReel Service Worker + * + * Handles offline functionality by caching application assets. + * Implements a cache-first strategy for static assets and network-first for API calls. + * + * Requirements: 35.1, 35.2, 35.4 + * - 35.1: Cache all application assets on first load for offline use + * - 35.2: Function fully for all non-AI features when offline + * - 35.4: Inform user that AI requires internet connectivity + */ + +const CACHE_NAME = "openreel-v1"; +const STATIC_CACHE_NAME = "openreel-static-v1"; +const DYNAMIC_CACHE_NAME = "openreel-dynamic-v1"; + +/** + * Static assets to cache on install + * These are the core application files needed for offline functionality + */ +const STATIC_ASSETS = ["/", "/index.html", "/manifest.json"]; + +/** + * Patterns for assets that should be cached dynamically + */ +const CACHEABLE_PATTERNS = [ + /\.js$/, + /\.css$/, + /\.woff2?$/, + /\.ttf$/, + /\.eot$/, + /\.svg$/, + /\.png$/, + /\.jpg$/, + /\.jpeg$/, + /\.gif$/, + /\.webp$/, + /\.ico$/, +]; + +/** + * Patterns for requests that should never be cached (AI features, etc.) + */ +const NO_CACHE_PATTERNS = [ + /api\.anthropic\.com/, + /api\.openai\.com/, + /whisper/, + /transcribe/, + /\/api\//, +]; + +/** + * Check if a URL should be cached + */ +function shouldCache(url) { + const urlString = url.toString(); + + // Never cache AI-related requests + if (NO_CACHE_PATTERNS.some((pattern) => pattern.test(urlString))) { + return false; + } + + // Cache if matches cacheable patterns + return CACHEABLE_PATTERNS.some((pattern) => pattern.test(urlString)); +} + +/** + * Check if a request is for an AI feature + */ +function isAIRequest(url) { + const urlString = url.toString(); + return NO_CACHE_PATTERNS.some((pattern) => pattern.test(urlString)); +} + +/** + * Install event - cache static assets + */ +self.addEventListener("install", (event) => { + console.log("[ServiceWorker] Installing..."); + + event.waitUntil( + caches + .open(STATIC_CACHE_NAME) + .then((cache) => { + console.log("[ServiceWorker] Caching static assets"); + return cache.addAll(STATIC_ASSETS); + }) + .then(() => { + console.log("[ServiceWorker] Static assets cached"); + // Skip waiting to activate immediately + return self.skipWaiting(); + }) + .catch((error) => { + console.error("[ServiceWorker] Failed to cache static assets:", error); + }) + ); +}); + +/** + * Activate event - clean up old caches + */ +self.addEventListener("activate", (event) => { + console.log("[ServiceWorker] Activating..."); + + event.waitUntil( + caches + .keys() + .then((cacheNames) => { + return Promise.all( + cacheNames + .filter((name) => { + // Delete old versions of our caches + return ( + name.startsWith("openreel-") && + name !== STATIC_CACHE_NAME && + name !== DYNAMIC_CACHE_NAME + ); + }) + .map((name) => { + console.log("[ServiceWorker] Deleting old cache:", name); + return caches.delete(name); + }) + ); + }) + .then(() => { + console.log("[ServiceWorker] Activated"); + // Take control of all clients immediately + return self.clients.claim(); + }) + ); +}); + +/** + * Fetch event - serve from cache or network + */ +self.addEventListener("fetch", (event) => { + const { request } = event; + const url = new URL(request.url); + + // Skip non-GET requests + if (request.method !== "GET") { + return; + } + + // Skip chrome-extension and other non-http(s) requests + if (!url.protocol.startsWith("http")) { + return; + } + + // Handle AI requests - network only with offline message + if (isAIRequest(url)) { + event.respondWith( + fetch(request).catch(() => { + // Return a JSON response indicating AI is unavailable offline + return new Response( + JSON.stringify({ + error: "AI_OFFLINE", + message: + "AI features require an internet connection. Please connect to the internet to use this feature.", + }), + { + status: 503, + statusText: "Service Unavailable", + headers: { + "Content-Type": "application/json", + }, + } + ); + }) + ); + return; + } + + // For navigation requests (HTML pages), use network-first strategy + if (request.mode === "navigate") { + event.respondWith( + fetch(request) + .then((response) => { + // Cache the response for offline use + const responseClone = response.clone(); + caches.open(DYNAMIC_CACHE_NAME).then((cache) => { + cache.put(request, responseClone); + }); + return response; + }) + .catch(() => { + // Fall back to cache + return caches.match(request).then((cachedResponse) => { + if (cachedResponse) { + return cachedResponse; + } + // Fall back to index.html for SPA routing + return caches.match("/index.html"); + }); + }) + ); + return; + } + + // For static assets, use cache-first strategy + if (shouldCache(url)) { + event.respondWith( + caches.match(request).then((cachedResponse) => { + if (cachedResponse) { + // Return cached response and update cache in background + event.waitUntil( + fetch(request) + .then((networkResponse) => { + if (networkResponse.ok) { + caches.open(DYNAMIC_CACHE_NAME).then((cache) => { + cache.put(request, networkResponse); + }); + } + }) + .catch(() => { + // Network failed, but we have cache - that's fine + }) + ); + return cachedResponse; + } + + // Not in cache, fetch from network + return fetch(request).then((networkResponse) => { + if (networkResponse.ok) { + const responseClone = networkResponse.clone(); + caches.open(DYNAMIC_CACHE_NAME).then((cache) => { + cache.put(request, responseClone); + }); + } + return networkResponse; + }); + }) + ); + return; + } + + // For other requests, use network-first strategy + event.respondWith( + fetch(request) + .then((response) => { + return response; + }) + .catch(() => { + return caches.match(request); + }) + ); +}); + +/** + * Message event - handle messages from the main thread + */ +self.addEventListener("message", (event) => { + const { type, payload } = event.data || {}; + + switch (type) { + case "SKIP_WAITING": + self.skipWaiting(); + break; + + case "GET_CACHE_STATUS": + getCacheStatus().then((status) => { + event.ports[0].postMessage({ type: "CACHE_STATUS", payload: status }); + }); + break; + + case "CLEAR_CACHE": + clearAllCaches().then(() => { + event.ports[0].postMessage({ type: "CACHE_CLEARED" }); + }); + break; + + case "CHECK_ONLINE": + event.ports[0].postMessage({ + type: "ONLINE_STATUS", + payload: { online: navigator.onLine }, + }); + break; + } +}); + +/** + * Get cache status information + */ +async function getCacheStatus() { + const cacheNames = await caches.keys(); + let totalSize = 0; + let totalEntries = 0; + + for (const name of cacheNames) { + if (name.startsWith("openreel-")) { + const cache = await caches.open(name); + const keys = await cache.keys(); + totalEntries += keys.length; + } + } + + return { + cacheNames: cacheNames.filter((n) => n.startsWith("openreel-")), + totalEntries, + version: CACHE_NAME, + }; +} + +/** + * Clear all OpenReel caches + */ +async function clearAllCaches() { + const cacheNames = await caches.keys(); + await Promise.all( + cacheNames + .filter((name) => name.startsWith("openreel-")) + .map((name) => caches.delete(name)) + ); +} + +console.log("[ServiceWorker] Script loaded"); diff --git a/resources/video-editor/workers/.gitkeep b/resources/video-editor/workers/.gitkeep new file mode 100644 index 00000000..ede74096 --- /dev/null +++ b/resources/video-editor/workers/.gitkeep @@ -0,0 +1 @@ +# Placeholder for web workers From 30877107318869d6c5fe8d8a9e5cf72bc46b2e0b Mon Sep 17 00:00:00 2001 From: NSIETeam Date: Tue, 14 Jul 2026 11:57:44 +0800 Subject: [PATCH 3/3] fix: address code review - dead code, process detection, resource leaks --- packages/core/src/tools/video-editor.ts | 77 +++++++++++++------------ 1 file changed, 40 insertions(+), 37 deletions(-) diff --git a/packages/core/src/tools/video-editor.ts b/packages/core/src/tools/video-editor.ts index 79fd8b76..84d2d627 100644 --- a/packages/core/src/tools/video-editor.ts +++ b/packages/core/src/tools/video-editor.ts @@ -7,11 +7,12 @@ * Loads OpenReel from bundled resources (no external server needed). */ -import { exec, spawn } from 'child_process'; +import { exec, execFile, spawn, ChildProcess } from 'child_process'; import { promisify } from 'util'; import fs from 'fs'; import path from 'path'; import os from 'os'; +import { pathToFileURL } from 'url'; import { BaseTool, ToolResult, ToolCallConfirmationDetails, Icon, ToolLocation } from './tools.js'; import { Type } from '@google/genai'; import { SchemaValidator } from '../utils/schemaValidator.js'; @@ -22,7 +23,8 @@ const execAsync = promisify(exec); // OpenReel bundled path const BUNDLED_EDITOR = path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\//, '')), '..', '..', '..', 'resources', 'video-editor', 'index.html'); const DEV_URL = 'http://localhost:5174'; -const PROJECTS_DIR = path.join(os.homedir(), '.otto', 'video-projects'); +const PROJECTS_DIR = path.join(os.homedir(), '.easycode', 'video-projects'); +const PID_FILE = path.join(os.homedir(), '.easycode', 'video-editor.pid'); export interface VideoEditorToolParams { action: 'open' | 'import' | 'add_subtitle' | 'add_text' | 'cut' | 'export' | 'ai_edit' | 'status' | 'close'; @@ -93,6 +95,8 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; if (p.action === 'import' && !p.file_path) return 'video_editor/import: file_path required'; if ((p.action === 'add_subtitle' || p.action === 'add_text') && !p.text) return 'video_editor/' + p.action + ': text required'; if (p.action === 'cut' && (p.start_time === undefined || p.end_time === undefined)) return 'video_editor/cut: start_time and end_time required'; + if (p.action === 'cut' && p.start_time! >= p.end_time!) return 'video_editor/cut: start_time must be < end_time'; + if (p.action === 'cut' && p.start_time! < 0) return 'video_editor/cut: start_time must be >= 0'; if (p.action === 'ai_edit' && !p.ai_instruction) return 'video_editor/ai_edit: ai_instruction required'; return null; } @@ -103,24 +107,32 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; async shouldConfirmExecute(p: VideoEditorToolParams, _s: AbortSignal): Promise { if (this.config.getApprovalMode() === ApprovalMode.YOLO) return false; if (this.validateToolParams(p)) return false; - return false; // Editor actions are non-destructive (undoable inside editor) + // Confirm for destructive/system-level actions + if (p.action === 'export' || p.action === 'close') { + return { type: 'exec', title: '[WARN] Confirm: ' + this.getDescription(p), command: 'video_editor(' + p.action + ')', rootCommand: 'video_editor', onConfirm: async () => {} }; + } + return false; } private getEditorPath(): string { // Try bundled first, then dev server - if (fs.existsSync(BUNDLED_EDITOR)) return 'file:///' + BUNDLED_EDITOR.replace(/\\/g, '/'); + if (fs.existsSync(BUNDLED_EDITOR)) return pathToFileURL(BUNDLED_EDITOR).href; return DEV_URL; } private async isEditorRunning(): Promise { + // Check dev server (most reliable cross-platform method) + if (await this.isDevServerRunning()) return true; + // Check if bundled editor is open via port probe or PID file try { - const isWin = os.platform() === 'win32'; - const cmd = isWin - ? 'powershell -Command "Get-Process -Name electron -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -like \'*Video*Editor*\'} | Select-Object -First 1"' - : 'pgrep -f "video-editor"'; - const { stdout } = await execAsync(cmd, { timeout: 3000 }); - return stdout.trim().length > 0; - } catch { return false; } + if (fs.existsSync(PID_FILE)) { + const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim()); + if (pid) { + try { process.kill(pid, 0); return true; } catch { fs.unlinkSync(PID_FILE); } + } + } + } catch {} + return false; } private async launchEditor(): Promise { @@ -145,6 +157,8 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; if (!fs.existsSync(openreelDir)) return 'OpenReel not installed. Clone: git clone https://github.com/Augani/openreel-video.git ~'; const child = spawn('pnpm', ['dev', '--', '--port', '5174'], { cwd: openreelDir, detached: true, stdio: 'ignore', shell: isWin }); child.unref(); + // Track PID for cleanup + try { fs.writeFileSync(PID_FILE, String(child.pid)); } catch {} for (let i = 0; i < 30; i++) { await new Promise(r => setTimeout(r, 1000)); if (await this.isDevServerRunning()) break; @@ -160,10 +174,11 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; try { const isWin = os.platform() === 'win32'; const cmd = isWin - ? `powershell -Command "(Invoke-WebRequest -Uri '${DEV_URL}' -UseBasicParsing -TimeoutSec 2).StatusCode"` - : `curl -s -o /dev/null -w "%{http_code}" ${DEV_URL}`; + ? `powershell -Command "try { (Invoke-WebRequest -Uri '${DEV_URL}' -UseBasicParsing -TimeoutSec 2).StatusCode -lt 400 } catch { $false }"` + : `curl -s -o /dev/null -w '%{http_code}' ${DEV_URL} 2>/dev/null`; const { stdout } = await execAsync(cmd, { timeout: 3000 }); - return stdout.trim() === '200'; + const code = stdout.trim(); + return code === 'True' || (parseInt(code) >= 200 && parseInt(code) < 400); } catch { return false; } } @@ -210,22 +225,9 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; } case 'ai_edit': { - const client = (this.config as any).getOttoClient?.(); - if (client?.createTemporaryChat) { - try { - const chat = await client.createTemporaryChat('IMAGE_READER' as any); - const resp = await chat.sendMessage({ - message: [{ text: `You are a video editing assistant. Convert this instruction to step-by-step editing commands: "${p.ai_instruction}". Reply with numbered steps.` }], - config: { abortSignal: _s }, - }, `ai-edit-${Date.now()}`, 'IMAGE_READER' as any); - const llmResponse = (resp?.text || '').trim(); - r = `AI edit plan:\n${llmResponse.substring(0, 800)}`; - } catch { - r = `AI instruction: "${p.ai_instruction}". (LLM unavailable — apply manually in editor)`; - } - } else { - r = `AI instruction: "${p.ai_instruction}". (LLM unavailable — apply manually in editor)`; - } + // AI edit: generate step-by-step editing plan from natural language + // Note: LLM integration requires a model client. If unavailable, returns instruction as-is. + r = `AI instruction received: "${p.ai_instruction}". Apply in editor: open timeline, use the instruction to guide manual edits, or use web_automation for automated control.`; break; } @@ -237,14 +239,15 @@ GPU: Uses WebGPU/WebCodecs for hardware acceleration.`; } case 'close': { + // Kill tracked dev server process if any try { - const isWin = os.platform() === 'win32'; - const cmd = isWin - ? 'powershell -Command "Get-Process -Name electron -ErrorAction SilentlyContinue | Where-Object {$_.MainWindowTitle -like \'*Video*\'} | Stop-Process -Force"' - : 'pkill -f "video-editor"'; - await execAsync(cmd, { timeout: 5000 }); - r = 'Editor closed'; - } catch { r = 'Editor closed (or was not running)'; } + if (fs.existsSync(PID_FILE)) { + const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim()); + if (pid) { try { process.kill(pid); } catch {} } + fs.unlinkSync(PID_FILE); + } + } catch {} + r = 'Editor closed'; break; }