diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c851ed8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,83 @@ +name: CI + +on: + push: + pull_request: + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + web: + name: Web (lint + build) + runs-on: ubuntu-latest + defaults: + run: + working-directory: web + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Lint + run: npm run lint + + - name: Build + run: npm run build + env: + # Placeholders so CI can compile without Vercel secrets. + NEXT_PUBLIC_SUPABASE_URL: https://placeholder.supabase.co + NEXT_PUBLIC_SUPABASE_ANON_KEY: placeholder-anon-key + + extension: + name: Extension (lint + build) + runs-on: ubuntu-latest + defaults: + run: + working-directory: inlineExtension + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: inlineExtension/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Lint + run: npm run lint + + - name: Build + run: npm run build + + backend: + name: Backend (build) + runs-on: ubuntu-latest + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: backend/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Build + run: npm run build diff --git a/README.md b/README.md index 483a1b3..63ef850 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,17 @@ Inline is a workspace and Chrome extension for capturing, annotating, rewriting, ## What Is In This Repo -- `web/` - Next.js workspace app, marketing site, dashboard, document editor, library, map, graph, history, settings, and AI API routes. +- `web/` - Next.js workspace app, marketing site, dashboard, document editor, library, history, analytics, settings, and AI API routes. - `backend/` - Express API used by the extension for annotation persistence. - `inlineExtension/` - Chrome extension built with React and Vite. It injects the Inline dock, selection tools, AI panels, notes, drawings, handwriting, stamps, search, layers, sharing, and browser-page overlays. - `supabase/` - Database migrations for extension persistence, workspace data, and RAG/search support. ## Core Features -- Chrome extension dock with AI, rewrite, search, annotation, drawing, handwriting, screenshot, layers, share, and settings workflows. +- Chrome extension dock with AI, rewrite, search, annotation, drawing, handwriting, screenshot, layers, share, and settings. - Persistent webpage annotations including highlights, sticky notes, paper notes, drawings, handwriting, stamps, and AI replacements. -- Workspace dashboard for activity, library documents, notes, maps, graphs, workflows, settings, and captured web sources. -- AI workflows for page recap, rewrite, insight generation, page risk, RAG indexing, search, and text-to-speech. +- Workspace dashboard for activity, library documents, captures, analytics, settings, and source-backed briefs. +- AI capabilities for page recap, rewrite, insight generation, page risk, RAG indexing, search, and text-to-speech. - Supabase-backed persistence and workspace synchronization. ## Local Development diff --git a/backend/dist/apiBranch/AnnotationsAPI.js b/backend/dist/apiBranch/AnnotationsAPI.js index fc93749..6c8135d 100644 --- a/backend/dist/apiBranch/AnnotationsAPI.js +++ b/backend/dist/apiBranch/AnnotationsAPI.js @@ -16,9 +16,12 @@ exports.saveAnnotations = saveAnnotations; exports.getAnnotations = getAnnotations; const supabase_js_1 = require("@supabase/supabase-js"); const db_1 = __importDefault(require("../config/db")); -const SUPABASE_URL = process.env.SECRET_DATABASE_CONNECTION || ''; -const SUPABASE_KEY = process.env.SECRET_DATABASE_KEY || ''; -const NEXT_APP_URL = process.env.NEXT_APP_URL || 'http://localhost:3000'; +const SUPABASE_URL = process.env.SECRET_DATABASE_CONNECTION || ""; +const SUPABASE_KEY = process.env.SECRET_DATABASE_KEY || ""; +const NEXT_APP_URL = process.env.NEXT_APP_URL || + (process.env.NODE_ENV === "production" + ? "https://useinline.vercel.app" + : "http://localhost:3000"); const MIRROR_DEBOUNCE_MS = 30000; const lastRecapCall = new Map(); function looksLikeJwt(token) { @@ -27,26 +30,30 @@ function looksLikeJwt(token) { // otherwise causes Supabase to throw "Expected 3 parts in JWT; got 1". if (!token) return false; - const parts = token.split('.'); + const parts = token.split("."); if (parts.length !== 3) return false; return parts.every((p) => p.length > 0); } function clientFromRequest(req) { - const header = req.header('authorization') || ''; - const bearer = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; + const header = req.header("authorization") || ""; + const bearer = header.startsWith("Bearer ") ? header.slice(7).trim() : ""; if (!looksLikeJwt(bearer) || !SUPABASE_URL || !SUPABASE_KEY) return db_1.default; return (0, supabase_js_1.createClient)(SUPABASE_URL, SUPABASE_KEY, { global: { headers: { Authorization: `Bearer ${bearer}` } }, - auth: { autoRefreshToken: false, persistSession: false, detectSessionInUrl: false }, + auth: { + autoRefreshToken: false, + persistSession: false, + detectSessionInUrl: false, + }, }); } function itemId(item) { - if (!item || typeof item !== 'object') + if (!item || typeof item !== "object") return null; const anyItem = item; - if (typeof anyItem.id === 'string' && anyItem.id) + if (typeof anyItem.id === "string" && anyItem.id) return anyItem.id; return null; } @@ -57,7 +64,7 @@ function safeDomain(pageUrl, fallback) { return new URL(pageUrl).hostname; } catch (_a) { - return ''; + return ""; } } /** @@ -69,26 +76,46 @@ function safeDomain(pageUrl, fallback) { */ function noteTypeForFeature(featureKey) { switch (featureKey) { - case 'stickyNotes': return 'text'; - case 'anchorNotes': return 'text'; - case 'paperNotes': return 'text'; - case 'highlights': return 'text'; - case 'drawPaths': return 'canvas'; - case 'handwriting': return 'canvas'; - case 'stamps': return 'canvas'; - default: return null; // rewrites/summaries stay blob-only + case "stickyNotes": + return "text"; + case "anchorNotes": + return "text"; + case "paperNotes": + return "text"; + case "highlights": + return "text"; + case "manualRewrites": + return "text"; + case "drawPaths": + return "canvas"; + case "handwriting": + return "canvas"; + case "stamps": + return "canvas"; + default: + return null; // rewrites/summaries stay blob-only } } function tagsForFeature(featureKey) { switch (featureKey) { - case 'stickyNotes': return ['sticky']; - case 'anchorNotes': return ['anchor']; - case 'paperNotes': return ['paper-note']; - case 'highlights': return ['highlight']; - case 'drawPaths': return ['drawing']; - case 'handwriting': return ['handwriting']; - case 'stamps': return ['stamp']; - default: return [featureKey]; + case "stickyNotes": + return ["sticky"]; + case "anchorNotes": + return ["anchor"]; + case "paperNotes": + return ["paper-note"]; + case "highlights": + return ["highlight"]; + case "manualRewrites": + return ["manual", "rewrite"]; + case "drawPaths": + return ["drawing"]; + case "handwriting": + return ["handwriting"]; + case "stamps": + return ["stamp"]; + default: + return [featureKey]; } } /** @@ -97,81 +124,109 @@ function tagsForFeature(featureKey) { */ function shapeItemForNotes(featureKey, item) { var _a; - if (!item || typeof item !== 'object') + if (!item || typeof item !== "object") return null; const r = item; const id = itemId(r); if (!id) return null; - const str = (v, d = '') => (typeof v === 'string' ? v : d); - const num = (v, d = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : d); + const str = (v, d = "") => (typeof v === "string" ? v : d); + const num = (v, d = 0) => typeof v === "number" && Number.isFinite(v) ? v : d; switch (featureKey) { - case 'stickyNotes': - case 'paperNotes': { + case "stickyNotes": + case "paperNotes": { return { externalId: id, - content: str(r.content, ''), - color: str(r.color, '#FFEB3B'), + content: str(r.content, ""), + color: str(r.color, "#FFEB3B"), posX: num(r.x, 200), posY: num(r.y, 200), width: num(r.width, 240), height: num(r.height, 160), }; } - case 'anchorNotes': { + case "anchorNotes": { return { externalId: id, - content: str(r.text, '') || str(r.content, ''), - color: str(r.color, '#FDFBF7'), + content: str(r.text, "") || str(r.content, ""), + color: str(r.color, "#FDFBF7"), posX: num(r.x, 40), posY: num(r.y, 140), width: 240, height: 150, }; } - case 'highlights': { - const text = str(r.text, '') || str(r.selectedText, '') || str(r.content, ''); + case "highlights": { + const text = str(r.text, "") || str(r.selectedText, "") || str(r.content, ""); return { externalId: id, content: text, - color: str(r.color, '#FFEB3B'), - posX: 0, posY: 0, width: 0, height: 0, + color: str(r.color, "#FFEB3B"), + posX: 0, + posY: 0, + width: 0, + height: 0, + }; + } + case "manualRewrites": { + const from = str(r.originalText, ""); + const to = str(r.text, "") || str(r.aiText, ""); + const snippet = (s) => (s.length > 120 ? `${s.slice(0, 117)}…` : s); + return { + externalId: id, + content: to + ? `Manual edit: "${snippet(from)}" → "${snippet(to)}"` + : `Manual edit: "${snippet(from)}"`, + color: "#93C5FD", + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'drawPaths': { + case "drawPaths": { // Prefer a readable description ("Pen stroke (42 points)", "Arrow", // etc) so Dashboard/History/Graph show something meaningful instead of // the raw JSON blob. The original data is already saved in the // per-page annotations.elements blob. const shapeLabels = { - path: 'Pen stroke', line: 'Line', rect: 'Rectangle', - arrow: 'Arrow', ellipse: 'Ellipse', + path: "Pen stroke", + line: "Line", + rect: "Rectangle", + arrow: "Arrow", + ellipse: "Ellipse", }; - const kindKey = typeof r.type === 'string' ? r.type : ''; - const shapeName = (_a = shapeLabels[kindKey]) !== null && _a !== void 0 ? _a : 'Sketch'; + const kindKey = typeof r.type === "string" ? r.type : ""; + const shapeName = (_a = shapeLabels[kindKey]) !== null && _a !== void 0 ? _a : "Sketch"; const points = Array.isArray(r.points) ? r.points.length : 0; - const descriptor = points > 0 ? ` · ${points} points` : ''; + const descriptor = points > 0 ? ` · ${points} points` : ""; return { externalId: id, content: `Drawing — ${shapeName}${descriptor}`, - color: str(r.stroke, '#1C1E26'), - posX: 0, posY: 0, width: 0, height: 0, + color: str(r.stroke, "#1C1E26"), + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'handwriting': { + case "handwriting": { const pts = Array.isArray(r.points) ? r.points.length : 0; return { externalId: id, - content: pts > 0 ? `Handwriting — ${pts} points` : 'Handwriting', - color: str(r.color, '#1C1E26'), - posX: 0, posY: 0, width: 0, height: 0, + content: pts > 0 ? `Handwriting — ${pts} points` : "Handwriting", + color: str(r.color, "#1C1E26"), + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'stamps': { + case "stamps": { return { externalId: id, - content: str(r.label, '') || str(r.emoji, '') || str(r.content, 'Stamp'), - color: str(r.color, '#fffbe0'), + content: str(r.label, "") || str(r.emoji, "") || str(r.content, "Stamp"), + color: str(r.color, "#fffbe0"), posX: num(r.x, 0), posY: num(r.y, 0), width: num(r.width, 48), @@ -185,7 +240,7 @@ function shapeItemForNotes(featureKey, item) { function mirrorToNotes(supabase, params) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; - const { pageUrl, featureKey, previous, incoming, workspaceId, pageTitle, domain, userIdFallback, clearedAt, authHeader } = params; + const { pageUrl, featureKey, previous, incoming, workspaceId, pageTitle, domain, userIdFallback, clearedAt, authHeader, } = params; const type = noteTypeForFeature(featureKey); if (!type) return; @@ -199,11 +254,13 @@ function mirrorToNotes(supabase, params) { if ((_a = authData === null || authData === void 0 ? void 0 : authData.user) === null || _a === void 0 ? void 0 : _a.id) userId = authData.user.id; } - catch ( /* ignore */_c) { /* ignore */ } + catch (_c) { + /* ignore */ + } if (!userId) return; // no user → cannot satisfy RLS → skip mirror - const prevIds = new Set(previous.map(i => itemId(i)).filter((x) => !!x)); - const nextIds = new Set(incoming.map(i => itemId(i)).filter((x) => !!x)); + const prevIds = new Set(previous.map((i) => itemId(i)).filter((x) => !!x)); + const nextIds = new Set(incoming.map((i) => itemId(i)).filter((x) => !!x)); const baseTags = tagsForFeature(featureKey); const rowsToInsert = []; for (const item of incoming) { @@ -232,87 +289,103 @@ function mirrorToNotes(supabase, params) { // instead of upsert-on-conflict we manually delete the previous anchor_id // set for this feature and re-insert. This keeps the mirror idempotent // without requiring a schema migration. - const incomingAnchorIds = rowsToInsert.map(r => r.anchor_id).filter((x) => !!x); + const incomingAnchorIds = rowsToInsert + .map((r) => r.anchor_id) + .filter((x) => !!x); if (incomingAnchorIds.length > 0) { - const del = yield sb.from('notes') + const del = yield sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags) - .in('anchor_id', incomingAnchorIds); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags) + .in("anchor_id", incomingAnchorIds); if (del.error) - console.warn('[Inline mirror] pre-clean failed:', del.error.message); - const up = yield sb.from('notes').insert(rowsToInsert); + console.warn("[Inline mirror] pre-clean failed:", del.error.message); + const up = yield sb.from("notes").insert(rowsToInsert); if (up.error) - console.error('[Inline mirror] insert notes failed:', up.error.message); + console.error("[Inline mirror] insert notes failed:", up.error.message); } - const idsToDelete = [...prevIds].filter(id => !nextIds.has(id)); + const idsToDelete = [...prevIds].filter((id) => !nextIds.has(id)); const clearedAll = !!clearedAt; if (clearedAll) { - const result = yield sb.from('notes') + const result = yield sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags); if (result.error) - console.error('[Inline mirror] clear-all failed:', result.error.message); + console.error("[Inline mirror] clear-all failed:", result.error.message); } else if (idsToDelete.length > 0) { - const result = yield sb.from('notes') + const result = yield sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags) - .in('anchor_id', idsToDelete); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags) + .in("anchor_id", idsToDelete); if (result.error) - console.error('[Inline mirror] delete-some failed:', result.error.message); + console.error("[Inline mirror] delete-some failed:", result.error.message); } // Best-effort: mark the page recap stale + trigger regeneration. Both calls // silently no-op if public.documents / the recap route don't exist yet. try { - yield sb.from('documents') + yield sb + .from("documents") .update({ recap_stale: true, updated_at: new Date().toISOString() }) - .eq('user_id', userId) - .eq('workspace_id', workspaceId !== null && workspaceId !== void 0 ? workspaceId : '') - .eq('page_url', pageUrl); + .eq("user_id", userId) + .eq("workspace_id", workspaceId !== null && workspaceId !== void 0 ? workspaceId : "") + .eq("page_url", pageUrl); + } + catch (_d) { + /* documents table may not exist yet — ignore */ } - catch ( /* documents table may not exist yet — ignore */_d) { /* documents table may not exist yet — ignore */ } - const key = `${userId}|${workspaceId !== null && workspaceId !== void 0 ? workspaceId : ''}|${pageUrl}`; + const key = `${userId}|${workspaceId !== null && workspaceId !== void 0 ? workspaceId : ""}|${pageUrl}`; const last = (_b = lastRecapCall.get(key)) !== null && _b !== void 0 ? _b : 0; if (Date.now() - last > MIRROR_DEBOUNCE_MS) { lastRecapCall.set(key, Date.now()); - const headers = { 'Content-Type': 'application/json' }; + const headers = { + "Content-Type": "application/json", + }; if (authHeader) headers.Authorization = authHeader; void fetch(`${NEXT_APP_URL}/api/ai/page-recap`, { - method: 'POST', + method: "POST", headers, - body: JSON.stringify({ workspaceId: workspaceId !== null && workspaceId !== void 0 ? workspaceId : '', pageUrl }), - }).catch(() => { }); + body: JSON.stringify({ workspaceId: workspaceId !== null && workspaceId !== void 0 ? workspaceId : "", pageUrl }), + }).catch(() => { + /* recap route may be absent — ignore */ + }); // Embed the mirrored notes for semantic retrieval (RAG). Fire-and-forget, // same debounce window as the recap call. void fetch(`${NEXT_APP_URL}/api/ai/index`, { - method: 'POST', + method: "POST", headers, - body: JSON.stringify({ pageUrl, workspaceId: workspaceId !== null && workspaceId !== void 0 ? workspaceId : '' }), - }).catch(() => { }); + body: JSON.stringify({ pageUrl, workspaceId: workspaceId !== null && workspaceId !== void 0 ? workspaceId : "" }), + }).catch(() => { + /* index route may be absent — ignore */ + }); } }); } function saveAnnotations(req, res) { return __awaiter(this, void 0, void 0, function* () { - var _a, _b, _c; + var _a, _b, _c, _d; const { pageUrl, featureKey, data, workspaceId, pageTitle, domain, userId: userIdFromBody, clearedAt, } = req.body; if (!pageUrl || !featureKey || data === undefined) { - res.status(400).json({ error: 'pageUrl, featureKey, and data are required' }); + res + .status(400) + .json({ error: "pageUrl, featureKey, and data are required" }); return; } const supabase = clientFromRequest(req); // 1. Fetch existing annotations blob (for merge + mirror diff). const fetchResult = yield supabase - .from('annotations') - .select('elements') - .eq('page_url', pageUrl) + .from("annotations") + .select("elements") + .eq("page_url", pageUrl) .maybeSingle(); if (fetchResult.error) { res.status(500).json({ error: fetchResult.error.message }); @@ -320,14 +393,26 @@ function saveAnnotations(req, res) { } const existingElements = ((_b = (_a = fetchResult.data) === null || _a === void 0 ? void 0 : _a.elements) !== null && _b !== void 0 ? _b : {}); const mergedElements = Object.assign(Object.assign({}, existingElements), { [featureKey]: data }); + let userId = userIdFromBody !== null && userIdFromBody !== void 0 ? userIdFromBody : null; + try { + const { data: authData } = yield supabase.auth.getUser(); + if ((_c = authData === null || authData === void 0 ? void 0 : authData.user) === null || _c === void 0 ? void 0 : _c.id) + userId = authData.user.id; + } + catch (_e) { + /* ignore */ + } // 2. Upsert merged blob. // eslint-disable-next-line @typescript-eslint/no-explicit-any - const annotationsTable = supabase.from('annotations'); - const upsertResult = yield annotationsTable.upsert({ + const annotationsTable = supabase.from("annotations"); + const upsertPayload = { page_url: pageUrl, elements: mergedElements, updated_at: new Date().toISOString(), - }, { onConflict: 'page_url' }); + }; + if (userId) + upsertPayload.user_id = userId; + const upsertResult = (yield annotationsTable.upsert(upsertPayload, { onConflict: "page_url" })); if (upsertResult.error) { res.status(500).json({ error: upsertResult.error.message }); return; @@ -345,15 +430,15 @@ function saveAnnotations(req, res) { previous: prev, incoming: next, workspaceId: workspaceId !== null && workspaceId !== void 0 ? workspaceId : null, - pageTitle: pageTitle !== null && pageTitle !== void 0 ? pageTitle : '', + pageTitle: pageTitle !== null && pageTitle !== void 0 ? pageTitle : "", domain: safeDomain(pageUrl, domain), userIdFallback: userIdFromBody !== null && userIdFromBody !== void 0 ? userIdFromBody : null, clearedAt, - authHeader: (_c = req.header('authorization')) !== null && _c !== void 0 ? _c : undefined, + authHeader: (_d = req.header("authorization")) !== null && _d !== void 0 ? _d : undefined, }); } catch (err) { - console.error('[Inline] mirror failed:', err); + console.error("[Inline] mirror failed:", err); } res.status(200).json({ success: true }); }); @@ -363,14 +448,14 @@ function getAnnotations(req, res) { var _a, _b; const pageUrl = req.query.url; if (!pageUrl) { - res.status(400).json({ error: 'url query parameter is required' }); + res.status(400).json({ error: "url query parameter is required" }); return; } const supabase = clientFromRequest(req); const fetchResult = yield supabase - .from('annotations') - .select('elements') - .eq('page_url', pageUrl) + .from("annotations") + .select("elements") + .eq("page_url", pageUrl) .maybeSingle(); if (fetchResult.error) { res.status(500).json({ error: fetchResult.error.message }); diff --git a/backend/src/apiBranch/AnnotationsAPI.ts b/backend/src/apiBranch/AnnotationsAPI.ts index f51172c..33f0942 100644 --- a/backend/src/apiBranch/AnnotationsAPI.ts +++ b/backend/src/apiBranch/AnnotationsAPI.ts @@ -1,7 +1,7 @@ -import { Request, Response } from 'express'; -import { createClient, type SupabaseClient } from '@supabase/supabase-js'; -import defaultSupabase from '../config/db'; -import type { Database } from '../config/database.types'; +import { Request, Response } from "express"; +import { createClient, type SupabaseClient } from "@supabase/supabase-js"; +import defaultSupabase from "../config/db"; +import type { Database } from "../config/database.types"; /** * Universal annotation save pipeline. @@ -15,7 +15,8 @@ import type { Database } from '../config/database.types'; * Expected request body: * pageUrl — normalized URL of the page * featureKey — which feature is saving (stickyNotes | drawPaths | handwriting | - * highlights | anchorNotes | paperNotes | stamps | rewrites | summaries) + * highlights | anchorNotes | paperNotes | stamps | manualRewrites | + * aiReplacements | rewrites | summaries) * data — full state array/object for that feature * workspaceId — optional workspace UUID (falls back to null = "default") * pageTitle — optional document.title @@ -30,11 +31,13 @@ type JsonObj = Record; type ElementsRow = { elements: JsonObj | null } | null; type SupabaseError = { message: string } | null; -const SUPABASE_URL = process.env.SECRET_DATABASE_CONNECTION || ''; -const SUPABASE_KEY = process.env.SECRET_DATABASE_KEY || ''; +const SUPABASE_URL = process.env.SECRET_DATABASE_CONNECTION || ""; +const SUPABASE_KEY = process.env.SECRET_DATABASE_KEY || ""; const NEXT_APP_URL = process.env.NEXT_APP_URL || - (process.env.NODE_ENV === 'production' ? 'https://useinline.vercel.app' : 'http://localhost:3000'); + (process.env.NODE_ENV === "production" + ? "https://useinline.vercel.app" + : "http://localhost:3000"); const MIRROR_DEBOUNCE_MS = 30_000; const lastRecapCall = new Map(); @@ -44,31 +47,40 @@ function looksLikeJwt(token: string): boolean { // Reject anything that is empty, placeholder text, or missing dots, which // otherwise causes Supabase to throw "Expected 3 parts in JWT; got 1". if (!token) return false; - const parts = token.split('.'); + const parts = token.split("."); if (parts.length !== 3) return false; return parts.every((p) => p.length > 0); } function clientFromRequest(req: Request): SupabaseClient { - const header = req.header('authorization') || ''; - const bearer = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; - if (!looksLikeJwt(bearer) || !SUPABASE_URL || !SUPABASE_KEY) return defaultSupabase; + const header = req.header("authorization") || ""; + const bearer = header.startsWith("Bearer ") ? header.slice(7).trim() : ""; + if (!looksLikeJwt(bearer) || !SUPABASE_URL || !SUPABASE_KEY) + return defaultSupabase; return createClient(SUPABASE_URL, SUPABASE_KEY, { global: { headers: { Authorization: `Bearer ${bearer}` } }, - auth: { autoRefreshToken: false, persistSession: false, detectSessionInUrl: false }, + auth: { + autoRefreshToken: false, + persistSession: false, + detectSessionInUrl: false, + }, }); } function itemId(item: unknown): string | null { - if (!item || typeof item !== 'object') return null; + if (!item || typeof item !== "object") return null; const anyItem = item as Record; - if (typeof anyItem.id === 'string' && anyItem.id) return anyItem.id; + if (typeof anyItem.id === "string" && anyItem.id) return anyItem.id; return null; } function safeDomain(pageUrl: string, fallback: string | undefined): string { if (fallback && fallback.trim()) return fallback.trim(); - try { return new URL(pageUrl).hostname; } catch { return ''; } + try { + return new URL(pageUrl).hostname; + } catch { + return ""; + } } /** @@ -80,27 +92,47 @@ function safeDomain(pageUrl: string, fallback: string | undefined): string { */ function noteTypeForFeature(featureKey: string): string | null { switch (featureKey) { - case 'stickyNotes': return 'text'; - case 'anchorNotes': return 'text'; - case 'paperNotes': return 'text'; - case 'highlights': return 'text'; - case 'drawPaths': return 'canvas'; - case 'handwriting': return 'canvas'; - case 'stamps': return 'canvas'; - default: return null; // rewrites/summaries stay blob-only + case "stickyNotes": + return "text"; + case "anchorNotes": + return "text"; + case "paperNotes": + return "text"; + case "highlights": + return "text"; + case "manualRewrites": + return "text"; + case "drawPaths": + return "canvas"; + case "handwriting": + return "canvas"; + case "stamps": + return "canvas"; + default: + return null; // rewrites/summaries stay blob-only } } function tagsForFeature(featureKey: string): string[] { switch (featureKey) { - case 'stickyNotes': return ['sticky']; - case 'anchorNotes': return ['anchor']; - case 'paperNotes': return ['paper-note']; - case 'highlights': return ['highlight']; - case 'drawPaths': return ['drawing']; - case 'handwriting': return ['handwriting']; - case 'stamps': return ['stamp']; - default: return [featureKey]; + case "stickyNotes": + return ["sticky"]; + case "anchorNotes": + return ["anchor"]; + case "paperNotes": + return ["paper-note"]; + case "highlights": + return ["highlight"]; + case "manualRewrites": + return ["manual", "rewrite"]; + case "drawPaths": + return ["drawing"]; + case "handwriting": + return ["handwriting"]; + case "stamps": + return ["stamp"]; + default: + return [featureKey]; } } @@ -108,92 +140,128 @@ function tagsForFeature(featureKey: string): string[] { * Turn one element out of the per-featureKey array into the fields that `notes` * needs. Returns null for items the mirror should skip (no stable id, etc). */ -function shapeItemForNotes(featureKey: string, item: unknown): { +function shapeItemForNotes( + featureKey: string, + item: unknown, +): { externalId: string; content: string; color: string; - posX: number; posY: number; - width: number; height: number; + posX: number; + posY: number; + width: number; + height: number; } | null { - if (!item || typeof item !== 'object') return null; + if (!item || typeof item !== "object") return null; const r = item as Record; const id = itemId(r); if (!id) return null; - const str = (v: unknown, d = '') => (typeof v === 'string' ? v : d); - const num = (v: unknown, d = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : d); + const str = (v: unknown, d = "") => (typeof v === "string" ? v : d); + const num = (v: unknown, d = 0) => + typeof v === "number" && Number.isFinite(v) ? v : d; switch (featureKey) { - case 'stickyNotes': - case 'paperNotes': { + case "stickyNotes": + case "paperNotes": { return { externalId: id, - content: str(r.content, ''), - color: str(r.color, '#FFEB3B'), - posX: num(r.x, 200), - posY: num(r.y, 200), - width: num(r.width, 240), - height: num(r.height, 160), + content: str(r.content, ""), + color: str(r.color, "#FFEB3B"), + posX: num(r.x, 200), + posY: num(r.y, 200), + width: num(r.width, 240), + height: num(r.height, 160), }; } - case 'anchorNotes': { + case "anchorNotes": { return { externalId: id, - content: str(r.text, '') || str(r.content, ''), - color: str(r.color, '#FDFBF7'), - posX: num(r.x, 40), - posY: num(r.y, 140), - width: 240, - height: 150, + content: str(r.text, "") || str(r.content, ""), + color: str(r.color, "#FDFBF7"), + posX: num(r.x, 40), + posY: num(r.y, 140), + width: 240, + height: 150, }; } - case 'highlights': { - const text = str(r.text, '') || str(r.selectedText, '') || str(r.content, ''); + case "highlights": { + const text = + str(r.text, "") || str(r.selectedText, "") || str(r.content, ""); return { externalId: id, content: text, - color: str(r.color, '#FFEB3B'), - posX: 0, posY: 0, width: 0, height: 0, + color: str(r.color, "#FFEB3B"), + posX: 0, + posY: 0, + width: 0, + height: 0, + }; + } + case "manualRewrites": { + const from = str(r.originalText, ""); + const to = str(r.text, "") || str(r.aiText, ""); + const snippet = (s: string) => (s.length > 120 ? `${s.slice(0, 117)}…` : s); + return { + externalId: id, + content: to + ? `Manual edit: "${snippet(from)}" → "${snippet(to)}"` + : `Manual edit: "${snippet(from)}"`, + color: "#93C5FD", + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'drawPaths': { + case "drawPaths": { // Prefer a readable description ("Pen stroke (42 points)", "Arrow", // etc) so Dashboard/History/Graph show something meaningful instead of // the raw JSON blob. The original data is already saved in the // per-page annotations.elements blob. const shapeLabels: Record = { - path: 'Pen stroke', line: 'Line', rect: 'Rectangle', - arrow: 'Arrow', ellipse: 'Ellipse', + path: "Pen stroke", + line: "Line", + rect: "Rectangle", + arrow: "Arrow", + ellipse: "Ellipse", }; - const kindKey = typeof r.type === 'string' ? r.type : ''; - const shapeName = shapeLabels[kindKey] ?? 'Sketch'; + const kindKey = typeof r.type === "string" ? r.type : ""; + const shapeName = shapeLabels[kindKey] ?? "Sketch"; const points = Array.isArray(r.points) ? r.points.length : 0; - const descriptor = points > 0 ? ` · ${points} points` : ''; + const descriptor = points > 0 ? ` · ${points} points` : ""; return { externalId: id, content: `Drawing — ${shapeName}${descriptor}`, - color: str(r.stroke, '#1C1E26'), - posX: 0, posY: 0, width: 0, height: 0, + color: str(r.stroke, "#1C1E26"), + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'handwriting': { + case "handwriting": { const pts = Array.isArray(r.points) ? r.points.length : 0; return { externalId: id, - content: pts > 0 ? `Handwriting — ${pts} points` : 'Handwriting', - color: str(r.color, '#1C1E26'), - posX: 0, posY: 0, width: 0, height: 0, + content: pts > 0 ? `Handwriting — ${pts} points` : "Handwriting", + color: str(r.color, "#1C1E26"), + posX: 0, + posY: 0, + width: 0, + height: 0, }; } - case 'stamps': { + case "stamps": { return { externalId: id, - content: str(r.label, '') || str(r.emoji, '') || str(r.content, 'Stamp'), - color: str(r.color, '#fffbe0'), - posX: num(r.x, 0), - posY: num(r.y, 0), - width: num(r.width, 48), - height: num(r.height, 48), + content: + str(r.label, "") || str(r.emoji, "") || str(r.content, "Stamp"), + color: str(r.color, "#fffbe0"), + posX: num(r.x, 0), + posY: num(r.y, 0), + width: num(r.width, 48), + height: num(r.height, 48), }; } default: @@ -204,14 +272,30 @@ function shapeItemForNotes(featureKey: string, item: unknown): { async function mirrorToNotes( supabase: SupabaseClient, params: { - pageUrl: string; featureKey: string; - previous: unknown[]; incoming: unknown[]; - workspaceId: string | null; pageTitle: string; domain: string; - userIdFallback: string | null; clearedAt?: unknown; + pageUrl: string; + featureKey: string; + previous: unknown[]; + incoming: unknown[]; + workspaceId: string | null; + pageTitle: string; + domain: string; + userIdFallback: string | null; + clearedAt?: unknown; authHeader?: string; }, ): Promise { - const { pageUrl, featureKey, previous, incoming, workspaceId, pageTitle, domain, userIdFallback, clearedAt, authHeader } = params; + const { + pageUrl, + featureKey, + previous, + incoming, + workspaceId, + pageTitle, + domain, + userIdFallback, + clearedAt, + authHeader, + } = params; const type = noteTypeForFeature(featureKey); if (!type) return; @@ -224,11 +308,17 @@ async function mirrorToNotes( try { const { data: authData } = await supabase.auth.getUser(); if (authData?.user?.id) userId = authData.user.id; - } catch { /* ignore */ } + } catch { + /* ignore */ + } if (!userId) return; // no user → cannot satisfy RLS → skip mirror - const prevIds = new Set(previous.map(i => itemId(i)).filter((x): x is string => !!x)); - const nextIds = new Set(incoming.map(i => itemId(i)).filter((x): x is string => !!x)); + const prevIds = new Set( + previous.map((i) => itemId(i)).filter((x): x is string => !!x), + ); + const nextIds = new Set( + incoming.map((i) => itemId(i)).filter((x): x is string => !!x), + ); const baseTags = tagsForFeature(featureKey); const rowsToInsert: Record[] = []; @@ -236,21 +326,21 @@ async function mirrorToNotes( const shape = shapeItemForNotes(featureKey, item); if (!shape) continue; rowsToInsert.push({ - user_id: userId, + user_id: userId, workspace_id: workspaceId, - page_url: pageUrl, + page_url: pageUrl, domain, - page_title: pageTitle, - content: shape.content.slice(0, 20_000), + page_title: pageTitle, + content: shape.content.slice(0, 20_000), type, - color: shape.color, - pos_x: shape.posX, - pos_y: shape.posY, - width: shape.width || 240, - height: shape.height || 160, - tags: baseTags, - anchor_id: shape.externalId, - updated_at: new Date().toISOString(), + color: shape.color, + pos_x: shape.posX, + pos_y: shape.posY, + width: shape.width || 240, + height: shape.height || 160, + tags: baseTags, + anchor_id: shape.externalId, + updated_at: new Date().toISOString(), }); } @@ -258,73 +348,97 @@ async function mirrorToNotes( // instead of upsert-on-conflict we manually delete the previous anchor_id // set for this feature and re-insert. This keeps the mirror idempotent // without requiring a schema migration. - const incomingAnchorIds = rowsToInsert.map(r => r.anchor_id).filter((x): x is string => !!x); + const incomingAnchorIds = rowsToInsert + .map((r) => r.anchor_id) + .filter((x): x is string => !!x); if (incomingAnchorIds.length > 0) { - const del = await sb.from('notes') + const del = await sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags) - .in('anchor_id', incomingAnchorIds); - if (del.error) console.warn('[Inline mirror] pre-clean failed:', del.error.message); - - const up = await sb.from('notes').insert(rowsToInsert); - if (up.error) console.error('[Inline mirror] insert notes failed:', up.error.message); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags) + .in("anchor_id", incomingAnchorIds); + if (del.error) + console.warn("[Inline mirror] pre-clean failed:", del.error.message); + + const up = await sb.from("notes").insert(rowsToInsert); + if (up.error) + console.error("[Inline mirror] insert notes failed:", up.error.message); } - const idsToDelete = [...prevIds].filter(id => !nextIds.has(id)); + const idsToDelete = [...prevIds].filter((id) => !nextIds.has(id)); const clearedAll = !!clearedAt; if (clearedAll) { - const result: { error: SupabaseError } = await sb.from('notes') + const result: { error: SupabaseError } = await sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags); - if (result.error) console.error('[Inline mirror] clear-all failed:', result.error.message); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags); + if (result.error) + console.error("[Inline mirror] clear-all failed:", result.error.message); } else if (idsToDelete.length > 0) { - const result: { error: SupabaseError } = await sb.from('notes') + const result: { error: SupabaseError } = await sb + .from("notes") .delete() - .eq('user_id', userId) - .eq('page_url', pageUrl) - .contains('tags', baseTags) - .in('anchor_id', idsToDelete); - if (result.error) console.error('[Inline mirror] delete-some failed:', result.error.message); + .eq("user_id", userId) + .eq("page_url", pageUrl) + .contains("tags", baseTags) + .in("anchor_id", idsToDelete); + if (result.error) + console.error( + "[Inline mirror] delete-some failed:", + result.error.message, + ); } // Best-effort: mark the page recap stale + trigger regeneration. Both calls // silently no-op if public.documents / the recap route don't exist yet. try { - await sb.from('documents') + await sb + .from("documents") .update({ recap_stale: true, updated_at: new Date().toISOString() }) - .eq('user_id', userId) - .eq('workspace_id', workspaceId ?? '') - .eq('page_url', pageUrl); - } catch { /* documents table may not exist yet — ignore */ } + .eq("user_id", userId) + .eq("workspace_id", workspaceId ?? "") + .eq("page_url", pageUrl); + } catch { + /* documents table may not exist yet — ignore */ + } - const key = `${userId}|${workspaceId ?? ''}|${pageUrl}`; + const key = `${userId}|${workspaceId ?? ""}|${pageUrl}`; const last = lastRecapCall.get(key) ?? 0; if (Date.now() - last > MIRROR_DEBOUNCE_MS) { lastRecapCall.set(key, Date.now()); - const headers: Record = { 'Content-Type': 'application/json' }; + const headers: Record = { + "Content-Type": "application/json", + }; if (authHeader) headers.Authorization = authHeader; void fetch(`${NEXT_APP_URL}/api/ai/page-recap`, { - method: 'POST', + method: "POST", headers, - body: JSON.stringify({ workspaceId: workspaceId ?? '', pageUrl }), - }).catch(() => { /* recap route may be absent — ignore */ }); + body: JSON.stringify({ workspaceId: workspaceId ?? "", pageUrl }), + }).catch(() => { + /* recap route may be absent — ignore */ + }); // Embed the mirrored notes for semantic retrieval (RAG). Fire-and-forget, // same debounce window as the recap call. void fetch(`${NEXT_APP_URL}/api/ai/index`, { - method: 'POST', + method: "POST", headers, - body: JSON.stringify({ pageUrl, workspaceId: workspaceId ?? '' }), - }).catch(() => { /* index route may be absent — ignore */ }); + body: JSON.stringify({ pageUrl, workspaceId: workspaceId ?? "" }), + }).catch(() => { + /* index route may be absent — ignore */ + }); } } -export async function saveAnnotations(req: Request, res: Response): Promise { +export async function saveAnnotations( + req: Request, + res: Response, +): Promise { const { pageUrl, featureKey, @@ -335,13 +449,20 @@ export async function saveAnnotations(req: Request, res: Response): Promise); + .from("annotations") + .select("elements") + .eq("page_url", pageUrl) + .maybeSingle() as unknown as Promise<{ + data: ElementsRow; + error: SupabaseError; + }>); if (fetchResult.error) { res.status(500).json({ error: fetchResult.error.message }); @@ -362,17 +486,28 @@ export async function saveAnnotations(req: Request, res: Response): Promise = { + page_url: pageUrl, + elements: mergedElements, + updated_at: new Date().toISOString(), + }; + if (userId) upsertPayload.user_id = userId; + + const upsertResult = (await annotationsTable.upsert( + upsertPayload, + { onConflict: "page_url" }, + )) as { error: SupabaseError }; if (upsertResult.error) { res.status(500).json({ error: upsertResult.error.message }); @@ -392,34 +527,40 @@ export async function saveAnnotations(req: Request, res: Response): Promise { +export async function getAnnotations( + req: Request, + res: Response, +): Promise { const pageUrl = req.query.url as string | undefined; if (!pageUrl) { - res.status(400).json({ error: 'url query parameter is required' }); + res.status(400).json({ error: "url query parameter is required" }); return; } const supabase = clientFromRequest(req); const fetchResult = await (supabase - .from('annotations') - .select('elements') - .eq('page_url', pageUrl) - .maybeSingle() as unknown as Promise<{ data: ElementsRow; error: SupabaseError }>); + .from("annotations") + .select("elements") + .eq("page_url", pageUrl) + .maybeSingle() as unknown as Promise<{ + data: ElementsRow; + error: SupabaseError; + }>); if (fetchResult.error) { res.status(500).json({ error: fetchResult.error.message }); diff --git a/inlineExtension/dist/background.js b/inlineExtension/dist/background.js index 7f3121d..3791468 100644 --- a/inlineExtension/dist/background.js +++ b/inlineExtension/dist/background.js @@ -1 +1 @@ -(function(){"use strict";const E="inlineLocalDataKey",F=new TextEncoder,z=new TextDecoder;function C(e){let n="";for(let r=0;re.id));function V(e){return e&&H.has(e)?e:P}const $="https://useinline.vercel.app",q=$,Y=$,Q=new Set(["localhost","127.0.0.1","::1"]);function b(e){try{const n=new URL(e);if(n.protocol==="https:"||n.protocol==="wss:"||(n.protocol==="http:"||n.protocol==="ws:")&&Q.has(n.hostname))return!0}catch{return!1}return!1}function g(e){if(!b(e))throw new Error("Inline blocks non-local insecure network requests. Use HTTPS for synced workspace and AI requests.")}function X(e){const n=e.replace(/\/$/,"");return g(n),n}const x=Y,j=q;function m(e){if(!e)return!1;const n=e.split(".");return n.length===3&&n.every(t=>t.length>0)}function Z(e){let n=2166136261;for(let t=0;t>>0).toString(36)}function J(e){return`inlineLocalAnnotations:${Z(e)}`}function U(e,n){if(!e||typeof e!="object")return{pageUrl:n,pageTitle:"",domain:"",elements:{},updatedAt:0};const t=e,r=t.elements&&typeof t.elements=="object"&&!Array.isArray(t.elements)?t.elements:{};return{pageUrl:typeof t.pageUrl=="string"?t.pageUrl:n,pageTitle:typeof t.pageTitle=="string"?t.pageTitle:"",domain:typeof t.domain=="string"?t.domain:"",elements:r,updatedAt:typeof t.updatedAt=="number"?t.updatedAt:0,clearedAt:typeof t.clearedAt=="number"?t.clearedAt:null}}async function A(e){const n=J(e),t=await chrome.storage.local.get(n);if(M(t[n]))try{return U(await D(t[n]),e)}catch{return U(null,e)}const r=U(t[n],e);return t[n]&&await chrome.storage.local.set({[n]:await S(r)}),r}async function L(e){const n=J(e.pageUrl),t=await A(e.pageUrl),r={...t,pageTitle:e.pageTitle??t.pageTitle,domain:e.domain??t.domain,elements:{...t.elements,[e.featureKey]:e.data},updatedAt:Date.now(),clearedAt:e.clearedAt??t.clearedAt??null};return await chrome.storage.local.set({[n]:await S(r)}),r}function T(e,n){const r=(typeof e=="string"&&e?e:n).replace(/\/$/,"");return b(r)?r:X(n)}function R(e){const n=new Uint8Array(e);let t="";for(let r=0;r{chrome.alarms.create("inline-sync-retry",{periodInMinutes:2}),chrome.contextMenus.removeAll(()=>{chrome.contextMenus.create({id:"inline-analyze-risk",title:"Analyze page risk (Inline)",contexts:["page"]}),chrome.contextMenus.create({id:"inline-root",title:"Inline",contexts:["selection"]}),chrome.contextMenus.create({id:"notes",parentId:"inline-root",title:"📝 Add Note",contexts:["selection"]}),chrome.contextMenus.create({id:"highlight",parentId:"inline-root",title:"🖊️ Highlight",contexts:["selection"]}),chrome.contextMenus.create({id:"rewrite",parentId:"inline-root",title:"✏️ Rewrite",contexts:["selection"]}),chrome.contextMenus.create({id:"ai",parentId:"inline-root",title:"✨ Ask AI",contexts:["selection"]}),chrome.contextMenus.create({id:"clip-to-workspace",parentId:"inline-root",title:"📎 Clip to Workspace",contexts:["selection"]})})}),chrome.contextMenus.onClicked.addListener((e,n)=>{if(e.menuItemId==="inline-analyze-risk"&&n?.id!=null){chrome.tabs.sendMessage(n.id,{type:"INLINE_PAGE_RISK"}).catch(()=>{});return}!n?.id||e.menuItemId==="inline-root"||chrome.tabs.sendMessage(n.id,{type:"INLINE_FEATURE",featureId:e.menuItemId,selectedText:e.selectionText??""})}),chrome.runtime.onMessageExternal.addListener((e,n,t)=>{if(e?.type==="INLINE_SYNC_VOICE_SETTINGS"){const r=e.payload,o={};return r.voiceId!==void 0&&(o.inlineVoiceId=V(r.voiceId)),r.stability!==void 0&&(o.inlineVoiceStability=r.stability),r.similarity!==void 0&&(o.inlineVoiceSimilarity=r.similarity),chrome.storage.local.remove(["inlineElevenLabsKey"]),chrome.storage.local.set(o,()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}if(e?.type==="INLINE_SYNC_BLOCKLIST"){const r=e.payload;if(!Array.isArray(r?.blockedDomains))return t({ok:!1,error:"blockedDomains must be an array"}),!0;const o=r.blockedDomains.filter(i=>typeof i=="string").map(i=>i.trim().toLowerCase()).filter(Boolean);return chrome.storage.local.set({inlineBlockedDomains:JSON.stringify(o)},()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}if(e?.type==="INLINE_SYNC_AUTH"){const r=e.payload,o={};if(typeof r.accessToken=="string"&&(o.inlineAccessToken=r.accessToken),typeof r.userId=="string"&&(o.inlineUserId=r.userId),typeof r.workspaceId=="string"&&r.workspaceId&&(o.inlineActiveWorkspaceId=r.workspaceId),typeof r.apiBase=="string"&&r.apiBase){const i=r.apiBase.replace(/\/$/,"");if(!b(i))return t({ok:!1,error:"Workspace sync must use HTTPS outside local development."}),!0;o.inlineApiBase=i}if(typeof r.backendBase=="string"&&r.backendBase){const i=r.backendBase.replace(/\/$/,"");if(!b(i))return t({ok:!1,error:"Workspace sync must use HTTPS outside local development."}),!0;o.inlineBackendBase=i}return typeof r.email=="string"&&r.email&&(o.inlineUserEmail=r.email),typeof r.name=="string"&&r.name&&(o.inlineUserName=r.name),typeof r.avatarUrl=="string"&&r.avatarUrl&&(o.inlineUserAvatarUrl=r.avatarUrl),chrome.storage.local.set(o,()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}}),chrome.runtime.onMessage.addListener((e,n,t)=>{if(e.type==="INLINE_PROXY_FETCH"){const r=e.payload,o=typeof r?.url=="string"?r.url:"";return o?((async()=>{try{g(o);const i=await fetch(o,{method:r.method??"GET",headers:r.headers??{},body:r.body}),s=await i.text().catch(()=>"");t({ok:i.ok,status:i.status,bodyText:s})}catch(i){t({ok:!1,status:0,bodyText:"",error:i instanceof Error?i.message:"proxy fetch failed"})}})(),!0):(t({ok:!1,status:0,bodyText:"",error:"url required"}),!0)}if(e.type==="INLINE_TTS"){const r=e.payload,o=typeof r?.text=="string"?r.text:"";return o.trim()?(chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineVoiceId","inlineVoiceStability","inlineVoiceSimilarity"],async i=>{const s=T(i.inlineApiBase,j),l=V(typeof r.voiceId=="string"&&r.voiceId||typeof i.inlineVoiceId=="string"&&i.inlineVoiceId||P),a=parseFloat(typeof i.inlineVoiceStability=="string"?i.inlineVoiceStability:"0.5"),c=parseFloat(typeof i.inlineVoiceSimilarity=="string"?i.inlineVoiceSimilarity:"0.75"),y=typeof i.inlineAccessToken=="string"?i.inlineAccessToken:"",u={"Content-Type":"application/json"};m(y)&&(u.Authorization=`Bearer ${y}`);try{const d=`${s}/api/tts`;g(d);const f=await fetch(d,{method:"POST",headers:u,body:JSON.stringify({text:o.slice(0,3e3),voiceId:l,stability:Number.isFinite(a)?a:.5,similarityBoost:Number.isFinite(c)?c:.75})});if(!f.ok){const p=await f.text().catch(()=>`HTTP ${f.status}`);t({ok:!1,error:p});return}const h=await f.arrayBuffer();t({ok:!0,audioBase64:R(h),mimeType:f.headers.get("Content-Type")||"audio/mpeg"})}catch(d){t({ok:!1,error:d instanceof Error?d.message:"TTS fetch failed"})}}),!0):(t({ok:!1,error:"empty text"}),!0)}if(e.type==="CAPTURE_TAB"){const r=n.tab?.windowId;return r==null?(t({ok:!1,error:"No tab context for capture"}),!0):(chrome.tabs.captureVisibleTab(r,{format:"png"},o=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0,dataUrl:o})}),!0)}if(e.type==="CLIP_TO_WORKSPACE"){const{pageUrl:r,pageTitle:o,selection:i,highlights:s,workspaceId:l}=e.payload;return chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineActiveWorkspaceId"],async a=>{const c=T(a.inlineApiBase,j),y=typeof a.inlineAccessToken=="string"?a.inlineAccessToken:"",u=l||(typeof a.inlineActiveWorkspaceId=="string"?a.inlineActiveWorkspaceId:""),d={"Content-Type":"application/json"};if(m(y)&&(d.Authorization=`Bearer ${y}`),!m(y)||!u){t({ok:!1,storageMode:"local",error:"Sign in to sync clips."});return}try{const f=`${c}/api/clip`;g(f);const h=await fetch(f,{method:"POST",headers:d,body:JSON.stringify({pageUrl:r,pageTitle:o,selection:i,highlights:s,workspaceId:u})}),p=await h.json();if(!h.ok){t({ok:!1,error:p.error??`HTTP ${h.status}`});return}t({ok:!0,data:p})}catch(f){t({ok:!1,error:f instanceof Error?f.message:"Clip failed"})}}),!0}if(e.type==="SAVE_ANNOTATIONS"){const{pageUrl:r,featureKey:o,data:i,pageTitle:s,domain:l,clearedAt:a}=e.payload;return chrome.storage.local.get(["inlineBackendBase","inlineAccessToken","inlineActiveWorkspaceId","inlineUserId"],async c=>{const y=T(c.inlineBackendBase,x),u=typeof c.inlineAccessToken=="string"?c.inlineAccessToken:"",d=typeof c.inlineActiveWorkspaceId=="string"?c.inlineActiveWorkspaceId:"",f=typeof c.inlineUserId=="string"?c.inlineUserId:"",h={"Content-Type":"application/json"};if(m(u)&&(h.Authorization=`Bearer ${u}`),!m(u)||!d){try{const p=await L({pageUrl:r,featureKey:o,data:i,pageTitle:s,domain:l,clearedAt:a});t({ok:!0,data:p,storageMode:"local"});return}catch{}t({ok:!1,storageMode:"local",error:"Browser storage is full."});return}try{await L({pageUrl:r,featureKey:o,data:i,pageTitle:s,domain:l,clearedAt:a});const p=`${y}/api/annotations`;g(p);const v=await fetch(p,{method:"POST",headers:h,body:JSON.stringify({pageUrl:r,featureKey:o,data:i,pageTitle:s??"",domain:l??"",workspaceId:d,userId:f,clearedAt:a??null})}),ee=await v.text();let k;try{k=JSON.parse(ee)}catch{t({ok:!1,error:"Server did not return JSON (check API URL / is the app running?)."});return}if(!v.ok){const te=typeof k=="object"&&k!==null&&"error"in k?String(k.error):`HTTP ${v.status}`;t({ok:!1,error:te});return}t({ok:!0,data:k,storageMode:"workspace"})}catch{try{await L({pageUrl:r,featureKey:o,data:i,pageTitle:s,domain:l,clearedAt:a}),await G({pageUrl:r,featureKey:o,data:i,timestamp:Date.now()})}catch{}t({ok:!1,queued:!0,storageMode:"local",error:"Queued for retry (backend unreachable)"})}}),!0}if(e.type==="LOAD_ANNOTATIONS"){const{pageUrl:r}=e.payload;return chrome.storage.local.get(["inlineBackendBase","inlineAccessToken"],async o=>{const i=T(o.inlineBackendBase,x),s=typeof o.inlineAccessToken=="string"?o.inlineAccessToken:"",l={};if(m(s)&&(l.Authorization=`Bearer ${s}`),!m(s)){const a=await A(r);t({ok:!0,data:a,storageMode:"local"});return}try{const a=`${i}/api/annotations?url=${encodeURIComponent(r)}`;g(a);const c=await fetch(a,{headers:l}),y=await c.text();let u;try{u=JSON.parse(y)}catch{const d=await A(r);t({ok:!0,data:d,storageMode:"local",warning:"Using browser copy."});return}if(!c.ok){const d=await A(r);t({ok:!0,data:d,storageMode:"local",warning:"Using browser copy."});return}t({ok:!0,data:u})}catch(a){const c=await A(r);t({ok:!0,data:c,storageMode:"local",warning:a instanceof Error?a.message:"Using browser copy."})}}),!0}}),chrome.commands.onCommand.addListener(e=>{chrome.tabs.query({active:!0,currentWindow:!0},n=>{const t=n[0]?.id;t!=null&&chrome.tabs.sendMessage(t,{type:"INLINE_COMMAND",command:e})})}),chrome.alarms.onAlarm.addListener(async e=>{if(e.name!=="inline-sync-retry")return;const n=await K();if(n.length===0)return;const t=await chrome.storage.local.get(["inlineBackendBase","inlineAccessToken","inlineActiveWorkspaceId"]),r=T(t.inlineBackendBase,x),o=typeof t.inlineAccessToken=="string"?t.inlineAccessToken:"",i=typeof t.inlineActiveWorkspaceId=="string"?t.inlineActiveWorkspaceId:"",s={"Content-Type":"application/json"};m(o)&&(s.Authorization=`Bearer ${o}`);const l=[...n];for(let a=0;ae.id));function K(e){return e&&q.has(e)?e:D}const W="https://useinline.vercel.app",Q=W,X=W,Z=new Set(["localhost","127.0.0.1","::1"]);function b(e){try{const n=new URL(e);if(n.protocol==="https:"||n.protocol==="wss:"||(n.protocol==="http:"||n.protocol==="ws:")&&Z.has(n.hostname))return!0}catch{return!1}return!1}function h(e){if(!b(e))throw new Error("Inline blocks non-local insecure network requests. Use HTTPS for synced workspace and AI requests.")}function R(e){const n=e.replace(/\/$/,"");return h(n),n}const V=X,P=Q;function k(e){if(!e)return!1;const n=e.split(".");return n.length===3&&n.every(t=>t.length>0)}function ee(e){let n=2166136261;for(let t=0;t>>0).toString(36)}function j(e){return`inlineLocalAnnotations:${ee(e)}`}function te(e,n){if(!e||typeof e!="object")return{pageUrl:n,pageTitle:"",domain:"",elements:{},updatedAt:0};const t=e,r=t.elements&&typeof t.elements=="object"&&!Array.isArray(t.elements)?t.elements:{};return{pageUrl:typeof t.pageUrl=="string"?t.pageUrl:n,pageTitle:typeof t.pageTitle=="string"?t.pageTitle:"",domain:typeof t.domain=="string"?t.domain:"",elements:r,updatedAt:typeof t.updatedAt=="number"?t.updatedAt:0,clearedAt:typeof t.clearedAt=="number"?t.clearedAt:null}}async function w(e){const n=j(e),t=await chrome.storage.local.get(n);return te(t[n],e)}async function x(e){const n=j(e.pageUrl),t=await w(e.pageUrl),r={...t,pageTitle:e.pageTitle??t.pageTitle,domain:e.domain??t.domain,elements:{...t.elements,[e.featureKey]:e.data},updatedAt:Date.now(),clearedAt:e.clearedAt??t.clearedAt??null};return await chrome.storage.local.set({[n]:r}),r}function J(e,n){return k(e)&&!!n}function E(e,n){const r=(typeof e=="string"&&e?e:n).replace(/\/$/,"");return b(r)?r:R(n)}function re(e){const n=new Uint8Array(e);let t="";for(let r=0;r{chrome.contextMenus.removeAll(()=>{chrome.contextMenus.create({id:"inline-analyze-risk",title:"Analyze page risk (Inline)",contexts:["page"]}),chrome.contextMenus.create({id:"inline-root",title:"Inline",contexts:["selection"]}),chrome.contextMenus.create({id:"notes",parentId:"inline-root",title:"📝 Add Note",contexts:["selection"]}),chrome.contextMenus.create({id:"highlight",parentId:"inline-root",title:"🖊️ Highlight",contexts:["selection"]}),chrome.contextMenus.create({id:"rewrite",parentId:"inline-root",title:"✏️ Rewrite",contexts:["selection"]}),chrome.contextMenus.create({id:"ai",parentId:"inline-root",title:"✨ Ask AI",contexts:["selection"]}),chrome.contextMenus.create({id:"clip-to-workspace",parentId:"inline-root",title:"📎 Clip to Workspace",contexts:["selection"]})})}),chrome.contextMenus.onClicked.addListener((e,n)=>{if(e.menuItemId==="inline-analyze-risk"&&n?.id!=null){chrome.tabs.sendMessage(n.id,{type:"INLINE_PAGE_RISK"}).catch(()=>{});return}!n?.id||e.menuItemId==="inline-root"||chrome.tabs.sendMessage(n.id,{type:"INLINE_FEATURE",featureId:e.menuItemId,selectedText:e.selectionText??""})}),chrome.runtime.onMessageExternal.addListener((e,n,t)=>{if(e?.type==="INLINE_SYNC_VOICE_SETTINGS"){const r=e.payload,o={};return r.voiceId!==void 0&&(o.inlineVoiceId=K(r.voiceId)),r.stability!==void 0&&(o.inlineVoiceStability=r.stability),r.similarity!==void 0&&(o.inlineVoiceSimilarity=r.similarity),chrome.storage.local.remove(["inlineElevenLabsKey"]),chrome.storage.local.set(o,()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}if(e?.type==="INLINE_SYNC_BLOCKLIST"){const r=e.payload;if(!Array.isArray(r?.blockedDomains))return t({ok:!1,error:"blockedDomains must be an array"}),!0;const o=r.blockedDomains.filter(a=>typeof a=="string").map(a=>a.trim().toLowerCase()).filter(Boolean);return chrome.storage.local.set({inlineBlockedDomains:JSON.stringify(o)},()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}if(e?.type==="INLINE_SYNC_AUTH"){const r=e.payload,o={};if(typeof r.accessToken=="string"&&(o.inlineAccessToken=r.accessToken),typeof r.userId=="string"&&(o.inlineUserId=r.userId),typeof r.workspaceId=="string"&&r.workspaceId&&(o.inlineActiveWorkspaceId=r.workspaceId),typeof r.apiBase=="string"&&r.apiBase){const a=r.apiBase.replace(/\/$/,"");if(!b(a))return t({ok:!1,error:"Workspace sync must use HTTPS outside local development."}),!0;o.inlineApiBase=a}if(typeof r.backendBase=="string"&&r.backendBase){const a=r.backendBase.replace(/\/$/,"");if(!b(a))return t({ok:!1,error:"Workspace sync must use HTTPS outside local development."}),!0;o.inlineBackendBase=a}return typeof r.email=="string"&&r.email&&(o.inlineUserEmail=r.email),typeof r.name=="string"&&r.name&&(o.inlineUserName=r.name),typeof r.avatarUrl=="string"&&r.avatarUrl&&(o.inlineUserAvatarUrl=r.avatarUrl),chrome.storage.local.set(o,()=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0})}),!0}}),chrome.runtime.onMessage.addListener((e,n,t)=>{if(e.type==="INLINE_PROXY_FETCH"){const r=e.payload,o=typeof r?.url=="string"?r.url:"";return o?((async()=>{try{h(o);const a=await fetch(o,{method:r.method??"GET",headers:r.headers??{},body:r.body}),d=await a.text().catch(()=>"");t({ok:a.ok,status:a.status,bodyText:d})}catch(a){t({ok:!1,status:0,bodyText:"",error:a instanceof Error?a.message:"proxy fetch failed"})}})(),!0):(t({ok:!1,status:0,bodyText:"",error:"url required"}),!0)}if(e.type==="INLINE_TTS"){const r=e.payload,o=typeof r?.text=="string"?r.text:"";return o.trim()?(chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineVoiceId","inlineVoiceStability","inlineVoiceSimilarity"],async a=>{const d=E(a.inlineApiBase,P),m=K(typeof r.voiceId=="string"&&r.voiceId||typeof a.inlineVoiceId=="string"&&a.inlineVoiceId||D),s=parseFloat(typeof a.inlineVoiceStability=="string"?a.inlineVoiceStability:"0.5"),i=parseFloat(typeof a.inlineVoiceSimilarity=="string"?a.inlineVoiceSimilarity:"0.75"),u=typeof a.inlineAccessToken=="string"?a.inlineAccessToken:"",f={"Content-Type":"application/json"};k(u)&&(f.Authorization=`Bearer ${u}`);try{const l=`${d}/api/tts`;h(l);const c=await fetch(l,{method:"POST",headers:f,body:JSON.stringify({text:o.slice(0,3e3),voiceId:m,stability:Number.isFinite(s)?s:.5,similarityBoost:Number.isFinite(i)?i:.75})});if(!c.ok){const y=await c.text().catch(()=>`HTTP ${c.status}`);t({ok:!1,error:y});return}const p=await c.arrayBuffer();t({ok:!0,audioBase64:re(p),mimeType:c.headers.get("Content-Type")||"audio/mpeg"})}catch(l){t({ok:!1,error:l instanceof Error?l.message:"TTS fetch failed"})}}),!0):(t({ok:!1,error:"empty text"}),!0)}if(e.type==="CAPTURE_TAB"){const r=n.tab?.windowId;return r==null?(t({ok:!1,error:"No tab context for capture"}),!0):(chrome.tabs.captureVisibleTab(r,{format:"png"},o=>{if(chrome.runtime.lastError){t({ok:!1,error:chrome.runtime.lastError.message});return}t({ok:!0,dataUrl:o})}),!0)}if(e.type==="CLIP_TO_WORKSPACE"){const{pageUrl:r,pageTitle:o,selection:a,highlights:d,workspaceId:m}=e.payload;return chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineActiveWorkspaceId"],async s=>{const i=E(s.inlineApiBase,P),u=typeof s.inlineAccessToken=="string"?s.inlineAccessToken:"",f=m||(typeof s.inlineActiveWorkspaceId=="string"?s.inlineActiveWorkspaceId:""),l={"Content-Type":"application/json"};if(k(u)&&(l.Authorization=`Bearer ${u}`),!k(u)||!f){t({ok:!1,storageMode:"local",error:"Sign in to sync clips."});return}try{const c=`${i}/api/clip`;h(c);const p=await fetch(c,{method:"POST",headers:l,body:JSON.stringify({pageUrl:r,pageTitle:o,selection:a,highlights:d,workspaceId:f})}),y=await p.json();if(!p.ok){t({ok:!1,error:y.error??`HTTP ${p.status}`});return}t({ok:!0,data:y})}catch(c){t({ok:!1,error:c instanceof Error?c.message:"Clip failed"})}}),!0}if(e.type==="SAVE_ANNOTATIONS"){const{pageUrl:r,featureKey:o,data:a,pageTitle:d,domain:m,clearedAt:s}=e.payload;return chrome.storage.local.get(["inlineBackendBase","inlineAccessToken","inlineActiveWorkspaceId","inlineUserId"],async i=>{const u=E(i.inlineBackendBase,V),f=typeof i.inlineAccessToken=="string"?i.inlineAccessToken:"",l=typeof i.inlineActiveWorkspaceId=="string"?i.inlineActiveWorkspaceId:"",c=typeof i.inlineUserId=="string"?i.inlineUserId:"",p={"Content-Type":"application/json"};k(f)&&(p.Authorization=`Bearer ${f}`);const y={pageUrl:r,featureKey:o,data:a,pageTitle:d,domain:m,clearedAt:s};if(!J(f,l)){try{const g=await x(y);t({ok:!0,data:g,storageMode:"local"})}catch{t({ok:!1,storageMode:"local",error:"Browser storage is full."})}return}try{const g=await x(y),S=`${u}/api/annotations`;h(S);const B=await fetch(S,{method:"POST",headers:p,body:JSON.stringify({pageUrl:r,featureKey:o,data:a,pageTitle:d??"",domain:m??"",workspaceId:l,userId:c,clearedAt:s??null})}),ne=await B.text();let A;try{A=JSON.parse(ne)}catch{t({ok:!0,data:g,storageMode:"local",warning:"Server did not return JSON (saved in browser)."});return}if(!B.ok){const oe=typeof A=="object"&&A!==null&&"error"in A?String(A.error):`HTTP ${B.status}`;await _({pageUrl:r,featureKey:o,data:a,timestamp:Date.now()}).catch(()=>{}),t({ok:!0,data:g,storageMode:"local",warning:oe});return}t({ok:!0,data:A,storageMode:"workspace"})}catch(g){try{const S=await x(y);await _({pageUrl:r,featureKey:o,data:a,timestamp:Date.now()}).catch(()=>{}),t({ok:!0,data:S,storageMode:"local",warning:g instanceof Error?g.message:"Backend unreachable"})}catch{t({ok:!1,storageMode:"local",error:"Browser storage is full."})}}}),!0}if(e.type==="LOAD_ANNOTATIONS"){const{pageUrl:r}=e.payload;return chrome.storage.local.get(["inlineBackendBase","inlineAccessToken","inlineActiveWorkspaceId"],async o=>{const a=E(o.inlineBackendBase,V),d=typeof o.inlineAccessToken=="string"?o.inlineAccessToken:"",m=typeof o.inlineActiveWorkspaceId=="string"?o.inlineActiveWorkspaceId:"",s={};if(k(d)&&(s.Authorization=`Bearer ${d}`),!J(d,m)){const i=await w(r);t({ok:!0,data:i,storageMode:"local"});return}try{const i=`${a}/api/annotations?url=${encodeURIComponent(r)}`;h(i);const u=await fetch(i,{headers:s}),f=await u.text();let l;try{l=JSON.parse(f)}catch{const y=await w(r);t({ok:!0,data:y,storageMode:"local",warning:"Using browser copy."});return}if(!u.ok){const y=await w(r);t({ok:!0,data:y,storageMode:"local",warning:"Using browser copy."});return}const c=l,p=c.elements&&typeof c.elements=="object"&&!Array.isArray(c.elements)?c.elements:{};t({ok:!0,data:{elements:p},storageMode:"workspace"})}catch(i){const u=await w(r);t({ok:!0,data:u,storageMode:"local",warning:i instanceof Error?i.message:"Using browser copy."})}}),!0}}),chrome.commands.onCommand.addListener(e=>{chrome.tabs.query({active:!0,currentWindow:!0},n=>{const t=n[0]?.id;t!=null&&chrome.tabs.sendMessage(t,{type:"INLINE_COMMAND",command:e})})})})(); diff --git a/inlineExtension/dist/content.js b/inlineExtension/dist/content.js index a072f8b..f830f8e 100644 --- a/inlineExtension/dist/content.js +++ b/inlineExtension/dist/content.js @@ -1,62 +1,139 @@ -(function(){"use strict";var ko={exports:{}},ss={};var Gf;function zb(){if(Gf)return ss;Gf=1;var i=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function l(r,d,f){var h=null;if(f!==void 0&&(h=""+f),d.key!==void 0&&(h=""+d.key),"key"in d){f={};for(var p in d)p!=="key"&&(f[p]=d[p])}else f=d;return d=f.ref,{$$typeof:i,type:r,key:h,ref:d!==void 0?d:null,props:f}}return ss.Fragment=a,ss.jsx=l,ss.jsxs=l,ss}var qf;function Lb(){return qf||(qf=1,ko.exports=zb()),ko.exports}var u=Lb(),Ro={exports:{}},ls={},Do={exports:{}},zo={};var Xf;function Ob(){return Xf||(Xf=1,(function(i){function a(B,at){var G=B.length;B.push(at);t:for(;0>>1,bt=B[ct];if(0>>1;ctd(nt,G))dtd(vt,nt)?(B[ct]=vt,B[dt]=G,ct=dt):(B[ct]=nt,B[K]=G,ct=K);else if(dtd(vt,G))B[ct]=vt,B[dt]=G,ct=dt;else break t}}return at}function d(B,at){var G=B.sortIndex-at.sortIndex;return G!==0?G:B.id-at.id}if(i.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var f=performance;i.unstable_now=function(){return f.now()}}else{var h=Date,p=h.now();i.unstable_now=function(){return h.now()-p}}var y=[],g=[],b=1,S=null,A=3,j=!1,k=!1,D=!1,O=!1,F=typeof setTimeout=="function"?setTimeout:null,Q=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;function T(B){for(var at=l(g);at!==null;){if(at.callback===null)r(g);else if(at.startTime<=B)r(g),at.sortIndex=at.expirationTime,a(y,at);else break;at=l(g)}}function L(B){if(D=!1,T(B),!k)if(l(y)!==null)k=!0,U||(U=!0,it());else{var at=l(g);at!==null&&kt(L,at.startTime-B)}}var U=!1,$=-1,tt=5,P=-1;function W(){return O?!0:!(i.unstable_now()-PB&&W());){var ct=S.callback;if(typeof ct=="function"){S.callback=null,A=S.priorityLevel;var bt=ct(S.expirationTime<=B);if(B=i.unstable_now(),typeof bt=="function"){S.callback=bt,T(B),at=!0;break e}S===l(y)&&r(y),T(B)}else r(y);S=l(y)}if(S!==null)at=!0;else{var M=l(g);M!==null&&kt(L,M.startTime-B),at=!1}}break t}finally{S=null,A=G,j=!1}at=void 0}}finally{at?it():U=!1}}}var it;if(typeof E=="function")it=function(){E(lt)};else if(typeof MessageChannel<"u"){var rt=new MessageChannel,mt=rt.port2;rt.port1.onmessage=lt,it=function(){mt.postMessage(null)}}else it=function(){F(lt,0)};function kt(B,at){$=F(function(){B(i.unstable_now())},at)}i.unstable_IdlePriority=5,i.unstable_ImmediatePriority=1,i.unstable_LowPriority=4,i.unstable_NormalPriority=3,i.unstable_Profiling=null,i.unstable_UserBlockingPriority=2,i.unstable_cancelCallback=function(B){B.callback=null},i.unstable_forceFrameRate=function(B){0>B||125ct?(B.sortIndex=G,a(g,B),l(y)===null&&B===l(g)&&(D?(Q($),$=-1):D=!0,kt(L,G-ct))):(B.sortIndex=bt,a(y,B),k||j||(k=!0,U||(U=!0,it()))),B},i.unstable_shouldYield=W,i.unstable_wrapCallback=function(B){var at=A;return function(){var G=A;A=at;try{return B.apply(this,arguments)}finally{A=G}}}})(zo)),zo}var Ff;function Bb(){return Ff||(Ff=1,Do.exports=Ob()),Do.exports}var Lo={exports:{}},Mt={};var Pf;function Nb(){if(Pf)return Mt;Pf=1;var i=Symbol.for("react.transitional.element"),a=Symbol.for("react.portal"),l=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),f=Symbol.for("react.consumer"),h=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),b=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),A=Symbol.iterator;function j(M){return M===null||typeof M!="object"?null:(M=A&&M[A]||M["@@iterator"],typeof M=="function"?M:null)}var k={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},D=Object.assign,O={};function F(M,K,nt){this.props=M,this.context=K,this.refs=O,this.updater=nt||k}F.prototype.isReactComponent={},F.prototype.setState=function(M,K){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,K,"setState")},F.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function Q(){}Q.prototype=F.prototype;function E(M,K,nt){this.props=M,this.context=K,this.refs=O,this.updater=nt||k}var T=E.prototype=new Q;T.constructor=E,D(T,F.prototype),T.isPureReactComponent=!0;var L=Array.isArray;function U(){}var $={H:null,A:null,T:null,S:null},tt=Object.prototype.hasOwnProperty;function P(M,K,nt){var dt=nt.ref;return{$$typeof:i,type:M,key:K,ref:dt!==void 0?dt:null,props:nt}}function W(M,K){return P(M.type,K,M.props)}function lt(M){return typeof M=="object"&&M!==null&&M.$$typeof===i}function it(M){var K={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(nt){return K[nt]})}var rt=/\/+/g;function mt(M,K){return typeof M=="object"&&M!==null&&M.key!=null?it(""+M.key):K.toString(36)}function kt(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(U,U):(M.status="pending",M.then(function(K){M.status==="pending"&&(M.status="fulfilled",M.value=K)},function(K){M.status==="pending"&&(M.status="rejected",M.reason=K)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function B(M,K,nt,dt,vt){var Y=typeof M;(Y==="undefined"||Y==="boolean")&&(M=null);var H=!1;if(M===null)H=!0;else switch(Y){case"bigint":case"string":case"number":H=!0;break;case"object":switch(M.$$typeof){case i:case a:H=!0;break;case b:return H=M._init,B(H(M._payload),K,nt,dt,vt)}}if(H)return vt=vt(M),H=dt===""?"."+mt(M,0):dt,L(vt)?(nt="",H!=null&&(nt=H.replace(rt,"$&/")+"/"),B(vt,K,nt,"",function(Tt){return Tt})):vt!=null&&(lt(vt)&&(vt=W(vt,nt+(vt.key==null||M&&M.key===vt.key?"":(""+vt.key).replace(rt,"$&/")+"/")+H)),K.push(vt)),1;H=0;var st=dt===""?".":dt+":";if(L(M))for(var ht=0;ht"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(a){console.error(a)}}return i(),Bo.exports=_b(),Bo.exports}var Zf;function Ub(){if(Zf)return ls;Zf=1;var i=Bb(),a=Oo(),l=Vb();function r(t){var e="https://react.dev/errors/"+t;if(1bt||(t.current=ct[bt],ct[bt]=null,bt--)}function nt(t,e){bt++,ct[bt]=t.current,t.current=e}var dt=M(null),vt=M(null),Y=M(null),H=M(null);function st(t,e){switch(nt(Y,e),nt(vt,t),nt(dt,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?eb(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=eb(e),t=nb(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}K(dt),nt(dt,t)}function ht(){K(dt),K(vt),K(Y)}function Tt(t){t.memoizedState!==null&&nt(H,t);var e=dt.current,n=nb(e,t.type);e!==n&&(nt(vt,t),nt(dt,n))}function Vt(t){vt.current===t&&(K(dt),K(vt)),H.current===t&&(K(H),gl._currentValue=G)}var ut,It;function Et(t){if(ut===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);ut=e&&e[1]||"",It=-1)":-1>>1,bt=B[dt];if(0>>1;dtd(nt,Y))ftd(vt,nt)?(B[dt]=vt,B[ft]=Y,dt=ft):(B[dt]=nt,B[P]=Y,dt=P);else if(ftd(vt,Y))B[dt]=vt,B[ft]=Y,dt=ft;else break t}}return at}function d(B,at){var Y=B.sortIndex-at.sortIndex;return Y!==0?Y:B.id-at.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var f=performance;n.unstable_now=function(){return f.now()}}else{var h=Date,p=h.now();n.unstable_now=function(){return h.now()-p}}var y=[],g=[],b=1,w=null,A=3,j=!1,k=!1,D=!1,O=!1,q=typeof setTimeout=="function"?setTimeout:null,W=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;function T(B){for(var at=l(g);at!==null;){if(at.callback===null)r(g);else if(at.startTime<=B)r(g),at.sortIndex=at.expirationTime,a(y,at);else break;at=l(g)}}function L(B){if(D=!1,T(B),!k)if(l(y)!==null)k=!0,H||(H=!0,it());else{var at=l(g);at!==null&&Mt(L,at.startTime-B)}}var H=!1,J=-1,$=5,F=-1;function K(){return O?!0:!(n.unstable_now()-F<$)}function lt(){if(O=!1,H){var B=n.unstable_now();F=B;var at=!0;try{t:{k=!1,D&&(D=!1,W(J),J=-1),j=!0;var Y=A;try{e:{for(T(B),w=l(y);w!==null&&!(w.expirationTime>B&&K());){var dt=w.callback;if(typeof dt=="function"){w.callback=null,A=w.priorityLevel;var bt=dt(w.expirationTime<=B);if(B=n.unstable_now(),typeof bt=="function"){w.callback=bt,T(B),at=!0;break e}w===l(y)&&r(y),T(B)}else r(y);w=l(y)}if(w!==null)at=!0;else{var M=l(g);M!==null&&Mt(L,M.startTime-B),at=!1}}break t}finally{w=null,A=Y,j=!1}at=void 0}}finally{at?it():H=!1}}}var it;if(typeof E=="function")it=function(){E(lt)};else if(typeof MessageChannel<"u"){var rt=new MessageChannel,ht=rt.port2;rt.port1.onmessage=lt,it=function(){ht.postMessage(null)}}else it=function(){q(lt,0)};function Mt(B,at){J=q(function(){B(n.unstable_now())},at)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(B){B.callback=null},n.unstable_forceFrameRate=function(B){0>B||125dt?(B.sortIndex=Y,a(g,B),l(y)===null&&B===l(g)&&(D?(W(J),J=-1):D=!0,Mt(L,Y-dt))):(B.sortIndex=bt,a(y,B),k||j||(k=!0,H||(H=!0,it()))),B},n.unstable_shouldYield=K,n.unstable_wrapCallback=function(B){var at=A;return function(){var Y=A;A=at;try{return B.apply(this,arguments)}finally{A=Y}}}})(Uo)),Uo}var nh;function Jb(){return nh||(nh=1,_o.exports=$b()),_o.exports}var Ho={exports:{}},Ct={};var ih;function tv(){if(ih)return Ct;ih=1;var n=Symbol.for("react.transitional.element"),a=Symbol.for("react.portal"),l=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),f=Symbol.for("react.consumer"),h=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),b=Symbol.for("react.lazy"),w=Symbol.for("react.activity"),A=Symbol.iterator;function j(M){return M===null||typeof M!="object"?null:(M=A&&M[A]||M["@@iterator"],typeof M=="function"?M:null)}var k={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},D=Object.assign,O={};function q(M,P,nt){this.props=M,this.context=P,this.refs=O,this.updater=nt||k}q.prototype.isReactComponent={},q.prototype.setState=function(M,P){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,P,"setState")},q.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function W(){}W.prototype=q.prototype;function E(M,P,nt){this.props=M,this.context=P,this.refs=O,this.updater=nt||k}var T=E.prototype=new W;T.constructor=E,D(T,q.prototype),T.isPureReactComponent=!0;var L=Array.isArray;function H(){}var J={H:null,A:null,T:null,S:null},$=Object.prototype.hasOwnProperty;function F(M,P,nt){var ft=nt.ref;return{$$typeof:n,type:M,key:P,ref:ft!==void 0?ft:null,props:nt}}function K(M,P){return F(M.type,P,M.props)}function lt(M){return typeof M=="object"&&M!==null&&M.$$typeof===n}function it(M){var P={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(nt){return P[nt]})}var rt=/\/+/g;function ht(M,P){return typeof M=="object"&&M!==null&&M.key!=null?it(""+M.key):P.toString(36)}function Mt(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(H,H):(M.status="pending",M.then(function(P){M.status==="pending"&&(M.status="fulfilled",M.value=P)},function(P){M.status==="pending"&&(M.status="rejected",M.reason=P)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function B(M,P,nt,ft,vt){var I=typeof M;(I==="undefined"||I==="boolean")&&(M=null);var V=!1;if(M===null)V=!0;else switch(I){case"bigint":case"string":case"number":V=!0;break;case"object":switch(M.$$typeof){case n:case a:V=!0;break;case b:return V=M._init,B(V(M._payload),P,nt,ft,vt)}}if(V)return vt=vt(M),V=ft===""?"."+ht(M,0):ft,L(vt)?(nt="",V!=null&&(nt=V.replace(rt,"$&/")+"/"),B(vt,P,nt,"",function(Tt){return Tt})):vt!=null&&(lt(vt)&&(vt=K(vt,nt+(vt.key==null||M&&M.key===vt.key?"":(""+vt.key).replace(rt,"$&/")+"/")+V)),P.push(vt)),1;V=0;var st=ft===""?".":ft+":";if(L(M))for(var pt=0;pt"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(a){console.error(a)}}return n(),Io.exports=ev(),Io.exports}var rh;function iv(){if(rh)return ds;rh=1;var n=Jb(),a=Vo(),l=nv();function r(t){var e="https://react.dev/errors/"+t;if(1bt||(t.current=dt[bt],dt[bt]=null,bt--)}function nt(t,e){bt++,dt[bt]=t.current,t.current=e}var ft=M(null),vt=M(null),I=M(null),V=M(null);function st(t,e){switch(nt(I,e),nt(vt,t),nt(ft,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?bb(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=bb(e),t=vb(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}P(ft),nt(ft,t)}function pt(){P(ft),P(vt),P(I)}function Tt(t){t.memoizedState!==null&&nt(V,t);var e=ft.current,i=vb(e,t.type);e!==i&&(nt(vt,t),nt(ft,i))}function Vt(t){vt.current===t&&(P(ft),P(vt)),V.current===t&&(P(V),wl._currentValue=Y)}var ct,It;function jt(t){if(ct===void 0)try{throw Error()}catch(i){var e=i.stack.trim().match(/\n( *(at )?)/);ct=e&&e[1]||"",It=-1)":-1o||C[s]!==_[o]){var Z=` -`+C[s].replace(" at new "," at ");return t.displayName&&Z.includes("")&&(Z=Z.replace("",t.displayName)),Z}while(1<=s&&0<=o);break}}}finally{jt=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?Et(n):""}function ot(t,e){switch(t.tag){case 26:case 27:case 5:return Et(t.type);case 16:return Et("Lazy");case 13:return t.child!==e&&e!==null?Et("Suspense Fallback"):Et("Suspense");case 19:return Et("SuspenseList");case 0:case 15:return X(t.type,!1);case 11:return X(t.type.render,!1);case 1:return X(t.type,!0);case 31:return Et("Activity");default:return""}}function pt(t){try{var e="",n=null;do e+=ot(t,n),n=t,t=t.return;while(t);return e}catch(s){return` +`+C[s].replace(" at new "," at ");return t.displayName&&Z.includes("")&&(Z=Z.replace("",t.displayName)),Z}while(1<=s&&0<=o);break}}}finally{Et=!1,Error.prepareStackTrace=i}return(i=t?t.displayName||t.name:"")?jt(i):""}function ot(t,e){switch(t.tag){case 26:case 27:case 5:return jt(t.type);case 16:return jt("Lazy");case 13:return t.child!==e&&e!==null?jt("Suspense Fallback"):jt("Suspense");case 19:return jt("SuspenseList");case 0:case 15:return X(t.type,!1);case 11:return X(t.type.render,!1);case 1:return X(t.type,!0);case 31:return jt("Activity");default:return""}}function mt(t){try{var e="",i=null;do e+=ot(t,i),i=t,t=t.return;while(t);return e}catch(s){return` Error generating stack: `+s.message+` -`+s.stack}}var zt=Object.prototype.hasOwnProperty,Xt=i.unstable_scheduleCallback,ze=i.unstable_cancelCallback,I=i.unstable_shouldYield,ft=i.unstable_requestPaint,Ct=i.unstable_now,Ut=i.unstable_getCurrentPriorityLevel,Wt=i.unstable_ImmediatePriority,Ft=i.unstable_UserBlockingPriority,le=i.unstable_NormalPriority,cr=i.unstable_LowPriority,bn=i.unstable_IdlePriority,ui=i.log,dr=i.unstable_setDisableYieldValue,Ms=null,qe=null;function ci(t){if(typeof ui=="function"&&dr(t),qe&&typeof qe.setStrictMode=="function")try{qe.setStrictMode(Ms,t)}catch{}}var Xe=Math.clz32?Math.clz32:qE,YE=Math.log,GE=Math.LN2;function qE(t){return t>>>=0,t===0?32:31-(YE(t)/GE|0)|0}var fr=256,hr=262144,pr=4194304;function Gi(t){var e=t&42;if(e!==0)return e;switch(t&-t){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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function mr(t,e,n){var s=t.pendingLanes;if(s===0)return 0;var o=0,c=t.suspendedLanes,m=t.pingedLanes;t=t.warmLanes;var w=s&134217727;return w!==0?(s=w&~c,s!==0?o=Gi(s):(m&=w,m!==0?o=Gi(m):n||(n=w&~t,n!==0&&(o=Gi(n))))):(w=s&~c,w!==0?o=Gi(w):m!==0?o=Gi(m):n||(n=s&~t,n!==0&&(o=Gi(n)))),o===0?0:e!==0&&e!==o&&(e&c)===0&&(c=o&-o,n=e&-e,c>=n||c===32&&(n&4194048)!==0)?e:o}function ks(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function XE(t,e){switch(t){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32: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+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ny(){var t=pr;return pr<<=1,(pr&62914560)===0&&(pr=4194304),t}function Rc(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function Rs(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function FE(t,e,n,s,o,c){var m=t.pendingLanes;t.pendingLanes=n,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=n,t.entangledLanes&=n,t.errorRecoveryDisabledLanes&=n,t.shellSuspendCounter=0;var w=t.entanglements,C=t.expirationTimes,_=t.hiddenUpdates;for(n=m&~n;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var $E=/[\n"\\]/g;function nn(t){return t.replace($E,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function Nc(t,e,n,s,o,c,m,w){t.name="",m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"?t.type=m:t.removeAttribute("type"),e!=null?m==="number"?(e===0&&t.value===""||t.value!=e)&&(t.value=""+en(e)):t.value!==""+en(e)&&(t.value=""+en(e)):m!=="submit"&&m!=="reset"||t.removeAttribute("value"),e!=null?_c(t,m,en(e)):n!=null?_c(t,m,en(n)):s!=null&&t.removeAttribute("value"),o==null&&c!=null&&(t.defaultChecked=!!c),o!=null&&(t.checked=o&&typeof o!="function"&&typeof o!="symbol"),w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"?t.name=""+en(w):t.removeAttribute("name")}function Wy(t,e,n,s,o,c,m,w){if(c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(t.type=c),e!=null||n!=null){if(!(c!=="submit"&&c!=="reset"||e!=null)){Bc(t);return}n=n!=null?""+en(n):"",e=e!=null?""+en(e):n,w||e===t.value||(t.value=e),t.defaultValue=e}s=s??o,s=typeof s!="function"&&typeof s!="symbol"&&!!s,t.checked=w?t.checked:!!s,t.defaultChecked=!!s,m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(t.name=m),Bc(t)}function _c(t,e,n){e==="number"&&xr(t.ownerDocument)===t||t.defaultValue===""+n||(t.defaultValue=""+n)}function ja(t,e,n,s){if(t=t.options,e){e={};for(var o=0;o"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Yc=!1;if(Un)try{var Os={};Object.defineProperty(Os,"passive",{get:function(){Yc=!0}}),window.addEventListener("test",Os,Os),window.removeEventListener("test",Os,Os)}catch{Yc=!1}var fi=null,Gc=null,vr=null;function n0(){if(vr)return vr;var t,e=Gc,n=e.length,s,o="value"in fi?fi.value:fi.textContent,c=o.length;for(t=0;t=_s),o0=" ",u0=!1;function c0(t,e){switch(t){case"keyup":return jj.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function d0(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ra=!1;function Mj(t,e){switch(t){case"compositionend":return d0(e);case"keypress":return e.which!==32?null:(u0=!0,o0);case"textInput":return t=e.data,t===o0&&u0?null:t;default:return null}}function kj(t,e){if(Ra)return t==="compositionend"||!Kc&&c0(t,e)?(t=n0(),vr=Gc=fi=null,Ra=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=s}t:{for(;n;){if(n.nextSibling){n=n.nextSibling;break t}n=n.parentNode}n=void 0}n=b0(n)}}function S0(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?S0(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function w0(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=xr(t.document);e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=xr(t.document)}return e}function Zc(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}var _j=Un&&"documentMode"in document&&11>=document.documentMode,Da=null,$c=null,Is=null,Jc=!1;function A0(t,e,n){var s=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Jc||Da==null||Da!==xr(s)||(s=Da,"selectionStart"in s&&Zc(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),Is&&Hs(Is,s)||(Is=s,s=po($c,"onSelect"),0>=m,o-=m,Rn=1<<32-Xe(e)+o|n<Dt?(Nt=St,St=null):Nt=St.sibling;var Gt=V(z,St,N[Dt],J);if(Gt===null){St===null&&(St=Nt);break}t&&St&&Gt.alternate===null&&e(z,St),R=c(Gt,R,Dt),Yt===null?wt=Gt:Yt.sibling=Gt,Yt=Gt,St=Nt}if(Dt===N.length)return n(z,St),Ht&&In(z,Dt),wt;if(St===null){for(;DtDt?(Nt=St,St=null):Nt=St.sibling;var Oi=V(z,St,Gt.value,J);if(Oi===null){St===null&&(St=Nt);break}t&&St&&Oi.alternate===null&&e(z,St),R=c(Oi,R,Dt),Yt===null?wt=Oi:Yt.sibling=Oi,Yt=Oi,St=Nt}if(Gt.done)return n(z,St),Ht&&In(z,Dt),wt;if(St===null){for(;!Gt.done;Dt++,Gt=N.next())Gt=et(z,Gt.value,J),Gt!==null&&(R=c(Gt,R,Dt),Yt===null?wt=Gt:Yt.sibling=Gt,Yt=Gt);return Ht&&In(z,Dt),wt}for(St=s(St);!Gt.done;Dt++,Gt=N.next())Gt=q(St,z,Dt,Gt.value,J),Gt!==null&&(t&&Gt.alternate!==null&&St.delete(Gt.key===null?Dt:Gt.key),R=c(Gt,R,Dt),Yt===null?wt=Gt:Yt.sibling=Gt,Yt=Gt);return t&&St.forEach(function(iC){return e(z,iC)}),Ht&&In(z,Dt),wt}function $t(z,R,N,J){if(typeof N=="object"&&N!==null&&N.type===D&&N.key===null&&(N=N.props.children),typeof N=="object"&&N!==null){switch(N.$$typeof){case j:t:{for(var wt=N.key;R!==null;){if(R.key===wt){if(wt=N.type,wt===D){if(R.tag===7){n(z,R.sibling),J=o(R,N.props.children),J.return=z,z=J;break t}}else if(R.elementType===wt||typeof wt=="object"&&wt!==null&&wt.$$typeof===tt&&ta(wt)===R.type){n(z,R.sibling),J=o(R,N.props),Ps(J,N),J.return=z,z=J;break t}n(z,R);break}else e(z,R);R=R.sibling}N.type===D?(J=Wi(N.props.children,z.mode,J,N.key),J.return=z,z=J):(J=Rr(N.type,N.key,N.props,null,z.mode,J),Ps(J,N),J.return=z,z=J)}return m(z);case k:t:{for(wt=N.key;R!==null;){if(R.key===wt)if(R.tag===4&&R.stateNode.containerInfo===N.containerInfo&&R.stateNode.implementation===N.implementation){n(z,R.sibling),J=o(R,N.children||[]),J.return=z,z=J;break t}else{n(z,R);break}else e(z,R);R=R.sibling}J=ld(N,z.mode,J),J.return=z,z=J}return m(z);case tt:return N=ta(N),$t(z,R,N,J)}if(kt(N))return yt(z,R,N,J);if(it(N)){if(wt=it(N),typeof wt!="function")throw Error(r(150));return N=wt.call(N),At(z,R,N,J)}if(typeof N.then=="function")return $t(z,R,_r(N),J);if(N.$$typeof===E)return $t(z,R,Lr(z,N),J);Vr(z,N)}return typeof N=="string"&&N!==""||typeof N=="number"||typeof N=="bigint"?(N=""+N,R!==null&&R.tag===6?(n(z,R.sibling),J=o(R,N),J.return=z,z=J):(n(z,R),J=sd(N,z.mode,J),J.return=z,z=J),m(z)):n(z,R)}return function(z,R,N,J){try{Fs=0;var wt=$t(z,R,N,J);return Ya=null,wt}catch(St){if(St===Ia||St===Br)throw St;var Yt=Pe(29,St,null,z.mode);return Yt.lanes=J,Yt.return=z,Yt}}}var na=F0(!0),P0=F0(!1),yi=!1;function xd(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function bd(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function xi(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function bi(t,e,n){var s=t.updateQueue;if(s===null)return null;if(s=s.shared,(qt&2)!==0){var o=s.pending;return o===null?e.next=e:(e.next=o.next,o.next=e),s.pending=e,e=kr(t),R0(t,null,n),e}return Mr(t,s,e,n),kr(t)}function Ks(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194048)!==0)){var s=e.lanes;s&=t.pendingLanes,n|=s,e.lanes=n,Vy(t,n)}}function vd(t,e){var n=t.updateQueue,s=t.alternate;if(s!==null&&(s=s.updateQueue,n===s)){var o=null,c=null;if(n=n.firstBaseUpdate,n!==null){do{var m={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};c===null?o=c=m:c=c.next=m,n=n.next}while(n!==null);c===null?o=c=e:c=c.next=e}else o=c=e;n={baseState:s.baseState,firstBaseUpdate:o,lastBaseUpdate:c,shared:s.shared,callbacks:s.callbacks},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}var Sd=!1;function Ws(){if(Sd){var t=Ha;if(t!==null)throw t}}function Qs(t,e,n,s){Sd=!1;var o=t.updateQueue;yi=!1;var c=o.firstBaseUpdate,m=o.lastBaseUpdate,w=o.shared.pending;if(w!==null){o.shared.pending=null;var C=w,_=C.next;C.next=null,m===null?c=_:m.next=_,m=C;var Z=t.alternate;Z!==null&&(Z=Z.updateQueue,w=Z.lastBaseUpdate,w!==m&&(w===null?Z.firstBaseUpdate=_:w.next=_,Z.lastBaseUpdate=C))}if(c!==null){var et=o.baseState;m=0,Z=_=C=null,w=c;do{var V=w.lane&-536870913,q=V!==w.lane;if(q?(Bt&V)===V:(s&V)===V){V!==0&&V===Ua&&(Sd=!0),Z!==null&&(Z=Z.next={lane:0,tag:w.tag,payload:w.payload,callback:null,next:null});t:{var yt=t,At=w;V=e;var $t=n;switch(At.tag){case 1:if(yt=At.payload,typeof yt=="function"){et=yt.call($t,et,V);break t}et=yt;break t;case 3:yt.flags=yt.flags&-65537|128;case 0:if(yt=At.payload,V=typeof yt=="function"?yt.call($t,et,V):yt,V==null)break t;et=S({},et,V);break t;case 2:yi=!0}}V=w.callback,V!==null&&(t.flags|=64,q&&(t.flags|=8192),q=o.callbacks,q===null?o.callbacks=[V]:q.push(V))}else q={lane:V,tag:w.tag,payload:w.payload,callback:w.callback,next:null},Z===null?(_=Z=q,C=et):Z=Z.next=q,m|=V;if(w=w.next,w===null){if(w=o.shared.pending,w===null)break;q=w,w=q.next,q.next=null,o.lastBaseUpdate=q,o.shared.pending=null}}while(!0);Z===null&&(C=et),o.baseState=C,o.firstBaseUpdate=_,o.lastBaseUpdate=Z,c===null&&(o.shared.lanes=0),Ti|=m,t.lanes=m,t.memoizedState=et}}function K0(t,e){if(typeof t!="function")throw Error(r(191,t));t.call(e)}function W0(t,e){var n=t.callbacks;if(n!==null)for(t.callbacks=null,t=0;tc?c:8;var m=B.T,w={};B.T=w,Hd(t,!1,e,n);try{var C=o(),_=B.S;if(_!==null&&_(w,C),C!==null&&typeof C=="object"&&typeof C.then=="function"){var Z=Fj(C,s);Js(t,e,Z,$e(t))}else Js(t,e,s,$e(t))}catch(et){Js(t,e,{then:function(){},status:"rejected",reason:et},$e())}finally{at.p=c,m!==null&&w.types!==null&&(m.types=w.types),B.T=m}}function $j(){}function Vd(t,e,n,s){if(t.tag!==5)throw Error(r(476));var o=C1(t).queue;j1(t,o,e,G,n===null?$j:function(){return M1(t),n(s)})}function C1(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:G,baseState:G,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Xn,lastRenderedState:G},next:null};var n={};return e.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Xn,lastRenderedState:n},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function M1(t){var e=C1(t);e.next===null&&(e=t.alternate.memoizedState),Js(t,e.next.queue,{},$e())}function Ud(){return Ee(gl)}function k1(){return ce().memoizedState}function R1(){return ce().memoizedState}function Jj(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var n=$e();t=xi(n);var s=bi(e,t,n);s!==null&&(Ie(s,e,n),Ks(s,e,n)),e={cache:pd()},t.payload=e;return}e=e.return}}function t4(t,e,n){var s=$e();n={lane:s,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Kr(t)?z1(e,n):(n=id(t,e,n,s),n!==null&&(Ie(n,t,s),L1(n,e,s)))}function D1(t,e,n){var s=$e();Js(t,e,n,s)}function Js(t,e,n,s){var o={lane:s,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Kr(t))z1(e,o);else{var c=t.alternate;if(t.lanes===0&&(c===null||c.lanes===0)&&(c=e.lastRenderedReducer,c!==null))try{var m=e.lastRenderedState,w=c(m,n);if(o.hasEagerState=!0,o.eagerState=w,Fe(w,m))return Mr(t,e,o,0),te===null&&Cr(),!1}catch{}if(n=id(t,e,o,s),n!==null)return Ie(n,t,s),L1(n,e,s),!0}return!1}function Hd(t,e,n,s){if(s={lane:2,revertLane:bf(),gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},Kr(t)){if(e)throw Error(r(479))}else e=id(t,n,s,2),e!==null&&Ie(e,t,2)}function Kr(t){var e=t.alternate;return t===Rt||e!==null&&e===Rt}function z1(t,e){qa=Ir=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function L1(t,e,n){if((n&4194048)!==0){var s=e.lanes;s&=t.pendingLanes,n|=s,e.lanes=n,Vy(t,n)}}var tl={readContext:Ee,use:qr,useCallback:re,useContext:re,useEffect:re,useImperativeHandle:re,useLayoutEffect:re,useInsertionEffect:re,useMemo:re,useReducer:re,useRef:re,useState:re,useDebugValue:re,useDeferredValue:re,useTransition:re,useSyncExternalStore:re,useId:re,useHostTransitionStatus:re,useFormState:re,useActionState:re,useOptimistic:re,useMemoCache:re,useCacheRefresh:re};tl.useEffectEvent=re;var O1={readContext:Ee,use:qr,useCallback:function(t,e){return Le().memoizedState=[t,e===void 0?null:e],t},useContext:Ee,useEffect:y1,useImperativeHandle:function(t,e,n){n=n!=null?n.concat([t]):null,Fr(4194308,4,S1.bind(null,e,t),n)},useLayoutEffect:function(t,e){return Fr(4194308,4,t,e)},useInsertionEffect:function(t,e){Fr(4,2,t,e)},useMemo:function(t,e){var n=Le();e=e===void 0?null:e;var s=t();if(ia){ci(!0);try{t()}finally{ci(!1)}}return n.memoizedState=[s,e],s},useReducer:function(t,e,n){var s=Le();if(n!==void 0){var o=n(e);if(ia){ci(!0);try{n(e)}finally{ci(!1)}}}else o=e;return s.memoizedState=s.baseState=o,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:o},s.queue=t,t=t.dispatch=t4.bind(null,Rt,t),[s.memoizedState,t]},useRef:function(t){var e=Le();return t={current:t},e.memoizedState=t},useState:function(t){t=Ld(t);var e=t.queue,n=D1.bind(null,Rt,e);return e.dispatch=n,[t.memoizedState,n]},useDebugValue:Nd,useDeferredValue:function(t,e){var n=Le();return _d(n,t,e)},useTransition:function(){var t=Ld(!1);return t=j1.bind(null,Rt,t.queue,!0,!1),Le().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,n){var s=Rt,o=Le();if(Ht){if(n===void 0)throw Error(r(407));n=n()}else{if(n=e(),te===null)throw Error(r(349));(Bt&127)!==0||e1(s,e,n)}o.memoizedState=n;var c={value:n,getSnapshot:e};return o.queue=c,y1(i1.bind(null,s,c,t),[t]),s.flags|=2048,Fa(9,{destroy:void 0},n1.bind(null,s,c,n,e),null),n},useId:function(){var t=Le(),e=te.identifierPrefix;if(Ht){var n=Dn,s=Rn;n=(s&~(1<<32-Xe(s)-1)).toString(32)+n,e="_"+e+"R_"+n,n=Yr++,0<\/script>",c=c.removeChild(c.firstChild);break;case"select":c=typeof s.is=="string"?m.createElement("select",{is:s.is}):m.createElement("select"),s.multiple?c.multiple=!0:s.size&&(c.size=s.size);break;default:c=typeof s.is=="string"?m.createElement(o,{is:s.is}):m.createElement(o)}}c[Ae]=e,c[Be]=s;t:for(m=e.child;m!==null;){if(m.tag===5||m.tag===6)c.appendChild(m.stateNode);else if(m.tag!==4&&m.tag!==27&&m.child!==null){m.child.return=m,m=m.child;continue}if(m===e)break t;for(;m.sibling===null;){if(m.return===null||m.return===e)break t;m=m.return}m.sibling.return=m.return,m=m.sibling}e.stateNode=c;t:switch(Ce(c,o,s),o){case"button":case"input":case"select":case"textarea":s=!!s.autoFocus;break t;case"img":s=!0;break t;default:s=!1}s&&Pn(e)}}return ie(e),tf(e,e.type,t===null?null:t.memoizedProps,e.pendingProps,n),null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==s&&Pn(e);else{if(typeof s!="string"&&e.stateNode===null)throw Error(r(166));if(t=Y.current,_a(e)){if(t=e.stateNode,n=e.memoizedProps,s=null,o=Te,o!==null)switch(o.tag){case 27:case 5:s=o.memoizedProps}t[Ae]=e,t=!!(t.nodeValue===n||s!==null&&s.suppressHydrationWarning===!0||Jx(t.nodeValue,n)),t||mi(e,!0)}else t=mo(t).createTextNode(s),t[Ae]=e,e.stateNode=t}return ie(e),null;case 31:if(n=e.memoizedState,t===null||t.memoizedState!==null){if(s=_a(e),n!==null){if(t===null){if(!s)throw Error(r(318));if(t=e.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[Ae]=e}else Qi(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;ie(e),t=!1}else n=cd(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=n),t=!0;if(!t)return e.flags&256?(We(e),e):(We(e),null);if((e.flags&128)!==0)throw Error(r(558))}return ie(e),null;case 13:if(s=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(o=_a(e),s!==null&&s.dehydrated!==null){if(t===null){if(!o)throw Error(r(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(r(317));o[Ae]=e}else Qi(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;ie(e),o=!1}else o=cd(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),o=!0;if(!o)return e.flags&256?(We(e),e):(We(e),null)}return We(e),(e.flags&128)!==0?(e.lanes=n,e):(n=s!==null,t=t!==null&&t.memoizedState!==null,n&&(s=e.child,o=null,s.alternate!==null&&s.alternate.memoizedState!==null&&s.alternate.memoizedState.cachePool!==null&&(o=s.alternate.memoizedState.cachePool.pool),c=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),c!==o&&(s.flags|=2048)),n!==t&&n&&(e.child.flags|=8192),Jr(e,e.updateQueue),ie(e),null);case 4:return ht(),t===null&&Af(e.stateNode.containerInfo),ie(e),null;case 10:return Gn(e.type),ie(e),null;case 19:if(K(ue),s=e.memoizedState,s===null)return ie(e),null;if(o=(e.flags&128)!==0,c=s.rendering,c===null)if(o)nl(s,!1);else{if(oe!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(c=Hr(t),c!==null){for(e.flags|=128,nl(s,!1),t=c.updateQueue,e.updateQueue=t,Jr(e,t),e.subtreeFlags=0,t=n,n=e.child;n!==null;)D0(n,t),n=n.sibling;return nt(ue,ue.current&1|2),Ht&&In(e,s.treeForkCount),e.child}t=t.sibling}s.tail!==null&&Ct()>ao&&(e.flags|=128,o=!0,nl(s,!1),e.lanes=4194304)}else{if(!o)if(t=Hr(c),t!==null){if(e.flags|=128,o=!0,t=t.updateQueue,e.updateQueue=t,Jr(e,t),nl(s,!0),s.tail===null&&s.tailMode==="hidden"&&!c.alternate&&!Ht)return ie(e),null}else 2*Ct()-s.renderingStartTime>ao&&n!==536870912&&(e.flags|=128,o=!0,nl(s,!1),e.lanes=4194304);s.isBackwards?(c.sibling=e.child,e.child=c):(t=s.last,t!==null?t.sibling=c:e.child=c,s.last=c)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Ct(),t.sibling=null,n=ue.current,nt(ue,o?n&1|2:n&1),Ht&&In(e,s.treeForkCount),t):(ie(e),null);case 22:case 23:return We(e),Ad(),s=e.memoizedState!==null,t!==null?t.memoizedState!==null!==s&&(e.flags|=8192):s&&(e.flags|=8192),s?(n&536870912)!==0&&(e.flags&128)===0&&(ie(e),e.subtreeFlags&6&&(e.flags|=8192)):ie(e),n=e.updateQueue,n!==null&&Jr(e,n.retryQueue),n=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),s=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),s!==n&&(e.flags|=2048),t!==null&&K(Ji),null;case 24:return n=null,t!==null&&(n=t.memoizedState.cache),e.memoizedState.cache!==n&&(e.flags|=2048),Gn(fe),ie(e),null;case 25:return null;case 30:return null}throw Error(r(156,e.tag))}function s4(t,e){switch(od(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Gn(fe),ht(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return Vt(e),null;case 31:if(e.memoizedState!==null){if(We(e),e.alternate===null)throw Error(r(340));Qi()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 13:if(We(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(r(340));Qi()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return K(ue),null;case 4:return ht(),null;case 10:return Gn(e.type),null;case 22:case 23:return We(e),Ad(),t!==null&&K(Ji),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return Gn(fe),null;case 25:return null;default:return null}}function ax(t,e){switch(od(e),e.tag){case 3:Gn(fe),ht();break;case 26:case 27:case 5:Vt(e);break;case 4:ht();break;case 31:e.memoizedState!==null&&We(e);break;case 13:We(e);break;case 19:K(ue);break;case 10:Gn(e.type);break;case 22:case 23:We(e),Ad(),t!==null&&K(Ji);break;case 24:Gn(fe)}}function il(t,e){try{var n=e.updateQueue,s=n!==null?n.lastEffect:null;if(s!==null){var o=s.next;n=o;do{if((n.tag&t)===t){s=void 0;var c=n.create,m=n.inst;s=c(),m.destroy=s}n=n.next}while(n!==o)}}catch(w){Kt(e,e.return,w)}}function wi(t,e,n){try{var s=e.updateQueue,o=s!==null?s.lastEffect:null;if(o!==null){var c=o.next;s=c;do{if((s.tag&t)===t){var m=s.inst,w=m.destroy;if(w!==void 0){m.destroy=void 0,o=e;var C=n,_=w;try{_()}catch(Z){Kt(o,C,Z)}}}s=s.next}while(s!==c)}}catch(Z){Kt(e,e.return,Z)}}function sx(t){var e=t.updateQueue;if(e!==null){var n=t.stateNode;try{W0(e,n)}catch(s){Kt(t,t.return,s)}}}function lx(t,e,n){n.props=aa(t.type,t.memoizedProps),n.state=t.memoizedState;try{n.componentWillUnmount()}catch(s){Kt(t,e,s)}}function al(t,e){try{var n=t.ref;if(n!==null){switch(t.tag){case 26:case 27:case 5:var s=t.stateNode;break;case 30:s=t.stateNode;break;default:s=t.stateNode}typeof n=="function"?t.refCleanup=n(s):n.current=s}}catch(o){Kt(t,e,o)}}function zn(t,e){var n=t.ref,s=t.refCleanup;if(n!==null)if(typeof s=="function")try{s()}catch(o){Kt(t,e,o)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(o){Kt(t,e,o)}else n.current=null}function rx(t){var e=t.type,n=t.memoizedProps,s=t.stateNode;try{t:switch(e){case"button":case"input":case"select":case"textarea":n.autoFocus&&s.focus();break t;case"img":n.src?s.src=n.src:n.srcSet&&(s.srcset=n.srcSet)}}catch(o){Kt(t,t.return,o)}}function ef(t,e,n){try{var s=t.stateNode;C4(s,t.type,n,e),s[Be]=e}catch(o){Kt(t,t.return,o)}}function ox(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&ki(t.type)||t.tag===4}function nf(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||ox(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&ki(t.type)||t.flags&2||t.child===null||t.tag===4)continue t;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function af(t,e,n){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?(n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n).insertBefore(t,e):(e=n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n,e.appendChild(t),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Vn));else if(s!==4&&(s===27&&ki(t.type)&&(n=t.stateNode,e=null),t=t.child,t!==null))for(af(t,e,n),t=t.sibling;t!==null;)af(t,e,n),t=t.sibling}function to(t,e,n){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(s!==4&&(s===27&&ki(t.type)&&(n=t.stateNode),t=t.child,t!==null))for(to(t,e,n),t=t.sibling;t!==null;)to(t,e,n),t=t.sibling}function ux(t){var e=t.stateNode,n=t.memoizedProps;try{for(var s=t.type,o=e.attributes;o.length;)e.removeAttributeNode(o[0]);Ce(e,s,n),e[Ae]=t,e[Be]=n}catch(c){Kt(t,t.return,c)}}var Kn=!1,me=!1,sf=!1,cx=typeof WeakSet=="function"?WeakSet:Set,ve=null;function l4(t,e){if(t=t.containerInfo,jf=wo,t=w0(t),Zc(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else t:{n=(n=t.ownerDocument)&&n.defaultView||window;var s=n.getSelection&&n.getSelection();if(s&&s.rangeCount!==0){n=s.anchorNode;var o=s.anchorOffset,c=s.focusNode;s=s.focusOffset;try{n.nodeType,c.nodeType}catch{n=null;break t}var m=0,w=-1,C=-1,_=0,Z=0,et=t,V=null;e:for(;;){for(var q;et!==n||o!==0&&et.nodeType!==3||(w=m+o),et!==c||s!==0&&et.nodeType!==3||(C=m+s),et.nodeType===3&&(m+=et.nodeValue.length),(q=et.firstChild)!==null;)V=et,et=q;for(;;){if(et===t)break e;if(V===n&&++_===o&&(w=m),V===c&&++Z===s&&(C=m),(q=et.nextSibling)!==null)break;et=V,V=et.parentNode}et=q}n=w===-1||C===-1?null:{start:w,end:C}}else n=null}n=n||{start:0,end:0}}else n=null;for(Cf={focusedElem:t,selectionRange:n},wo=!1,ve=e;ve!==null;)if(e=ve,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,ve=t;else for(;ve!==null;){switch(e=ve,c=e.alternate,t=e.flags,e.tag){case 0:if((t&4)!==0&&(t=e.updateQueue,t=t!==null?t.events:null,t!==null))for(n=0;n title"))),Ce(c,s,n),c[Ae]=t,be(c),s=c;break t;case"link":var m=gb("link","href",o).get(s+(n.href||""));if(m){for(var w=0;w$t&&(m=$t,$t=At,At=m);var z=v0(w,At),R=v0(w,$t);if(z&&R&&(q.rangeCount!==1||q.anchorNode!==z.node||q.anchorOffset!==z.offset||q.focusNode!==R.node||q.focusOffset!==R.offset)){var N=et.createRange();N.setStart(z.node,z.offset),q.removeAllRanges(),At>$t?(q.addRange(N),q.extend(R.node,R.offset)):(N.setEnd(R.node,R.offset),q.addRange(N))}}}}for(et=[],q=w;q=q.parentNode;)q.nodeType===1&&et.push({element:q,left:q.scrollLeft,top:q.scrollTop});for(typeof w.focus=="function"&&w.focus(),w=0;wn?32:n,B.T=null,n=ff,ff=null;var c=ji,m=Jn;if(xe=0,Za=ji=null,Jn=0,(qt&6)!==0)throw Error(r(331));var w=qt;if(qt|=4,Sx(c.current),xx(c,c.current,m,n),qt=w,cl(0,!1),qe&&typeof qe.onPostCommitFiberRoot=="function")try{qe.onPostCommitFiberRoot(Ms,c)}catch{}return!0}finally{at.p=o,B.T=s,Ux(t,e)}}function Ix(t,e,n){e=sn(n,e),e=qd(t.stateNode,e,2),t=bi(t,e,2),t!==null&&(Rs(t,2),Ln(t))}function Kt(t,e,n){if(t.tag===3)Ix(t,t,n);else for(;e!==null;){if(e.tag===3){Ix(e,t,n);break}else if(e.tag===1){var s=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof s.componentDidCatch=="function"&&(Ei===null||!Ei.has(s))){t=sn(n,t),n=Y1(2),s=bi(e,n,2),s!==null&&(G1(n,s,e,t),Rs(s,2),Ln(s));break}}e=e.return}}function gf(t,e,n){var s=t.pingCache;if(s===null){s=t.pingCache=new u4;var o=new Set;s.set(e,o)}else o=s.get(e),o===void 0&&(o=new Set,s.set(e,o));o.has(n)||(of=!0,o.add(n),t=p4.bind(null,t,e,n),e.then(t,t))}function p4(t,e,n){var s=t.pingCache;s!==null&&s.delete(e),t.pingedLanes|=t.suspendedLanes&n,t.warmLanes&=~n,te===t&&(Bt&n)===n&&(oe===4||oe===3&&(Bt&62914560)===Bt&&300>Ct()-io?(qt&2)===0&&$a(t,0):uf|=n,Qa===Bt&&(Qa=0)),Ln(t)}function Yx(t,e){e===0&&(e=Ny()),t=Ki(t,e),t!==null&&(Rs(t,e),Ln(t))}function m4(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),Yx(t,n)}function g4(t,e){var n=0;switch(t.tag){case 31:case 13:var s=t.stateNode,o=t.memoizedState;o!==null&&(n=o.retryLane);break;case 19:s=t.stateNode;break;case 22:s=t.stateNode._retryCache;break;default:throw Error(r(314))}s!==null&&s.delete(e),Yx(t,n)}function y4(t,e){return Xt(t,e)}var co=null,ts=null,yf=!1,fo=!1,xf=!1,Mi=0;function Ln(t){t!==ts&&t.next===null&&(ts===null?co=ts=t:ts=ts.next=t),fo=!0,yf||(yf=!0,b4())}function cl(t,e){if(!xf&&fo){xf=!0;do for(var n=!1,s=co;s!==null;){if(t!==0){var o=s.pendingLanes;if(o===0)var c=0;else{var m=s.suspendedLanes,w=s.pingedLanes;c=(1<<31-Xe(42|t)+1)-1,c&=o&~(m&~w),c=c&201326741?c&201326741|1:c?c|2:0}c!==0&&(n=!0,Fx(s,c))}else c=Bt,c=mr(s,s===te?c:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),(c&3)===0||ks(s,c)||(n=!0,Fx(s,c));s=s.next}while(n);xf=!1}}function x4(){Gx()}function Gx(){fo=yf=!1;var t=0;Mi!==0&&k4()&&(t=Mi);for(var e=Ct(),n=null,s=co;s!==null;){var o=s.next,c=qx(s,e);c===0?(s.next=null,n===null?co=o:n.next=o,o===null&&(ts=n)):(n=s,(t!==0||(c&3)!==0)&&(fo=!0)),s=o}xe!==0&&xe!==5||cl(t),Mi!==0&&(Mi=0)}function qx(t,e){for(var n=t.suspendedLanes,s=t.pingedLanes,o=t.expirationTimes,c=t.pendingLanes&-62914561;0w)break;var Z=C.transferSize,et=C.initiatorType;Z&&tb(et)&&(C=C.responseEnd,m+=Z*(C"u"?null:document;function fb(t,e,n){var s=es;if(s&&typeof e=="string"&&e){var o=nn(e);o='link[rel="'+t+'"][href="'+o+'"]',typeof n=="string"&&(o+='[crossorigin="'+n+'"]'),db.has(o)||(db.add(o),t={rel:t,crossOrigin:n,href:e},s.querySelector(o)===null&&(e=s.createElement("link"),Ce(e,"link",t),be(e),s.head.appendChild(e)))}}function V4(t){ti.D(t),fb("dns-prefetch",t,null)}function U4(t,e){ti.C(t,e),fb("preconnect",t,e)}function H4(t,e,n){ti.L(t,e,n);var s=es;if(s&&t&&e){var o='link[rel="preload"][as="'+nn(e)+'"]';e==="image"&&n&&n.imageSrcSet?(o+='[imagesrcset="'+nn(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(o+='[imagesizes="'+nn(n.imageSizes)+'"]')):o+='[href="'+nn(t)+'"]';var c=o;switch(e){case"style":c=ns(t);break;case"script":c=is(t)}dn.has(c)||(t=S({rel:"preload",href:e==="image"&&n&&n.imageSrcSet?void 0:t,as:e},n),dn.set(c,t),s.querySelector(o)!==null||e==="style"&&s.querySelector(pl(c))||e==="script"&&s.querySelector(ml(c))||(e=s.createElement("link"),Ce(e,"link",t),be(e),s.head.appendChild(e)))}}function I4(t,e){ti.m(t,e);var n=es;if(n&&t){var s=e&&typeof e.as=="string"?e.as:"script",o='link[rel="modulepreload"][as="'+nn(s)+'"][href="'+nn(t)+'"]',c=o;switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":c=is(t)}if(!dn.has(c)&&(t=S({rel:"modulepreload",href:t},e),dn.set(c,t),n.querySelector(o)===null)){switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(ml(c)))return}s=n.createElement("link"),Ce(s,"link",t),be(s),n.head.appendChild(s)}}}function Y4(t,e,n){ti.S(t,e,n);var s=es;if(s&&t){var o=Ta(s).hoistableStyles,c=ns(t);e=e||"default";var m=o.get(c);if(!m){var w={loading:0,preload:null};if(m=s.querySelector(pl(c)))w.loading=5;else{t=S({rel:"stylesheet",href:t,"data-precedence":e},n),(n=dn.get(c))&&Of(t,n);var C=m=s.createElement("link");be(C),Ce(C,"link",t),C._p=new Promise(function(_,Z){C.onload=_,C.onerror=Z}),C.addEventListener("load",function(){w.loading|=1}),C.addEventListener("error",function(){w.loading|=2}),w.loading|=4,yo(m,e,s)}m={type:"stylesheet",instance:m,count:1,state:w},o.set(c,m)}}}function G4(t,e){ti.X(t,e);var n=es;if(n&&t){var s=Ta(n).hoistableScripts,o=is(t),c=s.get(o);c||(c=n.querySelector(ml(o)),c||(t=S({src:t,async:!0},e),(e=dn.get(o))&&Bf(t,e),c=n.createElement("script"),be(c),Ce(c,"link",t),n.head.appendChild(c)),c={type:"script",instance:c,count:1,state:null},s.set(o,c))}}function q4(t,e){ti.M(t,e);var n=es;if(n&&t){var s=Ta(n).hoistableScripts,o=is(t),c=s.get(o);c||(c=n.querySelector(ml(o)),c||(t=S({src:t,async:!0,type:"module"},e),(e=dn.get(o))&&Bf(t,e),c=n.createElement("script"),be(c),Ce(c,"link",t),n.head.appendChild(c)),c={type:"script",instance:c,count:1,state:null},s.set(o,c))}}function hb(t,e,n,s){var o=(o=Y.current)?go(o):null;if(!o)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(e=ns(n.href),n=Ta(o).hoistableStyles,s=n.get(e),s||(s={type:"style",instance:null,count:0,state:null},n.set(e,s)),s):{type:"void",instance:null,count:0,state:null};case"link":if(n.rel==="stylesheet"&&typeof n.href=="string"&&typeof n.precedence=="string"){t=ns(n.href);var c=Ta(o).hoistableStyles,m=c.get(t);if(m||(o=o.ownerDocument||o,m={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},c.set(t,m),(c=o.querySelector(pl(t)))&&!c._p&&(m.instance=c,m.state.loading=5),dn.has(t)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},dn.set(t,n),c||X4(o,t,n,m.state))),e&&s===null)throw Error(r(528,""));return m}if(e&&s!==null)throw Error(r(529,""));return null;case"script":return e=n.async,n=n.src,typeof n=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=is(n),n=Ta(o).hoistableScripts,s=n.get(e),s||(s={type:"script",instance:null,count:0,state:null},n.set(e,s)),s):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function ns(t){return'href="'+nn(t)+'"'}function pl(t){return'link[rel="stylesheet"]['+t+"]"}function pb(t){return S({},t,{"data-precedence":t.precedence,precedence:null})}function X4(t,e,n,s){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?s.loading=1:(e=t.createElement("link"),s.preload=e,e.addEventListener("load",function(){return s.loading|=1}),e.addEventListener("error",function(){return s.loading|=2}),Ce(e,"link",n),be(e),t.head.appendChild(e))}function is(t){return'[src="'+nn(t)+'"]'}function ml(t){return"script[async]"+t}function mb(t,e,n){if(e.count++,e.instance===null)switch(e.type){case"style":var s=t.querySelector('style[data-href~="'+nn(n.href)+'"]');if(s)return e.instance=s,be(s),s;var o=S({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return s=(t.ownerDocument||t).createElement("style"),be(s),Ce(s,"style",o),yo(s,n.precedence,t),e.instance=s;case"stylesheet":o=ns(n.href);var c=t.querySelector(pl(o));if(c)return e.state.loading|=4,e.instance=c,be(c),c;s=pb(n),(o=dn.get(o))&&Of(s,o),c=(t.ownerDocument||t).createElement("link"),be(c);var m=c;return m._p=new Promise(function(w,C){m.onload=w,m.onerror=C}),Ce(c,"link",s),e.state.loading|=4,yo(c,n.precedence,t),e.instance=c;case"script":return c=is(n.src),(o=t.querySelector(ml(c)))?(e.instance=o,be(o),o):(s=n,(o=dn.get(c))&&(s=S({},n),Bf(s,o)),t=t.ownerDocument||t,o=t.createElement("script"),be(o),Ce(o,"link",s),t.head.appendChild(o),e.instance=o);case"void":return null;default:throw Error(r(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(s=e.instance,e.state.loading|=4,yo(s,n.precedence,t));return e.instance}function yo(t,e,n){for(var s=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),o=s.length?s[s.length-1]:null,c=o,m=0;m title"):null)}function F4(t,e,n){if(n===1||e.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;return e.rel==="stylesheet"?(t=e.disabled,typeof e.precedence=="string"&&t==null):!0;case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function xb(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function P4(t,e,n,s){if(n.type==="stylesheet"&&(typeof s.media!="string"||matchMedia(s.media).matches!==!1)&&(n.state.loading&4)===0){if(n.instance===null){var o=ns(s.href),c=e.querySelector(pl(o));if(c){e=c._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(t.count++,t=bo.bind(t),e.then(t,t)),n.state.loading|=4,n.instance=c,be(c);return}c=e.ownerDocument||e,s=pb(s),(o=dn.get(o))&&Of(s,o),c=c.createElement("link"),be(c);var m=c;m._p=new Promise(function(w,C){m.onload=w,m.onerror=C}),Ce(c,"link",s),n.instance=c}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(n,e),(e=n.state.preload)&&(n.state.loading&3)===0&&(t.count++,n=bo.bind(t),e.addEventListener("load",n),e.addEventListener("error",n))}}var Nf=0;function K4(t,e){return t.stylesheets&&t.count===0&&So(t,t.stylesheets),0Nf?50:800)+e);return t.unsuspend=n,function(){t.unsuspend=null,clearTimeout(s),clearTimeout(o)}}:null}function bo(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)So(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var vo=null;function So(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,vo=new Map,e.forEach(W4,t),vo=null,bo.call(t))}function W4(t,e){if(!(e.state.loading&4)){var n=vo.get(t);if(n)var s=n.get(null);else{n=new Map,vo.set(t,n);for(var o=t.querySelectorAll("link[data-precedence],style[data-precedence]"),c=0;c"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(a){console.error(a)}}return i(),Ro.exports=Ub(),Ro.exports}var Ib=Hb(),v=Oo();const No=v.createContext({});function _o(i){const a=v.useRef(null);return a.current===null&&(a.current=i()),a.current}const Jf=typeof window<"u"?v.useLayoutEffect:v.useEffect,vl=v.createContext(null);function Vo(i,a){i.indexOf(a)===-1&&i.push(a)}function Sl(i,a){const l=i.indexOf(a);l>-1&&i.splice(l,1)}const An=(i,a,l)=>l>a?a:l{};const ei={},th=i=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(i);function eh(i){return typeof i=="object"&&i!==null}const nh=i=>/^0[^.\s]+$/u.test(i);function ih(i){let a;return()=>(a===void 0&&(a=i()),a)}const Je=i=>i,Yb=(i,a)=>l=>a(i(l)),rs=(...i)=>i.reduce(Yb),os=(i,a,l)=>{const r=a-i;return r===0?1:(l-i)/r};class Ho{constructor(){this.subscriptions=[]}add(a){return Vo(this.subscriptions,a),()=>Sl(this.subscriptions,a)}notify(a,l,r){const d=this.subscriptions.length;if(d)if(d===1)this.subscriptions[0](a,l,r);else for(let f=0;fi*1e3,tn=i=>i/1e3;function ah(i,a){return a?i*(1e3/a):0}const sh=(i,a,l)=>(((1-3*l+3*a)*i+(3*l-6*a))*i+3*a)*i,Gb=1e-7,qb=12;function Xb(i,a,l,r,d){let f,h,p=0;do h=a+(l-a)/2,f=sh(h,r,d)-i,f>0?l=h:a=h;while(Math.abs(f)>Gb&&++pXb(f,0,1,i,l);return f=>f===0||f===1?f:sh(d(f),a,r)}const lh=i=>a=>a<=.5?i(2*a)/2:(2-i(2*(1-a)))/2,rh=i=>a=>1-i(1-a),oh=us(.33,1.53,.69,.99),Io=rh(oh),uh=lh(Io),ch=i=>i>=1?1:(i*=2)<1?.5*Io(i):.5*(2-Math.pow(2,-10*(i-1))),Yo=i=>1-Math.sin(Math.acos(i)),dh=rh(Yo),fh=lh(Yo),Fb=us(.42,0,1,1),Pb=us(0,0,.58,1),hh=us(.42,0,.58,1),Kb=i=>Array.isArray(i)&&typeof i[0]!="number",ph=i=>Array.isArray(i)&&typeof i[0]=="number",Wb={linear:Je,easeIn:Fb,easeInOut:hh,easeOut:Pb,circIn:Yo,circInOut:fh,circOut:dh,backIn:Io,backInOut:uh,backOut:oh,anticipate:ch},Qb=i=>typeof i=="string",mh=i=>{if(ph(i)){Uo(i.length===4);const[a,l,r,d]=i;return us(a,l,r,d)}else if(Qb(i))return Wb[i];return i},wl=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Zb(i,a){let l=new Set,r=new Set,d=!1,f=!1;const h=new WeakSet;let p={delta:0,timestamp:0,isProcessing:!1};function y(b){h.has(b)&&(g.schedule(b),i()),b(p)}const g={schedule:(b,S=!1,A=!1)=>{const k=A&&d?l:r;return S&&h.add(b),k.add(b),b},cancel:b=>{r.delete(b),h.delete(b)},process:b=>{if(p=b,d){f=!0;return}d=!0;const S=l;l=r,r=S,l.forEach(y),l.clear(),d=!1,f&&(f=!1,g.process(b))}};return g}const $b=40;function gh(i,a){let l=!1,r=!0;const d={delta:0,timestamp:0,isProcessing:!1},f=()=>l=!0,h=wl.reduce((E,T)=>(E[T]=Zb(f),E),{}),{setup:p,read:y,resolveKeyframes:g,preUpdate:b,update:S,preRender:A,render:j,postRender:k}=h,D=()=>{const E=ei.useManualTiming,T=E?d.timestamp:performance.now();l=!1,E||(d.delta=r?1e3/60:Math.max(Math.min(T-d.timestamp,$b),1)),d.timestamp=T,d.isProcessing=!0,p.process(d),y.process(d),g.process(d),b.process(d),S.process(d),A.process(d),j.process(d),k.process(d),d.isProcessing=!1,l&&a&&(r=!1,i(D))},O=()=>{l=!0,r=!0,d.isProcessing||i(D)};return{schedule:wl.reduce((E,T)=>{const L=h[T];return E[T]=(U,$=!1,tt=!1)=>(l||O(),L.schedule(U,$,tt)),E},{}),cancel:E=>{for(let T=0;T(Al===void 0&&ke.set(Se.isProcessing||ei.useManualTiming?Se.timestamp:performance.now()),Al),set:i=>{Al=i,queueMicrotask(Jb)}},yh=i=>a=>typeof a=="string"&&a.startsWith(i),xh=yh("--"),tv=yh("var(--"),qo=i=>tv(i)?ev.test(i.split("/*")[0].trim()):!1,ev=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function bh(i){return typeof i!="string"?!1:i.split("/*")[0].includes("var(--")}const ra={test:i=>typeof i=="number",parse:parseFloat,transform:i=>i},cs={...ra,transform:i=>An(0,1,i)},Tl={...ra,default:1},ds=i=>Math.round(i*1e5)/1e5,Xo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function nv(i){return i==null}const iv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Fo=(i,a)=>l=>!!(typeof l=="string"&&iv.test(l)&&l.startsWith(i)||a&&!nv(l)&&Object.prototype.hasOwnProperty.call(l,a)),vh=(i,a,l)=>r=>{if(typeof r!="string")return r;const[d,f,h,p]=r.match(Xo);return{[i]:parseFloat(d),[a]:parseFloat(f),[l]:parseFloat(h),alpha:p!==void 0?parseFloat(p):1}},av=i=>An(0,255,i),Po={...ra,transform:i=>Math.round(av(i))},Bi={test:Fo("rgb","red"),parse:vh("red","green","blue"),transform:({red:i,green:a,blue:l,alpha:r=1})=>"rgba("+Po.transform(i)+", "+Po.transform(a)+", "+Po.transform(l)+", "+ds(cs.transform(r))+")"};function sv(i){let a="",l="",r="",d="";return i.length>5?(a=i.substring(1,3),l=i.substring(3,5),r=i.substring(5,7),d=i.substring(7,9)):(a=i.substring(1,2),l=i.substring(2,3),r=i.substring(3,4),d=i.substring(4,5),a+=a,l+=l,r+=r,d+=d),{red:parseInt(a,16),green:parseInt(l,16),blue:parseInt(r,16),alpha:d?parseInt(d,16)/255:1}}const Ko={test:Fo("#"),parse:sv,transform:Bi.transform},fs=i=>({test:a=>typeof a=="string"&&a.endsWith(i)&&a.split(" ").length===1,parse:parseFloat,transform:a=>`${a}${i}`}),ii=fs("deg"),Tn=fs("%"),xt=fs("px"),lv=fs("vh"),rv=fs("vw"),Sh={...Tn,parse:i=>Tn.parse(i)/100,transform:i=>Tn.transform(i*100)},oa={test:Fo("hsl","hue"),parse:vh("hue","saturation","lightness"),transform:({hue:i,saturation:a,lightness:l,alpha:r=1})=>"hsla("+Math.round(i)+", "+Tn.transform(ds(a))+", "+Tn.transform(ds(l))+", "+ds(cs.transform(r))+")"},de={test:i=>Bi.test(i)||Ko.test(i)||oa.test(i),parse:i=>Bi.test(i)?Bi.parse(i):oa.test(i)?oa.parse(i):Ko.parse(i),transform:i=>typeof i=="string"?i:i.hasOwnProperty("red")?Bi.transform(i):oa.transform(i),getAnimatableNone:i=>{const a=de.parse(i);return a.alpha=0,de.transform(a)}},ov=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function uv(i){return isNaN(i)&&typeof i=="string"&&(i.match(Xo)?.length||0)+(i.match(ov)?.length||0)>0}const wh="number",Ah="color",cv="var",dv="var(",Th="${}",fv=/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 ua(i){const a=i.toString(),l=[],r={color:[],number:[],var:[]},d=[];let f=0;const p=a.replace(fv,y=>(de.test(y)?(r.color.push(f),d.push(Ah),l.push(de.parse(y))):y.startsWith(dv)?(r.var.push(f),d.push(cv),l.push(y)):(r.number.push(f),d.push(wh),l.push(parseFloat(y))),++f,Th)).split(Th);return{values:l,split:p,indexes:r,types:d}}function hv(i){return ua(i).values}function Eh({split:i,types:a}){const l=i.length;return r=>{let d="";for(let f=0;ftypeof i=="number"?0:de.test(i)?de.getAnimatableNone(i):i,gv=(i,a)=>typeof i=="number"?a?.trim().endsWith("/")?i:0:mv(i);function yv(i){const a=ua(i);return Eh(a)(a.values.map((r,d)=>gv(r,a.split[d])))}const fn={test:uv,parse:hv,createTransformer:pv,getAnimatableNone:yv};function Wo(i,a,l){return l<0&&(l+=1),l>1&&(l-=1),l<1/6?i+(a-i)*6*l:l<1/2?a:l<2/3?i+(a-i)*(2/3-l)*6:i}function xv({hue:i,saturation:a,lightness:l,alpha:r}){i/=360,a/=100,l/=100;let d=0,f=0,h=0;if(!a)d=f=h=l;else{const p=l<.5?l*(1+a):l+a-l*a,y=2*l-p;d=Wo(y,p,i+1/3),f=Wo(y,p,i),h=Wo(y,p,i-1/3)}return{red:Math.round(d*255),green:Math.round(f*255),blue:Math.round(h*255),alpha:r}}function El(i,a){return l=>l>0?a:i}const ee=(i,a,l)=>i+(a-i)*l,Qo=(i,a,l)=>{const r=i*i,d=l*(a*a-r)+r;return d<0?0:Math.sqrt(d)},bv=[Ko,Bi,oa],vv=i=>bv.find(a=>a.test(i));function jh(i){const a=vv(i);if(!a)return!1;let l=a.parse(i);return a===oa&&(l=xv(l)),l}const Ch=(i,a)=>{const l=jh(i),r=jh(a);if(!l||!r)return El(i,a);const d={...l};return f=>(d.red=Qo(l.red,r.red,f),d.green=Qo(l.green,r.green,f),d.blue=Qo(l.blue,r.blue,f),d.alpha=ee(l.alpha,r.alpha,f),Bi.transform(d))},Zo=new Set(["none","hidden"]);function Sv(i,a){return Zo.has(i)?l=>l<=0?i:a:l=>l>=1?a:i}function wv(i,a){return l=>ee(i,a,l)}function $o(i){return typeof i=="number"?wv:typeof i=="string"?qo(i)?El:de.test(i)?Ch:Ev:Array.isArray(i)?Mh:typeof i=="object"?de.test(i)?Ch:Av:El}function Mh(i,a){const l=[...i],r=l.length,d=i.map((f,h)=>$o(f)(f,a[h]));return f=>{for(let h=0;h{for(const f in r)l[f]=r[f](d);return l}}function Tv(i,a){const l=[],r={color:0,var:0,number:0};for(let d=0;d{const l=fn.createTransformer(a),r=ua(i),d=ua(a);return r.indexes.var.length===d.indexes.var.length&&r.indexes.color.length===d.indexes.color.length&&r.indexes.number.length>=d.indexes.number.length?Zo.has(i)&&!d.values.length||Zo.has(a)&&!r.values.length?Sv(i,a):rs(Mh(Tv(r,d),d.values),l):El(i,a)};function kh(i,a,l){return typeof i=="number"&&typeof a=="number"&&typeof l=="number"?ee(i,a,l):$o(i)(i,a)}const jv=i=>{const a=({timestamp:l})=>i(l);return{start:(l=!0)=>Jt.update(a,l),stop:()=>ni(a),now:()=>Se.isProcessing?Se.timestamp:ke.now()}},Rh=(i,a,l=10)=>{let r="";const d=Math.max(Math.round(a/l),2);for(let f=0;f=jl?1/0:a}function Cv(i,a=100,l){const r=l({...i,keyframes:[0,a]}),d=Math.min(Jo(r),jl);return{type:"keyframes",ease:f=>r.next(d*f).value/a,duration:tn(d)}}const se={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};function tu(i,a){return i*Math.sqrt(1-a*a)}const Mv=12;function kv(i,a,l){let r=l;for(let d=1;d{const b=g*h,S=b*i,A=b-l,j=tu(g,h),k=Math.exp(-S);return eu-A/j*k},f=g=>{const S=g*h*i,A=S*l+l,j=Math.pow(h,2)*Math.pow(g,2)*i,k=Math.exp(-S),D=tu(Math.pow(g,2),h);return(-d(g)+eu>0?-1:1)*((A-j)*k)/D}):(d=g=>{const b=Math.exp(-g*i),S=(g-l)*i+1;return-eu+b*S},f=g=>{const b=Math.exp(-g*i),S=(l-g)*(i*i);return b*S});const p=5/i,y=kv(d,f,p);if(i=Ye(i),isNaN(y))return{stiffness:se.stiffness,damping:se.damping,duration:i};{const g=Math.pow(y,2)*r;return{stiffness:g,damping:h*2*Math.sqrt(r*g),duration:i}}}const Dv=["duration","bounce"],zv=["stiffness","damping","mass"];function Dh(i,a){return a.some(l=>i[l]!==void 0)}function Lv(i){let a={velocity:se.velocity,stiffness:se.stiffness,damping:se.damping,mass:se.mass,isResolvedFromDuration:!1,...i};if(!Dh(i,zv)&&Dh(i,Dv))if(a.velocity=0,i.visualDuration){const l=i.visualDuration,r=2*Math.PI/(l*1.2),d=r*r,f=2*An(.05,1,1-(i.bounce||0))*Math.sqrt(d);a={...a,mass:se.mass,stiffness:d,damping:f}}else{const l=Rv({...i,velocity:0});a={...a,...l,mass:se.mass},a.isResolvedFromDuration=!0}return a}function Cl(i=se.visualDuration,a=se.bounce){const l=typeof i!="object"?{visualDuration:i,keyframes:[0,1],bounce:a}:i;let{restSpeed:r,restDelta:d}=l;const f=l.keyframes[0],h=l.keyframes[l.keyframes.length-1],p={done:!1,value:f},{stiffness:y,damping:g,mass:b,duration:S,velocity:A,isResolvedFromDuration:j}=Lv({...l,velocity:-tn(l.velocity||0)}),k=A||0,D=g/(2*Math.sqrt(y*b)),O=h-f,F=tn(Math.sqrt(y/b)),Q=Math.abs(O)<5;r||(r=Q?se.restSpeed.granular:se.restSpeed.default),d||(d=Q?se.restDelta.granular:se.restDelta.default);let E,T,L,U,$,tt;if(D<1)L=tu(F,D),U=(k+D*F*O)/L,E=W=>{const lt=Math.exp(-D*F*W);return h-lt*(U*Math.sin(L*W)+O*Math.cos(L*W))},$=D*F*U+O*L,tt=D*F*O-U*L,T=W=>Math.exp(-D*F*W)*($*Math.sin(L*W)+tt*Math.cos(L*W));else if(D===1){E=lt=>h-Math.exp(-F*lt)*(O+(k+F*O)*lt);const W=k+F*O;T=lt=>Math.exp(-F*lt)*(F*W*lt-k)}else{const W=F*Math.sqrt(D*D-1);E=mt=>{const kt=Math.exp(-D*F*mt),B=Math.min(W*mt,300);return h-kt*((k+D*F*O)*Math.sinh(B)+W*O*Math.cosh(B))/W};const lt=(k+D*F*O)/W,it=D*F*lt-O*W,rt=D*F*O-lt*W;T=mt=>{const kt=Math.exp(-D*F*mt),B=Math.min(W*mt,300);return kt*(it*Math.sinh(B)+rt*Math.cosh(B))}}const P={calculatedDuration:j&&S||null,velocity:W=>Ye(T(W)),next:W=>{if(!j&&D<1){const it=Math.exp(-D*F*W),rt=Math.sin(L*W),mt=Math.cos(L*W),kt=h-it*(U*rt+O*mt),B=Ye(it*($*rt+tt*mt));return p.done=Math.abs(B)<=r&&Math.abs(h-kt)<=d,p.value=p.done?h:kt,p}const lt=E(W);if(j)p.done=W>=S;else{const it=Ye(T(W));p.done=Math.abs(it)<=r&&Math.abs(h-lt)<=d}return p.value=p.done?h:lt,p},toString:()=>{const W=Math.min(Jo(P),jl),lt=Rh(it=>P.next(W*it).value,W,30);return W+"ms "+lt},toTransition:()=>{}};return P}Cl.applyToOptions=i=>{const a=Cv(i,100,Cl);return i.ease=a.ease,i.duration=Ye(a.duration),i.type="keyframes",i};const Ov=5;function zh(i,a,l){const r=Math.max(a-Ov,0);return ah(l-i(r),a-r)}function nu({keyframes:i,velocity:a=0,power:l=.8,timeConstant:r=325,bounceDamping:d=10,bounceStiffness:f=500,modifyTarget:h,min:p,max:y,restDelta:g=.5,restSpeed:b}){const S=i[0],A={done:!1,value:S},j=tt=>p!==void 0&&tty,k=tt=>p===void 0?y:y===void 0||Math.abs(p-tt)-D*Math.exp(-tt/r),E=tt=>F+Q(tt),T=tt=>{const P=Q(tt),W=E(tt);A.done=Math.abs(P)<=g,A.value=A.done?F:W};let L,U;const $=tt=>{j(A.value)&&(L=tt,U=Cl({keyframes:[A.value,k(A.value)],velocity:zh(E,tt,A.value),damping:d,stiffness:f,restDelta:g,restSpeed:b}))};return $(0),{calculatedDuration:null,next:tt=>{let P=!1;return!U&&L===void 0&&(P=!0,T(tt),$(tt)),L!==void 0&&tt>=L?U.next(tt-L):(!P&&T(tt),A)}}}function Bv(i,a,l){const r=[],d=l||ei.mix||kh,f=i.length-1;for(let h=0;ha[0];if(f===2&&a[0]===a[1])return()=>a[1];const h=i[0]===i[1];i[0]>i[f-1]&&(i=[...i].reverse(),a=[...a].reverse());const p=Bv(a,r,d),y=p.length,g=b=>{if(h&&b1)for(;Sg(An(i[0],i[f-1],b)):g}function _v(i,a){const l=i[i.length-1];for(let r=1;r<=a;r++){const d=os(0,a,r);i.push(ee(l,1,d))}}function Vv(i){const a=[0];return _v(a,i.length-1),a}function Uv(i,a){return i.map(l=>l*a)}function Hv(i,a){return i.map(()=>a||hh).splice(0,i.length-1)}function hs({duration:i=300,keyframes:a,times:l,ease:r="easeInOut"}){const d=Kb(r)?r.map(mh):mh(r),f={done:!1,value:a[0]},h=Uv(l&&l.length===a.length?l:Vv(a),i),p=Nv(h,a,{ease:Array.isArray(d)?d:Hv(a,d)});return{calculatedDuration:i,next:y=>(f.value=p(y),f.done=y>=i,f)}}const Iv=i=>i!==null;function Ml(i,{repeat:a,repeatType:l="loop"},r,d=1){const f=i.filter(Iv),p=d<0||a&&l!=="loop"&&a%2===1?0:f.length-1;return!p||r===void 0?f[p]:r}const Yv={decay:nu,inertia:nu,tween:hs,keyframes:hs,spring:Cl};function Lh(i){typeof i.type=="string"&&(i.type=Yv[i.type])}class iu{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(a=>{this.resolve=a})}notifyFinished(){this.resolve()}then(a,l){return this.finished.then(a,l)}}const Gv=i=>i/100;class kl extends iu{constructor(a){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{const{motionValue:l}=this.options;l&&l.updatedAt!==ke.now()&&this.tick(ke.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=a,this.initAnimation(),this.play(),a.autoplay===!1&&this.pause()}initAnimation(){const{options:a}=this;Lh(a);const{type:l=hs,repeat:r=0,repeatDelay:d=0,repeatType:f,velocity:h=0}=a;let{keyframes:p}=a;const y=l||hs;y!==hs&&typeof p[0]!="number"&&(this.mixKeyframes=rs(Gv,kh(p[0],p[1])),p=[0,100]);const g=y({...a,keyframes:p});f==="mirror"&&(this.mirroredGenerator=y({...a,keyframes:[...p].reverse(),velocity:-h})),g.calculatedDuration===null&&(g.calculatedDuration=Jo(g));const{calculatedDuration:b}=g;this.calculatedDuration=b,this.resolvedDuration=b+d,this.totalDuration=this.resolvedDuration*(r+1)-d,this.generator=g}updateTime(a){const l=Math.round(a-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=l}tick(a,l=!1){const{generator:r,totalDuration:d,mixKeyframes:f,mirroredGenerator:h,resolvedDuration:p,calculatedDuration:y}=this;if(this.startTime===null)return r.next(0);const{delay:g=0,keyframes:b,repeat:S,repeatType:A,repeatDelay:j,type:k,onUpdate:D,finalKeyframe:O}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,a):this.speed<0&&(this.startTime=Math.min(a-d/this.speed,this.startTime)),l?this.currentTime=a:this.updateTime(a);const F=this.currentTime-g*(this.playbackSpeed>=0?1:-1),Q=this.playbackSpeed>=0?F<0:F>d;this.currentTime=Math.max(F,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=d);let E=this.currentTime,T=r;if(S){const tt=Math.min(this.currentTime,d)/p;let P=Math.floor(tt),W=tt%1;!W&&tt>=1&&(W=1),W===1&&P--,P=Math.min(P,S+1),P%2&&(A==="reverse"?(W=1-W,j&&(W-=j/p)):A==="mirror"&&(T=h)),E=An(0,1,W)*p}let L;Q?(this.delayState.value=b[0],L=this.delayState):L=T.next(E),f&&!Q&&(L.value=f(L.value));let{done:U}=L;!Q&&y!==null&&(U=this.playbackSpeed>=0?this.currentTime>=d:this.currentTime<=0);const $=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&U);return $&&k!==nu&&(L.value=Ml(b,this.options,O,this.speed)),D&&D(L.value),$&&this.finish(),L}then(a,l){return this.finished.then(a,l)}get duration(){return tn(this.calculatedDuration)}get iterationDuration(){const{delay:a=0}=this.options||{};return this.duration+tn(a)}get time(){return tn(this.currentTime)}set time(a){a=Ye(a),this.currentTime=a,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=a:this.driver&&(this.startTime=this.driver.now()-a/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=a,this.tick(a))}getGeneratorVelocity(){const a=this.currentTime;if(a<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(a);const l=this.generator.next(a).value;return zh(r=>this.generator.next(r).value,a,l)}get speed(){return this.playbackSpeed}set speed(a){const l=this.playbackSpeed!==a;l&&this.driver&&this.updateTime(ke.now()),this.playbackSpeed=a,l&&this.driver&&(this.time=tn(this.currentTime))}play(){if(this.isStopped)return;const{driver:a=jv,startTime:l}=this.options;this.driver||(this.driver=a(d=>this.tick(d))),this.options.onPlay?.();const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=l??r),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(ke.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(a){return this.startTime=0,this.tick(a,!0)}attachTimeline(a){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),a.observe(this)}}function qv(i){for(let a=1;ai*180/Math.PI,au=i=>{const a=Ni(Math.atan2(i[1],i[0]));return su(a)},Xv={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:i=>(Math.abs(i[0])+Math.abs(i[3]))/2,rotate:au,rotateZ:au,skewX:i=>Ni(Math.atan(i[1])),skewY:i=>Ni(Math.atan(i[2])),skew:i=>(Math.abs(i[1])+Math.abs(i[2]))/2},su=i=>(i=i%360,i<0&&(i+=360),i),Oh=au,Bh=i=>Math.sqrt(i[0]*i[0]+i[1]*i[1]),Nh=i=>Math.sqrt(i[4]*i[4]+i[5]*i[5]),Fv={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Bh,scaleY:Nh,scale:i=>(Bh(i)+Nh(i))/2,rotateX:i=>su(Ni(Math.atan2(i[6],i[5]))),rotateY:i=>su(Ni(Math.atan2(-i[2],i[0]))),rotateZ:Oh,rotate:Oh,skewX:i=>Ni(Math.atan(i[4])),skewY:i=>Ni(Math.atan(i[1])),skew:i=>(Math.abs(i[1])+Math.abs(i[4]))/2};function lu(i){return i.includes("scale")?1:0}function ru(i,a){if(!i||i==="none")return lu(a);const l=i.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,d;if(l)r=Fv,d=l;else{const p=i.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Xv,d=p}if(!d)return lu(a);const f=r[a],h=d[1].split(",").map(Kv);return typeof f=="function"?f(h):h[f]}const Pv=(i,a)=>{const{transform:l="none"}=getComputedStyle(i);return ru(l,a)};function Kv(i){return parseFloat(i.trim())}const ca=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],da=new Set(ca),_h=i=>i===ra||i===xt,Wv=new Set(["x","y","z"]),Qv=ca.filter(i=>!Wv.has(i));function Zv(i){const a=[];return Qv.forEach(l=>{const r=i.getValue(l);r!==void 0&&(a.push([l,r.get()]),r.set(l.startsWith("scale")?1:0))}),a}const ai={width:({x:i},{paddingLeft:a="0",paddingRight:l="0",boxSizing:r})=>{const d=i.max-i.min;return r==="border-box"?d:d-parseFloat(a)-parseFloat(l)},height:({y:i},{paddingTop:a="0",paddingBottom:l="0",boxSizing:r})=>{const d=i.max-i.min;return r==="border-box"?d:d-parseFloat(a)-parseFloat(l)},top:(i,{top:a})=>parseFloat(a),left:(i,{left:a})=>parseFloat(a),bottom:({y:i},{top:a})=>parseFloat(a)+(i.max-i.min),right:({x:i},{left:a})=>parseFloat(a)+(i.max-i.min),x:(i,{transform:a})=>ru(a,"x"),y:(i,{transform:a})=>ru(a,"y")};ai.translateX=ai.x,ai.translateY=ai.y;const _i=new Set;let ou=!1,uu=!1,cu=!1;function Vh(){if(uu){const i=Array.from(_i).filter(r=>r.needsMeasurement),a=new Set(i.map(r=>r.element)),l=new Map;a.forEach(r=>{const d=Zv(r);d.length&&(l.set(r,d),r.render())}),i.forEach(r=>r.measureInitialState()),a.forEach(r=>{r.render();const d=l.get(r);d&&d.forEach(([f,h])=>{r.getValue(f)?.set(h)})}),i.forEach(r=>r.measureEndState()),i.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}uu=!1,ou=!1,_i.forEach(i=>i.complete(cu)),_i.clear()}function Uh(){_i.forEach(i=>{i.readKeyframes(),i.needsMeasurement&&(uu=!0)})}function $v(){cu=!0,Uh(),Vh(),cu=!1}class du{constructor(a,l,r,d,f,h=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...a],this.onComplete=l,this.name=r,this.motionValue=d,this.element=f,this.isAsync=h}scheduleResolve(){this.state="scheduled",this.isAsync?(_i.add(this),ou||(ou=!0,Jt.read(Uh),Jt.resolveKeyframes(Vh))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:a,name:l,element:r,motionValue:d}=this;if(a[0]===null){const f=d?.get(),h=a[a.length-1];if(f!==void 0)a[0]=f;else if(r&&l){const p=r.readValue(l,h);p!=null&&(a[0]=p)}a[0]===void 0&&(a[0]=h),d&&f===void 0&&d.set(a[0])}qv(a)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(a=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,a),_i.delete(this)}cancel(){this.state==="scheduled"&&(_i.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Jv=i=>i.startsWith("--");function Hh(i,a,l){Jv(a)?i.style.setProperty(a,l):i.style[a]=l}const t2={};function Ih(i,a){const l=ih(i);return()=>t2[a]??l()}const e2=Ih(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Yh=Ih(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),ps=([i,a,l,r])=>`cubic-bezier(${i}, ${a}, ${l}, ${r})`,Gh={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:ps([0,.65,.55,1]),circOut:ps([.55,0,1,.45]),backIn:ps([.31,.01,.66,-.59]),backOut:ps([.33,1.53,.69,.99])};function qh(i,a){if(i)return typeof i=="function"?Yh()?Rh(i,a):"ease-out":ph(i)?ps(i):Array.isArray(i)?i.map(l=>qh(l,a)||Gh.easeOut):Gh[i]}function n2(i,a,l,{delay:r=0,duration:d=300,repeat:f=0,repeatType:h="loop",ease:p="easeOut",times:y}={},g=void 0){const b={[a]:l};y&&(b.offset=y);const S=qh(p,d);Array.isArray(S)&&(b.easing=S);const A={delay:r,duration:d,easing:Array.isArray(S)?"linear":S,fill:"both",iterations:f+1,direction:h==="reverse"?"alternate":"normal"};return g&&(A.pseudoElement=g),i.animate(b,A)}function Xh(i){return typeof i=="function"&&"applyToOptions"in i}function i2({type:i,...a}){return Xh(i)&&Yh()?i.applyToOptions(a):(a.duration??(a.duration=300),a.ease??(a.ease="easeOut"),a)}class Fh extends iu{constructor(a){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!a)return;const{element:l,name:r,keyframes:d,pseudoElement:f,allowFlatten:h=!1,finalKeyframe:p,onComplete:y}=a;this.isPseudoElement=!!f,this.allowFlatten=h,this.options=a,Uo(typeof a.type!="string");const g=i2(a);this.animation=n2(l,r,d,g,f),g.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!f){const b=Ml(d,this.options,p,this.speed);this.updateMotionValue&&this.updateMotionValue(b),Hh(l,r,b),this.animation.cancel()}y?.(),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:a}=this;a==="idle"||a==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){const a=this.options?.element;!this.isPseudoElement&&a?.isConnected&&this.animation.commitStyles?.()}get duration(){const a=this.animation.effect?.getComputedTiming?.().duration||0;return tn(Number(a))}get iterationDuration(){const{delay:a=0}=this.options||{};return this.duration+tn(a)}get time(){return tn(Number(this.animation.currentTime)||0)}set time(a){const l=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ye(a),l&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(a){a<0&&(this.finishedTime=null),this.animation.playbackRate=a}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(a){this.manualStartTime=this.animation.startTime=a}attachTimeline({timeline:a,rangeStart:l,rangeEnd:r,observe:d}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,a&&e2()?(this.animation.timeline=a,l&&(this.animation.rangeStart=l),r&&(this.animation.rangeEnd=r),Je):d(this)}}const Ph={anticipate:ch,backInOut:uh,circInOut:fh};function a2(i){return i in Ph}function s2(i){typeof i.ease=="string"&&a2(i.ease)&&(i.ease=Ph[i.ease])}const fu=10;class l2 extends Fh{constructor(a){s2(a),Lh(a),super(a),a.startTime!==void 0&&a.autoplay!==!1&&(this.startTime=a.startTime),this.options=a}updateMotionValue(a){const{motionValue:l,onUpdate:r,onComplete:d,element:f,...h}=this.options;if(!l)return;if(a!==void 0){l.set(a);return}const p=new kl({...h,autoplay:!1}),y=Math.max(fu,ke.now()-this.startTime),g=An(0,fu,y-fu),b=p.sample(y).value,{name:S}=this.options;f&&S&&Hh(f,S,b),l.setWithVelocity(p.sample(Math.max(0,y-g)).value,b,g),p.stop()}}const Kh=(i,a)=>a==="zIndex"?!1:!!(typeof i=="number"||Array.isArray(i)||typeof i=="string"&&(fn.test(i)||i==="0")&&!i.startsWith("url("));function r2(i){const a=i[0];if(i.length===1)return!0;for(let l=0;lObject.hasOwnProperty.call(Element.prototype,"animate"));function h2(i){const{motionValue:a,name:l,repeatDelay:r,repeatType:d,damping:f,type:h,keyframes:p}=i;if(!(a?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:g,transformTemplate:b}=a.owner.getProps();return f2()&&l&&(Wh.has(l)||d2.has(l)&&c2(p))&&(l!=="transform"||!b)&&!g&&!r&&d!=="mirror"&&f!==0&&h!=="inertia"}const p2=40;class m2 extends iu{constructor({autoplay:a=!0,delay:l=0,type:r="keyframes",repeat:d=0,repeatDelay:f=0,repeatType:h="loop",keyframes:p,name:y,motionValue:g,element:b,...S}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ke.now();const A={autoplay:a,delay:l,type:r,repeat:d,repeatDelay:f,repeatType:h,name:y,motionValue:g,element:b,...S},j=b?.KeyframeResolver||du;this.keyframeResolver=new j(p,(k,D,O)=>this.onKeyframesResolved(k,D,A,!O),y,g,b),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(a,l,r,d){this.keyframeResolver=void 0;const{name:f,type:h,velocity:p,delay:y,isHandoff:g,onUpdate:b}=r;this.resolvedAt=ke.now();let S=!0;o2(a,f,h,p)||(S=!1,(ei.instantAnimations||!y)&&b?.(Ml(a,r,l)),a[0]=a[a.length-1],hu(r),r.repeat=0);const j={startTime:d?this.resolvedAt?this.resolvedAt-this.createdAt>p2?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:l,...r,keyframes:a},k=S&&!g&&h2(j),D=j.motionValue?.owner?.current;let O;if(k)try{O=new l2({...j,element:D})}catch{O=new kl(j)}else O=new kl(j);O.finished.then(()=>{this.notifyFinished()}).catch(Je),this.pendingTimeline&&(this.stopTimeline=O.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=O}get finished(){return this._animation?this.animation.finished:this._finished}then(a,l){return this.finished.finally(a).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),$v()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(a){this.animation.time=a}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(a){this.animation.speed=a}get startTime(){return this.animation.startTime}attachTimeline(a){return this._animation?this.stopTimeline=this.animation.attachTimeline(a):this.pendingTimeline=a,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}function Qh(i,a,l,r=0,d=1){const f=Array.from(i).sort((g,b)=>g.sortNodePosition(b)).indexOf(a),h=i.size,p=(h-1)*r;return typeof l=="function"?l(f,h):d===1?f*r:p-f*r}const g2=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function y2(i){const a=g2.exec(i);if(!a)return[,];const[,l,r,d]=a;return[`--${l??r}`,d]}function Zh(i,a,l=1){const[r,d]=y2(i);if(!r)return;const f=window.getComputedStyle(a).getPropertyValue(r);if(f){const h=f.trim();return th(h)?parseFloat(h):h}return qo(d)?Zh(d,a,l+1):d}const x2={type:"spring",stiffness:500,damping:25,restSpeed:10},b2=i=>({type:"spring",stiffness:550,damping:i===0?2*Math.sqrt(550):30,restSpeed:10}),v2={type:"keyframes",duration:.8},S2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},w2=(i,{keyframes:a})=>a.length>2?v2:da.has(i)?i.startsWith("scale")?b2(a[1]):x2:S2;function $h(i,a){if(i?.inherit&&a){const{inherit:l,...r}=i;return{...a,...r}}return i}function pu(i,a){const l=i?.[a]??i?.default??i;return l!==i?$h(l,i):l}const A2=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function T2(i){for(const a in i)if(!A2.has(a))return!0;return!1}const mu=(i,a,l,r={},d,f)=>h=>{const p=pu(r,i)||{},y=p.delay||r.delay||0;let{elapsed:g=0}=r;g=g-Ye(y);const b={keyframes:Array.isArray(l)?l:[null,l],ease:"easeOut",velocity:a.getVelocity(),...p,delay:-g,onUpdate:A=>{a.set(A),p.onUpdate&&p.onUpdate(A)},onComplete:()=>{h(),p.onComplete&&p.onComplete()},name:i,motionValue:a,element:f?void 0:d};T2(p)||Object.assign(b,w2(i,b)),b.duration&&(b.duration=Ye(b.duration)),b.repeatDelay&&(b.repeatDelay=Ye(b.repeatDelay)),b.from!==void 0&&(b.keyframes[0]=b.from);let S=!1;if((b.type===!1||b.duration===0&&!b.repeatDelay)&&(hu(b),b.delay===0&&(S=!0)),(ei.instantAnimations||ei.skipAnimations||d?.shouldSkipAnimations)&&(S=!0,hu(b),b.delay=0),b.allowFlatten=!p.type&&!p.ease,S&&!f&&a.get()!==void 0){const A=Ml(b.keyframes,p);if(A!==void 0){Jt.update(()=>{b.onUpdate(A),b.onComplete()});return}}return p.isSync?new kl(b):new m2(b)};function Jh(i){const a=[{},{}];return i?.values.forEach((l,r)=>{a[0][r]=l.get(),a[1][r]=l.getVelocity()}),a}function gu(i,a,l,r){if(typeof a=="function"){const[d,f]=Jh(r);a=a(l!==void 0?l:i.custom,d,f)}if(typeof a=="string"&&(a=i.variants&&i.variants[a]),typeof a=="function"){const[d,f]=Jh(r);a=a(l!==void 0?l:i.custom,d,f)}return a}function Vi(i,a,l){const r=i.getProps();return gu(r,a,l!==void 0?l:r.custom,i)}const tp=new Set(["width","height","top","left","right","bottom",...ca]),ep=30,E2=i=>!isNaN(parseFloat(i));class j2{constructor(a,l={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{const d=ke.now();if(this.updatedAt!==d&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const f of this.dependents)f.dirty()},this.hasAnimated=!1,this.setCurrent(a),this.owner=l.owner}setCurrent(a){this.current=a,this.updatedAt=ke.now(),this.canTrackVelocity===null&&a!==void 0&&(this.canTrackVelocity=E2(this.current))}setPrevFrameValue(a=this.current){this.prevFrameValue=a,this.prevUpdatedAt=this.updatedAt}onChange(a){return this.on("change",a)}on(a,l){this.events[a]||(this.events[a]=new Ho);const r=this.events[a].add(l);return a==="change"?()=>{r(),Jt.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const a in this.events)this.events[a].clear()}attach(a,l){this.passiveEffect=a,this.stopPassiveEffect=l}set(a){this.passiveEffect?this.passiveEffect(a,this.updateAndNotify):this.updateAndNotify(a)}setWithVelocity(a,l,r){this.set(l),this.prev=void 0,this.prevFrameValue=a,this.prevUpdatedAt=this.updatedAt-r}jump(a,l=!0){this.updateAndNotify(a),this.prev=a,this.prevUpdatedAt=this.prevFrameValue=void 0,l&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(a){this.dependents||(this.dependents=new Set),this.dependents.add(a)}removeDependent(a){this.dependents&&this.dependents.delete(a)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const a=ke.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||a-this.updatedAt>ep)return 0;const l=Math.min(this.updatedAt-this.prevUpdatedAt,ep);return ah(parseFloat(this.current)-parseFloat(this.prevFrameValue),l)}start(a){return this.stop(),new Promise(l=>{this.hasAnimated=!0,this.animation=a(l),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 fa(i,a){return new j2(i,a)}const yu=i=>Array.isArray(i);function C2(i,a,l){i.hasValue(a)?i.getValue(a).set(l):i.addValue(a,fa(l))}function M2(i){return yu(i)?i[i.length-1]||0:i}function k2(i,a){const l=Vi(i,a);let{transitionEnd:r={},transition:d={},...f}=l||{};f={...f,...r};for(const h in f){const p=M2(f[h]);C2(i,h,p)}}const we=i=>!!(i&&i.getVelocity);function R2(i){return!!(we(i)&&i.add)}function xu(i,a){const l=i.getValue("willChange");if(R2(l))return l.add(a);if(!l&&ei.WillChange){const r=new ei.WillChange("auto");i.addValue("willChange",r),r.add(a)}}function bu(i){return i.replace(/([A-Z])/g,a=>`-${a.toLowerCase()}`)}const np="data-"+bu("framerAppearId");function ip(i){return i.props[np]}function D2({protectedKeys:i,needsAnimating:a},l){const r=i.hasOwnProperty(l)&&a[l]!==!0;return a[l]=!1,r}function ap(i,a,{delay:l=0,transitionOverride:r,type:d}={}){let{transition:f,transitionEnd:h,...p}=a;const y=i.getDefaultTransition();f=f?$h(f,y):y;const g=f?.reduceMotion;r&&(f=r);const b=[],S=d&&i.animationState&&i.animationState.getState()[d];for(const A in p){const j=i.getValue(A,i.latestValues[A]??null),k=p[A];if(k===void 0||S&&D2(S,A))continue;const D={delay:l,...pu(f||{},A)},O=j.get();if(O!==void 0&&!j.isAnimating()&&!Array.isArray(k)&&k===O&&!D.velocity){Jt.update(()=>j.set(k));continue}let F=!1;if(window.MotionHandoffAnimation){const T=ip(i);if(T){const L=window.MotionHandoffAnimation(T,A,Jt);L!==null&&(D.startTime=L,F=!0)}}xu(i,A);const Q=g??i.shouldReduceMotion;j.start(mu(A,j,k,Q&&tp.has(A)?{type:!1}:D,i,F));const E=j.animation;E&&b.push(E)}if(h){const A=()=>Jt.update(()=>{h&&k2(i,h)});b.length?Promise.all(b).then(A):A()}return b}function vu(i,a,l={}){const r=Vi(i,a,l.type==="exit"?i.presenceContext?.custom:void 0);let{transition:d=i.getDefaultTransition()||{}}=r||{};l.transitionOverride&&(d=l.transitionOverride);const f=r?()=>Promise.all(ap(i,r,l)):()=>Promise.resolve(),h=i.variantChildren&&i.variantChildren.size?(y=0)=>{const{delayChildren:g=0,staggerChildren:b,staggerDirection:S}=d;return z2(i,a,y,g,b,S,l)}:()=>Promise.resolve(),{when:p}=d;if(p){const[y,g]=p==="beforeChildren"?[f,h]:[h,f];return y().then(()=>g())}else return Promise.all([f(),h(l.delay)])}function z2(i,a,l=0,r=0,d=0,f=1,h){const p=[];for(const y of i.variantChildren)y.notify("AnimationStart",a),p.push(vu(y,a,{...h,delay:l+(typeof r=="function"?0:r)+Qh(i.variantChildren,y,r,d,f)}).then(()=>y.notify("AnimationComplete",a)));return Promise.all(p)}function L2(i,a,l={}){i.notify("AnimationStart",a);let r;if(Array.isArray(a)){const d=a.map(f=>vu(i,f,l));r=Promise.all(d)}else if(typeof a=="string")r=vu(i,a,l);else{const d=typeof a=="function"?Vi(i,a,l.custom):a;r=Promise.all(ap(i,d,l))}return r.then(()=>{i.notify("AnimationComplete",a)})}const O2={test:i=>i==="auto",parse:i=>i},sp=i=>a=>a.test(i),lp=[ra,xt,Tn,ii,rv,lv,O2],rp=i=>lp.find(sp(i));function B2(i){return typeof i=="number"?i===0:i!==null?i==="none"||i==="0"||nh(i):!0}const N2=new Set(["brightness","contrast","saturate","opacity"]);function _2(i){const[a,l]=i.slice(0,-1).split("(");if(a==="drop-shadow")return i;const[r]=l.match(Xo)||[];if(!r)return i;const d=l.replace(r,"");let f=N2.has(a)?1:0;return r!==l&&(f*=100),a+"("+f+d+")"}const V2=/\b([a-z-]*)\(.*?\)/gu,Su={...fn,getAnimatableNone:i=>{const a=i.match(V2);return a?a.map(_2).join(" "):i}},wu={...fn,getAnimatableNone:i=>{const a=fn.parse(i);return fn.createTransformer(i)(a.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},op={...ra,transform:Math.round},Au={borderWidth:xt,borderTopWidth:xt,borderRightWidth:xt,borderBottomWidth:xt,borderLeftWidth:xt,borderRadius:xt,borderTopLeftRadius:xt,borderTopRightRadius:xt,borderBottomRightRadius:xt,borderBottomLeftRadius:xt,width:xt,maxWidth:xt,height:xt,maxHeight:xt,top:xt,right:xt,bottom:xt,left:xt,inset:xt,insetBlock:xt,insetBlockStart:xt,insetBlockEnd:xt,insetInline:xt,insetInlineStart:xt,insetInlineEnd:xt,padding:xt,paddingTop:xt,paddingRight:xt,paddingBottom:xt,paddingLeft:xt,paddingBlock:xt,paddingBlockStart:xt,paddingBlockEnd:xt,paddingInline:xt,paddingInlineStart:xt,paddingInlineEnd:xt,margin:xt,marginTop:xt,marginRight:xt,marginBottom:xt,marginLeft:xt,marginBlock:xt,marginBlockStart:xt,marginBlockEnd:xt,marginInline:xt,marginInlineStart:xt,marginInlineEnd:xt,fontSize:xt,backgroundPositionX:xt,backgroundPositionY:xt,...{rotate:ii,rotateX:ii,rotateY:ii,rotateZ:ii,scale:Tl,scaleX:Tl,scaleY:Tl,scaleZ:Tl,skew:ii,skewX:ii,skewY:ii,distance:xt,translateX:xt,translateY:xt,translateZ:xt,x:xt,y:xt,z:xt,perspective:xt,transformPerspective:xt,opacity:cs,originX:Sh,originY:Sh,originZ:xt},zIndex:op,fillOpacity:cs,strokeOpacity:cs,numOctaves:op},U2={...Au,color:de,backgroundColor:de,outlineColor:de,fill:de,stroke:de,borderColor:de,borderTopColor:de,borderRightColor:de,borderBottomColor:de,borderLeftColor:de,filter:Su,WebkitFilter:Su,mask:wu,WebkitMask:wu},up=i=>U2[i],H2=new Set([Su,wu]);function cp(i,a){let l=up(i);return H2.has(l)||(l=fn),l.getAnimatableNone?l.getAnimatableNone(a):void 0}const I2=new Set(["auto","none","0"]);function Y2(i,a,l){let r=0,d;for(;r{a.getValue(p).set(y)}),this.resolveNoneKeyframes()}}function dp(i,a,l){if(i==null)return[];if(i instanceof EventTarget)return[i];if(typeof i=="string"){let r=document;const d=l?.[i]??r.querySelectorAll(i);return d?Array.from(d):[]}return Array.from(i).filter(r=>r!=null)}const fp=(i,a)=>a&&typeof i=="number"?a.transform(i):i;function Rl(i){return eh(i)&&"offsetHeight"in i&&!("ownerSVGElement"in i)}const{schedule:Tu}=gh(queueMicrotask,!1),hn={x:!1,y:!1};function hp(){return hn.x||hn.y}function q2(i){return i==="x"||i==="y"?hn[i]?null:(hn[i]=!0,()=>{hn[i]=!1}):hn.x||hn.y?null:(hn.x=hn.y=!0,()=>{hn.x=hn.y=!1})}function pp(i,a){const l=dp(i),r=new AbortController,d={passive:!0,...a,signal:r.signal};return[l,d,()=>r.abort()]}function X2(i){return!(i.pointerType==="touch"||hp())}function F2(i,a,l={}){const[r,d,f]=pp(i,l);return r.forEach(h=>{let p=!1,y=!1,g;const b=()=>{h.removeEventListener("pointerleave",k)},S=O=>{g&&(g(O),g=void 0),b()},A=O=>{p=!1,window.removeEventListener("pointerup",A),window.removeEventListener("pointercancel",A),y&&(y=!1,S(O))},j=()=>{p=!0,window.addEventListener("pointerup",A,d),window.addEventListener("pointercancel",A,d)},k=O=>{if(O.pointerType!=="touch"){if(p){y=!0;return}S(O)}},D=O=>{if(!X2(O))return;y=!1;const F=a(h,O);typeof F=="function"&&(g=F,h.addEventListener("pointerleave",k,d))};h.addEventListener("pointerenter",D,d),h.addEventListener("pointerdown",j,d)}),f}const mp=(i,a)=>a?i===a?!0:mp(i,a.parentElement):!1,Eu=i=>i.pointerType==="mouse"?typeof i.button!="number"||i.button<=0:i.isPrimary!==!1,P2=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function K2(i){return P2.has(i.tagName)||i.isContentEditable===!0}const W2=new Set(["INPUT","SELECT","TEXTAREA"]);function Q2(i){return W2.has(i.tagName)||i.isContentEditable===!0}const Dl=new WeakSet;function gp(i){return a=>{a.key==="Enter"&&i(a)}}function ju(i,a){i.dispatchEvent(new PointerEvent("pointer"+a,{isPrimary:!0,bubbles:!0}))}const Z2=(i,a)=>{const l=i.currentTarget;if(!l)return;const r=gp(()=>{if(Dl.has(l))return;ju(l,"down");const d=gp(()=>{ju(l,"up")}),f=()=>ju(l,"cancel");l.addEventListener("keyup",d,a),l.addEventListener("blur",f,a)});l.addEventListener("keydown",r,a),l.addEventListener("blur",()=>l.removeEventListener("keydown",r),a)};function yp(i){return Eu(i)&&!hp()}const xp=new WeakSet;function $2(i,a,l={}){const[r,d,f]=pp(i,l),h=p=>{const y=p.currentTarget;if(!yp(p)||xp.has(p))return;Dl.add(y),l.stopPropagation&&xp.add(p);const g=a(y,p),b=(j,k)=>{window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",A),Dl.has(y)&&Dl.delete(y),yp(j)&&typeof g=="function"&&g(j,{success:k})},S=j=>{b(j,y===window||y===document||l.useGlobalTarget||mp(y,j.target))},A=j=>{b(j,!1)};window.addEventListener("pointerup",S,d),window.addEventListener("pointercancel",A,d)};return r.forEach(p=>{(l.useGlobalTarget?window:p).addEventListener("pointerdown",h,d),Rl(p)&&(p.addEventListener("focus",g=>Z2(g,d)),!K2(p)&&!p.hasAttribute("tabindex")&&(p.tabIndex=0))}),f}function Cu(i){return eh(i)&&"ownerSVGElement"in i}const zl=new WeakMap;let Ll;const bp=(i,a,l)=>(r,d)=>d&&d[0]?d[0][i+"Size"]:Cu(r)&&"getBBox"in r?r.getBBox()[a]:r[l],J2=bp("inline","width","offsetWidth"),tS=bp("block","height","offsetHeight");function eS({target:i,borderBoxSize:a}){zl.get(i)?.forEach(l=>{l(i,{get width(){return J2(i,a)},get height(){return tS(i,a)}})})}function nS(i){i.forEach(eS)}function iS(){typeof ResizeObserver>"u"||(Ll=new ResizeObserver(nS))}function aS(i,a){Ll||iS();const l=dp(i);return l.forEach(r=>{let d=zl.get(r);d||(d=new Set,zl.set(r,d)),d.add(a),Ll?.observe(r)}),()=>{l.forEach(r=>{const d=zl.get(r);d?.delete(a),d?.size||Ll?.unobserve(r)})}}const Ol=new Set;let ha;function sS(){ha=()=>{const i={get width(){return window.innerWidth},get height(){return window.innerHeight}};Ol.forEach(a=>a(i))},window.addEventListener("resize",ha)}function lS(i){return Ol.add(i),ha||sS(),()=>{Ol.delete(i),!Ol.size&&typeof ha=="function"&&(window.removeEventListener("resize",ha),ha=void 0)}}function vp(i,a){return typeof i=="function"?lS(i):aS(i,a)}function rS(i){return Cu(i)&&i.tagName==="svg"}const oS=[...lp,de,fn],uS=i=>oS.find(sp(i)),Sp=()=>({translate:0,scale:1,origin:0,originPoint:0}),pa=()=>({x:Sp(),y:Sp()}),wp=()=>({min:0,max:0}),ge=()=>({x:wp(),y:wp()}),cS=new WeakMap;function Bl(i){return i!==null&&typeof i=="object"&&typeof i.start=="function"}function ms(i){return typeof i=="string"||Array.isArray(i)}const Mu=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ku=["initial",...Mu];function Nl(i){return Bl(i.animate)||ku.some(a=>ms(i[a]))}function Ap(i){return!!(Nl(i)||i.variants)}function dS(i,a,l){for(const r in a){const d=a[r],f=l[r];if(we(d))i.addValue(r,d);else if(we(f))i.addValue(r,fa(d,{owner:i}));else if(f!==d)if(i.hasValue(r)){const h=i.getValue(r);h.liveStyle===!0?h.jump(d):h.hasAnimated||h.set(d)}else{const h=i.getStaticValue(r);i.addValue(r,fa(h!==void 0?h:d,{owner:i}))}}for(const r in l)a[r]===void 0&&i.removeValue(r);return a}const Ru={current:null},Tp={current:!1},fS=typeof window<"u";function hS(){if(Tp.current=!0,!!fS)if(window.matchMedia){const i=window.matchMedia("(prefers-reduced-motion)"),a=()=>Ru.current=i.matches;i.addEventListener("change",a),a()}else Ru.current=!1}const Ep=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let _l={};function jp(i){_l=i}function pS(){return _l}class mS{scrapeMotionValuesFromProps(a,l,r){return{}}constructor({parent:a,props:l,presenceContext:r,reducedMotionConfig:d,skipAnimations:f,blockInitialAnimation:h,visualState:p},y={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=du,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,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 j=ke.now();this.renderScheduledAtthis.bindToMotionValue(r,l)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Tp.current||hS(),this.shouldReduceMotion=Ru.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),ni(this.notifyUpdate),ni(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const l=this.features[a];l&&(l.unmount(),l.isMounted=!1)}this.current=null}addChild(a){this.children.add(a),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(a)}removeChild(a){this.children.delete(a),this.enteringChildren&&this.enteringChildren.delete(a)}bindToMotionValue(a,l){if(this.valueSubscriptions.has(a)&&this.valueSubscriptions.get(a)(),l.accelerate&&Wh.has(a)&&this.current instanceof HTMLElement){const{factory:h,keyframes:p,times:y,ease:g,duration:b}=l.accelerate,S=new Fh({element:this.current,name:a,keyframes:p,times:y,ease:g,duration:Ye(b)}),A=h(S);this.valueSubscriptions.set(a,()=>{A(),S.cancel()});return}const r=da.has(a);r&&this.onBindTransform&&this.onBindTransform();const d=l.on("change",h=>{this.latestValues[a]=h,this.props.onUpdate&&Jt.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let f;typeof window<"u"&&window.MotionCheckAppearSync&&(f=window.MotionCheckAppearSync(this,a,l)),this.valueSubscriptions.set(a,()=>{d(),f&&f(),l.owner&&l.stop()})}sortNodePosition(a){return!this.current||!this.sortInstanceNodePosition||this.type!==a.type?0:this.sortInstanceNodePosition(this.current,a.current)}updateFeatures(){let a="animation";for(a in _l){const l=_l[a];if(!l)continue;const{isEnabled:r,Feature:d}=l;if(!this.features[a]&&d&&r(this.props)&&(this.features[a]=new d(this)),this.features[a]){const f=this.features[a];f.isMounted?f.update():(f.mount(),f.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ge()}getStaticValue(a){return this.latestValues[a]}setStaticValue(a,l){this.latestValues[a]=l}update(a,l){(a.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=a,this.prevPresenceContext=this.presenceContext,this.presenceContext=l;for(let r=0;rl.variantChildren.delete(a)}addValue(a,l){const r=this.values.get(a);l!==r&&(r&&this.removeValue(a),this.bindToMotionValue(a,l),this.values.set(a,l),this.latestValues[a]=l.get())}removeValue(a){this.values.delete(a);const l=this.valueSubscriptions.get(a);l&&(l(),this.valueSubscriptions.delete(a)),delete this.latestValues[a],this.removeValueFromRenderState(a,this.renderState)}hasValue(a){return this.values.has(a)}getValue(a,l){if(this.props.values&&this.props.values[a])return this.props.values[a];let r=this.values.get(a);return r===void 0&&l!==void 0&&(r=fa(l===null?void 0:l,{owner:this}),this.addValue(a,r)),r}readValue(a,l){let r=this.latestValues[a]!==void 0||!this.current?this.latestValues[a]:this.getBaseTargetFromProps(this.props,a)??this.readValueFromInstance(this.current,a,this.options);return r!=null&&(typeof r=="string"&&(th(r)||nh(r))?r=parseFloat(r):!uS(r)&&fn.test(l)&&(r=cp(a,l)),this.setBaseTarget(a,we(r)?r.get():r)),we(r)?r.get():r}setBaseTarget(a,l){this.baseTarget[a]=l}getBaseTarget(a){const{initial:l}=this.props;let r;if(typeof l=="string"||typeof l=="object"){const f=gu(this.props,l,this.presenceContext?.custom);f&&(r=f[a])}if(l&&r!==void 0)return r;const d=this.getBaseTargetFromProps(this.props,a);return d!==void 0&&!we(d)?d:this.initialValues[a]!==void 0&&r===void 0?void 0:this.baseTarget[a]}on(a,l){return this.events[a]||(this.events[a]=new Ho),this.events[a].add(l)}notify(a,...l){this.events[a]&&this.events[a].notify(...l)}scheduleRenderMicrotask(){Tu.render(this.render)}}class Cp extends mS{constructor(){super(...arguments),this.KeyframeResolver=G2}sortInstanceNodePosition(a,l){return a.compareDocumentPosition(l)&2?1:-1}getBaseTargetFromProps(a,l){const r=a.style;return r?r[l]:void 0}removeValueFromRenderState(a,{vars:l,style:r}){delete l[a],delete r[a]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:a}=this.props;we(a)&&(this.childSubscription=a.on("change",l=>{this.current&&(this.current.textContent=`${l}`)}))}}class si{constructor(a){this.isMounted=!1,this.node=a}update(){}}function Mp({top:i,left:a,right:l,bottom:r}){return{x:{min:a,max:l},y:{min:i,max:r}}}function gS({x:i,y:a}){return{top:a.min,right:i.max,bottom:a.max,left:i.min}}function yS(i,a){if(!a)return i;const l=a({x:i.left,y:i.top}),r=a({x:i.right,y:i.bottom});return{top:l.y,left:l.x,bottom:r.y,right:r.x}}function Du(i){return i===void 0||i===1}function zu({scale:i,scaleX:a,scaleY:l}){return!Du(i)||!Du(a)||!Du(l)}function Ui(i){return zu(i)||kp(i)||i.z||i.rotate||i.rotateX||i.rotateY||i.skewX||i.skewY}function kp(i){return Rp(i.x)||Rp(i.y)}function Rp(i){return i&&i!=="0%"}function Vl(i,a,l){const r=i-l,d=a*r;return l+d}function Dp(i,a,l,r,d){return d!==void 0&&(i=Vl(i,d,r)),Vl(i,l,r)+a}function Lu(i,a=0,l=1,r,d){i.min=Dp(i.min,a,l,r,d),i.max=Dp(i.max,a,l,r,d)}function zp(i,{x:a,y:l}){Lu(i.x,a.translate,a.scale,a.originPoint),Lu(i.y,l.translate,l.scale,l.originPoint)}const Lp=.999999999999,Op=1.0000000000001;function xS(i,a,l,r=!1){const d=l.length;if(!d)return;a.x=a.y=1;let f,h;for(let p=0;pLp&&(a.x=1),a.yLp&&(a.y=1)}function En(i,a){i.min+=a,i.max+=a}function Bp(i,a,l,r,d=.5){const f=ee(i.min,i.max,d);Lu(i,a,l,f,r)}function Np(i,a){return typeof i=="string"?parseFloat(i)/100*(a.max-a.min):i}function Ul(i,a,l){const r=l??i;Bp(i.x,Np(a.x,r.x),a.scaleX,a.scale,a.originX),Bp(i.y,Np(a.y,r.y),a.scaleY,a.scale,a.originY)}function _p(i,a){return Mp(yS(i.getBoundingClientRect(),a))}function bS(i,a,l){const r=_p(i,l),{scroll:d}=a;return d&&(En(r.x,d.offset.x),En(r.y,d.offset.y)),r}const vS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},SS=ca.length;function wS(i,a,l){let r="",d=!0;for(let f=0;f{if(!a.target)return i;if(typeof i=="string")if(xt.test(i))i=parseFloat(i);else return i;const l=Up(i,a.target.x),r=Up(i,a.target.y);return`${l}% ${r}%`}},AS={correct:(i,{treeScale:a,projectionDelta:l})=>{const r=i,d=fn.parse(i);if(d.length>5)return r;const f=fn.createTransformer(i),h=typeof d[0]!="number"?1:0,p=l.x.scale*a.x,y=l.y.scale*a.y;d[0+h]/=p,d[1+h]/=y;const g=ee(p,y,.5);return typeof d[2+h]=="number"&&(d[2+h]/=g),typeof d[3+h]=="number"&&(d[3+h]/=g),f(d)}},Bu={borderRadius:{...gs,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:gs,borderTopRightRadius:gs,borderBottomLeftRadius:gs,borderBottomRightRadius:gs,boxShadow:AS};function Hp(i,{layout:a,layoutId:l}){return da.has(i)||i.startsWith("origin")||(a||l!==void 0)&&(!!Bu[i]||i==="opacity")}function Nu(i,a,l){const r=i.style,d=a?.style,f={};if(!r)return f;for(const h in r)(we(r[h])||d&&we(d[h])||Hp(h,i)||l?.getValue(h)?.liveStyle!==void 0)&&(f[h]=r[h]);return f}function TS(i){return window.getComputedStyle(i)}class ES extends Cp{constructor(){super(...arguments),this.type="html",this.renderInstance=Vp}readValueFromInstance(a,l){if(da.has(l))return this.projection?.isProjecting?lu(l):Pv(a,l);{const r=TS(a),d=(xh(l)?r.getPropertyValue(l):r[l])||0;return typeof d=="string"?d.trim():d}}measureInstanceViewportBox(a,{transformPagePoint:l}){return _p(a,l)}build(a,l,r){Ou(a,l,r.transformTemplate)}scrapeMotionValuesFromProps(a,l,r){return Nu(a,l,r)}}const jS={offset:"stroke-dashoffset",array:"stroke-dasharray"},CS={offset:"strokeDashoffset",array:"strokeDasharray"};function MS(i,a,l=1,r=0,d=!0){i.pathLength=1;const f=d?jS:CS;i[f.offset]=`${-r}`,i[f.array]=`${a} ${l}`}const kS=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Ip(i,{attrX:a,attrY:l,attrScale:r,pathLength:d,pathSpacing:f=1,pathOffset:h=0,...p},y,g,b){if(Ou(i,p,g),y){i.style.viewBox&&(i.attrs.viewBox=i.style.viewBox);return}i.attrs=i.style,i.style={};const{attrs:S,style:A}=i;S.transform&&(A.transform=S.transform,delete S.transform),(A.transform||S.transformOrigin)&&(A.transformOrigin=S.transformOrigin??"50% 50%",delete S.transformOrigin),A.transform&&(A.transformBox=b?.transformBox??"fill-box",delete S.transformBox);for(const j of kS)S[j]!==void 0&&(A[j]=S[j],delete S[j]);a!==void 0&&(S.x=a),l!==void 0&&(S.y=l),r!==void 0&&(S.scale=r),d!==void 0&&MS(S,d,f,h,!1)}const Yp=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"]),Gp=i=>typeof i=="string"&&i.toLowerCase()==="svg";function RS(i,a,l,r){Vp(i,a,void 0,r);for(const d in a.attrs)i.setAttribute(Yp.has(d)?d:bu(d),a.attrs[d])}function qp(i,a,l){const r=Nu(i,a,l);for(const d in i)if(we(i[d])||we(a[d])){const f=ca.indexOf(d)!==-1?"attr"+d.charAt(0).toUpperCase()+d.substring(1):d;r[f]=i[d]}return r}class DS extends Cp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(a,l){return a[l]}readValueFromInstance(a,l){if(da.has(l)){const r=up(l);return r&&r.default||0}return l=Yp.has(l)?l:bu(l),a.getAttribute(l)}scrapeMotionValuesFromProps(a,l,r){return qp(a,l,r)}build(a,l,r){Ip(a,l,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(a,l,r,d){RS(a,l,r,d)}mount(a){this.isSVGTag=Gp(a.tagName),super.mount(a)}}const zS=ku.length;function Xp(i){if(!i)return;if(!i.isControllingVariants){const l=i.parent?Xp(i.parent)||{}:{};return i.props.initial!==void 0&&(l.initial=i.props.initial),l}const a={};for(let l=0;lPromise.all(a.map(({animation:l,options:r})=>L2(i,l,r)))}function NS(i){let a=BS(i),l=Pp(),r=!0,d=!1;const f=g=>(b,S)=>{const A=Vi(i,S,g==="exit"?i.presenceContext?.custom:void 0);if(A){const{transition:j,transitionEnd:k,...D}=A;b={...b,...D,...k}}return b};function h(g){a=g(i)}function p(g){const{props:b}=i,S=Xp(i.parent)||{},A=[],j=new Set;let k={},D=1/0;for(let F=0;FD&&L,W=!1;const lt=Array.isArray(T)?T:[T];let it=lt.reduce(f(Q),{});U===!1&&(it={});const{prevResolvedValues:rt={}}=E,mt={...rt,...it},kt=G=>{P=!0,j.has(G)&&(W=!0,j.delete(G)),E.needsAnimating[G]=!0;const ct=i.getValue(G);ct&&(ct.liveStyle=!1)};for(const G in mt){const ct=it[G],bt=rt[G];if(k.hasOwnProperty(G))continue;let M=!1;yu(ct)&&yu(bt)?M=!Fp(ct,bt):M=ct!==bt,M?ct!=null?kt(G):j.add(G):ct!==void 0&&j.has(G)?kt(G):E.protectedKeys[G]=!0}E.prevProp=T,E.prevResolvedValues=it,E.isActive&&(k={...k,...it}),(r||d)&&i.blockInitialAnimation&&(P=!1);const B=$&&tt;P&&(!B||W)&&A.push(...lt.map(G=>{const ct={type:Q};if(typeof G=="string"&&(r||d)&&!B&&i.manuallyAnimateOnMount&&i.parent){const{parent:bt}=i,M=Vi(bt,G);if(bt.enteringChildren&&M){const{delayChildren:K}=M.transition||{};ct.delay=Qh(bt.enteringChildren,i,K)}}return{animation:G,options:ct}}))}if(j.size){const F={};if(typeof b.initial!="boolean"){const Q=Vi(i,Array.isArray(b.initial)?b.initial[0]:b.initial);Q&&Q.transition&&(F.transition=Q.transition)}j.forEach(Q=>{const E=i.getBaseTarget(Q),T=i.getValue(Q);T&&(T.liveStyle=!0),F[Q]=E??null}),A.push({animation:F})}let O=!!A.length;return r&&(b.initial===!1||b.initial===b.animate)&&!i.manuallyAnimateOnMount&&(O=!1),r=!1,d=!1,O?a(A):Promise.resolve()}function y(g,b){if(l[g].isActive===b)return Promise.resolve();i.variantChildren?.forEach(A=>A.animationState?.setActive(g,b)),l[g].isActive=b;const S=p(g);for(const A in l)l[A].protectedKeys={};return S}return{animateChanges:p,setActive:y,setAnimateFunction:h,getState:()=>l,reset:()=>{l=Pp(),d=!0}}}function _S(i,a){return typeof a=="string"?a!==i:Array.isArray(a)?!Fp(a,i):!1}function Hi(i=!1){return{isActive:i,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pp(){return{animate:Hi(!0),whileInView:Hi(),whileHover:Hi(),whileTap:Hi(),whileDrag:Hi(),whileFocus:Hi(),exit:Hi()}}function _u(i,a){i.min=a.min,i.max=a.max}function pn(i,a){_u(i.x,a.x),_u(i.y,a.y)}function Kp(i,a){i.translate=a.translate,i.scale=a.scale,i.originPoint=a.originPoint,i.origin=a.origin}const Wp=1e-4,VS=1-Wp,US=1+Wp,Qp=.01,HS=0-Qp,IS=0+Qp;function Re(i){return i.max-i.min}function YS(i,a,l){return Math.abs(i-a)<=l}function Zp(i,a,l,r=.5){i.origin=r,i.originPoint=ee(a.min,a.max,i.origin),i.scale=Re(l)/Re(a),i.translate=ee(l.min,l.max,i.origin)-i.originPoint,(i.scale>=VS&&i.scale<=US||isNaN(i.scale))&&(i.scale=1),(i.translate>=HS&&i.translate<=IS||isNaN(i.translate))&&(i.translate=0)}function ys(i,a,l,r){Zp(i.x,a.x,l.x,r?r.originX:void 0),Zp(i.y,a.y,l.y,r?r.originY:void 0)}function $p(i,a,l,r=0){const d=r?ee(l.min,l.max,r):l.min;i.min=d+a.min,i.max=i.min+Re(a)}function GS(i,a,l,r){$p(i.x,a.x,l.x,r?.x),$p(i.y,a.y,l.y,r?.y)}function Jp(i,a,l,r=0){const d=r?ee(l.min,l.max,r):l.min;i.min=a.min-d,i.max=i.min+Re(a)}function Hl(i,a,l,r){Jp(i.x,a.x,l.x,r?.x),Jp(i.y,a.y,l.y,r?.y)}function tm(i,a,l,r,d){return i-=a,i=Vl(i,1/l,r),d!==void 0&&(i=Vl(i,1/d,r)),i}function qS(i,a=0,l=1,r=.5,d,f=i,h=i){if(Tn.test(a)&&(a=parseFloat(a),a=ee(h.min,h.max,a/100)-h.min),typeof a!="number")return;let p=ee(f.min,f.max,r);i===f&&(p-=a),i.min=tm(i.min,a,l,p,d),i.max=tm(i.max,a,l,p,d)}function em(i,a,[l,r,d],f,h){qS(i,a[l],a[r],a[d],a.scale,f,h)}const XS=["x","scaleX","originX"],FS=["y","scaleY","originY"];function nm(i,a,l,r){em(i.x,a,XS,l?l.x:void 0,r?r.x:void 0),em(i.y,a,FS,l?l.y:void 0,r?r.y:void 0)}function im(i){return i.translate===0&&i.scale===1}function am(i){return im(i.x)&&im(i.y)}function sm(i,a){return i.min===a.min&&i.max===a.max}function PS(i,a){return sm(i.x,a.x)&&sm(i.y,a.y)}function lm(i,a){return Math.round(i.min)===Math.round(a.min)&&Math.round(i.max)===Math.round(a.max)}function rm(i,a){return lm(i.x,a.x)&&lm(i.y,a.y)}function om(i){return Re(i.x)/Re(i.y)}function um(i,a){return i.translate===a.translate&&i.scale===a.scale&&i.originPoint===a.originPoint}function jn(i){return[i("x"),i("y")]}function KS(i,a,l){let r="";const d=i.x.translate/a.x,f=i.y.translate/a.y,h=l?.z||0;if((d||f||h)&&(r=`translate3d(${d}px, ${f}px, ${h}px) `),(a.x!==1||a.y!==1)&&(r+=`scale(${1/a.x}, ${1/a.y}) `),l){const{transformPerspective:g,rotate:b,rotateX:S,rotateY:A,skewX:j,skewY:k}=l;g&&(r=`perspective(${g}px) ${r}`),b&&(r+=`rotate(${b}deg) `),S&&(r+=`rotateX(${S}deg) `),A&&(r+=`rotateY(${A}deg) `),j&&(r+=`skewX(${j}deg) `),k&&(r+=`skewY(${k}deg) `)}const p=i.x.scale*a.x,y=i.y.scale*a.y;return(p!==1||y!==1)&&(r+=`scale(${p}, ${y})`),r||"none"}const cm=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],WS=cm.length,dm=i=>typeof i=="string"?parseFloat(i):i,fm=i=>typeof i=="number"||xt.test(i);function QS(i,a,l,r,d,f){d?(i.opacity=ee(0,l.opacity??1,ZS(r)),i.opacityExit=ee(a.opacity??1,0,$S(r))):f&&(i.opacity=ee(a.opacity??1,l.opacity??1,r));for(let h=0;hra?1:l(os(i,a,r))}function JS(i,a,l){const r=we(i)?i:fa(i);return r.start(mu("",r,a,l)),r.animation}function xs(i,a,l,r={passive:!0}){return i.addEventListener(a,l,r),()=>i.removeEventListener(a,l)}const tw=(i,a)=>i.depth-a.depth;class ew{constructor(){this.children=[],this.isDirty=!1}add(a){Vo(this.children,a),this.isDirty=!0}remove(a){Sl(this.children,a),this.isDirty=!0}forEach(a){this.isDirty&&this.children.sort(tw),this.isDirty=!1,this.children.forEach(a)}}function nw(i,a){const l=ke.now(),r=({timestamp:d})=>{const f=d-l;f>=a&&(ni(r),i(f-a))};return Jt.setup(r,!0),()=>ni(r)}function Il(i){return we(i)?i.get():i}class iw{constructor(){this.members=[]}add(a){Vo(this.members,a);for(let l=this.members.length-1;l>=0;l--){const r=this.members[l];if(r===a||r===this.lead||r===this.prevLead)continue;const d=r.instance;(!d||d.isConnected===!1)&&!r.snapshot&&(Sl(this.members,r),r.unmount())}a.scheduleRender()}remove(a){if(Sl(this.members,a),a===this.prevLead&&(this.prevLead=void 0),a===this.lead){const l=this.members[this.members.length-1];l&&this.promote(l)}}relegate(a){for(let l=this.members.indexOf(a)-1;l>=0;l--){const r=this.members[l];if(r.isPresent!==!1&&r.instance?.isConnected!==!1)return this.promote(r),!0}return!1}promote(a,l){const r=this.lead;if(a!==r&&(this.prevLead=r,this.lead=a,a.show(),r)){r.updateSnapshot(),a.scheduleRender();const{layoutDependency:d}=r.options,{layoutDependency:f}=a.options;(d===void 0||d!==f)&&(a.resumeFrom=r,l&&(r.preserveOpacity=!0),r.snapshot&&(a.snapshot=r.snapshot,a.snapshot.latestValues=r.animationValues||r.latestValues),a.root?.isUpdating&&(a.isLayoutDirty=!0)),a.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(a=>{a.options.onExitComplete?.(),a.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(a=>a.instance&&a.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}}const Yl={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Vu=["","X","Y","Z"],aw=1e3;let sw=0;function Uu(i,a,l,r){const{latestValues:d}=a;d[i]&&(l[i]=d[i],a.setStaticValue(i,0),r&&(r[i]=0))}function mm(i){if(i.hasCheckedOptimisedAppear=!0,i.root===i)return;const{visualElement:a}=i.options;if(!a)return;const l=ip(a);if(window.MotionHasOptimisedAnimation(l,"transform")){const{layout:d,layoutId:f}=i.options;window.MotionCancelOptimisedAnimation(l,"transform",Jt,!(d||f))}const{parent:r}=i;r&&!r.hasCheckedOptimisedAppear&&mm(r)}function gm({attachResizeListener:i,defaultParent:a,measureScroll:l,checkIsScrollRoot:r,resetTransform:d}){return class{constructor(h={},p=a?.()){this.id=sw++,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(ow),this.nodes.forEach(pw),this.nodes.forEach(mw),this.nodes.forEach(uw)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=h,this.root=p?p.root||p:this,this.path=p?[...p.path,p]:[],this.parent=p,this.depth=p?p.depth+1:0;for(let y=0;ythis.root.updateBlockedByResize=!1;Jt.read(()=>{S=window.innerWidth}),i(h,()=>{const j=window.innerWidth;j!==S&&(S=j,this.root.updateBlockedByResize=!0,b&&b(),b=nw(A,250),Yl.hasAnimatedSinceResize&&(Yl.hasAnimatedSinceResize=!1,this.nodes.forEach(bm)))})}p&&this.root.registerSharedNode(p,this),this.options.animate!==!1&&g&&(p||y)&&this.addEventListener("didUpdate",({delta:b,hasLayoutChanged:S,hasRelativeLayoutChanged:A,layout:j})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const k=this.options.transition||g.getDefaultTransition()||vw,{onLayoutAnimationStart:D,onLayoutAnimationComplete:O}=g.getProps(),F=!this.targetLayout||!rm(this.targetLayout,j),Q=!S&&A;if(this.options.layoutRoot||this.resumeFrom||Q||S&&(F||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...pu(k,"layout"),onPlay:D,onComplete:O};(g.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(b,Q)}else S||bm(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=j})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const h=this.getStack();h&&h.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),ni(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(gw),this.animationId++)}getTransformTemplate(){const{visualElement:h}=this.options;return h&&h.getProps().transformTemplate}willUpdate(h=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&mm(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let b=0;b{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Re(this.snapshot.measuredBox.x)&&!Re(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 y=0;y{const L=T/1e3;vm(S.x,h.x,L),vm(S.y,h.y,L),this.setTargetDelta(S),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Hl(A,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),xw(this.relativeTarget,this.relativeTargetOrigin,A,L),E&&PS(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ge()),pn(E,this.relativeTarget)),D&&(this.animationValues=b,QS(b,g,this.latestValues,L,Q,F)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(h){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ni(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Jt.update(()=>{Yl.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=fa(0)),this.motionValue.jump(0,!1),this.currentAnimation=JS(this.motionValue,[0,1e3],{...h,velocity:0,isSync:!0,onUpdate:p=>{this.mixTargetDelta(p),h.onUpdate&&h.onUpdate(p)},onStop:()=>{},onComplete:()=>{h.onComplete&&h.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 h=this.getStack();h&&h.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(aw),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const h=this.getLead();let{targetWithTransforms:p,target:y,layout:g,latestValues:b}=h;if(!(!p||!y||!g)){if(this!==h&&this.layout&&g&&Em(this.options.animationType,this.layout.layoutBox,g.layoutBox)){y=this.target||ge();const S=Re(this.layout.layoutBox.x);y.x.min=h.target.x.min,y.x.max=y.x.min+S;const A=Re(this.layout.layoutBox.y);y.y.min=h.target.y.min,y.y.max=y.y.min+A}pn(p,y),Ul(p,b),ys(this.projectionDeltaWithTransform,this.layoutCorrected,p,b)}}registerSharedNode(h,p){this.sharedNodes.has(h)||this.sharedNodes.set(h,new iw),this.sharedNodes.get(h).add(p);const g=p.options.initialPromotionConfig;p.promote({transition:g?g.transition:void 0,preserveFollowOpacity:g&&g.shouldPreserveFollowOpacity?g.shouldPreserveFollowOpacity(p):void 0})}isLead(){const h=this.getStack();return h?h.lead===this:!0}getLead(){const{layoutId:h}=this.options;return h?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:h}=this.options;return h?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:h}=this.options;if(h)return this.root.sharedNodes.get(h)}promote({needsReset:h,transition:p,preserveFollowOpacity:y}={}){const g=this.getStack();g&&g.promote(this,y),h&&(this.projectionDelta=void 0,this.needsReset=!0),p&&this.setOptions({transition:p})}relegate(){const h=this.getStack();return h?h.relegate(this):!1}resetSkewAndRotation(){const{visualElement:h}=this.options;if(!h)return;let p=!1;const{latestValues:y}=h;if((y.z||y.rotate||y.rotateX||y.rotateY||y.rotateZ||y.skewX||y.skewY)&&(p=!0),!p)return;const g={};y.z&&Uu("z",h,g,this.animationValues);for(let b=0;bh.currentAnimation?.stop()),this.root.nodes.forEach(ym),this.root.sharedNodes.clear()}}}function lw(i){i.updateLayout()}function rw(i){const a=i.resumeFrom?.snapshot||i.snapshot;if(i.isLead()&&i.layout&&a&&i.hasListeners("didUpdate")){const{layoutBox:l,measuredBox:r}=i.layout,{animationType:d}=i.options,f=a.source!==i.layout.source;if(d==="size")jn(b=>{const S=f?a.measuredBox[b]:a.layoutBox[b],A=Re(S);S.min=l[b].min,S.max=S.min+A});else if(d==="x"||d==="y"){const b=d==="x"?"y":"x";_u(f?a.measuredBox[b]:a.layoutBox[b],l[b])}else Em(d,a.layoutBox,l)&&jn(b=>{const S=f?a.measuredBox[b]:a.layoutBox[b],A=Re(l[b]);S.max=S.min+A,i.relativeTarget&&!i.currentAnimation&&(i.isProjectionDirty=!0,i.relativeTarget[b].max=i.relativeTarget[b].min+A)});const h=pa();ys(h,l,a.layoutBox);const p=pa();f?ys(p,i.applyTransform(r,!0),a.measuredBox):ys(p,l,a.layoutBox);const y=!am(h);let g=!1;if(!i.resumeFrom){const b=i.getClosestProjectingParent();if(b&&!b.resumeFrom){const{snapshot:S,layout:A}=b;if(S&&A){const j=i.options.layoutAnchor||void 0,k=ge();Hl(k,a.layoutBox,S.layoutBox,j);const D=ge();Hl(D,l,A.layoutBox,j),rm(k,D)||(g=!0),b.options.layoutRoot&&(i.relativeTarget=D,i.relativeTargetOrigin=k,i.relativeParent=b)}}}i.notifyListeners("didUpdate",{layout:l,snapshot:a,delta:p,layoutDelta:h,hasLayoutChanged:y,hasRelativeLayoutChanged:g})}else if(i.isLead()){const{onExitComplete:l}=i.options;l&&l()}i.options.transition=void 0}function ow(i){i.parent&&(i.isProjecting()||(i.isProjectionDirty=i.parent.isProjectionDirty),i.isSharedProjectionDirty||(i.isSharedProjectionDirty=!!(i.isProjectionDirty||i.parent.isProjectionDirty||i.parent.isSharedProjectionDirty)),i.isTransformDirty||(i.isTransformDirty=i.parent.isTransformDirty))}function uw(i){i.isProjectionDirty=i.isSharedProjectionDirty=i.isTransformDirty=!1}function cw(i){i.clearSnapshot()}function ym(i){i.clearMeasurements()}function dw(i){i.isLayoutDirty=!0,i.updateLayout()}function xm(i){i.isLayoutDirty=!1}function fw(i){i.isAnimationBlocked&&i.layout&&!i.isLayoutDirty&&(i.snapshot=i.layout,i.isLayoutDirty=!0)}function hw(i){const{visualElement:a}=i.options;a&&a.getProps().onBeforeLayoutMeasure&&a.notify("BeforeLayoutMeasure"),i.resetTransform()}function bm(i){i.finishAnimation(),i.targetDelta=i.relativeTarget=i.target=void 0,i.isProjectionDirty=!0}function pw(i){i.resolveTargetDelta()}function mw(i){i.calcProjection()}function gw(i){i.resetSkewAndRotation()}function yw(i){i.removeLeadSnapshot()}function vm(i,a,l){i.translate=ee(a.translate,0,l),i.scale=ee(a.scale,1,l),i.origin=a.origin,i.originPoint=a.originPoint}function Sm(i,a,l,r){i.min=ee(a.min,l.min,r),i.max=ee(a.max,l.max,r)}function xw(i,a,l,r){Sm(i.x,a.x,l.x,r),Sm(i.y,a.y,l.y,r)}function bw(i){return i.animationValues&&i.animationValues.opacityExit!==void 0}const vw={duration:.45,ease:[.4,0,.1,1]},wm=i=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(i),Am=wm("applewebkit/")&&!wm("chrome/")?Math.round:Je;function Tm(i){i.min=Am(i.min),i.max=Am(i.max)}function Sw(i){Tm(i.x),Tm(i.y)}function Em(i,a,l){return i==="position"||i==="preserve-aspect"&&!YS(om(a),om(l),.2)}function ww(i){return i!==i.root&&i.scroll?.wasRoot}const Aw=gm({attachResizeListener:(i,a)=>xs(i,"resize",a),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Hu={current:void 0},jm=gm({measureScroll:i=>({x:i.scrollLeft,y:i.scrollTop}),defaultParent:()=>{if(!Hu.current){const i=new Aw({});i.mount(window),i.setOptions({layoutScroll:!0}),Hu.current=i}return Hu.current},resetTransform:(i,a)=>{i.style.transform=a!==void 0?a:"none"},checkIsScrollRoot:i=>window.getComputedStyle(i).position==="fixed"}),Iu=v.createContext({transformPagePoint:i=>i,isStatic:!1,reducedMotion:"never"});function Cm(i,a){if(typeof i=="function")return i(a);i!=null&&(i.current=a)}function Tw(...i){return a=>{let l=!1;const r=i.map(d=>{const f=Cm(d,a);return!l&&typeof f=="function"&&(l=!0),f});if(l)return()=>{for(let d=0;d{const{width:A,height:j,top:k,left:D,right:O,bottom:F}=y.current;if(a||f===!1||!p.current||!A||!j)return;const Q=l==="left"?`left: ${D}`:`right: ${O}`,E=r==="bottom"?`bottom: ${F}`:`top: ${k}`;p.current.dataset.motionPopId=h;const T=document.createElement("style");g&&(T.nonce=g);const L=d??document.head;return L.appendChild(T),T.sheet&&T.sheet.insertRule(` +`+s.stack}}var Nt=Object.prototype.hasOwnProperty,Xt=n.unstable_scheduleCallback,be=n.unstable_cancelCallback,Pt=n.unstable_shouldYield,Q=n.unstable_requestPaint,ut=n.unstable_now,zt=n.unstable_getCurrentPriorityLevel,Lt=n.unstable_ImmediatePriority,kt=n.unstable_UserBlockingPriority,oe=n.unstable_NormalPriority,Le=n.unstable_LowPriority,Sn=n.unstable_IdlePriority,fi=n.log,yr=n.unstable_setDisableYieldValue,Os=null,qe=null;function hi(t){if(typeof fi=="function"&&yr(t),qe&&typeof qe.setStrictMode=="function")try{qe.setStrictMode(Os,t)}catch{}}var Xe=Math.clz32?Math.clz32:Oj,zj=Math.log,Lj=Math.LN2;function Oj(t){return t>>>=0,t===0?32:31-(zj(t)/Lj|0)|0}var xr=256,br=262144,vr=4194304;function Ki(t){var e=t&42;if(e!==0)return e;switch(t&-t){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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Sr(t,e,i){var s=t.pendingLanes;if(s===0)return 0;var o=0,c=t.suspendedLanes,m=t.pingedLanes;t=t.warmLanes;var S=s&134217727;return S!==0?(s=S&~c,s!==0?o=Ki(s):(m&=S,m!==0?o=Ki(m):i||(i=S&~t,i!==0&&(o=Ki(i))))):(S=s&~c,S!==0?o=Ki(S):m!==0?o=Ki(m):i||(i=s&~t,i!==0&&(o=Ki(i)))),o===0?0:e!==0&&e!==o&&(e&c)===0&&(c=o&-o,i=e&-e,c>=i||c===32&&(i&4194048)!==0)?e:o}function Bs(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function Bj(t,e){switch(t){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32: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+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function t0(){var t=vr;return vr<<=1,(vr&62914560)===0&&(vr=4194304),t}function Vc(t){for(var e=[],i=0;31>i;i++)e.push(t);return e}function Ns(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Nj(t,e,i,s,o,c){var m=t.pendingLanes;t.pendingLanes=i,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=i,t.entangledLanes&=i,t.errorRecoveryDisabledLanes&=i,t.shellSuspendCounter=0;var S=t.entanglements,C=t.expirationTimes,_=t.hiddenUpdates;for(i=m&~i;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Yj=/[\n"\\]/g;function an(t){return t.replace(Yj,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function Xc(t,e,i,s,o,c,m,S){t.name="",m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"?t.type=m:t.removeAttribute("type"),e!=null?m==="number"?(e===0&&t.value===""||t.value!=e)&&(t.value=""+nn(e)):t.value!==""+nn(e)&&(t.value=""+nn(e)):m!=="submit"&&m!=="reset"||t.removeAttribute("value"),e!=null?Pc(t,m,nn(e)):i!=null?Pc(t,m,nn(i)):s!=null&&t.removeAttribute("value"),o==null&&c!=null&&(t.defaultChecked=!!c),o!=null&&(t.checked=o&&typeof o!="function"&&typeof o!="symbol"),S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?t.name=""+nn(S):t.removeAttribute("name")}function h0(t,e,i,s,o,c,m,S){if(c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(t.type=c),e!=null||i!=null){if(!(c!=="submit"&&c!=="reset"||e!=null)){qc(t);return}i=i!=null?""+nn(i):"",e=e!=null?""+nn(e):i,S||e===t.value||(t.value=e),t.defaultValue=e}s=s??o,s=typeof s!="function"&&typeof s!="symbol"&&!!s,t.checked=S?t.checked:!!s,t.defaultChecked=!!s,m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(t.name=m),qc(t)}function Pc(t,e,i){e==="number"&&Tr(t.ownerDocument)===t||t.defaultValue===""+i||(t.defaultValue=""+i)}function Da(t,e,i,s){if(t=t.options,e){e={};for(var o=0;o"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$c=!1;if(In)try{var Vs={};Object.defineProperty(Vs,"passive",{get:function(){$c=!0}}),window.addEventListener("test",Vs,Vs),window.removeEventListener("test",Vs,Vs)}catch{$c=!1}var mi=null,Jc=null,jr=null;function v0(){if(jr)return jr;var t,e=Jc,i=e.length,s,o="value"in mi?mi.value:mi.textContent,c=o.length;for(t=0;t=Gs),j0=" ",C0=!1;function M0(t,e){switch(t){case"keyup":return g4.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function k0(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ba=!1;function x4(t,e){switch(t){case"compositionend":return k0(e);case"keypress":return e.which!==32?null:(C0=!0,j0);case"textInput":return t=e.data,t===j0&&C0?null:t;default:return null}}function b4(t,e){if(Ba)return t==="compositionend"||!ad&&M0(t,e)?(t=v0(),jr=Jc=mi=null,Ba=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:i,offset:e-t};t=s}t:{for(;i;){if(i.nextSibling){i=i.nextSibling;break t}i=i.parentNode}i=void 0}i=_0(i)}}function H0(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?H0(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function V0(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=Tr(t.document);e instanceof t.HTMLIFrameElement;){try{var i=typeof e.contentWindow.location.href=="string"}catch{i=!1}if(i)t=e.contentWindow;else break;e=Tr(t.document)}return e}function rd(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}var C4=In&&"documentMode"in document&&11>=document.documentMode,Na=null,od=null,Ps=null,ud=!1;function I0(t,e,i){var s=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;ud||Na==null||Na!==Tr(s)||(s=Na,"selectionStart"in s&&rd(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),Ps&&Xs(Ps,s)||(Ps=s,s=vo(od,"onSelect"),0>=m,o-=m,zn=1<<32-Xe(e)+o|i<Dt?(Ut=St,St=null):Ut=St.sibling;var Ft=U(z,St,N[Dt],tt);if(Ft===null){St===null&&(St=Ut);break}t&&St&&Ft.alternate===null&&e(z,St),R=c(Ft,R,Dt),Gt===null?wt=Ft:Gt.sibling=Ft,Gt=Ft,St=Ut}if(Dt===N.length)return i(z,St),Yt&&Gn(z,Dt),wt;if(St===null){for(;DtDt?(Ut=St,St=null):Ut=St.sibling;var _i=U(z,St,Ft.value,tt);if(_i===null){St===null&&(St=Ut);break}t&&St&&_i.alternate===null&&e(z,St),R=c(_i,R,Dt),Gt===null?wt=_i:Gt.sibling=_i,Gt=_i,St=Ut}if(Ft.done)return i(z,St),Yt&&Gn(z,Dt),wt;if(St===null){for(;!Ft.done;Dt++,Ft=N.next())Ft=et(z,Ft.value,tt),Ft!==null&&(R=c(Ft,R,Dt),Gt===null?wt=Ft:Gt.sibling=Ft,Gt=Ft);return Yt&&Gn(z,Dt),wt}for(St=s(St);!Ft.done;Dt++,Ft=N.next())Ft=G(St,z,Dt,Ft.value,tt),Ft!==null&&(t&&Ft.alternate!==null&&St.delete(Ft.key===null?Dt:Ft.key),R=c(Ft,R,Dt),Gt===null?wt=Ft:Gt.sibling=Ft,Gt=Ft);return t&&St.forEach(function(PC){return e(z,PC)}),Yt&&Gn(z,Dt),wt}function $t(z,R,N,tt){if(typeof N=="object"&&N!==null&&N.type===D&&N.key===null&&(N=N.props.children),typeof N=="object"&&N!==null){switch(N.$$typeof){case j:t:{for(var wt=N.key;R!==null;){if(R.key===wt){if(wt=N.type,wt===D){if(R.tag===7){i(z,R.sibling),tt=o(R,N.props.children),tt.return=z,z=tt;break t}}else if(R.elementType===wt||typeof wt=="object"&&wt!==null&&wt.$$typeof===$&&sa(wt)===R.type){i(z,R.sibling),tt=o(R,N.props),Js(tt,N),tt.return=z,z=tt;break t}i(z,R);break}else e(z,R);R=R.sibling}N.type===D?(tt=ta(N.props.children,z.mode,tt,N.key),tt.return=z,z=tt):(tt=Nr(N.type,N.key,N.props,null,z.mode,tt),Js(tt,N),tt.return=z,z=tt)}return m(z);case k:t:{for(wt=N.key;R!==null;){if(R.key===wt)if(R.tag===4&&R.stateNode.containerInfo===N.containerInfo&&R.stateNode.implementation===N.implementation){i(z,R.sibling),tt=o(R,N.children||[]),tt.return=z,z=tt;break t}else{i(z,R);break}else e(z,R);R=R.sibling}tt=gd(N,z.mode,tt),tt.return=z,z=tt}return m(z);case $:return N=sa(N),$t(z,R,N,tt)}if(Mt(N))return yt(z,R,N,tt);if(it(N)){if(wt=it(N),typeof wt!="function")throw Error(r(150));return N=wt.call(N),At(z,R,N,tt)}if(typeof N.then=="function")return $t(z,R,Gr(N),tt);if(N.$$typeof===E)return $t(z,R,Hr(z,N),tt);Fr(z,N)}return typeof N=="string"&&N!==""||typeof N=="number"||typeof N=="bigint"?(N=""+N,R!==null&&R.tag===6?(i(z,R.sibling),tt=o(R,N),tt.return=z,z=tt):(i(z,R),tt=md(N,z.mode,tt),tt.return=z,z=tt),m(z)):i(z,R)}return function(z,R,N,tt){try{$s=0;var wt=$t(z,R,N,tt);return Pa=null,wt}catch(St){if(St===Xa||St===Ir)throw St;var Gt=Ke(29,St,null,z.mode);return Gt.lanes=tt,Gt.return=z,Gt}}}var ra=c1(!0),d1=c1(!1),vi=!1;function Md(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kd(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Si(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function wi(t,e,i){var s=t.updateQueue;if(s===null)return null;if(s=s.shared,(qt&2)!==0){var o=s.pending;return o===null?e.next=e:(e.next=o.next,o.next=e),s.pending=e,e=Br(t),K0(t,null,i),e}return Or(t,s,e,i),Br(t)}function tl(t,e,i){if(e=e.updateQueue,e!==null&&(e=e.shared,(i&4194048)!==0)){var s=e.lanes;s&=t.pendingLanes,i|=s,e.lanes=i,n0(t,i)}}function Rd(t,e){var i=t.updateQueue,s=t.alternate;if(s!==null&&(s=s.updateQueue,i===s)){var o=null,c=null;if(i=i.firstBaseUpdate,i!==null){do{var m={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};c===null?o=c=m:c=c.next=m,i=i.next}while(i!==null);c===null?o=c=e:c=c.next=e}else o=c=e;i={baseState:s.baseState,firstBaseUpdate:o,lastBaseUpdate:c,shared:s.shared,callbacks:s.callbacks},t.updateQueue=i;return}t=i.lastBaseUpdate,t===null?i.firstBaseUpdate=e:t.next=e,i.lastBaseUpdate=e}var Dd=!1;function el(){if(Dd){var t=qa;if(t!==null)throw t}}function nl(t,e,i,s){Dd=!1;var o=t.updateQueue;vi=!1;var c=o.firstBaseUpdate,m=o.lastBaseUpdate,S=o.shared.pending;if(S!==null){o.shared.pending=null;var C=S,_=C.next;C.next=null,m===null?c=_:m.next=_,m=C;var Z=t.alternate;Z!==null&&(Z=Z.updateQueue,S=Z.lastBaseUpdate,S!==m&&(S===null?Z.firstBaseUpdate=_:S.next=_,Z.lastBaseUpdate=C))}if(c!==null){var et=o.baseState;m=0,Z=_=C=null,S=c;do{var U=S.lane&-536870913,G=U!==S.lane;if(G?(_t&U)===U:(s&U)===U){U!==0&&U===Fa&&(Dd=!0),Z!==null&&(Z=Z.next={lane:0,tag:S.tag,payload:S.payload,callback:null,next:null});t:{var yt=t,At=S;U=e;var $t=i;switch(At.tag){case 1:if(yt=At.payload,typeof yt=="function"){et=yt.call($t,et,U);break t}et=yt;break t;case 3:yt.flags=yt.flags&-65537|128;case 0:if(yt=At.payload,U=typeof yt=="function"?yt.call($t,et,U):yt,U==null)break t;et=w({},et,U);break t;case 2:vi=!0}}U=S.callback,U!==null&&(t.flags|=64,G&&(t.flags|=8192),G=o.callbacks,G===null?o.callbacks=[U]:G.push(U))}else G={lane:U,tag:S.tag,payload:S.payload,callback:S.callback,next:null},Z===null?(_=Z=G,C=et):Z=Z.next=G,m|=U;if(S=S.next,S===null){if(S=o.shared.pending,S===null)break;G=S,S=G.next,G.next=null,o.lastBaseUpdate=G,o.shared.pending=null}}while(!0);Z===null&&(C=et),o.baseState=C,o.firstBaseUpdate=_,o.lastBaseUpdate=Z,c===null&&(o.shared.lanes=0),Ci|=m,t.lanes=m,t.memoizedState=et}}function f1(t,e){if(typeof t!="function")throw Error(r(191,t));t.call(e)}function h1(t,e){var i=t.callbacks;if(i!==null)for(t.callbacks=null,t=0;tc?c:8;var m=B.T,S={};B.T=S,Qd(t,!1,e,i);try{var C=o(),_=B.S;if(_!==null&&_(S,C),C!==null&&typeof C=="object"&&typeof C.then=="function"){var Z=N4(C,s);sl(t,e,Z,Je(t))}else sl(t,e,s,Je(t))}catch(et){sl(t,e,{then:function(){},status:"rejected",reason:et},Je())}finally{at.p=c,m!==null&&S.types!==null&&(m.types=S.types),B.T=m}}function Y4(){}function Kd(t,e,i,s){if(t.tag!==5)throw Error(r(476));var o=q1(t).queue;F1(t,o,e,Y,i===null?Y4:function(){return X1(t),i(s)})}function q1(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:Y,baseState:Y,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Pn,lastRenderedState:Y},next:null};var i={};return e.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Pn,lastRenderedState:i},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function X1(t){var e=q1(t);e.next===null&&(e=t.alternate.memoizedState),sl(t,e.next.queue,{},Je())}function Wd(){return je(wl)}function P1(){return ce().memoizedState}function K1(){return ce().memoizedState}function G4(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var i=Je();t=Si(i);var s=wi(e,t,i);s!==null&&(Ye(s,e,i),tl(s,e,i)),e={cache:Td()},t.payload=e;return}e=e.return}}function F4(t,e,i){var s=Je();i={lane:s,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},to(t)?Q1(e,i):(i=hd(t,e,i,s),i!==null&&(Ye(i,t,s),Z1(i,e,s)))}function W1(t,e,i){var s=Je();sl(t,e,i,s)}function sl(t,e,i,s){var o={lane:s,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(to(t))Q1(e,o);else{var c=t.alternate;if(t.lanes===0&&(c===null||c.lanes===0)&&(c=e.lastRenderedReducer,c!==null))try{var m=e.lastRenderedState,S=c(m,i);if(o.hasEagerState=!0,o.eagerState=S,Pe(S,m))return Or(t,e,o,0),te===null&&Lr(),!1}catch{}if(i=hd(t,e,o,s),i!==null)return Ye(i,t,s),Z1(i,e,s),!0}return!1}function Qd(t,e,i,s){if(s={lane:2,revertLane:kf(),gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},to(t)){if(e)throw Error(r(479))}else e=hd(t,i,s,2),e!==null&&Ye(e,t,2)}function to(t){var e=t.alternate;return t===Rt||e!==null&&e===Rt}function Q1(t,e){Wa=Pr=!0;var i=t.pending;i===null?e.next=e:(e.next=i.next,i.next=e),t.pending=e}function Z1(t,e,i){if((i&4194048)!==0){var s=e.lanes;s&=t.pendingLanes,i|=s,e.lanes=i,n0(t,i)}}var ll={readContext:je,use:Qr,useCallback:le,useContext:le,useEffect:le,useImperativeHandle:le,useLayoutEffect:le,useInsertionEffect:le,useMemo:le,useReducer:le,useRef:le,useState:le,useDebugValue:le,useDeferredValue:le,useTransition:le,useSyncExternalStore:le,useId:le,useHostTransitionStatus:le,useFormState:le,useActionState:le,useOptimistic:le,useMemoCache:le,useCacheRefresh:le};ll.useEffectEvent=le;var $1={readContext:je,use:Qr,useCallback:function(t,e){return Oe().memoizedState=[t,e===void 0?null:e],t},useContext:je,useEffect:B1,useImperativeHandle:function(t,e,i){i=i!=null?i.concat([t]):null,$r(4194308,4,H1.bind(null,e,t),i)},useLayoutEffect:function(t,e){return $r(4194308,4,t,e)},useInsertionEffect:function(t,e){$r(4,2,t,e)},useMemo:function(t,e){var i=Oe();e=e===void 0?null:e;var s=t();if(oa){hi(!0);try{t()}finally{hi(!1)}}return i.memoizedState=[s,e],s},useReducer:function(t,e,i){var s=Oe();if(i!==void 0){var o=i(e);if(oa){hi(!0);try{i(e)}finally{hi(!1)}}}else o=e;return s.memoizedState=s.baseState=o,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:o},s.queue=t,t=t.dispatch=F4.bind(null,Rt,t),[s.memoizedState,t]},useRef:function(t){var e=Oe();return t={current:t},e.memoizedState=t},useState:function(t){t=Gd(t);var e=t.queue,i=W1.bind(null,Rt,e);return e.dispatch=i,[t.memoizedState,i]},useDebugValue:Xd,useDeferredValue:function(t,e){var i=Oe();return Pd(i,t,e)},useTransition:function(){var t=Gd(!1);return t=F1.bind(null,Rt,t.queue,!0,!1),Oe().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,i){var s=Rt,o=Oe();if(Yt){if(i===void 0)throw Error(r(407));i=i()}else{if(i=e(),te===null)throw Error(r(349));(_t&127)!==0||b1(s,e,i)}o.memoizedState=i;var c={value:i,getSnapshot:e};return o.queue=c,B1(S1.bind(null,s,c,t),[t]),s.flags|=2048,Za(9,{destroy:void 0},v1.bind(null,s,c,i,e),null),i},useId:function(){var t=Oe(),e=te.identifierPrefix;if(Yt){var i=Ln,s=zn;i=(s&~(1<<32-Xe(s)-1)).toString(32)+i,e="_"+e+"R_"+i,i=Kr++,0<\/script>",c=c.removeChild(c.firstChild);break;case"select":c=typeof s.is=="string"?m.createElement("select",{is:s.is}):m.createElement("select"),s.multiple?c.multiple=!0:s.size&&(c.size=s.size);break;default:c=typeof s.is=="string"?m.createElement(o,{is:s.is}):m.createElement(o)}}c[Te]=e,c[Ne]=s;t:for(m=e.child;m!==null;){if(m.tag===5||m.tag===6)c.appendChild(m.stateNode);else if(m.tag!==4&&m.tag!==27&&m.child!==null){m.child.return=m,m=m.child;continue}if(m===e)break t;for(;m.sibling===null;){if(m.return===null||m.return===e)break t;m=m.return}m.sibling.return=m.return,m=m.sibling}e.stateNode=c;t:switch(Me(c,o,s),o){case"button":case"input":case"select":case"textarea":s=!!s.autoFocus;break t;case"img":s=!0;break t;default:s=!1}s&&Wn(e)}}return ie(e),df(e,e.type,t===null?null:t.memoizedProps,e.pendingProps,i),null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==s&&Wn(e);else{if(typeof s!="string"&&e.stateNode===null)throw Error(r(166));if(t=I.current,Ya(e)){if(t=e.stateNode,i=e.memoizedProps,s=null,o=Ee,o!==null)switch(o.tag){case 27:case 5:s=o.memoizedProps}t[Te]=e,t=!!(t.nodeValue===i||s!==null&&s.suppressHydrationWarning===!0||yb(t.nodeValue,i)),t||xi(e,!0)}else t=So(t).createTextNode(s),t[Te]=e,e.stateNode=t}return ie(e),null;case 31:if(i=e.memoizedState,t===null||t.memoizedState!==null){if(s=Ya(e),i!==null){if(t===null){if(!s)throw Error(r(318));if(t=e.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[Te]=e}else ea(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;ie(e),t=!1}else i=vd(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=i),t=!0;if(!t)return e.flags&256?(Qe(e),e):(Qe(e),null);if((e.flags&128)!==0)throw Error(r(558))}return ie(e),null;case 13:if(s=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(o=Ya(e),s!==null&&s.dehydrated!==null){if(t===null){if(!o)throw Error(r(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(r(317));o[Te]=e}else ea(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;ie(e),o=!1}else o=vd(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),o=!0;if(!o)return e.flags&256?(Qe(e),e):(Qe(e),null)}return Qe(e),(e.flags&128)!==0?(e.lanes=i,e):(i=s!==null,t=t!==null&&t.memoizedState!==null,i&&(s=e.child,o=null,s.alternate!==null&&s.alternate.memoizedState!==null&&s.alternate.memoizedState.cachePool!==null&&(o=s.alternate.memoizedState.cachePool.pool),c=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),c!==o&&(s.flags|=2048)),i!==t&&i&&(e.child.flags|=8192),so(e,e.updateQueue),ie(e),null);case 4:return pt(),t===null&&Lf(e.stateNode.containerInfo),ie(e),null;case 10:return qn(e.type),ie(e),null;case 19:if(P(ue),s=e.memoizedState,s===null)return ie(e),null;if(o=(e.flags&128)!==0,c=s.rendering,c===null)if(o)ol(s,!1);else{if(re!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(c=Xr(t),c!==null){for(e.flags|=128,ol(s,!1),t=c.updateQueue,e.updateQueue=t,so(e,t),e.subtreeFlags=0,t=i,i=e.child;i!==null;)W0(i,t),i=i.sibling;return nt(ue,ue.current&1|2),Yt&&Gn(e,s.treeForkCount),e.child}t=t.sibling}s.tail!==null&&ut()>co&&(e.flags|=128,o=!0,ol(s,!1),e.lanes=4194304)}else{if(!o)if(t=Xr(c),t!==null){if(e.flags|=128,o=!0,t=t.updateQueue,e.updateQueue=t,so(e,t),ol(s,!0),s.tail===null&&s.tailMode==="hidden"&&!c.alternate&&!Yt)return ie(e),null}else 2*ut()-s.renderingStartTime>co&&i!==536870912&&(e.flags|=128,o=!0,ol(s,!1),e.lanes=4194304);s.isBackwards?(c.sibling=e.child,e.child=c):(t=s.last,t!==null?t.sibling=c:e.child=c,s.last=c)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=ut(),t.sibling=null,i=ue.current,nt(ue,o?i&1|2:i&1),Yt&&Gn(e,s.treeForkCount),t):(ie(e),null);case 22:case 23:return Qe(e),Ld(),s=e.memoizedState!==null,t!==null?t.memoizedState!==null!==s&&(e.flags|=8192):s&&(e.flags|=8192),s?(i&536870912)!==0&&(e.flags&128)===0&&(ie(e),e.subtreeFlags&6&&(e.flags|=8192)):ie(e),i=e.updateQueue,i!==null&&so(e,i.retryQueue),i=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(i=t.memoizedState.cachePool.pool),s=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),s!==i&&(e.flags|=2048),t!==null&&P(aa),null;case 24:return i=null,t!==null&&(i=t.memoizedState.cache),e.memoizedState.cache!==i&&(e.flags|=2048),qn(fe),ie(e),null;case 25:return null;case 30:return null}throw Error(r(156,e.tag))}function W4(t,e){switch(xd(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return qn(fe),pt(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return Vt(e),null;case 31:if(e.memoizedState!==null){if(Qe(e),e.alternate===null)throw Error(r(340));ea()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 13:if(Qe(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(r(340));ea()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return P(ue),null;case 4:return pt(),null;case 10:return qn(e.type),null;case 22:case 23:return Qe(e),Ld(),t!==null&&P(aa),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return qn(fe),null;case 25:return null;default:return null}}function wx(t,e){switch(xd(e),e.tag){case 3:qn(fe),pt();break;case 26:case 27:case 5:Vt(e);break;case 4:pt();break;case 31:e.memoizedState!==null&&Qe(e);break;case 13:Qe(e);break;case 19:P(ue);break;case 10:qn(e.type);break;case 22:case 23:Qe(e),Ld(),t!==null&&P(aa);break;case 24:qn(fe)}}function ul(t,e){try{var i=e.updateQueue,s=i!==null?i.lastEffect:null;if(s!==null){var o=s.next;i=o;do{if((i.tag&t)===t){s=void 0;var c=i.create,m=i.inst;s=c(),m.destroy=s}i=i.next}while(i!==o)}}catch(S){Wt(e,e.return,S)}}function Ei(t,e,i){try{var s=e.updateQueue,o=s!==null?s.lastEffect:null;if(o!==null){var c=o.next;s=c;do{if((s.tag&t)===t){var m=s.inst,S=m.destroy;if(S!==void 0){m.destroy=void 0,o=e;var C=i,_=S;try{_()}catch(Z){Wt(o,C,Z)}}}s=s.next}while(s!==c)}}catch(Z){Wt(e,e.return,Z)}}function Ax(t){var e=t.updateQueue;if(e!==null){var i=t.stateNode;try{h1(e,i)}catch(s){Wt(t,t.return,s)}}}function Tx(t,e,i){i.props=ua(t.type,t.memoizedProps),i.state=t.memoizedState;try{i.componentWillUnmount()}catch(s){Wt(t,e,s)}}function cl(t,e){try{var i=t.ref;if(i!==null){switch(t.tag){case 26:case 27:case 5:var s=t.stateNode;break;case 30:s=t.stateNode;break;default:s=t.stateNode}typeof i=="function"?t.refCleanup=i(s):i.current=s}}catch(o){Wt(t,e,o)}}function On(t,e){var i=t.ref,s=t.refCleanup;if(i!==null)if(typeof s=="function")try{s()}catch(o){Wt(t,e,o)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(o){Wt(t,e,o)}else i.current=null}function Ex(t){var e=t.type,i=t.memoizedProps,s=t.stateNode;try{t:switch(e){case"button":case"input":case"select":case"textarea":i.autoFocus&&s.focus();break t;case"img":i.src?s.src=i.src:i.srcSet&&(s.srcset=i.srcSet)}}catch(o){Wt(t,t.return,o)}}function ff(t,e,i){try{var s=t.stateNode;yC(s,t.type,i,e),s[Ne]=e}catch(o){Wt(t,t.return,o)}}function jx(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&zi(t.type)||t.tag===4}function hf(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||jx(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&zi(t.type)||t.flags&2||t.child===null||t.tag===4)continue t;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function pf(t,e,i){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(t,e):(e=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,e.appendChild(t),i=i._reactRootContainer,i!=null||e.onclick!==null||(e.onclick=Vn));else if(s!==4&&(s===27&&zi(t.type)&&(i=t.stateNode,e=null),t=t.child,t!==null))for(pf(t,e,i),t=t.sibling;t!==null;)pf(t,e,i),t=t.sibling}function lo(t,e,i){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?i.insertBefore(t,e):i.appendChild(t);else if(s!==4&&(s===27&&zi(t.type)&&(i=t.stateNode),t=t.child,t!==null))for(lo(t,e,i),t=t.sibling;t!==null;)lo(t,e,i),t=t.sibling}function Cx(t){var e=t.stateNode,i=t.memoizedProps;try{for(var s=t.type,o=e.attributes;o.length;)e.removeAttributeNode(o[0]);Me(e,s,i),e[Te]=t,e[Ne]=i}catch(c){Wt(t,t.return,c)}}var Qn=!1,me=!1,mf=!1,Mx=typeof WeakSet=="function"?WeakSet:Set,Se=null;function Q4(t,e){if(t=t.containerInfo,Nf=Mo,t=V0(t),rd(t)){if("selectionStart"in t)var i={start:t.selectionStart,end:t.selectionEnd};else t:{i=(i=t.ownerDocument)&&i.defaultView||window;var s=i.getSelection&&i.getSelection();if(s&&s.rangeCount!==0){i=s.anchorNode;var o=s.anchorOffset,c=s.focusNode;s=s.focusOffset;try{i.nodeType,c.nodeType}catch{i=null;break t}var m=0,S=-1,C=-1,_=0,Z=0,et=t,U=null;e:for(;;){for(var G;et!==i||o!==0&&et.nodeType!==3||(S=m+o),et!==c||s!==0&&et.nodeType!==3||(C=m+s),et.nodeType===3&&(m+=et.nodeValue.length),(G=et.firstChild)!==null;)U=et,et=G;for(;;){if(et===t)break e;if(U===i&&++_===o&&(S=m),U===c&&++Z===s&&(C=m),(G=et.nextSibling)!==null)break;et=U,U=et.parentNode}et=G}i=S===-1||C===-1?null:{start:S,end:C}}else i=null}i=i||{start:0,end:0}}else i=null;for(_f={focusedElem:t,selectionRange:i},Mo=!1,Se=e;Se!==null;)if(e=Se,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Se=t;else for(;Se!==null;){switch(e=Se,c=e.alternate,t=e.flags,e.tag){case 0:if((t&4)!==0&&(t=e.updateQueue,t=t!==null?t.events:null,t!==null))for(i=0;i title"))),Me(c,s,i),c[Te]=t,ve(c),s=c;break t;case"link":var m=Ob("link","href",o).get(s+(i.href||""));if(m){for(var S=0;S$t&&(m=$t,$t=At,At=m);var z=U0(S,At),R=U0(S,$t);if(z&&R&&(G.rangeCount!==1||G.anchorNode!==z.node||G.anchorOffset!==z.offset||G.focusNode!==R.node||G.focusOffset!==R.offset)){var N=et.createRange();N.setStart(z.node,z.offset),G.removeAllRanges(),At>$t?(G.addRange(N),G.extend(R.node,R.offset)):(N.setEnd(R.node,R.offset),G.addRange(N))}}}}for(et=[],G=S;G=G.parentNode;)G.nodeType===1&&et.push({element:G,left:G.scrollLeft,top:G.scrollTop});for(typeof S.focus=="function"&&S.focus(),S=0;Si?32:i,B.T=null,i=wf,wf=null;var c=ki,m=ei;if(xe=0,ns=ki=null,ei=0,(qt&6)!==0)throw Error(r(331));var S=qt;if(qt|=4,Hx(c.current),Nx(c,c.current,m,i),qt=S,gl(0,!1),qe&&typeof qe.onPostCommitFiberRoot=="function")try{qe.onPostCommitFiberRoot(Os,c)}catch{}return!0}finally{at.p=o,B.T=s,ib(t,e)}}function sb(t,e,i){e=ln(i,e),e=tf(t.stateNode,e,2),t=wi(t,e,2),t!==null&&(Ns(t,2),Bn(t))}function Wt(t,e,i){if(t.tag===3)sb(t,t,i);else for(;e!==null;){if(e.tag===3){sb(e,t,i);break}else if(e.tag===1){var s=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof s.componentDidCatch=="function"&&(Mi===null||!Mi.has(s))){t=ln(i,t),i=lx(2),s=wi(e,i,2),s!==null&&(rx(i,s,e,t),Ns(s,2),Bn(s));break}}e=e.return}}function jf(t,e,i){var s=t.pingCache;if(s===null){s=t.pingCache=new J4;var o=new Set;s.set(e,o)}else o=s.get(e),o===void 0&&(o=new Set,s.set(e,o));o.has(i)||(xf=!0,o.add(i),t=aC.bind(null,t,e,i),e.then(t,t))}function aC(t,e,i){var s=t.pingCache;s!==null&&s.delete(e),t.pingedLanes|=t.suspendedLanes&i,t.warmLanes&=~i,te===t&&(_t&i)===i&&(re===4||re===3&&(_t&62914560)===_t&&300>ut()-uo?(qt&2)===0&&is(t,0):bf|=i,es===_t&&(es=0)),Bn(t)}function lb(t,e){e===0&&(e=t0()),t=Ji(t,e),t!==null&&(Ns(t,e),Bn(t))}function sC(t){var e=t.memoizedState,i=0;e!==null&&(i=e.retryLane),lb(t,i)}function lC(t,e){var i=0;switch(t.tag){case 31:case 13:var s=t.stateNode,o=t.memoizedState;o!==null&&(i=o.retryLane);break;case 19:s=t.stateNode;break;case 22:s=t.stateNode._retryCache;break;default:throw Error(r(314))}s!==null&&s.delete(e),lb(t,i)}function rC(t,e){return Xt(t,e)}var yo=null,ss=null,Cf=!1,xo=!1,Mf=!1,Di=0;function Bn(t){t!==ss&&t.next===null&&(ss===null?yo=ss=t:ss=ss.next=t),xo=!0,Cf||(Cf=!0,uC())}function gl(t,e){if(!Mf&&xo){Mf=!0;do for(var i=!1,s=yo;s!==null;){if(t!==0){var o=s.pendingLanes;if(o===0)var c=0;else{var m=s.suspendedLanes,S=s.pingedLanes;c=(1<<31-Xe(42|t)+1)-1,c&=o&~(m&~S),c=c&201326741?c&201326741|1:c?c|2:0}c!==0&&(i=!0,cb(s,c))}else c=_t,c=Sr(s,s===te?c:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),(c&3)===0||Bs(s,c)||(i=!0,cb(s,c));s=s.next}while(i);Mf=!1}}function oC(){rb()}function rb(){xo=Cf=!1;var t=0;Di!==0&&bC()&&(t=Di);for(var e=ut(),i=null,s=yo;s!==null;){var o=s.next,c=ob(s,e);c===0?(s.next=null,i===null?yo=o:i.next=o,o===null&&(ss=i)):(i=s,(t!==0||(c&3)!==0)&&(xo=!0)),s=o}xe!==0&&xe!==5||gl(t),Di!==0&&(Di=0)}function ob(t,e){for(var i=t.suspendedLanes,s=t.pingedLanes,o=t.expirationTimes,c=t.pendingLanes&-62914561;0S)break;var Z=C.transferSize,et=C.initiatorType;Z&&xb(et)&&(C=C.responseEnd,m+=Z*(C"u"?null:document;function Rb(t,e,i){var s=ls;if(s&&typeof e=="string"&&e){var o=an(e);o='link[rel="'+t+'"][href="'+o+'"]',typeof i=="string"&&(o+='[crossorigin="'+i+'"]'),kb.has(o)||(kb.add(o),t={rel:t,crossOrigin:i,href:e},s.querySelector(o)===null&&(e=s.createElement("link"),Me(e,"link",t),ve(e),s.head.appendChild(e)))}}function MC(t){ni.D(t),Rb("dns-prefetch",t,null)}function kC(t,e){ni.C(t,e),Rb("preconnect",t,e)}function RC(t,e,i){ni.L(t,e,i);var s=ls;if(s&&t&&e){var o='link[rel="preload"][as="'+an(e)+'"]';e==="image"&&i&&i.imageSrcSet?(o+='[imagesrcset="'+an(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(o+='[imagesizes="'+an(i.imageSizes)+'"]')):o+='[href="'+an(t)+'"]';var c=o;switch(e){case"style":c=rs(t);break;case"script":c=os(t)}fn.has(c)||(t=w({rel:"preload",href:e==="image"&&i&&i.imageSrcSet?void 0:t,as:e},i),fn.set(c,t),s.querySelector(o)!==null||e==="style"&&s.querySelector(vl(c))||e==="script"&&s.querySelector(Sl(c))||(e=s.createElement("link"),Me(e,"link",t),ve(e),s.head.appendChild(e)))}}function DC(t,e){ni.m(t,e);var i=ls;if(i&&t){var s=e&&typeof e.as=="string"?e.as:"script",o='link[rel="modulepreload"][as="'+an(s)+'"][href="'+an(t)+'"]',c=o;switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":c=os(t)}if(!fn.has(c)&&(t=w({rel:"modulepreload",href:t},e),fn.set(c,t),i.querySelector(o)===null)){switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Sl(c)))return}s=i.createElement("link"),Me(s,"link",t),ve(s),i.head.appendChild(s)}}}function zC(t,e,i){ni.S(t,e,i);var s=ls;if(s&&t){var o=ka(s).hoistableStyles,c=rs(t);e=e||"default";var m=o.get(c);if(!m){var S={loading:0,preload:null};if(m=s.querySelector(vl(c)))S.loading=5;else{t=w({rel:"stylesheet",href:t,"data-precedence":e},i),(i=fn.get(c))&&Ff(t,i);var C=m=s.createElement("link");ve(C),Me(C,"link",t),C._p=new Promise(function(_,Z){C.onload=_,C.onerror=Z}),C.addEventListener("load",function(){S.loading|=1}),C.addEventListener("error",function(){S.loading|=2}),S.loading|=4,Ao(m,e,s)}m={type:"stylesheet",instance:m,count:1,state:S},o.set(c,m)}}}function LC(t,e){ni.X(t,e);var i=ls;if(i&&t){var s=ka(i).hoistableScripts,o=os(t),c=s.get(o);c||(c=i.querySelector(Sl(o)),c||(t=w({src:t,async:!0},e),(e=fn.get(o))&&qf(t,e),c=i.createElement("script"),ve(c),Me(c,"link",t),i.head.appendChild(c)),c={type:"script",instance:c,count:1,state:null},s.set(o,c))}}function OC(t,e){ni.M(t,e);var i=ls;if(i&&t){var s=ka(i).hoistableScripts,o=os(t),c=s.get(o);c||(c=i.querySelector(Sl(o)),c||(t=w({src:t,async:!0,type:"module"},e),(e=fn.get(o))&&qf(t,e),c=i.createElement("script"),ve(c),Me(c,"link",t),i.head.appendChild(c)),c={type:"script",instance:c,count:1,state:null},s.set(o,c))}}function Db(t,e,i,s){var o=(o=I.current)?wo(o):null;if(!o)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(e=rs(i.href),i=ka(o).hoistableStyles,s=i.get(e),s||(s={type:"style",instance:null,count:0,state:null},i.set(e,s)),s):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){t=rs(i.href);var c=ka(o).hoistableStyles,m=c.get(t);if(m||(o=o.ownerDocument||o,m={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},c.set(t,m),(c=o.querySelector(vl(t)))&&!c._p&&(m.instance=c,m.state.loading=5),fn.has(t)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},fn.set(t,i),c||BC(o,t,i,m.state))),e&&s===null)throw Error(r(528,""));return m}if(e&&s!==null)throw Error(r(529,""));return null;case"script":return e=i.async,i=i.src,typeof i=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=os(i),i=ka(o).hoistableScripts,s=i.get(e),s||(s={type:"script",instance:null,count:0,state:null},i.set(e,s)),s):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function rs(t){return'href="'+an(t)+'"'}function vl(t){return'link[rel="stylesheet"]['+t+"]"}function zb(t){return w({},t,{"data-precedence":t.precedence,precedence:null})}function BC(t,e,i,s){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?s.loading=1:(e=t.createElement("link"),s.preload=e,e.addEventListener("load",function(){return s.loading|=1}),e.addEventListener("error",function(){return s.loading|=2}),Me(e,"link",i),ve(e),t.head.appendChild(e))}function os(t){return'[src="'+an(t)+'"]'}function Sl(t){return"script[async]"+t}function Lb(t,e,i){if(e.count++,e.instance===null)switch(e.type){case"style":var s=t.querySelector('style[data-href~="'+an(i.href)+'"]');if(s)return e.instance=s,ve(s),s;var o=w({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return s=(t.ownerDocument||t).createElement("style"),ve(s),Me(s,"style",o),Ao(s,i.precedence,t),e.instance=s;case"stylesheet":o=rs(i.href);var c=t.querySelector(vl(o));if(c)return e.state.loading|=4,e.instance=c,ve(c),c;s=zb(i),(o=fn.get(o))&&Ff(s,o),c=(t.ownerDocument||t).createElement("link"),ve(c);var m=c;return m._p=new Promise(function(S,C){m.onload=S,m.onerror=C}),Me(c,"link",s),e.state.loading|=4,Ao(c,i.precedence,t),e.instance=c;case"script":return c=os(i.src),(o=t.querySelector(Sl(c)))?(e.instance=o,ve(o),o):(s=i,(o=fn.get(c))&&(s=w({},i),qf(s,o)),t=t.ownerDocument||t,o=t.createElement("script"),ve(o),Me(o,"link",s),t.head.appendChild(o),e.instance=o);case"void":return null;default:throw Error(r(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(s=e.instance,e.state.loading|=4,Ao(s,i.precedence,t));return e.instance}function Ao(t,e,i){for(var s=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),o=s.length?s[s.length-1]:null,c=o,m=0;m title"):null)}function NC(t,e,i){if(i===1||e.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;return e.rel==="stylesheet"?(t=e.disabled,typeof e.precedence=="string"&&t==null):!0;case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function Nb(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function _C(t,e,i,s){if(i.type==="stylesheet"&&(typeof s.media!="string"||matchMedia(s.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var o=rs(s.href),c=e.querySelector(vl(o));if(c){e=c._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(t.count++,t=Eo.bind(t),e.then(t,t)),i.state.loading|=4,i.instance=c,ve(c);return}c=e.ownerDocument||e,s=zb(s),(o=fn.get(o))&&Ff(s,o),c=c.createElement("link"),ve(c);var m=c;m._p=new Promise(function(S,C){m.onload=S,m.onerror=C}),Me(c,"link",s),i.instance=c}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(i,e),(e=i.state.preload)&&(i.state.loading&3)===0&&(t.count++,i=Eo.bind(t),e.addEventListener("load",i),e.addEventListener("error",i))}}var Xf=0;function UC(t,e){return t.stylesheets&&t.count===0&&Co(t,t.stylesheets),0Xf?50:800)+e);return t.unsuspend=i,function(){t.unsuspend=null,clearTimeout(s),clearTimeout(o)}}:null}function Eo(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Co(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var jo=null;function Co(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,jo=new Map,e.forEach(HC,t),jo=null,Eo.call(t))}function HC(t,e){if(!(e.state.loading&4)){var i=jo.get(t);if(i)var s=i.get(null);else{i=new Map,jo.set(t,i);for(var o=t.querySelectorAll("link[data-precedence],style[data-precedence]"),c=0;c"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(a){console.error(a)}}return n(),No.exports=iv(),No.exports}var sv=av(),v=Vo();const Yo=v.createContext({});function Go(n){const a=v.useRef(null);return a.current===null&&(a.current=n()),a.current}const uh=typeof window<"u"?v.useLayoutEffect:v.useEffect,jl=v.createContext(null);function Fo(n,a){n.indexOf(a)===-1&&n.push(a)}function Cl(n,a){const l=n.indexOf(a);l>-1&&n.splice(l,1)}const En=(n,a,l)=>l>a?a:l{};const ii={},ch=n=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(n);function dh(n){return typeof n=="object"&&n!==null}const fh=n=>/^0[^.\s]+$/u.test(n);function hh(n){let a;return()=>(a===void 0&&(a=n()),a)}const tn=n=>n,lv=(n,a)=>l=>a(n(l)),fs=(...n)=>n.reduce(lv),hs=(n,a,l)=>{const r=a-n;return r===0?1:(l-n)/r};class Xo{constructor(){this.subscriptions=[]}add(a){return Fo(this.subscriptions,a),()=>Cl(this.subscriptions,a)}notify(a,l,r){const d=this.subscriptions.length;if(d)if(d===1)this.subscriptions[0](a,l,r);else for(let f=0;fn*1e3,en=n=>n/1e3;function ph(n,a){return a?n*(1e3/a):0}const mh=(n,a,l)=>(((1-3*l+3*a)*n+(3*l-6*a))*n+3*a)*n,rv=1e-7,ov=12;function uv(n,a,l,r,d){let f,h,p=0;do h=a+(l-a)/2,f=mh(h,r,d)-n,f>0?l=h:a=h;while(Math.abs(f)>rv&&++puv(f,0,1,n,l);return f=>f===0||f===1?f:mh(d(f),a,r)}const gh=n=>a=>a<=.5?n(2*a)/2:(2-n(2*(1-a)))/2,yh=n=>a=>1-n(1-a),xh=ps(.33,1.53,.69,.99),Po=yh(xh),bh=gh(Po),vh=n=>n>=1?1:(n*=2)<1?.5*Po(n):.5*(2-Math.pow(2,-10*(n-1))),Ko=n=>1-Math.sin(Math.acos(n)),Sh=yh(Ko),wh=gh(Ko),cv=ps(.42,0,1,1),dv=ps(0,0,.58,1),Ah=ps(.42,0,.58,1),fv=n=>Array.isArray(n)&&typeof n[0]!="number",Th=n=>Array.isArray(n)&&typeof n[0]=="number",hv={linear:tn,easeIn:cv,easeInOut:Ah,easeOut:dv,circIn:Ko,circInOut:wh,circOut:Sh,backIn:Po,backInOut:bh,backOut:xh,anticipate:vh},pv=n=>typeof n=="string",Eh=n=>{if(Th(n)){qo(n.length===4);const[a,l,r,d]=n;return ps(a,l,r,d)}else if(pv(n))return hv[n];return n},Ml=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function mv(n,a){let l=new Set,r=new Set,d=!1,f=!1;const h=new WeakSet;let p={delta:0,timestamp:0,isProcessing:!1};function y(b){h.has(b)&&(g.schedule(b),n()),b(p)}const g={schedule:(b,w=!1,A=!1)=>{const k=A&&d?l:r;return w&&h.add(b),k.add(b),b},cancel:b=>{r.delete(b),h.delete(b)},process:b=>{if(p=b,d){f=!0;return}d=!0;const w=l;l=r,r=w,l.forEach(y),l.clear(),d=!1,f&&(f=!1,g.process(b))}};return g}const gv=40;function jh(n,a){let l=!1,r=!0;const d={delta:0,timestamp:0,isProcessing:!1},f=()=>l=!0,h=Ml.reduce((E,T)=>(E[T]=mv(f),E),{}),{setup:p,read:y,resolveKeyframes:g,preUpdate:b,update:w,preRender:A,render:j,postRender:k}=h,D=()=>{const E=ii.useManualTiming,T=E?d.timestamp:performance.now();l=!1,E||(d.delta=r?1e3/60:Math.max(Math.min(T-d.timestamp,gv),1)),d.timestamp=T,d.isProcessing=!0,p.process(d),y.process(d),g.process(d),b.process(d),w.process(d),A.process(d),j.process(d),k.process(d),d.isProcessing=!1,l&&a&&(r=!1,n(D))},O=()=>{l=!0,r=!0,d.isProcessing||n(D)};return{schedule:Ml.reduce((E,T)=>{const L=h[T];return E[T]=(H,J=!1,$=!1)=>(l||O(),L.schedule(H,J,$)),E},{}),cancel:E=>{for(let T=0;T(kl===void 0&&Re.set(we.isProcessing||ii.useManualTiming?we.timestamp:performance.now()),kl),set:n=>{kl=n,queueMicrotask(yv)}},Ch=n=>a=>typeof a=="string"&&a.startsWith(n),Mh=Ch("--"),xv=Ch("var(--"),Qo=n=>xv(n)?bv.test(n.split("/*")[0].trim()):!1,bv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function kh(n){return typeof n!="string"?!1:n.split("/*")[0].includes("var(--")}const fa={test:n=>typeof n=="number",parse:parseFloat,transform:n=>n},ms={...fa,transform:n=>En(0,1,n)},Rl={...fa,default:1},gs=n=>Math.round(n*1e5)/1e5,Zo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function vv(n){return n==null}const Sv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,$o=(n,a)=>l=>!!(typeof l=="string"&&Sv.test(l)&&l.startsWith(n)||a&&!vv(l)&&Object.prototype.hasOwnProperty.call(l,a)),Rh=(n,a,l)=>r=>{if(typeof r!="string")return r;const[d,f,h,p]=r.match(Zo);return{[n]:parseFloat(d),[a]:parseFloat(f),[l]:parseFloat(h),alpha:p!==void 0?parseFloat(p):1}},wv=n=>En(0,255,n),Jo={...fa,transform:n=>Math.round(wv(n))},Ui={test:$o("rgb","red"),parse:Rh("red","green","blue"),transform:({red:n,green:a,blue:l,alpha:r=1})=>"rgba("+Jo.transform(n)+", "+Jo.transform(a)+", "+Jo.transform(l)+", "+gs(ms.transform(r))+")"};function Av(n){let a="",l="",r="",d="";return n.length>5?(a=n.substring(1,3),l=n.substring(3,5),r=n.substring(5,7),d=n.substring(7,9)):(a=n.substring(1,2),l=n.substring(2,3),r=n.substring(3,4),d=n.substring(4,5),a+=a,l+=l,r+=r,d+=d),{red:parseInt(a,16),green:parseInt(l,16),blue:parseInt(r,16),alpha:d?parseInt(d,16)/255:1}}const tu={test:$o("#"),parse:Av,transform:Ui.transform},ys=n=>({test:a=>typeof a=="string"&&a.endsWith(n)&&a.split(" ").length===1,parse:parseFloat,transform:a=>`${a}${n}`}),si=ys("deg"),jn=ys("%"),xt=ys("px"),Tv=ys("vh"),Ev=ys("vw"),Dh={...jn,parse:n=>jn.parse(n)/100,transform:n=>jn.transform(n*100)},ha={test:$o("hsl","hue"),parse:Rh("hue","saturation","lightness"),transform:({hue:n,saturation:a,lightness:l,alpha:r=1})=>"hsla("+Math.round(n)+", "+jn.transform(gs(a))+", "+jn.transform(gs(l))+", "+gs(ms.transform(r))+")"},de={test:n=>Ui.test(n)||tu.test(n)||ha.test(n),parse:n=>Ui.test(n)?Ui.parse(n):ha.test(n)?ha.parse(n):tu.parse(n),transform:n=>typeof n=="string"?n:n.hasOwnProperty("red")?Ui.transform(n):ha.transform(n),getAnimatableNone:n=>{const a=de.parse(n);return a.alpha=0,de.transform(a)}},jv=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Cv(n){return isNaN(n)&&typeof n=="string"&&(n.match(Zo)?.length||0)+(n.match(jv)?.length||0)>0}const zh="number",Lh="color",Mv="var",kv="var(",Oh="${}",Rv=/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 pa(n){const a=n.toString(),l=[],r={color:[],number:[],var:[]},d=[];let f=0;const p=a.replace(Rv,y=>(de.test(y)?(r.color.push(f),d.push(Lh),l.push(de.parse(y))):y.startsWith(kv)?(r.var.push(f),d.push(Mv),l.push(y)):(r.number.push(f),d.push(zh),l.push(parseFloat(y))),++f,Oh)).split(Oh);return{values:l,split:p,indexes:r,types:d}}function Dv(n){return pa(n).values}function Bh({split:n,types:a}){const l=n.length;return r=>{let d="";for(let f=0;ftypeof n=="number"?0:de.test(n)?de.getAnimatableNone(n):n,Ov=(n,a)=>typeof n=="number"?a?.trim().endsWith("/")?n:0:Lv(n);function Bv(n){const a=pa(n);return Bh(a)(a.values.map((r,d)=>Ov(r,a.split[d])))}const hn={test:Cv,parse:Dv,createTransformer:zv,getAnimatableNone:Bv};function eu(n,a,l){return l<0&&(l+=1),l>1&&(l-=1),l<1/6?n+(a-n)*6*l:l<1/2?a:l<2/3?n+(a-n)*(2/3-l)*6:n}function Nv({hue:n,saturation:a,lightness:l,alpha:r}){n/=360,a/=100,l/=100;let d=0,f=0,h=0;if(!a)d=f=h=l;else{const p=l<.5?l*(1+a):l+a-l*a,y=2*l-p;d=eu(y,p,n+1/3),f=eu(y,p,n),h=eu(y,p,n-1/3)}return{red:Math.round(d*255),green:Math.round(f*255),blue:Math.round(h*255),alpha:r}}function Dl(n,a){return l=>l>0?a:n}const ee=(n,a,l)=>n+(a-n)*l,nu=(n,a,l)=>{const r=n*n,d=l*(a*a-r)+r;return d<0?0:Math.sqrt(d)},_v=[tu,Ui,ha],Uv=n=>_v.find(a=>a.test(n));function Nh(n){const a=Uv(n);if(!a)return!1;let l=a.parse(n);return a===ha&&(l=Nv(l)),l}const _h=(n,a)=>{const l=Nh(n),r=Nh(a);if(!l||!r)return Dl(n,a);const d={...l};return f=>(d.red=nu(l.red,r.red,f),d.green=nu(l.green,r.green,f),d.blue=nu(l.blue,r.blue,f),d.alpha=ee(l.alpha,r.alpha,f),Ui.transform(d))},iu=new Set(["none","hidden"]);function Hv(n,a){return iu.has(n)?l=>l<=0?n:a:l=>l>=1?a:n}function Vv(n,a){return l=>ee(n,a,l)}function au(n){return typeof n=="number"?Vv:typeof n=="string"?Qo(n)?Dl:de.test(n)?_h:Gv:Array.isArray(n)?Uh:typeof n=="object"?de.test(n)?_h:Iv:Dl}function Uh(n,a){const l=[...n],r=l.length,d=n.map((f,h)=>au(f)(f,a[h]));return f=>{for(let h=0;h{for(const f in r)l[f]=r[f](d);return l}}function Yv(n,a){const l=[],r={color:0,var:0,number:0};for(let d=0;d{const l=hn.createTransformer(a),r=pa(n),d=pa(a);return r.indexes.var.length===d.indexes.var.length&&r.indexes.color.length===d.indexes.color.length&&r.indexes.number.length>=d.indexes.number.length?iu.has(n)&&!d.values.length||iu.has(a)&&!r.values.length?Hv(n,a):fs(Uh(Yv(r,d),d.values),l):Dl(n,a)};function Hh(n,a,l){return typeof n=="number"&&typeof a=="number"&&typeof l=="number"?ee(n,a,l):au(n)(n,a)}const Fv=n=>{const a=({timestamp:l})=>n(l);return{start:(l=!0)=>Jt.update(a,l),stop:()=>ai(a),now:()=>we.isProcessing?we.timestamp:Re.now()}},Vh=(n,a,l=10)=>{let r="";const d=Math.max(Math.round(a/l),2);for(let f=0;f=zl?1/0:a}function qv(n,a=100,l){const r=l({...n,keyframes:[0,a]}),d=Math.min(su(r),zl);return{type:"keyframes",ease:f=>r.next(d*f).value/a,duration:en(d)}}const se={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};function lu(n,a){return n*Math.sqrt(1-a*a)}const Xv=12;function Pv(n,a,l){let r=l;for(let d=1;d{const b=g*h,w=b*n,A=b-l,j=lu(g,h),k=Math.exp(-w);return ru-A/j*k},f=g=>{const w=g*h*n,A=w*l+l,j=Math.pow(h,2)*Math.pow(g,2)*n,k=Math.exp(-w),D=lu(Math.pow(g,2),h);return(-d(g)+ru>0?-1:1)*((A-j)*k)/D}):(d=g=>{const b=Math.exp(-g*n),w=(g-l)*n+1;return-ru+b*w},f=g=>{const b=Math.exp(-g*n),w=(l-g)*(n*n);return b*w});const p=5/n,y=Pv(d,f,p);if(n=Ge(n),isNaN(y))return{stiffness:se.stiffness,damping:se.damping,duration:n};{const g=Math.pow(y,2)*r;return{stiffness:g,damping:h*2*Math.sqrt(r*g),duration:n}}}const Wv=["duration","bounce"],Qv=["stiffness","damping","mass"];function Ih(n,a){return a.some(l=>n[l]!==void 0)}function Zv(n){let a={velocity:se.velocity,stiffness:se.stiffness,damping:se.damping,mass:se.mass,isResolvedFromDuration:!1,...n};if(!Ih(n,Qv)&&Ih(n,Wv))if(a.velocity=0,n.visualDuration){const l=n.visualDuration,r=2*Math.PI/(l*1.2),d=r*r,f=2*En(.05,1,1-(n.bounce||0))*Math.sqrt(d);a={...a,mass:se.mass,stiffness:d,damping:f}}else{const l=Kv({...n,velocity:0});a={...a,...l,mass:se.mass},a.isResolvedFromDuration=!0}return a}function Ll(n=se.visualDuration,a=se.bounce){const l=typeof n!="object"?{visualDuration:n,keyframes:[0,1],bounce:a}:n;let{restSpeed:r,restDelta:d}=l;const f=l.keyframes[0],h=l.keyframes[l.keyframes.length-1],p={done:!1,value:f},{stiffness:y,damping:g,mass:b,duration:w,velocity:A,isResolvedFromDuration:j}=Zv({...l,velocity:-en(l.velocity||0)}),k=A||0,D=g/(2*Math.sqrt(y*b)),O=h-f,q=en(Math.sqrt(y/b)),W=Math.abs(O)<5;r||(r=W?se.restSpeed.granular:se.restSpeed.default),d||(d=W?se.restDelta.granular:se.restDelta.default);let E,T,L,H,J,$;if(D<1)L=lu(q,D),H=(k+D*q*O)/L,E=K=>{const lt=Math.exp(-D*q*K);return h-lt*(H*Math.sin(L*K)+O*Math.cos(L*K))},J=D*q*H+O*L,$=D*q*O-H*L,T=K=>Math.exp(-D*q*K)*(J*Math.sin(L*K)+$*Math.cos(L*K));else if(D===1){E=lt=>h-Math.exp(-q*lt)*(O+(k+q*O)*lt);const K=k+q*O;T=lt=>Math.exp(-q*lt)*(q*K*lt-k)}else{const K=q*Math.sqrt(D*D-1);E=ht=>{const Mt=Math.exp(-D*q*ht),B=Math.min(K*ht,300);return h-Mt*((k+D*q*O)*Math.sinh(B)+K*O*Math.cosh(B))/K};const lt=(k+D*q*O)/K,it=D*q*lt-O*K,rt=D*q*O-lt*K;T=ht=>{const Mt=Math.exp(-D*q*ht),B=Math.min(K*ht,300);return Mt*(it*Math.sinh(B)+rt*Math.cosh(B))}}const F={calculatedDuration:j&&w||null,velocity:K=>Ge(T(K)),next:K=>{if(!j&&D<1){const it=Math.exp(-D*q*K),rt=Math.sin(L*K),ht=Math.cos(L*K),Mt=h-it*(H*rt+O*ht),B=Ge(it*(J*rt+$*ht));return p.done=Math.abs(B)<=r&&Math.abs(h-Mt)<=d,p.value=p.done?h:Mt,p}const lt=E(K);if(j)p.done=K>=w;else{const it=Ge(T(K));p.done=Math.abs(it)<=r&&Math.abs(h-lt)<=d}return p.value=p.done?h:lt,p},toString:()=>{const K=Math.min(su(F),zl),lt=Vh(it=>F.next(K*it).value,K,30);return K+"ms "+lt},toTransition:()=>{}};return F}Ll.applyToOptions=n=>{const a=qv(n,100,Ll);return n.ease=a.ease,n.duration=Ge(a.duration),n.type="keyframes",n};const $v=5;function Yh(n,a,l){const r=Math.max(a-$v,0);return ph(l-n(r),a-r)}function ou({keyframes:n,velocity:a=0,power:l=.8,timeConstant:r=325,bounceDamping:d=10,bounceStiffness:f=500,modifyTarget:h,min:p,max:y,restDelta:g=.5,restSpeed:b}){const w=n[0],A={done:!1,value:w},j=$=>p!==void 0&&$y,k=$=>p===void 0?y:y===void 0||Math.abs(p-$)-D*Math.exp(-$/r),E=$=>q+W($),T=$=>{const F=W($),K=E($);A.done=Math.abs(F)<=g,A.value=A.done?q:K};let L,H;const J=$=>{j(A.value)&&(L=$,H=Ll({keyframes:[A.value,k(A.value)],velocity:Yh(E,$,A.value),damping:d,stiffness:f,restDelta:g,restSpeed:b}))};return J(0),{calculatedDuration:null,next:$=>{let F=!1;return!H&&L===void 0&&(F=!0,T($),J($)),L!==void 0&&$>=L?H.next($-L):(!F&&T($),A)}}}function Jv(n,a,l){const r=[],d=l||ii.mix||Hh,f=n.length-1;for(let h=0;ha[0];if(f===2&&a[0]===a[1])return()=>a[1];const h=n[0]===n[1];n[0]>n[f-1]&&(n=[...n].reverse(),a=[...a].reverse());const p=Jv(a,r,d),y=p.length,g=b=>{if(h&&b1)for(;wg(En(n[0],n[f-1],b)):g}function e2(n,a){const l=n[n.length-1];for(let r=1;r<=a;r++){const d=hs(0,a,r);n.push(ee(l,1,d))}}function n2(n){const a=[0];return e2(a,n.length-1),a}function i2(n,a){return n.map(l=>l*a)}function a2(n,a){return n.map(()=>a||Ah).splice(0,n.length-1)}function xs({duration:n=300,keyframes:a,times:l,ease:r="easeInOut"}){const d=fv(r)?r.map(Eh):Eh(r),f={done:!1,value:a[0]},h=i2(l&&l.length===a.length?l:n2(a),n),p=t2(h,a,{ease:Array.isArray(d)?d:a2(a,d)});return{calculatedDuration:n,next:y=>(f.value=p(y),f.done=y>=n,f)}}const s2=n=>n!==null;function Ol(n,{repeat:a,repeatType:l="loop"},r,d=1){const f=n.filter(s2),p=d<0||a&&l!=="loop"&&a%2===1?0:f.length-1;return!p||r===void 0?f[p]:r}const l2={decay:ou,inertia:ou,tween:xs,keyframes:xs,spring:Ll};function Gh(n){typeof n.type=="string"&&(n.type=l2[n.type])}class uu{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(a=>{this.resolve=a})}notifyFinished(){this.resolve()}then(a,l){return this.finished.then(a,l)}}const r2=n=>n/100;class Bl extends uu{constructor(a){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{const{motionValue:l}=this.options;l&&l.updatedAt!==Re.now()&&this.tick(Re.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=a,this.initAnimation(),this.play(),a.autoplay===!1&&this.pause()}initAnimation(){const{options:a}=this;Gh(a);const{type:l=xs,repeat:r=0,repeatDelay:d=0,repeatType:f,velocity:h=0}=a;let{keyframes:p}=a;const y=l||xs;y!==xs&&typeof p[0]!="number"&&(this.mixKeyframes=fs(r2,Hh(p[0],p[1])),p=[0,100]);const g=y({...a,keyframes:p});f==="mirror"&&(this.mirroredGenerator=y({...a,keyframes:[...p].reverse(),velocity:-h})),g.calculatedDuration===null&&(g.calculatedDuration=su(g));const{calculatedDuration:b}=g;this.calculatedDuration=b,this.resolvedDuration=b+d,this.totalDuration=this.resolvedDuration*(r+1)-d,this.generator=g}updateTime(a){const l=Math.round(a-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=l}tick(a,l=!1){const{generator:r,totalDuration:d,mixKeyframes:f,mirroredGenerator:h,resolvedDuration:p,calculatedDuration:y}=this;if(this.startTime===null)return r.next(0);const{delay:g=0,keyframes:b,repeat:w,repeatType:A,repeatDelay:j,type:k,onUpdate:D,finalKeyframe:O}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,a):this.speed<0&&(this.startTime=Math.min(a-d/this.speed,this.startTime)),l?this.currentTime=a:this.updateTime(a);const q=this.currentTime-g*(this.playbackSpeed>=0?1:-1),W=this.playbackSpeed>=0?q<0:q>d;this.currentTime=Math.max(q,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=d);let E=this.currentTime,T=r;if(w){const $=Math.min(this.currentTime,d)/p;let F=Math.floor($),K=$%1;!K&&$>=1&&(K=1),K===1&&F--,F=Math.min(F,w+1),F%2&&(A==="reverse"?(K=1-K,j&&(K-=j/p)):A==="mirror"&&(T=h)),E=En(0,1,K)*p}let L;W?(this.delayState.value=b[0],L=this.delayState):L=T.next(E),f&&!W&&(L.value=f(L.value));let{done:H}=L;!W&&y!==null&&(H=this.playbackSpeed>=0?this.currentTime>=d:this.currentTime<=0);const J=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&H);return J&&k!==ou&&(L.value=Ol(b,this.options,O,this.speed)),D&&D(L.value),J&&this.finish(),L}then(a,l){return this.finished.then(a,l)}get duration(){return en(this.calculatedDuration)}get iterationDuration(){const{delay:a=0}=this.options||{};return this.duration+en(a)}get time(){return en(this.currentTime)}set time(a){a=Ge(a),this.currentTime=a,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=a:this.driver&&(this.startTime=this.driver.now()-a/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=a,this.tick(a))}getGeneratorVelocity(){const a=this.currentTime;if(a<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(a);const l=this.generator.next(a).value;return Yh(r=>this.generator.next(r).value,a,l)}get speed(){return this.playbackSpeed}set speed(a){const l=this.playbackSpeed!==a;l&&this.driver&&this.updateTime(Re.now()),this.playbackSpeed=a,l&&this.driver&&(this.time=en(this.currentTime))}play(){if(this.isStopped)return;const{driver:a=Fv,startTime:l}=this.options;this.driver||(this.driver=a(d=>this.tick(d))),this.options.onPlay?.();const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=l??r),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(Re.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(a){return this.startTime=0,this.tick(a,!0)}attachTimeline(a){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),a.observe(this)}}function o2(n){for(let a=1;an*180/Math.PI,cu=n=>{const a=Hi(Math.atan2(n[1],n[0]));return du(a)},u2={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:n=>(Math.abs(n[0])+Math.abs(n[3]))/2,rotate:cu,rotateZ:cu,skewX:n=>Hi(Math.atan(n[1])),skewY:n=>Hi(Math.atan(n[2])),skew:n=>(Math.abs(n[1])+Math.abs(n[2]))/2},du=n=>(n=n%360,n<0&&(n+=360),n),Fh=cu,qh=n=>Math.sqrt(n[0]*n[0]+n[1]*n[1]),Xh=n=>Math.sqrt(n[4]*n[4]+n[5]*n[5]),c2={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:qh,scaleY:Xh,scale:n=>(qh(n)+Xh(n))/2,rotateX:n=>du(Hi(Math.atan2(n[6],n[5]))),rotateY:n=>du(Hi(Math.atan2(-n[2],n[0]))),rotateZ:Fh,rotate:Fh,skewX:n=>Hi(Math.atan(n[4])),skewY:n=>Hi(Math.atan(n[1])),skew:n=>(Math.abs(n[1])+Math.abs(n[4]))/2};function fu(n){return n.includes("scale")?1:0}function hu(n,a){if(!n||n==="none")return fu(a);const l=n.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,d;if(l)r=c2,d=l;else{const p=n.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=u2,d=p}if(!d)return fu(a);const f=r[a],h=d[1].split(",").map(f2);return typeof f=="function"?f(h):h[f]}const d2=(n,a)=>{const{transform:l="none"}=getComputedStyle(n);return hu(l,a)};function f2(n){return parseFloat(n.trim())}const ma=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ga=new Set(ma),Ph=n=>n===fa||n===xt,h2=new Set(["x","y","z"]),p2=ma.filter(n=>!h2.has(n));function m2(n){const a=[];return p2.forEach(l=>{const r=n.getValue(l);r!==void 0&&(a.push([l,r.get()]),r.set(l.startsWith("scale")?1:0))}),a}const li={width:({x:n},{paddingLeft:a="0",paddingRight:l="0",boxSizing:r})=>{const d=n.max-n.min;return r==="border-box"?d:d-parseFloat(a)-parseFloat(l)},height:({y:n},{paddingTop:a="0",paddingBottom:l="0",boxSizing:r})=>{const d=n.max-n.min;return r==="border-box"?d:d-parseFloat(a)-parseFloat(l)},top:(n,{top:a})=>parseFloat(a),left:(n,{left:a})=>parseFloat(a),bottom:({y:n},{top:a})=>parseFloat(a)+(n.max-n.min),right:({x:n},{left:a})=>parseFloat(a)+(n.max-n.min),x:(n,{transform:a})=>hu(a,"x"),y:(n,{transform:a})=>hu(a,"y")};li.translateX=li.x,li.translateY=li.y;const Vi=new Set;let pu=!1,mu=!1,gu=!1;function Kh(){if(mu){const n=Array.from(Vi).filter(r=>r.needsMeasurement),a=new Set(n.map(r=>r.element)),l=new Map;a.forEach(r=>{const d=m2(r);d.length&&(l.set(r,d),r.render())}),n.forEach(r=>r.measureInitialState()),a.forEach(r=>{r.render();const d=l.get(r);d&&d.forEach(([f,h])=>{r.getValue(f)?.set(h)})}),n.forEach(r=>r.measureEndState()),n.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}mu=!1,pu=!1,Vi.forEach(n=>n.complete(gu)),Vi.clear()}function Wh(){Vi.forEach(n=>{n.readKeyframes(),n.needsMeasurement&&(mu=!0)})}function g2(){gu=!0,Wh(),Kh(),gu=!1}class yu{constructor(a,l,r,d,f,h=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...a],this.onComplete=l,this.name=r,this.motionValue=d,this.element=f,this.isAsync=h}scheduleResolve(){this.state="scheduled",this.isAsync?(Vi.add(this),pu||(pu=!0,Jt.read(Wh),Jt.resolveKeyframes(Kh))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:a,name:l,element:r,motionValue:d}=this;if(a[0]===null){const f=d?.get(),h=a[a.length-1];if(f!==void 0)a[0]=f;else if(r&&l){const p=r.readValue(l,h);p!=null&&(a[0]=p)}a[0]===void 0&&(a[0]=h),d&&f===void 0&&d.set(a[0])}o2(a)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(a=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,a),Vi.delete(this)}cancel(){this.state==="scheduled"&&(Vi.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const y2=n=>n.startsWith("--");function Qh(n,a,l){y2(a)?n.style.setProperty(a,l):n.style[a]=l}const x2={};function Zh(n,a){const l=hh(n);return()=>x2[a]??l()}const b2=Zh(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),$h=Zh(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),bs=([n,a,l,r])=>`cubic-bezier(${n}, ${a}, ${l}, ${r})`,Jh={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:bs([0,.65,.55,1]),circOut:bs([.55,0,1,.45]),backIn:bs([.31,.01,.66,-.59]),backOut:bs([.33,1.53,.69,.99])};function tp(n,a){if(n)return typeof n=="function"?$h()?Vh(n,a):"ease-out":Th(n)?bs(n):Array.isArray(n)?n.map(l=>tp(l,a)||Jh.easeOut):Jh[n]}function v2(n,a,l,{delay:r=0,duration:d=300,repeat:f=0,repeatType:h="loop",ease:p="easeOut",times:y}={},g=void 0){const b={[a]:l};y&&(b.offset=y);const w=tp(p,d);Array.isArray(w)&&(b.easing=w);const A={delay:r,duration:d,easing:Array.isArray(w)?"linear":w,fill:"both",iterations:f+1,direction:h==="reverse"?"alternate":"normal"};return g&&(A.pseudoElement=g),n.animate(b,A)}function ep(n){return typeof n=="function"&&"applyToOptions"in n}function S2({type:n,...a}){return ep(n)&&$h()?n.applyToOptions(a):(a.duration??(a.duration=300),a.ease??(a.ease="easeOut"),a)}class np extends uu{constructor(a){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!a)return;const{element:l,name:r,keyframes:d,pseudoElement:f,allowFlatten:h=!1,finalKeyframe:p,onComplete:y}=a;this.isPseudoElement=!!f,this.allowFlatten=h,this.options=a,qo(typeof a.type!="string");const g=S2(a);this.animation=v2(l,r,d,g,f),g.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!f){const b=Ol(d,this.options,p,this.speed);this.updateMotionValue&&this.updateMotionValue(b),Qh(l,r,b),this.animation.cancel()}y?.(),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:a}=this;a==="idle"||a==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){const a=this.options?.element;!this.isPseudoElement&&a?.isConnected&&this.animation.commitStyles?.()}get duration(){const a=this.animation.effect?.getComputedTiming?.().duration||0;return en(Number(a))}get iterationDuration(){const{delay:a=0}=this.options||{};return this.duration+en(a)}get time(){return en(Number(this.animation.currentTime)||0)}set time(a){const l=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ge(a),l&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(a){a<0&&(this.finishedTime=null),this.animation.playbackRate=a}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(a){this.manualStartTime=this.animation.startTime=a}attachTimeline({timeline:a,rangeStart:l,rangeEnd:r,observe:d}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,a&&b2()?(this.animation.timeline=a,l&&(this.animation.rangeStart=l),r&&(this.animation.rangeEnd=r),tn):d(this)}}const ip={anticipate:vh,backInOut:bh,circInOut:wh};function w2(n){return n in ip}function A2(n){typeof n.ease=="string"&&w2(n.ease)&&(n.ease=ip[n.ease])}const xu=10;class T2 extends np{constructor(a){A2(a),Gh(a),super(a),a.startTime!==void 0&&a.autoplay!==!1&&(this.startTime=a.startTime),this.options=a}updateMotionValue(a){const{motionValue:l,onUpdate:r,onComplete:d,element:f,...h}=this.options;if(!l)return;if(a!==void 0){l.set(a);return}const p=new Bl({...h,autoplay:!1}),y=Math.max(xu,Re.now()-this.startTime),g=En(0,xu,y-xu),b=p.sample(y).value,{name:w}=this.options;f&&w&&Qh(f,w,b),l.setWithVelocity(p.sample(Math.max(0,y-g)).value,b,g),p.stop()}}const ap=(n,a)=>a==="zIndex"?!1:!!(typeof n=="number"||Array.isArray(n)||typeof n=="string"&&(hn.test(n)||n==="0")&&!n.startsWith("url("));function E2(n){const a=n[0];if(n.length===1)return!0;for(let l=0;lObject.hasOwnProperty.call(Element.prototype,"animate"));function D2(n){const{motionValue:a,name:l,repeatDelay:r,repeatType:d,damping:f,type:h,keyframes:p}=n;if(!(a?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:g,transformTemplate:b}=a.owner.getProps();return R2()&&l&&(sp.has(l)||k2.has(l)&&M2(p))&&(l!=="transform"||!b)&&!g&&!r&&d!=="mirror"&&f!==0&&h!=="inertia"}const z2=40;class L2 extends uu{constructor({autoplay:a=!0,delay:l=0,type:r="keyframes",repeat:d=0,repeatDelay:f=0,repeatType:h="loop",keyframes:p,name:y,motionValue:g,element:b,...w}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Re.now();const A={autoplay:a,delay:l,type:r,repeat:d,repeatDelay:f,repeatType:h,name:y,motionValue:g,element:b,...w},j=b?.KeyframeResolver||yu;this.keyframeResolver=new j(p,(k,D,O)=>this.onKeyframesResolved(k,D,A,!O),y,g,b),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(a,l,r,d){this.keyframeResolver=void 0;const{name:f,type:h,velocity:p,delay:y,isHandoff:g,onUpdate:b}=r;this.resolvedAt=Re.now();let w=!0;j2(a,f,h,p)||(w=!1,(ii.instantAnimations||!y)&&b?.(Ol(a,r,l)),a[0]=a[a.length-1],bu(r),r.repeat=0);const j={startTime:d?this.resolvedAt?this.resolvedAt-this.createdAt>z2?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:l,...r,keyframes:a},k=w&&!g&&D2(j),D=j.motionValue?.owner?.current;let O;if(k)try{O=new T2({...j,element:D})}catch{O=new Bl(j)}else O=new Bl(j);O.finished.then(()=>{this.notifyFinished()}).catch(tn),this.pendingTimeline&&(this.stopTimeline=O.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=O}get finished(){return this._animation?this.animation.finished:this._finished}then(a,l){return this.finished.finally(a).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),g2()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(a){this.animation.time=a}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(a){this.animation.speed=a}get startTime(){return this.animation.startTime}attachTimeline(a){return this._animation?this.stopTimeline=this.animation.attachTimeline(a):this.pendingTimeline=a,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}function lp(n,a,l,r=0,d=1){const f=Array.from(n).sort((g,b)=>g.sortNodePosition(b)).indexOf(a),h=n.size,p=(h-1)*r;return typeof l=="function"?l(f,h):d===1?f*r:p-f*r}const O2=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function B2(n){const a=O2.exec(n);if(!a)return[,];const[,l,r,d]=a;return[`--${l??r}`,d]}function rp(n,a,l=1){const[r,d]=B2(n);if(!r)return;const f=window.getComputedStyle(a).getPropertyValue(r);if(f){const h=f.trim();return ch(h)?parseFloat(h):h}return Qo(d)?rp(d,a,l+1):d}const N2={type:"spring",stiffness:500,damping:25,restSpeed:10},_2=n=>({type:"spring",stiffness:550,damping:n===0?2*Math.sqrt(550):30,restSpeed:10}),U2={type:"keyframes",duration:.8},H2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},V2=(n,{keyframes:a})=>a.length>2?U2:ga.has(n)?n.startsWith("scale")?_2(a[1]):N2:H2;function op(n,a){if(n?.inherit&&a){const{inherit:l,...r}=n;return{...a,...r}}return n}function vu(n,a){const l=n?.[a]??n?.default??n;return l!==n?op(l,n):l}const I2=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function Y2(n){for(const a in n)if(!I2.has(a))return!0;return!1}const Su=(n,a,l,r={},d,f)=>h=>{const p=vu(r,n)||{},y=p.delay||r.delay||0;let{elapsed:g=0}=r;g=g-Ge(y);const b={keyframes:Array.isArray(l)?l:[null,l],ease:"easeOut",velocity:a.getVelocity(),...p,delay:-g,onUpdate:A=>{a.set(A),p.onUpdate&&p.onUpdate(A)},onComplete:()=>{h(),p.onComplete&&p.onComplete()},name:n,motionValue:a,element:f?void 0:d};Y2(p)||Object.assign(b,V2(n,b)),b.duration&&(b.duration=Ge(b.duration)),b.repeatDelay&&(b.repeatDelay=Ge(b.repeatDelay)),b.from!==void 0&&(b.keyframes[0]=b.from);let w=!1;if((b.type===!1||b.duration===0&&!b.repeatDelay)&&(bu(b),b.delay===0&&(w=!0)),(ii.instantAnimations||ii.skipAnimations||d?.shouldSkipAnimations)&&(w=!0,bu(b),b.delay=0),b.allowFlatten=!p.type&&!p.ease,w&&!f&&a.get()!==void 0){const A=Ol(b.keyframes,p);if(A!==void 0){Jt.update(()=>{b.onUpdate(A),b.onComplete()});return}}return p.isSync?new Bl(b):new L2(b)};function up(n){const a=[{},{}];return n?.values.forEach((l,r)=>{a[0][r]=l.get(),a[1][r]=l.getVelocity()}),a}function wu(n,a,l,r){if(typeof a=="function"){const[d,f]=up(r);a=a(l!==void 0?l:n.custom,d,f)}if(typeof a=="string"&&(a=n.variants&&n.variants[a]),typeof a=="function"){const[d,f]=up(r);a=a(l!==void 0?l:n.custom,d,f)}return a}function Ii(n,a,l){const r=n.getProps();return wu(r,a,l!==void 0?l:r.custom,n)}const cp=new Set(["width","height","top","left","right","bottom",...ma]),dp=30,G2=n=>!isNaN(parseFloat(n));class F2{constructor(a,l={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{const d=Re.now();if(this.updatedAt!==d&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const f of this.dependents)f.dirty()},this.hasAnimated=!1,this.setCurrent(a),this.owner=l.owner}setCurrent(a){this.current=a,this.updatedAt=Re.now(),this.canTrackVelocity===null&&a!==void 0&&(this.canTrackVelocity=G2(this.current))}setPrevFrameValue(a=this.current){this.prevFrameValue=a,this.prevUpdatedAt=this.updatedAt}onChange(a){return this.on("change",a)}on(a,l){this.events[a]||(this.events[a]=new Xo);const r=this.events[a].add(l);return a==="change"?()=>{r(),Jt.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const a in this.events)this.events[a].clear()}attach(a,l){this.passiveEffect=a,this.stopPassiveEffect=l}set(a){this.passiveEffect?this.passiveEffect(a,this.updateAndNotify):this.updateAndNotify(a)}setWithVelocity(a,l,r){this.set(l),this.prev=void 0,this.prevFrameValue=a,this.prevUpdatedAt=this.updatedAt-r}jump(a,l=!0){this.updateAndNotify(a),this.prev=a,this.prevUpdatedAt=this.prevFrameValue=void 0,l&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(a){this.dependents||(this.dependents=new Set),this.dependents.add(a)}removeDependent(a){this.dependents&&this.dependents.delete(a)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const a=Re.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||a-this.updatedAt>dp)return 0;const l=Math.min(this.updatedAt-this.prevUpdatedAt,dp);return ph(parseFloat(this.current)-parseFloat(this.prevFrameValue),l)}start(a){return this.stop(),new Promise(l=>{this.hasAnimated=!0,this.animation=a(l),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 ya(n,a){return new F2(n,a)}const Au=n=>Array.isArray(n);function q2(n,a,l){n.hasValue(a)?n.getValue(a).set(l):n.addValue(a,ya(l))}function X2(n){return Au(n)?n[n.length-1]||0:n}function P2(n,a){const l=Ii(n,a);let{transitionEnd:r={},transition:d={},...f}=l||{};f={...f,...r};for(const h in f){const p=X2(f[h]);q2(n,h,p)}}const Ae=n=>!!(n&&n.getVelocity);function K2(n){return!!(Ae(n)&&n.add)}function Tu(n,a){const l=n.getValue("willChange");if(K2(l))return l.add(a);if(!l&&ii.WillChange){const r=new ii.WillChange("auto");n.addValue("willChange",r),r.add(a)}}function Eu(n){return n.replace(/([A-Z])/g,a=>`-${a.toLowerCase()}`)}const fp="data-"+Eu("framerAppearId");function hp(n){return n.props[fp]}function W2({protectedKeys:n,needsAnimating:a},l){const r=n.hasOwnProperty(l)&&a[l]!==!0;return a[l]=!1,r}function pp(n,a,{delay:l=0,transitionOverride:r,type:d}={}){let{transition:f,transitionEnd:h,...p}=a;const y=n.getDefaultTransition();f=f?op(f,y):y;const g=f?.reduceMotion;r&&(f=r);const b=[],w=d&&n.animationState&&n.animationState.getState()[d];for(const A in p){const j=n.getValue(A,n.latestValues[A]??null),k=p[A];if(k===void 0||w&&W2(w,A))continue;const D={delay:l,...vu(f||{},A)},O=j.get();if(O!==void 0&&!j.isAnimating()&&!Array.isArray(k)&&k===O&&!D.velocity){Jt.update(()=>j.set(k));continue}let q=!1;if(window.MotionHandoffAnimation){const T=hp(n);if(T){const L=window.MotionHandoffAnimation(T,A,Jt);L!==null&&(D.startTime=L,q=!0)}}Tu(n,A);const W=g??n.shouldReduceMotion;j.start(Su(A,j,k,W&&cp.has(A)?{type:!1}:D,n,q));const E=j.animation;E&&b.push(E)}if(h){const A=()=>Jt.update(()=>{h&&P2(n,h)});b.length?Promise.all(b).then(A):A()}return b}function ju(n,a,l={}){const r=Ii(n,a,l.type==="exit"?n.presenceContext?.custom:void 0);let{transition:d=n.getDefaultTransition()||{}}=r||{};l.transitionOverride&&(d=l.transitionOverride);const f=r?()=>Promise.all(pp(n,r,l)):()=>Promise.resolve(),h=n.variantChildren&&n.variantChildren.size?(y=0)=>{const{delayChildren:g=0,staggerChildren:b,staggerDirection:w}=d;return Q2(n,a,y,g,b,w,l)}:()=>Promise.resolve(),{when:p}=d;if(p){const[y,g]=p==="beforeChildren"?[f,h]:[h,f];return y().then(()=>g())}else return Promise.all([f(),h(l.delay)])}function Q2(n,a,l=0,r=0,d=0,f=1,h){const p=[];for(const y of n.variantChildren)y.notify("AnimationStart",a),p.push(ju(y,a,{...h,delay:l+(typeof r=="function"?0:r)+lp(n.variantChildren,y,r,d,f)}).then(()=>y.notify("AnimationComplete",a)));return Promise.all(p)}function Z2(n,a,l={}){n.notify("AnimationStart",a);let r;if(Array.isArray(a)){const d=a.map(f=>ju(n,f,l));r=Promise.all(d)}else if(typeof a=="string")r=ju(n,a,l);else{const d=typeof a=="function"?Ii(n,a,l.custom):a;r=Promise.all(pp(n,d,l))}return r.then(()=>{n.notify("AnimationComplete",a)})}const $2={test:n=>n==="auto",parse:n=>n},mp=n=>a=>a.test(n),gp=[fa,xt,jn,si,Ev,Tv,$2],yp=n=>gp.find(mp(n));function J2(n){return typeof n=="number"?n===0:n!==null?n==="none"||n==="0"||fh(n):!0}const tS=new Set(["brightness","contrast","saturate","opacity"]);function eS(n){const[a,l]=n.slice(0,-1).split("(");if(a==="drop-shadow")return n;const[r]=l.match(Zo)||[];if(!r)return n;const d=l.replace(r,"");let f=tS.has(a)?1:0;return r!==l&&(f*=100),a+"("+f+d+")"}const nS=/\b([a-z-]*)\(.*?\)/gu,Cu={...hn,getAnimatableNone:n=>{const a=n.match(nS);return a?a.map(eS).join(" "):n}},Mu={...hn,getAnimatableNone:n=>{const a=hn.parse(n);return hn.createTransformer(n)(a.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},xp={...fa,transform:Math.round},ku={borderWidth:xt,borderTopWidth:xt,borderRightWidth:xt,borderBottomWidth:xt,borderLeftWidth:xt,borderRadius:xt,borderTopLeftRadius:xt,borderTopRightRadius:xt,borderBottomRightRadius:xt,borderBottomLeftRadius:xt,width:xt,maxWidth:xt,height:xt,maxHeight:xt,top:xt,right:xt,bottom:xt,left:xt,inset:xt,insetBlock:xt,insetBlockStart:xt,insetBlockEnd:xt,insetInline:xt,insetInlineStart:xt,insetInlineEnd:xt,padding:xt,paddingTop:xt,paddingRight:xt,paddingBottom:xt,paddingLeft:xt,paddingBlock:xt,paddingBlockStart:xt,paddingBlockEnd:xt,paddingInline:xt,paddingInlineStart:xt,paddingInlineEnd:xt,margin:xt,marginTop:xt,marginRight:xt,marginBottom:xt,marginLeft:xt,marginBlock:xt,marginBlockStart:xt,marginBlockEnd:xt,marginInline:xt,marginInlineStart:xt,marginInlineEnd:xt,fontSize:xt,backgroundPositionX:xt,backgroundPositionY:xt,...{rotate:si,rotateX:si,rotateY:si,rotateZ:si,scale:Rl,scaleX:Rl,scaleY:Rl,scaleZ:Rl,skew:si,skewX:si,skewY:si,distance:xt,translateX:xt,translateY:xt,translateZ:xt,x:xt,y:xt,z:xt,perspective:xt,transformPerspective:xt,opacity:ms,originX:Dh,originY:Dh,originZ:xt},zIndex:xp,fillOpacity:ms,strokeOpacity:ms,numOctaves:xp},iS={...ku,color:de,backgroundColor:de,outlineColor:de,fill:de,stroke:de,borderColor:de,borderTopColor:de,borderRightColor:de,borderBottomColor:de,borderLeftColor:de,filter:Cu,WebkitFilter:Cu,mask:Mu,WebkitMask:Mu},bp=n=>iS[n],aS=new Set([Cu,Mu]);function vp(n,a){let l=bp(n);return aS.has(l)||(l=hn),l.getAnimatableNone?l.getAnimatableNone(a):void 0}const sS=new Set(["auto","none","0"]);function lS(n,a,l){let r=0,d;for(;r{a.getValue(p).set(y)}),this.resolveNoneKeyframes()}}function Sp(n,a,l){if(n==null)return[];if(n instanceof EventTarget)return[n];if(typeof n=="string"){let r=document;const d=l?.[n]??r.querySelectorAll(n);return d?Array.from(d):[]}return Array.from(n).filter(r=>r!=null)}const wp=(n,a)=>a&&typeof n=="number"?a.transform(n):n;function Nl(n){return dh(n)&&"offsetHeight"in n&&!("ownerSVGElement"in n)}const{schedule:Ru}=jh(queueMicrotask,!1),pn={x:!1,y:!1};function Ap(){return pn.x||pn.y}function oS(n){return n==="x"||n==="y"?pn[n]?null:(pn[n]=!0,()=>{pn[n]=!1}):pn.x||pn.y?null:(pn.x=pn.y=!0,()=>{pn.x=pn.y=!1})}function Tp(n,a){const l=Sp(n),r=new AbortController,d={passive:!0,...a,signal:r.signal};return[l,d,()=>r.abort()]}function uS(n){return!(n.pointerType==="touch"||Ap())}function cS(n,a,l={}){const[r,d,f]=Tp(n,l);return r.forEach(h=>{let p=!1,y=!1,g;const b=()=>{h.removeEventListener("pointerleave",k)},w=O=>{g&&(g(O),g=void 0),b()},A=O=>{p=!1,window.removeEventListener("pointerup",A),window.removeEventListener("pointercancel",A),y&&(y=!1,w(O))},j=()=>{p=!0,window.addEventListener("pointerup",A,d),window.addEventListener("pointercancel",A,d)},k=O=>{if(O.pointerType!=="touch"){if(p){y=!0;return}w(O)}},D=O=>{if(!uS(O))return;y=!1;const q=a(h,O);typeof q=="function"&&(g=q,h.addEventListener("pointerleave",k,d))};h.addEventListener("pointerenter",D,d),h.addEventListener("pointerdown",j,d)}),f}const Ep=(n,a)=>a?n===a?!0:Ep(n,a.parentElement):!1,Du=n=>n.pointerType==="mouse"?typeof n.button!="number"||n.button<=0:n.isPrimary!==!1,dS=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function fS(n){return dS.has(n.tagName)||n.isContentEditable===!0}const hS=new Set(["INPUT","SELECT","TEXTAREA"]);function pS(n){return hS.has(n.tagName)||n.isContentEditable===!0}const _l=new WeakSet;function jp(n){return a=>{a.key==="Enter"&&n(a)}}function zu(n,a){n.dispatchEvent(new PointerEvent("pointer"+a,{isPrimary:!0,bubbles:!0}))}const mS=(n,a)=>{const l=n.currentTarget;if(!l)return;const r=jp(()=>{if(_l.has(l))return;zu(l,"down");const d=jp(()=>{zu(l,"up")}),f=()=>zu(l,"cancel");l.addEventListener("keyup",d,a),l.addEventListener("blur",f,a)});l.addEventListener("keydown",r,a),l.addEventListener("blur",()=>l.removeEventListener("keydown",r),a)};function Cp(n){return Du(n)&&!Ap()}const Mp=new WeakSet;function gS(n,a,l={}){const[r,d,f]=Tp(n,l),h=p=>{const y=p.currentTarget;if(!Cp(p)||Mp.has(p))return;_l.add(y),l.stopPropagation&&Mp.add(p);const g=a(y,p),b=(j,k)=>{window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",A),_l.has(y)&&_l.delete(y),Cp(j)&&typeof g=="function"&&g(j,{success:k})},w=j=>{b(j,y===window||y===document||l.useGlobalTarget||Ep(y,j.target))},A=j=>{b(j,!1)};window.addEventListener("pointerup",w,d),window.addEventListener("pointercancel",A,d)};return r.forEach(p=>{(l.useGlobalTarget?window:p).addEventListener("pointerdown",h,d),Nl(p)&&(p.addEventListener("focus",g=>mS(g,d)),!fS(p)&&!p.hasAttribute("tabindex")&&(p.tabIndex=0))}),f}function Lu(n){return dh(n)&&"ownerSVGElement"in n}const Ul=new WeakMap;let Hl;const kp=(n,a,l)=>(r,d)=>d&&d[0]?d[0][n+"Size"]:Lu(r)&&"getBBox"in r?r.getBBox()[a]:r[l],yS=kp("inline","width","offsetWidth"),xS=kp("block","height","offsetHeight");function bS({target:n,borderBoxSize:a}){Ul.get(n)?.forEach(l=>{l(n,{get width(){return yS(n,a)},get height(){return xS(n,a)}})})}function vS(n){n.forEach(bS)}function SS(){typeof ResizeObserver>"u"||(Hl=new ResizeObserver(vS))}function wS(n,a){Hl||SS();const l=Sp(n);return l.forEach(r=>{let d=Ul.get(r);d||(d=new Set,Ul.set(r,d)),d.add(a),Hl?.observe(r)}),()=>{l.forEach(r=>{const d=Ul.get(r);d?.delete(a),d?.size||Hl?.unobserve(r)})}}const Vl=new Set;let xa;function AS(){xa=()=>{const n={get width(){return window.innerWidth},get height(){return window.innerHeight}};Vl.forEach(a=>a(n))},window.addEventListener("resize",xa)}function TS(n){return Vl.add(n),xa||AS(),()=>{Vl.delete(n),!Vl.size&&typeof xa=="function"&&(window.removeEventListener("resize",xa),xa=void 0)}}function Rp(n,a){return typeof n=="function"?TS(n):wS(n,a)}function ES(n){return Lu(n)&&n.tagName==="svg"}const jS=[...gp,de,hn],CS=n=>jS.find(mp(n)),Dp=()=>({translate:0,scale:1,origin:0,originPoint:0}),ba=()=>({x:Dp(),y:Dp()}),zp=()=>({min:0,max:0}),ge=()=>({x:zp(),y:zp()}),MS=new WeakMap;function Il(n){return n!==null&&typeof n=="object"&&typeof n.start=="function"}function vs(n){return typeof n=="string"||Array.isArray(n)}const Ou=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Bu=["initial",...Ou];function Yl(n){return Il(n.animate)||Bu.some(a=>vs(n[a]))}function Lp(n){return!!(Yl(n)||n.variants)}function kS(n,a,l){for(const r in a){const d=a[r],f=l[r];if(Ae(d))n.addValue(r,d);else if(Ae(f))n.addValue(r,ya(d,{owner:n}));else if(f!==d)if(n.hasValue(r)){const h=n.getValue(r);h.liveStyle===!0?h.jump(d):h.hasAnimated||h.set(d)}else{const h=n.getStaticValue(r);n.addValue(r,ya(h!==void 0?h:d,{owner:n}))}}for(const r in l)a[r]===void 0&&n.removeValue(r);return a}const Nu={current:null},Op={current:!1},RS=typeof window<"u";function DS(){if(Op.current=!0,!!RS)if(window.matchMedia){const n=window.matchMedia("(prefers-reduced-motion)"),a=()=>Nu.current=n.matches;n.addEventListener("change",a),a()}else Nu.current=!1}const Bp=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Gl={};function Np(n){Gl=n}function zS(){return Gl}class LS{scrapeMotionValuesFromProps(a,l,r){return{}}constructor({parent:a,props:l,presenceContext:r,reducedMotionConfig:d,skipAnimations:f,blockInitialAnimation:h,visualState:p},y={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=yu,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,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 j=Re.now();this.renderScheduledAtthis.bindToMotionValue(r,l)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Op.current||DS(),this.shouldReduceMotion=Nu.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),ai(this.notifyUpdate),ai(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const l=this.features[a];l&&(l.unmount(),l.isMounted=!1)}this.current=null}addChild(a){this.children.add(a),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(a)}removeChild(a){this.children.delete(a),this.enteringChildren&&this.enteringChildren.delete(a)}bindToMotionValue(a,l){if(this.valueSubscriptions.has(a)&&this.valueSubscriptions.get(a)(),l.accelerate&&sp.has(a)&&this.current instanceof HTMLElement){const{factory:h,keyframes:p,times:y,ease:g,duration:b}=l.accelerate,w=new np({element:this.current,name:a,keyframes:p,times:y,ease:g,duration:Ge(b)}),A=h(w);this.valueSubscriptions.set(a,()=>{A(),w.cancel()});return}const r=ga.has(a);r&&this.onBindTransform&&this.onBindTransform();const d=l.on("change",h=>{this.latestValues[a]=h,this.props.onUpdate&&Jt.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let f;typeof window<"u"&&window.MotionCheckAppearSync&&(f=window.MotionCheckAppearSync(this,a,l)),this.valueSubscriptions.set(a,()=>{d(),f&&f(),l.owner&&l.stop()})}sortNodePosition(a){return!this.current||!this.sortInstanceNodePosition||this.type!==a.type?0:this.sortInstanceNodePosition(this.current,a.current)}updateFeatures(){let a="animation";for(a in Gl){const l=Gl[a];if(!l)continue;const{isEnabled:r,Feature:d}=l;if(!this.features[a]&&d&&r(this.props)&&(this.features[a]=new d(this)),this.features[a]){const f=this.features[a];f.isMounted?f.update():(f.mount(),f.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ge()}getStaticValue(a){return this.latestValues[a]}setStaticValue(a,l){this.latestValues[a]=l}update(a,l){(a.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=a,this.prevPresenceContext=this.presenceContext,this.presenceContext=l;for(let r=0;rl.variantChildren.delete(a)}addValue(a,l){const r=this.values.get(a);l!==r&&(r&&this.removeValue(a),this.bindToMotionValue(a,l),this.values.set(a,l),this.latestValues[a]=l.get())}removeValue(a){this.values.delete(a);const l=this.valueSubscriptions.get(a);l&&(l(),this.valueSubscriptions.delete(a)),delete this.latestValues[a],this.removeValueFromRenderState(a,this.renderState)}hasValue(a){return this.values.has(a)}getValue(a,l){if(this.props.values&&this.props.values[a])return this.props.values[a];let r=this.values.get(a);return r===void 0&&l!==void 0&&(r=ya(l===null?void 0:l,{owner:this}),this.addValue(a,r)),r}readValue(a,l){let r=this.latestValues[a]!==void 0||!this.current?this.latestValues[a]:this.getBaseTargetFromProps(this.props,a)??this.readValueFromInstance(this.current,a,this.options);return r!=null&&(typeof r=="string"&&(ch(r)||fh(r))?r=parseFloat(r):!CS(r)&&hn.test(l)&&(r=vp(a,l)),this.setBaseTarget(a,Ae(r)?r.get():r)),Ae(r)?r.get():r}setBaseTarget(a,l){this.baseTarget[a]=l}getBaseTarget(a){const{initial:l}=this.props;let r;if(typeof l=="string"||typeof l=="object"){const f=wu(this.props,l,this.presenceContext?.custom);f&&(r=f[a])}if(l&&r!==void 0)return r;const d=this.getBaseTargetFromProps(this.props,a);return d!==void 0&&!Ae(d)?d:this.initialValues[a]!==void 0&&r===void 0?void 0:this.baseTarget[a]}on(a,l){return this.events[a]||(this.events[a]=new Xo),this.events[a].add(l)}notify(a,...l){this.events[a]&&this.events[a].notify(...l)}scheduleRenderMicrotask(){Ru.render(this.render)}}class _p extends LS{constructor(){super(...arguments),this.KeyframeResolver=rS}sortInstanceNodePosition(a,l){return a.compareDocumentPosition(l)&2?1:-1}getBaseTargetFromProps(a,l){const r=a.style;return r?r[l]:void 0}removeValueFromRenderState(a,{vars:l,style:r}){delete l[a],delete r[a]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:a}=this.props;Ae(a)&&(this.childSubscription=a.on("change",l=>{this.current&&(this.current.textContent=`${l}`)}))}}class ri{constructor(a){this.isMounted=!1,this.node=a}update(){}}function Up({top:n,left:a,right:l,bottom:r}){return{x:{min:a,max:l},y:{min:n,max:r}}}function OS({x:n,y:a}){return{top:a.min,right:n.max,bottom:a.max,left:n.min}}function BS(n,a){if(!a)return n;const l=a({x:n.left,y:n.top}),r=a({x:n.right,y:n.bottom});return{top:l.y,left:l.x,bottom:r.y,right:r.x}}function _u(n){return n===void 0||n===1}function Uu({scale:n,scaleX:a,scaleY:l}){return!_u(n)||!_u(a)||!_u(l)}function Yi(n){return Uu(n)||Hp(n)||n.z||n.rotate||n.rotateX||n.rotateY||n.skewX||n.skewY}function Hp(n){return Vp(n.x)||Vp(n.y)}function Vp(n){return n&&n!=="0%"}function Fl(n,a,l){const r=n-l,d=a*r;return l+d}function Ip(n,a,l,r,d){return d!==void 0&&(n=Fl(n,d,r)),Fl(n,l,r)+a}function Hu(n,a=0,l=1,r,d){n.min=Ip(n.min,a,l,r,d),n.max=Ip(n.max,a,l,r,d)}function Yp(n,{x:a,y:l}){Hu(n.x,a.translate,a.scale,a.originPoint),Hu(n.y,l.translate,l.scale,l.originPoint)}const Gp=.999999999999,Fp=1.0000000000001;function NS(n,a,l,r=!1){const d=l.length;if(!d)return;a.x=a.y=1;let f,h;for(let p=0;pGp&&(a.x=1),a.yGp&&(a.y=1)}function Cn(n,a){n.min+=a,n.max+=a}function qp(n,a,l,r,d=.5){const f=ee(n.min,n.max,d);Hu(n,a,l,f,r)}function Xp(n,a){return typeof n=="string"?parseFloat(n)/100*(a.max-a.min):n}function ql(n,a,l){const r=l??n;qp(n.x,Xp(a.x,r.x),a.scaleX,a.scale,a.originX),qp(n.y,Xp(a.y,r.y),a.scaleY,a.scale,a.originY)}function Pp(n,a){return Up(BS(n.getBoundingClientRect(),a))}function _S(n,a,l){const r=Pp(n,l),{scroll:d}=a;return d&&(Cn(r.x,d.offset.x),Cn(r.y,d.offset.y)),r}const US={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},HS=ma.length;function VS(n,a,l){let r="",d=!0;for(let f=0;f{if(!a.target)return n;if(typeof n=="string")if(xt.test(n))n=parseFloat(n);else return n;const l=Wp(n,a.target.x),r=Wp(n,a.target.y);return`${l}% ${r}%`}},IS={correct:(n,{treeScale:a,projectionDelta:l})=>{const r=n,d=hn.parse(n);if(d.length>5)return r;const f=hn.createTransformer(n),h=typeof d[0]!="number"?1:0,p=l.x.scale*a.x,y=l.y.scale*a.y;d[0+h]/=p,d[1+h]/=y;const g=ee(p,y,.5);return typeof d[2+h]=="number"&&(d[2+h]/=g),typeof d[3+h]=="number"&&(d[3+h]/=g),f(d)}},Iu={borderRadius:{...Ss,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Ss,borderTopRightRadius:Ss,borderBottomLeftRadius:Ss,borderBottomRightRadius:Ss,boxShadow:IS};function Qp(n,{layout:a,layoutId:l}){return ga.has(n)||n.startsWith("origin")||(a||l!==void 0)&&(!!Iu[n]||n==="opacity")}function Yu(n,a,l){const r=n.style,d=a?.style,f={};if(!r)return f;for(const h in r)(Ae(r[h])||d&&Ae(d[h])||Qp(h,n)||l?.getValue(h)?.liveStyle!==void 0)&&(f[h]=r[h]);return f}function YS(n){return window.getComputedStyle(n)}class GS extends _p{constructor(){super(...arguments),this.type="html",this.renderInstance=Kp}readValueFromInstance(a,l){if(ga.has(l))return this.projection?.isProjecting?fu(l):d2(a,l);{const r=YS(a),d=(Mh(l)?r.getPropertyValue(l):r[l])||0;return typeof d=="string"?d.trim():d}}measureInstanceViewportBox(a,{transformPagePoint:l}){return Pp(a,l)}build(a,l,r){Vu(a,l,r.transformTemplate)}scrapeMotionValuesFromProps(a,l,r){return Yu(a,l,r)}}const FS={offset:"stroke-dashoffset",array:"stroke-dasharray"},qS={offset:"strokeDashoffset",array:"strokeDasharray"};function XS(n,a,l=1,r=0,d=!0){n.pathLength=1;const f=d?FS:qS;n[f.offset]=`${-r}`,n[f.array]=`${a} ${l}`}const PS=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Zp(n,{attrX:a,attrY:l,attrScale:r,pathLength:d,pathSpacing:f=1,pathOffset:h=0,...p},y,g,b){if(Vu(n,p,g),y){n.style.viewBox&&(n.attrs.viewBox=n.style.viewBox);return}n.attrs=n.style,n.style={};const{attrs:w,style:A}=n;w.transform&&(A.transform=w.transform,delete w.transform),(A.transform||w.transformOrigin)&&(A.transformOrigin=w.transformOrigin??"50% 50%",delete w.transformOrigin),A.transform&&(A.transformBox=b?.transformBox??"fill-box",delete w.transformBox);for(const j of PS)w[j]!==void 0&&(A[j]=w[j],delete w[j]);a!==void 0&&(w.x=a),l!==void 0&&(w.y=l),r!==void 0&&(w.scale=r),d!==void 0&&XS(w,d,f,h,!1)}const $p=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"]),Jp=n=>typeof n=="string"&&n.toLowerCase()==="svg";function KS(n,a,l,r){Kp(n,a,void 0,r);for(const d in a.attrs)n.setAttribute($p.has(d)?d:Eu(d),a.attrs[d])}function tm(n,a,l){const r=Yu(n,a,l);for(const d in n)if(Ae(n[d])||Ae(a[d])){const f=ma.indexOf(d)!==-1?"attr"+d.charAt(0).toUpperCase()+d.substring(1):d;r[f]=n[d]}return r}class WS extends _p{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ge}getBaseTargetFromProps(a,l){return a[l]}readValueFromInstance(a,l){if(ga.has(l)){const r=bp(l);return r&&r.default||0}return l=$p.has(l)?l:Eu(l),a.getAttribute(l)}scrapeMotionValuesFromProps(a,l,r){return tm(a,l,r)}build(a,l,r){Zp(a,l,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(a,l,r,d){KS(a,l,r,d)}mount(a){this.isSVGTag=Jp(a.tagName),super.mount(a)}}const QS=Bu.length;function em(n){if(!n)return;if(!n.isControllingVariants){const l=n.parent?em(n.parent)||{}:{};return n.props.initial!==void 0&&(l.initial=n.props.initial),l}const a={};for(let l=0;lPromise.all(a.map(({animation:l,options:r})=>Z2(n,l,r)))}function tw(n){let a=JS(n),l=im(),r=!0,d=!1;const f=g=>(b,w)=>{const A=Ii(n,w,g==="exit"?n.presenceContext?.custom:void 0);if(A){const{transition:j,transitionEnd:k,...D}=A;b={...b,...D,...k}}return b};function h(g){a=g(n)}function p(g){const{props:b}=n,w=em(n.parent)||{},A=[],j=new Set;let k={},D=1/0;for(let q=0;q<$S;q++){const W=ZS[q],E=l[W],T=b[W]!==void 0?b[W]:w[W],L=vs(T),H=W===g?E.isActive:null;H===!1&&(D=q);let J=T===w[W]&&T!==b[W]&&L;if(J&&(r||d)&&n.manuallyAnimateOnMount&&(J=!1),E.protectedKeys={...k},!E.isActive&&H===null||!T&&!E.prevProp||Il(T)||typeof T=="boolean")continue;if(W==="exit"&&E.isActive&&H!==!0){E.prevResolvedValues&&(k={...k,...E.prevResolvedValues});continue}const $=ew(E.prevProp,T);let F=$||W===g&&E.isActive&&!J&&L||q>D&&L,K=!1;const lt=Array.isArray(T)?T:[T];let it=lt.reduce(f(W),{});H===!1&&(it={});const{prevResolvedValues:rt={}}=E,ht={...rt,...it},Mt=Y=>{F=!0,j.has(Y)&&(K=!0,j.delete(Y)),E.needsAnimating[Y]=!0;const dt=n.getValue(Y);dt&&(dt.liveStyle=!1)};for(const Y in ht){const dt=it[Y],bt=rt[Y];if(k.hasOwnProperty(Y))continue;let M=!1;Au(dt)&&Au(bt)?M=!nm(dt,bt):M=dt!==bt,M?dt!=null?Mt(Y):j.add(Y):dt!==void 0&&j.has(Y)?Mt(Y):E.protectedKeys[Y]=!0}E.prevProp=T,E.prevResolvedValues=it,E.isActive&&(k={...k,...it}),(r||d)&&n.blockInitialAnimation&&(F=!1);const B=J&&$;F&&(!B||K)&&A.push(...lt.map(Y=>{const dt={type:W};if(typeof Y=="string"&&(r||d)&&!B&&n.manuallyAnimateOnMount&&n.parent){const{parent:bt}=n,M=Ii(bt,Y);if(bt.enteringChildren&&M){const{delayChildren:P}=M.transition||{};dt.delay=lp(bt.enteringChildren,n,P)}}return{animation:Y,options:dt}}))}if(j.size){const q={};if(typeof b.initial!="boolean"){const W=Ii(n,Array.isArray(b.initial)?b.initial[0]:b.initial);W&&W.transition&&(q.transition=W.transition)}j.forEach(W=>{const E=n.getBaseTarget(W),T=n.getValue(W);T&&(T.liveStyle=!0),q[W]=E??null}),A.push({animation:q})}let O=!!A.length;return r&&(b.initial===!1||b.initial===b.animate)&&!n.manuallyAnimateOnMount&&(O=!1),r=!1,d=!1,O?a(A):Promise.resolve()}function y(g,b){if(l[g].isActive===b)return Promise.resolve();n.variantChildren?.forEach(A=>A.animationState?.setActive(g,b)),l[g].isActive=b;const w=p(g);for(const A in l)l[A].protectedKeys={};return w}return{animateChanges:p,setActive:y,setAnimateFunction:h,getState:()=>l,reset:()=>{l=im(),d=!0}}}function ew(n,a){return typeof a=="string"?a!==n:Array.isArray(a)?!nm(a,n):!1}function Gi(n=!1){return{isActive:n,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function im(){return{animate:Gi(!0),whileInView:Gi(),whileHover:Gi(),whileTap:Gi(),whileDrag:Gi(),whileFocus:Gi(),exit:Gi()}}function Gu(n,a){n.min=a.min,n.max=a.max}function mn(n,a){Gu(n.x,a.x),Gu(n.y,a.y)}function am(n,a){n.translate=a.translate,n.scale=a.scale,n.originPoint=a.originPoint,n.origin=a.origin}const sm=1e-4,nw=1-sm,iw=1+sm,lm=.01,aw=0-lm,sw=0+lm;function De(n){return n.max-n.min}function lw(n,a,l){return Math.abs(n-a)<=l}function rm(n,a,l,r=.5){n.origin=r,n.originPoint=ee(a.min,a.max,n.origin),n.scale=De(l)/De(a),n.translate=ee(l.min,l.max,n.origin)-n.originPoint,(n.scale>=nw&&n.scale<=iw||isNaN(n.scale))&&(n.scale=1),(n.translate>=aw&&n.translate<=sw||isNaN(n.translate))&&(n.translate=0)}function ws(n,a,l,r){rm(n.x,a.x,l.x,r?r.originX:void 0),rm(n.y,a.y,l.y,r?r.originY:void 0)}function om(n,a,l,r=0){const d=r?ee(l.min,l.max,r):l.min;n.min=d+a.min,n.max=n.min+De(a)}function rw(n,a,l,r){om(n.x,a.x,l.x,r?.x),om(n.y,a.y,l.y,r?.y)}function um(n,a,l,r=0){const d=r?ee(l.min,l.max,r):l.min;n.min=a.min-d,n.max=n.min+De(a)}function Xl(n,a,l,r){um(n.x,a.x,l.x,r?.x),um(n.y,a.y,l.y,r?.y)}function cm(n,a,l,r,d){return n-=a,n=Fl(n,1/l,r),d!==void 0&&(n=Fl(n,1/d,r)),n}function ow(n,a=0,l=1,r=.5,d,f=n,h=n){if(jn.test(a)&&(a=parseFloat(a),a=ee(h.min,h.max,a/100)-h.min),typeof a!="number")return;let p=ee(f.min,f.max,r);n===f&&(p-=a),n.min=cm(n.min,a,l,p,d),n.max=cm(n.max,a,l,p,d)}function dm(n,a,[l,r,d],f,h){ow(n,a[l],a[r],a[d],a.scale,f,h)}const uw=["x","scaleX","originX"],cw=["y","scaleY","originY"];function fm(n,a,l,r){dm(n.x,a,uw,l?l.x:void 0,r?r.x:void 0),dm(n.y,a,cw,l?l.y:void 0,r?r.y:void 0)}function hm(n){return n.translate===0&&n.scale===1}function pm(n){return hm(n.x)&&hm(n.y)}function mm(n,a){return n.min===a.min&&n.max===a.max}function dw(n,a){return mm(n.x,a.x)&&mm(n.y,a.y)}function gm(n,a){return Math.round(n.min)===Math.round(a.min)&&Math.round(n.max)===Math.round(a.max)}function ym(n,a){return gm(n.x,a.x)&&gm(n.y,a.y)}function xm(n){return De(n.x)/De(n.y)}function bm(n,a){return n.translate===a.translate&&n.scale===a.scale&&n.originPoint===a.originPoint}function Mn(n){return[n("x"),n("y")]}function fw(n,a,l){let r="";const d=n.x.translate/a.x,f=n.y.translate/a.y,h=l?.z||0;if((d||f||h)&&(r=`translate3d(${d}px, ${f}px, ${h}px) `),(a.x!==1||a.y!==1)&&(r+=`scale(${1/a.x}, ${1/a.y}) `),l){const{transformPerspective:g,rotate:b,rotateX:w,rotateY:A,skewX:j,skewY:k}=l;g&&(r=`perspective(${g}px) ${r}`),b&&(r+=`rotate(${b}deg) `),w&&(r+=`rotateX(${w}deg) `),A&&(r+=`rotateY(${A}deg) `),j&&(r+=`skewX(${j}deg) `),k&&(r+=`skewY(${k}deg) `)}const p=n.x.scale*a.x,y=n.y.scale*a.y;return(p!==1||y!==1)&&(r+=`scale(${p}, ${y})`),r||"none"}const vm=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],hw=vm.length,Sm=n=>typeof n=="string"?parseFloat(n):n,wm=n=>typeof n=="number"||xt.test(n);function pw(n,a,l,r,d,f){d?(n.opacity=ee(0,l.opacity??1,mw(r)),n.opacityExit=ee(a.opacity??1,0,gw(r))):f&&(n.opacity=ee(a.opacity??1,l.opacity??1,r));for(let h=0;hra?1:l(hs(n,a,r))}function yw(n,a,l){const r=Ae(n)?n:ya(n);return r.start(Su("",r,a,l)),r.animation}function As(n,a,l,r={passive:!0}){return n.addEventListener(a,l,r),()=>n.removeEventListener(a,l)}const xw=(n,a)=>n.depth-a.depth;class bw{constructor(){this.children=[],this.isDirty=!1}add(a){Fo(this.children,a),this.isDirty=!0}remove(a){Cl(this.children,a),this.isDirty=!0}forEach(a){this.isDirty&&this.children.sort(xw),this.isDirty=!1,this.children.forEach(a)}}function vw(n,a){const l=Re.now(),r=({timestamp:d})=>{const f=d-l;f>=a&&(ai(r),n(f-a))};return Jt.setup(r,!0),()=>ai(r)}function Pl(n){return Ae(n)?n.get():n}class Sw{constructor(){this.members=[]}add(a){Fo(this.members,a);for(let l=this.members.length-1;l>=0;l--){const r=this.members[l];if(r===a||r===this.lead||r===this.prevLead)continue;const d=r.instance;(!d||d.isConnected===!1)&&!r.snapshot&&(Cl(this.members,r),r.unmount())}a.scheduleRender()}remove(a){if(Cl(this.members,a),a===this.prevLead&&(this.prevLead=void 0),a===this.lead){const l=this.members[this.members.length-1];l&&this.promote(l)}}relegate(a){for(let l=this.members.indexOf(a)-1;l>=0;l--){const r=this.members[l];if(r.isPresent!==!1&&r.instance?.isConnected!==!1)return this.promote(r),!0}return!1}promote(a,l){const r=this.lead;if(a!==r&&(this.prevLead=r,this.lead=a,a.show(),r)){r.updateSnapshot(),a.scheduleRender();const{layoutDependency:d}=r.options,{layoutDependency:f}=a.options;(d===void 0||d!==f)&&(a.resumeFrom=r,l&&(r.preserveOpacity=!0),r.snapshot&&(a.snapshot=r.snapshot,a.snapshot.latestValues=r.animationValues||r.latestValues),a.root?.isUpdating&&(a.isLayoutDirty=!0)),a.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(a=>{a.options.onExitComplete?.(),a.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(a=>a.instance&&a.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}}const Kl={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Fu=["","X","Y","Z"],ww=1e3;let Aw=0;function qu(n,a,l,r){const{latestValues:d}=a;d[n]&&(l[n]=d[n],a.setStaticValue(n,0),r&&(r[n]=0))}function Em(n){if(n.hasCheckedOptimisedAppear=!0,n.root===n)return;const{visualElement:a}=n.options;if(!a)return;const l=hp(a);if(window.MotionHasOptimisedAnimation(l,"transform")){const{layout:d,layoutId:f}=n.options;window.MotionCancelOptimisedAnimation(l,"transform",Jt,!(d||f))}const{parent:r}=n;r&&!r.hasCheckedOptimisedAppear&&Em(r)}function jm({attachResizeListener:n,defaultParent:a,measureScroll:l,checkIsScrollRoot:r,resetTransform:d}){return class{constructor(h={},p=a?.()){this.id=Aw++,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(jw),this.nodes.forEach(zw),this.nodes.forEach(Lw),this.nodes.forEach(Cw)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=h,this.root=p?p.root||p:this,this.path=p?[...p.path,p]:[],this.parent=p,this.depth=p?p.depth+1:0;for(let y=0;ythis.root.updateBlockedByResize=!1;Jt.read(()=>{w=window.innerWidth}),n(h,()=>{const j=window.innerWidth;j!==w&&(w=j,this.root.updateBlockedByResize=!0,b&&b(),b=vw(A,250),Kl.hasAnimatedSinceResize&&(Kl.hasAnimatedSinceResize=!1,this.nodes.forEach(km)))})}p&&this.root.registerSharedNode(p,this),this.options.animate!==!1&&g&&(p||y)&&this.addEventListener("didUpdate",({delta:b,hasLayoutChanged:w,hasRelativeLayoutChanged:A,layout:j})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const k=this.options.transition||g.getDefaultTransition()||Uw,{onLayoutAnimationStart:D,onLayoutAnimationComplete:O}=g.getProps(),q=!this.targetLayout||!ym(this.targetLayout,j),W=!w&&A;if(this.options.layoutRoot||this.resumeFrom||W||w&&(q||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...vu(k,"layout"),onPlay:D,onComplete:O};(g.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(b,W)}else w||km(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=j})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const h=this.getStack();h&&h.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),ai(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(Ow),this.animationId++)}getTransformTemplate(){const{visualElement:h}=this.options;return h&&h.getProps().transformTemplate}willUpdate(h=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Em(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let b=0;b{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!De(this.snapshot.measuredBox.x)&&!De(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 y=0;y{const L=T/1e3;Rm(w.x,h.x,L),Rm(w.y,h.y,L),this.setTargetDelta(w),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xl(A,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Nw(this.relativeTarget,this.relativeTargetOrigin,A,L),E&&dw(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ge()),mn(E,this.relativeTarget)),D&&(this.animationValues=b,pw(b,g,this.latestValues,L,W,q)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(h){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(ai(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Jt.update(()=>{Kl.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ya(0)),this.motionValue.jump(0,!1),this.currentAnimation=yw(this.motionValue,[0,1e3],{...h,velocity:0,isSync:!0,onUpdate:p=>{this.mixTargetDelta(p),h.onUpdate&&h.onUpdate(p)},onStop:()=>{},onComplete:()=>{h.onComplete&&h.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 h=this.getStack();h&&h.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(ww),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const h=this.getLead();let{targetWithTransforms:p,target:y,layout:g,latestValues:b}=h;if(!(!p||!y||!g)){if(this!==h&&this.layout&&g&&Bm(this.options.animationType,this.layout.layoutBox,g.layoutBox)){y=this.target||ge();const w=De(this.layout.layoutBox.x);y.x.min=h.target.x.min,y.x.max=y.x.min+w;const A=De(this.layout.layoutBox.y);y.y.min=h.target.y.min,y.y.max=y.y.min+A}mn(p,y),ql(p,b),ws(this.projectionDeltaWithTransform,this.layoutCorrected,p,b)}}registerSharedNode(h,p){this.sharedNodes.has(h)||this.sharedNodes.set(h,new Sw),this.sharedNodes.get(h).add(p);const g=p.options.initialPromotionConfig;p.promote({transition:g?g.transition:void 0,preserveFollowOpacity:g&&g.shouldPreserveFollowOpacity?g.shouldPreserveFollowOpacity(p):void 0})}isLead(){const h=this.getStack();return h?h.lead===this:!0}getLead(){const{layoutId:h}=this.options;return h?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:h}=this.options;return h?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:h}=this.options;if(h)return this.root.sharedNodes.get(h)}promote({needsReset:h,transition:p,preserveFollowOpacity:y}={}){const g=this.getStack();g&&g.promote(this,y),h&&(this.projectionDelta=void 0,this.needsReset=!0),p&&this.setOptions({transition:p})}relegate(){const h=this.getStack();return h?h.relegate(this):!1}resetSkewAndRotation(){const{visualElement:h}=this.options;if(!h)return;let p=!1;const{latestValues:y}=h;if((y.z||y.rotate||y.rotateX||y.rotateY||y.rotateZ||y.skewX||y.skewY)&&(p=!0),!p)return;const g={};y.z&&qu("z",h,g,this.animationValues);for(let b=0;bh.currentAnimation?.stop()),this.root.nodes.forEach(Cm),this.root.sharedNodes.clear()}}}function Tw(n){n.updateLayout()}function Ew(n){const a=n.resumeFrom?.snapshot||n.snapshot;if(n.isLead()&&n.layout&&a&&n.hasListeners("didUpdate")){const{layoutBox:l,measuredBox:r}=n.layout,{animationType:d}=n.options,f=a.source!==n.layout.source;if(d==="size")Mn(b=>{const w=f?a.measuredBox[b]:a.layoutBox[b],A=De(w);w.min=l[b].min,w.max=w.min+A});else if(d==="x"||d==="y"){const b=d==="x"?"y":"x";Gu(f?a.measuredBox[b]:a.layoutBox[b],l[b])}else Bm(d,a.layoutBox,l)&&Mn(b=>{const w=f?a.measuredBox[b]:a.layoutBox[b],A=De(l[b]);w.max=w.min+A,n.relativeTarget&&!n.currentAnimation&&(n.isProjectionDirty=!0,n.relativeTarget[b].max=n.relativeTarget[b].min+A)});const h=ba();ws(h,l,a.layoutBox);const p=ba();f?ws(p,n.applyTransform(r,!0),a.measuredBox):ws(p,l,a.layoutBox);const y=!pm(h);let g=!1;if(!n.resumeFrom){const b=n.getClosestProjectingParent();if(b&&!b.resumeFrom){const{snapshot:w,layout:A}=b;if(w&&A){const j=n.options.layoutAnchor||void 0,k=ge();Xl(k,a.layoutBox,w.layoutBox,j);const D=ge();Xl(D,l,A.layoutBox,j),ym(k,D)||(g=!0),b.options.layoutRoot&&(n.relativeTarget=D,n.relativeTargetOrigin=k,n.relativeParent=b)}}}n.notifyListeners("didUpdate",{layout:l,snapshot:a,delta:p,layoutDelta:h,hasLayoutChanged:y,hasRelativeLayoutChanged:g})}else if(n.isLead()){const{onExitComplete:l}=n.options;l&&l()}n.options.transition=void 0}function jw(n){n.parent&&(n.isProjecting()||(n.isProjectionDirty=n.parent.isProjectionDirty),n.isSharedProjectionDirty||(n.isSharedProjectionDirty=!!(n.isProjectionDirty||n.parent.isProjectionDirty||n.parent.isSharedProjectionDirty)),n.isTransformDirty||(n.isTransformDirty=n.parent.isTransformDirty))}function Cw(n){n.isProjectionDirty=n.isSharedProjectionDirty=n.isTransformDirty=!1}function Mw(n){n.clearSnapshot()}function Cm(n){n.clearMeasurements()}function kw(n){n.isLayoutDirty=!0,n.updateLayout()}function Mm(n){n.isLayoutDirty=!1}function Rw(n){n.isAnimationBlocked&&n.layout&&!n.isLayoutDirty&&(n.snapshot=n.layout,n.isLayoutDirty=!0)}function Dw(n){const{visualElement:a}=n.options;a&&a.getProps().onBeforeLayoutMeasure&&a.notify("BeforeLayoutMeasure"),n.resetTransform()}function km(n){n.finishAnimation(),n.targetDelta=n.relativeTarget=n.target=void 0,n.isProjectionDirty=!0}function zw(n){n.resolveTargetDelta()}function Lw(n){n.calcProjection()}function Ow(n){n.resetSkewAndRotation()}function Bw(n){n.removeLeadSnapshot()}function Rm(n,a,l){n.translate=ee(a.translate,0,l),n.scale=ee(a.scale,1,l),n.origin=a.origin,n.originPoint=a.originPoint}function Dm(n,a,l,r){n.min=ee(a.min,l.min,r),n.max=ee(a.max,l.max,r)}function Nw(n,a,l,r){Dm(n.x,a.x,l.x,r),Dm(n.y,a.y,l.y,r)}function _w(n){return n.animationValues&&n.animationValues.opacityExit!==void 0}const Uw={duration:.45,ease:[.4,0,.1,1]},zm=n=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(n),Lm=zm("applewebkit/")&&!zm("chrome/")?Math.round:tn;function Om(n){n.min=Lm(n.min),n.max=Lm(n.max)}function Hw(n){Om(n.x),Om(n.y)}function Bm(n,a,l){return n==="position"||n==="preserve-aspect"&&!lw(xm(a),xm(l),.2)}function Vw(n){return n!==n.root&&n.scroll?.wasRoot}const Iw=jm({attachResizeListener:(n,a)=>As(n,"resize",a),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Xu={current:void 0},Nm=jm({measureScroll:n=>({x:n.scrollLeft,y:n.scrollTop}),defaultParent:()=>{if(!Xu.current){const n=new Iw({});n.mount(window),n.setOptions({layoutScroll:!0}),Xu.current=n}return Xu.current},resetTransform:(n,a)=>{n.style.transform=a!==void 0?a:"none"},checkIsScrollRoot:n=>window.getComputedStyle(n).position==="fixed"}),Pu=v.createContext({transformPagePoint:n=>n,isStatic:!1,reducedMotion:"never"});function _m(n,a){if(typeof n=="function")return n(a);n!=null&&(n.current=a)}function Yw(...n){return a=>{let l=!1;const r=n.map(d=>{const f=_m(d,a);return!l&&typeof f=="function"&&(l=!0),f});if(l)return()=>{for(let d=0;d{const{width:A,height:j,top:k,left:D,right:O,bottom:q}=y.current;if(a||f===!1||!p.current||!A||!j)return;const W=l==="left"?`left: ${D}`:`right: ${O}`,E=r==="bottom"?`bottom: ${q}`:`top: ${k}`;p.current.dataset.motionPopId=h;const T=document.createElement("style");g&&(T.nonce=g);const L=d??document.head;return L.appendChild(T),T.sheet&&T.sheet.insertRule(` [data-motion-pop-id="${h}"] { position: absolute !important; width: ${A}px !important; height: ${j}px !important; - ${Q}px !important; + ${W}px !important; ${E}px !important; } - `),()=>{p.current?.removeAttribute("data-motion-pop-id"),L.contains(T)&&L.removeChild(T)}},[a]),u.jsx(jw,{isPresent:a,childRef:p,sizeRef:y,pop:f,children:f===!1?i:v.cloneElement(i,{ref:S})})}const Mw=({children:i,initial:a,isPresent:l,onExitComplete:r,custom:d,presenceAffectsLayout:f,mode:h,anchorX:p,anchorY:y,root:g})=>{const b=_o(kw),S=v.useId();let A=!0,j=v.useMemo(()=>(A=!1,{id:S,initial:a,isPresent:l,custom:d,onExitComplete:k=>{b.set(k,!0);for(const D of b.values())if(!D)return;r&&r()},register:k=>(b.set(k,!1),()=>b.delete(k))}),[l,b,r]);return f&&A&&(j={...j}),v.useMemo(()=>{b.forEach((k,D)=>b.set(D,!1))},[l]),v.useEffect(()=>{!l&&!b.size&&r&&r()},[l]),i=u.jsx(Cw,{pop:h==="popLayout",isPresent:l,anchorX:p,anchorY:y,root:g,children:i}),u.jsx(vl.Provider,{value:j,children:i})};function kw(){return new Map}function Mm(i=!0){const a=v.useContext(vl);if(a===null)return[!0,null];const{isPresent:l,onExitComplete:r,register:d}=a,f=v.useId();v.useEffect(()=>{if(i)return d(f)},[i]);const h=v.useCallback(()=>i&&r&&r(f),[f,r,i]);return!l&&r?[!1,h]:[!0]}const Gl=i=>i.key||"";function km(i){const a=[];return v.Children.forEach(i,l=>{v.isValidElement(l)&&a.push(l)}),a}const On=({children:i,custom:a,initial:l=!0,onExitComplete:r,presenceAffectsLayout:d=!0,mode:f="sync",propagate:h=!1,anchorX:p="left",anchorY:y="top",root:g})=>{const[b,S]=Mm(h),A=v.useMemo(()=>km(i),[i]),j=h&&!b?[]:A.map(Gl),k=v.useRef(!0),D=v.useRef(A),O=_o(()=>new Map),F=v.useRef(new Set),[Q,E]=v.useState(A),[T,L]=v.useState(A);Jf(()=>{k.current=!1,D.current=A;for(let tt=0;tt{const P=Gl(tt),W=h&&!b?!1:A===T||j.includes(P),lt=()=>{if(F.current.has(P))return;if(O.has(P))F.current.add(P),O.set(P,!0);else return;let it=!0;O.forEach(rt=>{rt||(it=!1)}),it&&($?.(),L(D.current),h&&S?.(),r&&r())};return u.jsx(Mw,{isPresent:W,initial:!k.current||l?void 0:!1,custom:a,presenceAffectsLayout:d,mode:f,root:g,onExitComplete:W?void 0:lt,anchorX:p,anchorY:y,children:tt},P)})})},Rm=v.createContext({strict:!1}),Dm={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 zm=!1;function Rw(){if(zm)return;const i={};for(const a in Dm)i[a]={isEnabled:l=>Dm[a].some(r=>!!l[r])};jp(i),zm=!0}function Lm(){return Rw(),pS()}function Dw(i){const a=Lm();for(const l in i)a[l]={...a[l],...i[l]};jp(a)}const zw=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","propagate","ignoreStrict","viewport"]);function ql(i){return i.startsWith("while")||i.startsWith("drag")&&i!=="draggable"||i.startsWith("layout")||i.startsWith("onTap")||i.startsWith("onPan")||i.startsWith("onLayout")||zw.has(i)}let Om=i=>!ql(i);function Lw(i){typeof i=="function"&&(Om=a=>a.startsWith("on")?!ql(a):i(a))}try{Lw(require("@emotion/is-prop-valid").default)}catch{}function Ow(i,a,l){const r={};for(const d in i)d==="values"&&typeof i.values=="object"||we(i[d])||(Om(d)||l===!0&&ql(d)||!a&&!ql(d)||i.draggable&&d.startsWith("onDrag"))&&(r[d]=i[d]);return r}const Xl=v.createContext({});function Bw(i,a){if(Nl(i)){const{initial:l,animate:r}=i;return{initial:l===!1||ms(l)?l:void 0,animate:ms(r)?r:void 0}}return i.inherit!==!1?a:{}}function Nw(i){const{initial:a,animate:l}=Bw(i,v.useContext(Xl));return v.useMemo(()=>({initial:a,animate:l}),[Bm(a),Bm(l)])}function Bm(i){return Array.isArray(i)?i.join(" "):i}const Yu=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Nm(i,a,l){for(const r in a)!we(a[r])&&!Hp(r,l)&&(i[r]=a[r])}function _w({transformTemplate:i},a){return v.useMemo(()=>{const l=Yu();return Ou(l,a,i),Object.assign({},l.vars,l.style)},[a])}function Vw(i,a){const l=i.style||{},r={};return Nm(r,l,i),Object.assign(r,_w(i,a)),r}function Uw(i,a){const l={},r=Vw(i,a);return i.drag&&i.dragListener!==!1&&(l.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=i.drag===!0?"none":`pan-${i.drag==="x"?"y":"x"}`),i.tabIndex===void 0&&(i.onTap||i.onTapStart||i.whileTap)&&(l.tabIndex=0),l.style=r,l}const _m=()=>({...Yu(),attrs:{}});function Hw(i,a,l,r){const d=v.useMemo(()=>{const f=_m();return Ip(f,a,Gp(r),i.transformTemplate,i.style),{...f.attrs,style:{...f.style}}},[a]);if(i.style){const f={};Nm(f,i.style,i),d.style={...f,...d.style}}return d}const Iw=["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 Gu(i){return typeof i!="string"||i.includes("-")?!1:!!(Iw.indexOf(i)>-1||/[A-Z]/u.test(i))}function Yw(i,a,l,{latestValues:r},d,f=!1,h){const y=(h??Gu(i)?Hw:Uw)(a,r,d,i),g=Ow(a,typeof i=="string",f),b=i!==v.Fragment?{...g,...y,ref:l}:{},{children:S}=a,A=v.useMemo(()=>we(S)?S.get():S,[S]);return v.createElement(i,{...b,children:A})}function Gw({scrapeMotionValuesFromProps:i,createRenderState:a},l,r,d){return{latestValues:qw(l,r,d,i),renderState:a()}}function qw(i,a,l,r){const d={},f=r(i,{});for(const A in f)d[A]=Il(f[A]);let{initial:h,animate:p}=i;const y=Nl(i),g=Ap(i);a&&g&&!y&&i.inherit!==!1&&(h===void 0&&(h=a.initial),p===void 0&&(p=a.animate));let b=l?l.initial===!1:!1;b=b||h===!1;const S=b?p:h;if(S&&typeof S!="boolean"&&!Bl(S)){const A=Array.isArray(S)?S:[S];for(let j=0;j(a,l)=>{const r=v.useContext(Xl),d=v.useContext(vl),f=()=>Gw(i,a,r,d);return l?f():_o(f)},Xw=Vm({scrapeMotionValuesFromProps:Nu,createRenderState:Yu}),Fw=Vm({scrapeMotionValuesFromProps:qp,createRenderState:_m}),Pw=Symbol.for("motionComponentSymbol");function Kw(i,a,l){const r=v.useRef(l);v.useInsertionEffect(()=>{r.current=l});const d=v.useRef(null);return v.useCallback(f=>{f&&i.onMount?.(f);const h=r.current;if(typeof h=="function")if(f){const p=h(f);typeof p=="function"&&(d.current=p)}else d.current?(d.current(),d.current=null):h(f);else h&&(h.current=f);a&&(f?a.mount(f):a.unmount())},[a])}const Um=v.createContext({});function ma(i){return i&&typeof i=="object"&&Object.prototype.hasOwnProperty.call(i,"current")}function Ww(i,a,l,r,d,f){const{visualElement:h}=v.useContext(Xl),p=v.useContext(Rm),y=v.useContext(vl),g=v.useContext(Iu),b=g.reducedMotion,S=g.skipAnimations,A=v.useRef(null),j=v.useRef(!1);r=r||p.renderer,!A.current&&r&&(A.current=r(i,{visualState:a,parent:h,props:l,presenceContext:y,blockInitialAnimation:y?y.initial===!1:!1,reducedMotionConfig:b,skipAnimations:S,isSVG:f}),j.current&&A.current&&(A.current.manuallyAnimateOnMount=!0));const k=A.current,D=v.useContext(Um);k&&!k.projection&&d&&(k.type==="html"||k.type==="svg")&&Qw(A.current,l,d,D);const O=v.useRef(!1);v.useInsertionEffect(()=>{k&&O.current&&k.update(l,y)});const F=l[np],Q=v.useRef(!!F&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(F)&&window.MotionHasOptimisedAnimation?.(F));return Jf(()=>{j.current=!0,k&&(O.current=!0,window.MotionIsMounted=!0,k.updateFeatures(),k.scheduleRenderMicrotask(),Q.current&&k.animationState&&k.animationState.animateChanges())}),v.useEffect(()=>{k&&(!Q.current&&k.animationState&&k.animationState.animateChanges(),Q.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(F)}),Q.current=!1),k.enteringChildren=void 0)}),k}function Qw(i,a,l,r){const{layoutId:d,layout:f,drag:h,dragConstraints:p,layoutScroll:y,layoutRoot:g,layoutAnchor:b,layoutCrossfade:S}=a;i.projection=new l(i.latestValues,a["data-framer-portal-id"]?void 0:Hm(i.parent)),i.projection.setOptions({layoutId:d,layout:f,alwaysMeasureLayout:!!h||p&&ma(p),visualElement:i,animationType:typeof f=="string"?f:"both",initialPromotionConfig:r,crossfade:S,layoutScroll:y,layoutRoot:g,layoutAnchor:b})}function Hm(i){if(i)return i.options.allowProjection!==!1?i.projection:Hm(i.parent)}function qu(i,{forwardMotionProps:a=!1,type:l}={},r,d){r&&Dw(r);const f=l?l==="svg":Gu(i),h=f?Fw:Xw;function p(g,b){let S;const A={...v.useContext(Iu),...g,layoutId:Zw(g)},{isStatic:j}=A,k=Nw(g),D=h(g,j);if(!j&&typeof window<"u"){$w();const O=Jw(A);S=O.MeasureLayout,k.visualElement=Ww(i,D,A,d,O.ProjectionNode,f)}return u.jsxs(Xl.Provider,{value:k,children:[S&&k.visualElement?u.jsx(S,{visualElement:k.visualElement,...A}):null,Yw(i,g,Kw(D,k.visualElement,b),D,j,a,f)]})}p.displayName=`motion.${typeof i=="string"?i:`create(${i.displayName??i.name??""})`}`;const y=v.forwardRef(p);return y[Pw]=i,y}function Zw({layoutId:i}){const a=v.useContext(No).id;return a&&i!==void 0?a+"-"+i:i}function $w(i,a){v.useContext(Rm).strict}function Jw(i){const a=Lm(),{drag:l,layout:r}=a;if(!l&&!r)return{};const d={...l,...r};return{MeasureLayout:l?.isEnabled(i)||r?.isEnabled(i)?d.MeasureLayout:void 0,ProjectionNode:d.ProjectionNode}}function tA(i,a){if(typeof Proxy>"u")return qu;const l=new Map,r=(f,h)=>qu(f,h,i,a),d=(f,h)=>r(f,h);return new Proxy(d,{get:(f,h)=>h==="create"?r:(l.has(h)||l.set(h,qu(h,void 0,i,a)),l.get(h))})}const eA=(i,a)=>a.isSVG??Gu(i)?new DS(a):new ES(a,{allowProjection:i!==v.Fragment});class nA extends si{constructor(a){super(a),a.animationState||(a.animationState=NS(a))}updateAnimationControlsSubscription(){const{animate:a}=this.node.getProps();Bl(a)&&(this.unmountControls=a.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:a}=this.node.getProps(),{animate:l}=this.node.prevProps||{};a!==l&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let iA=0;class aA extends si{constructor(){super(...arguments),this.id=iA++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:a,onExitComplete:l}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||a===r)return;if(a&&r===!1){if(this.isExitComplete){const{initial:f,custom:h}=this.node.getProps();if(typeof f=="string"){const p=Vi(this.node,f,h);if(p){const{transition:y,transitionEnd:g,...b}=p;for(const S in b)this.node.getValue(S)?.jump(b[S])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const d=this.node.animationState.setActive("exit",!a);l&&!a&&d.then(()=>{this.isExitComplete=!0,l(this.id)})}mount(){const{register:a,onExitComplete:l}=this.node.presenceContext||{};l&&l(this.id),a&&(this.unmount=a(this.id))}unmount(){}}const sA={animation:{Feature:nA},exit:{Feature:aA}};function bs(i){return{point:{x:i.pageX,y:i.pageY}}}const lA=i=>a=>Eu(a)&&i(a,bs(a));function vs(i,a,l,r){return xs(i,a,lA(l),r)}const Im=({current:i})=>i?i.ownerDocument.defaultView:null,Ym=(i,a)=>Math.abs(i-a);function rA(i,a){const l=Ym(i.x,a.x),r=Ym(i.y,a.y);return Math.sqrt(l**2+r**2)}const Gm=new Set(["auto","scroll"]);class qm{constructor(a,l,{transformPagePoint:r,contextWindow:d=window,dragSnapToOrigin:f=!1,distanceThreshold:h=3,element:p}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=j=>{this.handleScroll(j.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Fl(this.lastRawMoveEventInfo,this.transformPagePoint));const j=Xu(this.lastMoveEventInfo,this.history),k=this.startEvent!==null,D=rA(j.offset,{x:0,y:0})>=this.distanceThreshold;if(!k&&!D)return;const{point:O}=j,{timestamp:F}=Se;this.history.push({...O,timestamp:F});const{onStart:Q,onMove:E}=this.handlers;k||(Q&&Q(this.lastMoveEvent,j),this.startEvent=this.lastMoveEvent),E&&E(this.lastMoveEvent,j)},this.handlePointerMove=(j,k)=>{this.lastMoveEvent=j,this.lastRawMoveEventInfo=k,this.lastMoveEventInfo=Fl(k,this.transformPagePoint),Jt.update(this.updatePoint,!0)},this.handlePointerUp=(j,k)=>{this.end();const{onEnd:D,onSessionEnd:O,resumeAnimation:F}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&F&&F(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const Q=Xu(j.type==="pointercancel"?this.lastMoveEventInfo:Fl(k,this.transformPagePoint),this.history);this.startEvent&&D&&D(j,Q),O&&O(j,Q)},!Eu(a))return;this.dragSnapToOrigin=f,this.handlers=l,this.transformPagePoint=r,this.distanceThreshold=h,this.contextWindow=d||window;const y=bs(a),g=Fl(y,this.transformPagePoint),{point:b}=g,{timestamp:S}=Se;this.history=[{...b,timestamp:S}];const{onSessionStart:A}=l;A&&A(a,Xu(g,this.history)),this.removeListeners=rs(vs(this.contextWindow,"pointermove",this.handlePointerMove),vs(this.contextWindow,"pointerup",this.handlePointerUp),vs(this.contextWindow,"pointercancel",this.handlePointerUp)),p&&this.startScrollTracking(p)}startScrollTracking(a){let l=a.parentElement;for(;l;){const r=getComputedStyle(l);(Gm.has(r.overflowX)||Gm.has(r.overflowY))&&this.scrollPositions.set(l,{x:l.scrollLeft,y:l.scrollTop}),l=l.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(a){const l=this.scrollPositions.get(a);if(!l)return;const r=a===window,d=r?{x:window.scrollX,y:window.scrollY}:{x:a.scrollLeft,y:a.scrollTop},f={x:d.x-l.x,y:d.y-l.y};f.x===0&&f.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=f.x,this.lastMoveEventInfo.point.y+=f.y):this.history.length>0&&(this.history[0].x-=f.x,this.history[0].y-=f.y),this.scrollPositions.set(a,d),Jt.update(this.updatePoint,!0))}updateHandlers(a){this.handlers=a}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ni(this.updatePoint)}}function Fl(i,a){return a?{point:a(i.point)}:i}function Xm(i,a){return{x:i.x-a.x,y:i.y-a.y}}function Xu({point:i},a){return{point:i,delta:Xm(i,Fm(a)),offset:Xm(i,oA(a)),velocity:uA(a,.1)}}function oA(i){return i[0]}function Fm(i){return i[i.length-1]}function uA(i,a){if(i.length<2)return{x:0,y:0};let l=i.length-1,r=null;const d=Fm(i);for(;l>=0&&(r=i[l],!(d.timestamp-r.timestamp>Ye(a)));)l--;if(!r)return{x:0,y:0};r===i[0]&&i.length>2&&d.timestamp-r.timestamp>Ye(a)*2&&(r=i[1]);const f=tn(d.timestamp-r.timestamp);if(f===0)return{x:0,y:0};const h={x:(d.x-r.x)/f,y:(d.y-r.y)/f};return h.x===1/0&&(h.x=0),h.y===1/0&&(h.y=0),h}function cA(i,{min:a,max:l},r){return a!==void 0&&il&&(i=r?ee(l,i,r.max):Math.min(i,l)),i}function Pm(i,a,l){return{min:a!==void 0?i.min+a:void 0,max:l!==void 0?i.max+l-(i.max-i.min):void 0}}function dA(i,{top:a,left:l,bottom:r,right:d}){return{x:Pm(i.x,l,d),y:Pm(i.y,a,r)}}function Km(i,a){let l=a.min-i.min,r=a.max-i.max;return a.max-a.minr?l=os(a.min,a.max-r,i.min):r>d&&(l=os(i.min,i.max-d,a.min)),An(0,1,l)}function pA(i,a){const l={};return a.min!==void 0&&(l.min=a.min-i.min),a.max!==void 0&&(l.max=a.max-i.min),l}const Fu=.35;function mA(i=Fu){return i===!1?i=0:i===!0&&(i=Fu),{x:Wm(i,"left","right"),y:Wm(i,"top","bottom")}}function Wm(i,a,l){return{min:Qm(i,a),max:Qm(i,l)}}function Qm(i,a){return typeof i=="number"?i:i[a]||0}const gA=new WeakMap;class yA{constructor(a){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ge(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=a}start(a,{snapToCursor:l=!1,distanceThreshold:r}={}){const{presenceContext:d}=this.visualElement;if(d&&d.isPresent===!1)return;const f=S=>{l&&this.snapToCursor(bs(S).point),this.stopAnimation()},h=(S,A)=>{const{drag:j,dragPropagation:k,onDragStart:D}=this.getProps();if(j&&!k&&(this.openDragLock&&this.openDragLock(),this.openDragLock=q2(j),!this.openDragLock))return;this.latestPointerEvent=S,this.latestPanInfo=A,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),jn(F=>{let Q=this.getAxisMotionValue(F).get()||0;if(Tn.test(Q)){const{projection:E}=this.visualElement;if(E&&E.layout){const T=E.layout.layoutBox[F];T&&(Q=Re(T)*(parseFloat(Q)/100))}}this.originPoint[F]=Q}),D&&Jt.update(()=>D(S,A),!1,!0),xu(this.visualElement,"transform");const{animationState:O}=this.visualElement;O&&O.setActive("whileDrag",!0)},p=(S,A)=>{this.latestPointerEvent=S,this.latestPanInfo=A;const{dragPropagation:j,dragDirectionLock:k,onDirectionLock:D,onDrag:O}=this.getProps();if(!j&&!this.openDragLock)return;const{offset:F}=A;if(k&&this.currentDirection===null){this.currentDirection=bA(F),this.currentDirection!==null&&D&&D(this.currentDirection);return}this.updateAxis("x",A.point,F),this.updateAxis("y",A.point,F),this.visualElement.render(),O&&Jt.update(()=>O(S,A),!1,!0)},y=(S,A)=>{this.latestPointerEvent=S,this.latestPanInfo=A,this.stop(S,A),this.latestPointerEvent=null,this.latestPanInfo=null},g=()=>{const{dragSnapToOrigin:S}=this.getProps();(S||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:b}=this.getProps();this.panSession=new qm(a,{onSessionStart:f,onStart:h,onMove:p,onSessionEnd:y,resumeAnimation:g},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:b,distanceThreshold:r,contextWindow:Im(this.visualElement),element:this.visualElement.current})}stop(a,l){const r=a||this.latestPointerEvent,d=l||this.latestPanInfo,f=this.isDragging;if(this.cancel(),!f||!d||!r)return;const{velocity:h}=d;this.startAnimation(h);const{onDragEnd:p}=this.getProps();p&&Jt.postRender(()=>p(r,d))}cancel(){this.isDragging=!1;const{projection:a,animationState:l}=this.visualElement;a&&(a.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),l&&l.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(a,l,r){const{drag:d}=this.getProps();if(!r||!Pl(a,d,this.currentDirection))return;const f=this.getAxisMotionValue(a);let h=this.originPoint[a]+r[a];this.constraints&&this.constraints[a]&&(h=cA(h,this.constraints[a],this.elastic[a])),f.set(h)}resolveConstraints(){const{dragConstraints:a,dragElastic:l}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,d=this.constraints;a&&ma(a)?this.constraints||(this.constraints=this.resolveRefConstraints()):a&&r?this.constraints=dA(r.layoutBox,a):this.constraints=!1,this.elastic=mA(l),d!==this.constraints&&!ma(a)&&r&&this.constraints&&!this.hasMutatedConstraints&&jn(f=>{this.constraints!==!1&&this.getAxisMotionValue(f)&&(this.constraints[f]=pA(r.layoutBox[f],this.constraints[f]))})}resolveRefConstraints(){const{dragConstraints:a,onMeasureDragConstraints:l}=this.getProps();if(!a||!ma(a))return!1;const r=a.current,{projection:d}=this.visualElement;if(!d||!d.layout)return!1;const f=bS(r,d.root,this.visualElement.getTransformPagePoint());let h=fA(d.layout.layoutBox,f);if(l){const p=l(gS(h));this.hasMutatedConstraints=!!p,p&&(h=Mp(p))}return h}startAnimation(a){const{drag:l,dragMomentum:r,dragElastic:d,dragTransition:f,dragSnapToOrigin:h,onDragTransitionEnd:p}=this.getProps(),y=this.constraints||{},g=jn(b=>{if(!Pl(b,l,this.currentDirection))return;let S=y&&y[b]||{};(h===!0||h===b)&&(S={min:0,max:0});const A=d?200:1e6,j=d?40:1e7,k={type:"inertia",velocity:r?a[b]:0,bounceStiffness:A,bounceDamping:j,timeConstant:750,restDelta:1,restSpeed:10,...f,...S};return this.startAxisValueAnimation(b,k)});return Promise.all(g).then(p)}startAxisValueAnimation(a,l){const r=this.getAxisMotionValue(a);return xu(this.visualElement,a),r.start(mu(a,r,0,l,this.visualElement,!1))}stopAnimation(){jn(a=>this.getAxisMotionValue(a).stop())}getAxisMotionValue(a){const l=`_drag${a.toUpperCase()}`,r=this.visualElement.getProps(),d=r[l];return d||this.visualElement.getValue(a,(r.initial?r.initial[a]:void 0)||0)}snapToCursor(a){jn(l=>{const{drag:r}=this.getProps();if(!Pl(l,r,this.currentDirection))return;const{projection:d}=this.visualElement,f=this.getAxisMotionValue(l);if(d&&d.layout){const{min:h,max:p}=d.layout.layoutBox[l],y=f.get()||0;f.set(a[l]-ee(h,p,.5)+y)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:a,dragConstraints:l}=this.getProps(),{projection:r}=this.visualElement;if(!ma(l)||!r||!this.constraints)return;this.stopAnimation();const d={x:0,y:0};jn(h=>{const p=this.getAxisMotionValue(h);if(p&&this.constraints!==!1){const y=p.get();d[h]=hA({min:y,max:y},this.constraints[h])}});const{transformTemplate:f}=this.visualElement.getProps();this.visualElement.current.style.transform=f?f({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),jn(h=>{if(!Pl(h,a,null))return;const p=this.getAxisMotionValue(h),{min:y,max:g}=this.constraints[h];p.set(ee(y,g,d[h]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;gA.set(this.visualElement,this);const a=this.visualElement.current,l=vs(a,"pointerdown",g=>{const{drag:b,dragListener:S=!0}=this.getProps(),A=g.target,j=A!==a&&Q2(A);b&&S&&!j&&this.start(g)});let r;const d=()=>{const{dragConstraints:g}=this.getProps();ma(g)&&g.current&&(this.constraints=this.resolveRefConstraints(),r||(r=xA(a,g.current,()=>this.scalePositionWithinConstraints())))},{projection:f}=this.visualElement,h=f.addEventListener("measure",d);f&&!f.layout&&(f.root&&f.root.updateScroll(),f.updateLayout()),Jt.read(d);const p=xs(window,"resize",()=>this.scalePositionWithinConstraints()),y=f.addEventListener("didUpdate",(({delta:g,hasLayoutChanged:b})=>{this.isDragging&&b&&(jn(S=>{const A=this.getAxisMotionValue(S);A&&(this.originPoint[S]+=g[S].translate,A.set(A.get()+g[S].translate))}),this.visualElement.render())}));return()=>{p(),l(),h(),y&&y(),r&&r()}}getProps(){const a=this.visualElement.getProps(),{drag:l=!1,dragDirectionLock:r=!1,dragPropagation:d=!1,dragConstraints:f=!1,dragElastic:h=Fu,dragMomentum:p=!0}=a;return{...a,drag:l,dragDirectionLock:r,dragPropagation:d,dragConstraints:f,dragElastic:h,dragMomentum:p}}}function Zm(i){let a=!0;return()=>{if(a){a=!1;return}i()}}function xA(i,a,l){const r=vp(i,Zm(l)),d=vp(a,Zm(l));return()=>{r(),d()}}function Pl(i,a,l){return(a===!0||a===i)&&(l===null||l===i)}function bA(i,a=10){let l=null;return Math.abs(i.y)>a?l="y":Math.abs(i.x)>a&&(l="x"),l}class vA extends si{constructor(a){super(a),this.removeGroupControls=Je,this.removeListeners=Je,this.controls=new yA(a)}mount(){const{dragControls:a}=this.node.getProps();a&&(this.removeGroupControls=a.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Je}update(){const{dragControls:a}=this.node.getProps(),{dragControls:l}=this.node.prevProps||{};a!==l&&(this.removeGroupControls(),a&&(this.removeGroupControls=a.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Pu=i=>(a,l)=>{i&&Jt.update(()=>i(a,l),!1,!0)};class SA extends si{constructor(){super(...arguments),this.removePointerDownListener=Je}onPointerDown(a){this.session=new qm(a,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Im(this.node)})}createPanHandlers(){const{onPanSessionStart:a,onPanStart:l,onPan:r,onPanEnd:d}=this.node.getProps();return{onSessionStart:Pu(a),onStart:Pu(l),onMove:Pu(r),onEnd:(f,h)=>{delete this.session,d&&Jt.postRender(()=>d(f,h))}}}mount(){this.removePointerDownListener=vs(this.node.current,"pointerdown",a=>this.onPointerDown(a))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let Ku=!1;class wA extends v.Component{componentDidMount(){const{visualElement:a,layoutGroup:l,switchLayoutGroup:r,layoutId:d}=this.props,{projection:f}=a;f&&(l.group&&l.group.add(f),r&&r.register&&d&&r.register(f),Ku&&f.root.didUpdate(),f.addEventListener("animationComplete",()=>{this.safeToRemove()}),f.setOptions({...f.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Yl.hasEverUpdated=!0}getSnapshotBeforeUpdate(a){const{layoutDependency:l,visualElement:r,drag:d,isPresent:f}=this.props,{projection:h}=r;return h&&(h.isPresent=f,a.layoutDependency!==l&&h.setOptions({...h.options,layoutDependency:l}),Ku=!0,d||a.layoutDependency!==l||l===void 0||a.isPresent!==f?h.willUpdate():this.safeToRemove(),a.isPresent!==f&&(f?h.promote():h.relegate()||Jt.postRender(()=>{const p=h.getStack();(!p||!p.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:a,layoutAnchor:l}=this.props,{projection:r}=a;r&&(r.options.layoutAnchor=l,r.root.didUpdate(),Tu.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:a,layoutGroup:l,switchLayoutGroup:r}=this.props,{projection:d}=a;Ku=!0,d&&(d.scheduleCheckAfterUnmount(),l&&l.group&&l.group.remove(d),r&&r.deregister&&r.deregister(d))}safeToRemove(){const{safeToRemove:a}=this.props;a&&a()}render(){return null}}function $m(i){const[a,l]=Mm(),r=v.useContext(No);return u.jsx(wA,{...i,layoutGroup:r,switchLayoutGroup:v.useContext(Um),isPresent:a,safeToRemove:l})}const AA={pan:{Feature:SA},drag:{Feature:vA,ProjectionNode:jm,MeasureLayout:$m}};function Jm(i,a,l){const{props:r}=i;i.animationState&&r.whileHover&&i.animationState.setActive("whileHover",l==="Start");const d="onHover"+l,f=r[d];f&&Jt.postRender(()=>f(a,bs(a)))}class TA extends si{mount(){const{current:a}=this.node;a&&(this.unmount=F2(a,(l,r)=>(Jm(this.node,r,"Start"),d=>Jm(this.node,d,"End"))))}unmount(){}}class EA extends si{constructor(){super(...arguments),this.isActive=!1}onFocus(){let a=!1;try{a=this.node.current.matches(":focus-visible")}catch{a=!0}!a||!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=rs(xs(this.node.current,"focus",()=>this.onFocus()),xs(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function tg(i,a,l){const{props:r}=i;if(i.current instanceof HTMLButtonElement&&i.current.disabled)return;i.animationState&&r.whileTap&&i.animationState.setActive("whileTap",l==="Start");const d="onTap"+(l==="End"?"":l),f=r[d];f&&Jt.postRender(()=>f(a,bs(a)))}class jA extends si{mount(){const{current:a}=this.node;if(!a)return;const{globalTapTarget:l,propagate:r}=this.node.props;this.unmount=$2(a,(d,f)=>(tg(this.node,f,"Start"),(h,{success:p})=>tg(this.node,h,p?"End":"Cancel")),{useGlobalTarget:l,stopPropagation:r?.tap===!1})}unmount(){}}const Wu=new WeakMap,Qu=new WeakMap,CA=i=>{const a=Wu.get(i.target);a&&a(i)},MA=i=>{i.forEach(CA)};function kA({root:i,...a}){const l=i||document;Qu.has(l)||Qu.set(l,{});const r=Qu.get(l),d=JSON.stringify(a);return r[d]||(r[d]=new IntersectionObserver(MA,{root:i,...a})),r[d]}function RA(i,a,l){const r=kA(a);return Wu.set(i,l),r.observe(i),()=>{Wu.delete(i),r.unobserve(i)}}const DA={some:0,all:1};class zA extends si{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:a={}}=this.node.getProps(),{root:l,margin:r,amount:d="some",once:f}=a,h={root:l?l.current:void 0,rootMargin:r,threshold:typeof d=="number"?d:DA[d]},p=y=>{const{isIntersecting:g}=y;if(this.isInView===g||(this.isInView=g,f&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:b,onViewportLeave:S}=this.node.getProps(),A=g?b:S;A&&A(y)};this.stopObserver=RA(this.node.current,h,p)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:a,prevProps:l}=this.node;["amount","margin","root"].some(LA(a,l))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function LA({viewport:i={}},{viewport:a={}}={}){return l=>i[l]!==a[l]}const OA={...sA,...{inView:{Feature:zA},tap:{Feature:jA},focus:{Feature:EA},hover:{Feature:TA}},...AA,...{layout:{ProjectionNode:jm,MeasureLayout:$m}}},Oe=tA(OA,eA),gt="'Geist', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",Kl="https://cdn.jsdelivr.net/npm/geist@1.3.1/dist/fonts/geist-sans",BA=` + `),()=>{p.current?.removeAttribute("data-motion-pop-id"),L.contains(T)&&L.removeChild(T)}},[a]),u.jsx(Fw,{isPresent:a,childRef:p,sizeRef:y,pop:f,children:f===!1?n:v.cloneElement(n,{ref:w})})}const Xw=({children:n,initial:a,isPresent:l,onExitComplete:r,custom:d,presenceAffectsLayout:f,mode:h,anchorX:p,anchorY:y,root:g})=>{const b=Go(Pw),w=v.useId();let A=!0,j=v.useMemo(()=>(A=!1,{id:w,initial:a,isPresent:l,custom:d,onExitComplete:k=>{b.set(k,!0);for(const D of b.values())if(!D)return;r&&r()},register:k=>(b.set(k,!1),()=>b.delete(k))}),[l,b,r]);return f&&A&&(j={...j}),v.useMemo(()=>{b.forEach((k,D)=>b.set(D,!1))},[l]),v.useEffect(()=>{!l&&!b.size&&r&&r()},[l]),n=u.jsx(qw,{pop:h==="popLayout",isPresent:l,anchorX:p,anchorY:y,root:g,children:n}),u.jsx(jl.Provider,{value:j,children:n})};function Pw(){return new Map}function Um(n=!0){const a=v.useContext(jl);if(a===null)return[!0,null];const{isPresent:l,onExitComplete:r,register:d}=a,f=v.useId();v.useEffect(()=>{if(n)return d(f)},[n]);const h=v.useCallback(()=>n&&r&&r(f),[f,r,n]);return!l&&r?[!1,h]:[!0]}const Wl=n=>n.key||"";function Hm(n){const a=[];return v.Children.forEach(n,l=>{v.isValidElement(l)&&a.push(l)}),a}const Nn=({children:n,custom:a,initial:l=!0,onExitComplete:r,presenceAffectsLayout:d=!0,mode:f="sync",propagate:h=!1,anchorX:p="left",anchorY:y="top",root:g})=>{const[b,w]=Um(h),A=v.useMemo(()=>Hm(n),[n]),j=h&&!b?[]:A.map(Wl),k=v.useRef(!0),D=v.useRef(A),O=Go(()=>new Map),q=v.useRef(new Set),[W,E]=v.useState(A),[T,L]=v.useState(A);uh(()=>{k.current=!1,D.current=A;for(let $=0;${const F=Wl($),K=h&&!b?!1:A===T||j.includes(F),lt=()=>{if(q.current.has(F))return;if(O.has(F))q.current.add(F),O.set(F,!0);else return;let it=!0;O.forEach(rt=>{rt||(it=!1)}),it&&(J?.(),L(D.current),h&&w?.(),r&&r())};return u.jsx(Xw,{isPresent:K,initial:!k.current||l?void 0:!1,custom:a,presenceAffectsLayout:d,mode:f,root:g,onExitComplete:K?void 0:lt,anchorX:p,anchorY:y,children:$},F)})})},Vm=v.createContext({strict:!1}),Im={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 Ym=!1;function Kw(){if(Ym)return;const n={};for(const a in Im)n[a]={isEnabled:l=>Im[a].some(r=>!!l[r])};Np(n),Ym=!0}function Gm(){return Kw(),zS()}function Ww(n){const a=Gm();for(const l in n)a[l]={...a[l],...n[l]};Np(a)}const Qw=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","propagate","ignoreStrict","viewport"]);function Ql(n){return n.startsWith("while")||n.startsWith("drag")&&n!=="draggable"||n.startsWith("layout")||n.startsWith("onTap")||n.startsWith("onPan")||n.startsWith("onLayout")||Qw.has(n)}let Fm=n=>!Ql(n);function Zw(n){typeof n=="function"&&(Fm=a=>a.startsWith("on")?!Ql(a):n(a))}try{Zw(require("@emotion/is-prop-valid").default)}catch{}function $w(n,a,l){const r={};for(const d in n)d==="values"&&typeof n.values=="object"||Ae(n[d])||(Fm(d)||l===!0&&Ql(d)||!a&&!Ql(d)||n.draggable&&d.startsWith("onDrag"))&&(r[d]=n[d]);return r}const Zl=v.createContext({});function Jw(n,a){if(Yl(n)){const{initial:l,animate:r}=n;return{initial:l===!1||vs(l)?l:void 0,animate:vs(r)?r:void 0}}return n.inherit!==!1?a:{}}function tA(n){const{initial:a,animate:l}=Jw(n,v.useContext(Zl));return v.useMemo(()=>({initial:a,animate:l}),[qm(a),qm(l)])}function qm(n){return Array.isArray(n)?n.join(" "):n}const Ku=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Xm(n,a,l){for(const r in a)!Ae(a[r])&&!Qp(r,l)&&(n[r]=a[r])}function eA({transformTemplate:n},a){return v.useMemo(()=>{const l=Ku();return Vu(l,a,n),Object.assign({},l.vars,l.style)},[a])}function nA(n,a){const l=n.style||{},r={};return Xm(r,l,n),Object.assign(r,eA(n,a)),r}function iA(n,a){const l={},r=nA(n,a);return n.drag&&n.dragListener!==!1&&(l.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=n.drag===!0?"none":`pan-${n.drag==="x"?"y":"x"}`),n.tabIndex===void 0&&(n.onTap||n.onTapStart||n.whileTap)&&(l.tabIndex=0),l.style=r,l}const Pm=()=>({...Ku(),attrs:{}});function aA(n,a,l,r){const d=v.useMemo(()=>{const f=Pm();return Zp(f,a,Jp(r),n.transformTemplate,n.style),{...f.attrs,style:{...f.style}}},[a]);if(n.style){const f={};Xm(f,n.style,n),d.style={...f,...d.style}}return d}const sA=["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 Wu(n){return typeof n!="string"||n.includes("-")?!1:!!(sA.indexOf(n)>-1||/[A-Z]/u.test(n))}function lA(n,a,l,{latestValues:r},d,f=!1,h){const y=(h??Wu(n)?aA:iA)(a,r,d,n),g=$w(a,typeof n=="string",f),b=n!==v.Fragment?{...g,...y,ref:l}:{},{children:w}=a,A=v.useMemo(()=>Ae(w)?w.get():w,[w]);return v.createElement(n,{...b,children:A})}function rA({scrapeMotionValuesFromProps:n,createRenderState:a},l,r,d){return{latestValues:oA(l,r,d,n),renderState:a()}}function oA(n,a,l,r){const d={},f=r(n,{});for(const A in f)d[A]=Pl(f[A]);let{initial:h,animate:p}=n;const y=Yl(n),g=Lp(n);a&&g&&!y&&n.inherit!==!1&&(h===void 0&&(h=a.initial),p===void 0&&(p=a.animate));let b=l?l.initial===!1:!1;b=b||h===!1;const w=b?p:h;if(w&&typeof w!="boolean"&&!Il(w)){const A=Array.isArray(w)?w:[w];for(let j=0;j(a,l)=>{const r=v.useContext(Zl),d=v.useContext(jl),f=()=>rA(n,a,r,d);return l?f():Go(f)},uA=Km({scrapeMotionValuesFromProps:Yu,createRenderState:Ku}),cA=Km({scrapeMotionValuesFromProps:tm,createRenderState:Pm}),dA=Symbol.for("motionComponentSymbol");function fA(n,a,l){const r=v.useRef(l);v.useInsertionEffect(()=>{r.current=l});const d=v.useRef(null);return v.useCallback(f=>{f&&n.onMount?.(f);const h=r.current;if(typeof h=="function")if(f){const p=h(f);typeof p=="function"&&(d.current=p)}else d.current?(d.current(),d.current=null):h(f);else h&&(h.current=f);a&&(f?a.mount(f):a.unmount())},[a])}const Wm=v.createContext({});function va(n){return n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"current")}function hA(n,a,l,r,d,f){const{visualElement:h}=v.useContext(Zl),p=v.useContext(Vm),y=v.useContext(jl),g=v.useContext(Pu),b=g.reducedMotion,w=g.skipAnimations,A=v.useRef(null),j=v.useRef(!1);r=r||p.renderer,!A.current&&r&&(A.current=r(n,{visualState:a,parent:h,props:l,presenceContext:y,blockInitialAnimation:y?y.initial===!1:!1,reducedMotionConfig:b,skipAnimations:w,isSVG:f}),j.current&&A.current&&(A.current.manuallyAnimateOnMount=!0));const k=A.current,D=v.useContext(Wm);k&&!k.projection&&d&&(k.type==="html"||k.type==="svg")&&pA(A.current,l,d,D);const O=v.useRef(!1);v.useInsertionEffect(()=>{k&&O.current&&k.update(l,y)});const q=l[fp],W=v.useRef(!!q&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(q)&&window.MotionHasOptimisedAnimation?.(q));return uh(()=>{j.current=!0,k&&(O.current=!0,window.MotionIsMounted=!0,k.updateFeatures(),k.scheduleRenderMicrotask(),W.current&&k.animationState&&k.animationState.animateChanges())}),v.useEffect(()=>{k&&(!W.current&&k.animationState&&k.animationState.animateChanges(),W.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(q)}),W.current=!1),k.enteringChildren=void 0)}),k}function pA(n,a,l,r){const{layoutId:d,layout:f,drag:h,dragConstraints:p,layoutScroll:y,layoutRoot:g,layoutAnchor:b,layoutCrossfade:w}=a;n.projection=new l(n.latestValues,a["data-framer-portal-id"]?void 0:Qm(n.parent)),n.projection.setOptions({layoutId:d,layout:f,alwaysMeasureLayout:!!h||p&&va(p),visualElement:n,animationType:typeof f=="string"?f:"both",initialPromotionConfig:r,crossfade:w,layoutScroll:y,layoutRoot:g,layoutAnchor:b})}function Qm(n){if(n)return n.options.allowProjection!==!1?n.projection:Qm(n.parent)}function Qu(n,{forwardMotionProps:a=!1,type:l}={},r,d){r&&Ww(r);const f=l?l==="svg":Wu(n),h=f?cA:uA;function p(g,b){let w;const A={...v.useContext(Pu),...g,layoutId:mA(g)},{isStatic:j}=A,k=tA(g),D=h(g,j);if(!j&&typeof window<"u"){gA();const O=yA(A);w=O.MeasureLayout,k.visualElement=hA(n,D,A,d,O.ProjectionNode,f)}return u.jsxs(Zl.Provider,{value:k,children:[w&&k.visualElement?u.jsx(w,{visualElement:k.visualElement,...A}):null,lA(n,g,fA(D,k.visualElement,b),D,j,a,f)]})}p.displayName=`motion.${typeof n=="string"?n:`create(${n.displayName??n.name??""})`}`;const y=v.forwardRef(p);return y[dA]=n,y}function mA({layoutId:n}){const a=v.useContext(Yo).id;return a&&n!==void 0?a+"-"+n:n}function gA(n,a){v.useContext(Vm).strict}function yA(n){const a=Gm(),{drag:l,layout:r}=a;if(!l&&!r)return{};const d={...l,...r};return{MeasureLayout:l?.isEnabled(n)||r?.isEnabled(n)?d.MeasureLayout:void 0,ProjectionNode:d.ProjectionNode}}function xA(n,a){if(typeof Proxy>"u")return Qu;const l=new Map,r=(f,h)=>Qu(f,h,n,a),d=(f,h)=>r(f,h);return new Proxy(d,{get:(f,h)=>h==="create"?r:(l.has(h)||l.set(h,Qu(h,void 0,n,a)),l.get(h))})}const bA=(n,a)=>a.isSVG??Wu(n)?new WS(a):new GS(a,{allowProjection:n!==v.Fragment});class vA extends ri{constructor(a){super(a),a.animationState||(a.animationState=tw(a))}updateAnimationControlsSubscription(){const{animate:a}=this.node.getProps();Il(a)&&(this.unmountControls=a.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:a}=this.node.getProps(),{animate:l}=this.node.prevProps||{};a!==l&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let SA=0;class wA extends ri{constructor(){super(...arguments),this.id=SA++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:a,onExitComplete:l}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||a===r)return;if(a&&r===!1){if(this.isExitComplete){const{initial:f,custom:h}=this.node.getProps();if(typeof f=="string"){const p=Ii(this.node,f,h);if(p){const{transition:y,transitionEnd:g,...b}=p;for(const w in b)this.node.getValue(w)?.jump(b[w])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const d=this.node.animationState.setActive("exit",!a);l&&!a&&d.then(()=>{this.isExitComplete=!0,l(this.id)})}mount(){const{register:a,onExitComplete:l}=this.node.presenceContext||{};l&&l(this.id),a&&(this.unmount=a(this.id))}unmount(){}}const AA={animation:{Feature:vA},exit:{Feature:wA}};function Ts(n){return{point:{x:n.pageX,y:n.pageY}}}const TA=n=>a=>Du(a)&&n(a,Ts(a));function Es(n,a,l,r){return As(n,a,TA(l),r)}const Zm=({current:n})=>n?n.ownerDocument.defaultView:null,$m=(n,a)=>Math.abs(n-a);function EA(n,a){const l=$m(n.x,a.x),r=$m(n.y,a.y);return Math.sqrt(l**2+r**2)}const Jm=new Set(["auto","scroll"]);class tg{constructor(a,l,{transformPagePoint:r,contextWindow:d=window,dragSnapToOrigin:f=!1,distanceThreshold:h=3,element:p}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=j=>{this.handleScroll(j.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=$l(this.lastRawMoveEventInfo,this.transformPagePoint));const j=Zu(this.lastMoveEventInfo,this.history),k=this.startEvent!==null,D=EA(j.offset,{x:0,y:0})>=this.distanceThreshold;if(!k&&!D)return;const{point:O}=j,{timestamp:q}=we;this.history.push({...O,timestamp:q});const{onStart:W,onMove:E}=this.handlers;k||(W&&W(this.lastMoveEvent,j),this.startEvent=this.lastMoveEvent),E&&E(this.lastMoveEvent,j)},this.handlePointerMove=(j,k)=>{this.lastMoveEvent=j,this.lastRawMoveEventInfo=k,this.lastMoveEventInfo=$l(k,this.transformPagePoint),Jt.update(this.updatePoint,!0)},this.handlePointerUp=(j,k)=>{this.end();const{onEnd:D,onSessionEnd:O,resumeAnimation:q}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&q&&q(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const W=Zu(j.type==="pointercancel"?this.lastMoveEventInfo:$l(k,this.transformPagePoint),this.history);this.startEvent&&D&&D(j,W),O&&O(j,W)},!Du(a))return;this.dragSnapToOrigin=f,this.handlers=l,this.transformPagePoint=r,this.distanceThreshold=h,this.contextWindow=d||window;const y=Ts(a),g=$l(y,this.transformPagePoint),{point:b}=g,{timestamp:w}=we;this.history=[{...b,timestamp:w}];const{onSessionStart:A}=l;A&&A(a,Zu(g,this.history)),this.removeListeners=fs(Es(this.contextWindow,"pointermove",this.handlePointerMove),Es(this.contextWindow,"pointerup",this.handlePointerUp),Es(this.contextWindow,"pointercancel",this.handlePointerUp)),p&&this.startScrollTracking(p)}startScrollTracking(a){let l=a.parentElement;for(;l;){const r=getComputedStyle(l);(Jm.has(r.overflowX)||Jm.has(r.overflowY))&&this.scrollPositions.set(l,{x:l.scrollLeft,y:l.scrollTop}),l=l.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(a){const l=this.scrollPositions.get(a);if(!l)return;const r=a===window,d=r?{x:window.scrollX,y:window.scrollY}:{x:a.scrollLeft,y:a.scrollTop},f={x:d.x-l.x,y:d.y-l.y};f.x===0&&f.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=f.x,this.lastMoveEventInfo.point.y+=f.y):this.history.length>0&&(this.history[0].x-=f.x,this.history[0].y-=f.y),this.scrollPositions.set(a,d),Jt.update(this.updatePoint,!0))}updateHandlers(a){this.handlers=a}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ai(this.updatePoint)}}function $l(n,a){return a?{point:a(n.point)}:n}function eg(n,a){return{x:n.x-a.x,y:n.y-a.y}}function Zu({point:n},a){return{point:n,delta:eg(n,ng(a)),offset:eg(n,jA(a)),velocity:CA(a,.1)}}function jA(n){return n[0]}function ng(n){return n[n.length-1]}function CA(n,a){if(n.length<2)return{x:0,y:0};let l=n.length-1,r=null;const d=ng(n);for(;l>=0&&(r=n[l],!(d.timestamp-r.timestamp>Ge(a)));)l--;if(!r)return{x:0,y:0};r===n[0]&&n.length>2&&d.timestamp-r.timestamp>Ge(a)*2&&(r=n[1]);const f=en(d.timestamp-r.timestamp);if(f===0)return{x:0,y:0};const h={x:(d.x-r.x)/f,y:(d.y-r.y)/f};return h.x===1/0&&(h.x=0),h.y===1/0&&(h.y=0),h}function MA(n,{min:a,max:l},r){return a!==void 0&&nl&&(n=r?ee(l,n,r.max):Math.min(n,l)),n}function ig(n,a,l){return{min:a!==void 0?n.min+a:void 0,max:l!==void 0?n.max+l-(n.max-n.min):void 0}}function kA(n,{top:a,left:l,bottom:r,right:d}){return{x:ig(n.x,l,d),y:ig(n.y,a,r)}}function ag(n,a){let l=a.min-n.min,r=a.max-n.max;return a.max-a.minr?l=hs(a.min,a.max-r,n.min):r>d&&(l=hs(n.min,n.max-d,a.min)),En(0,1,l)}function zA(n,a){const l={};return a.min!==void 0&&(l.min=a.min-n.min),a.max!==void 0&&(l.max=a.max-n.min),l}const $u=.35;function LA(n=$u){return n===!1?n=0:n===!0&&(n=$u),{x:sg(n,"left","right"),y:sg(n,"top","bottom")}}function sg(n,a,l){return{min:lg(n,a),max:lg(n,l)}}function lg(n,a){return typeof n=="number"?n:n[a]||0}const OA=new WeakMap;class BA{constructor(a){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ge(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=a}start(a,{snapToCursor:l=!1,distanceThreshold:r}={}){const{presenceContext:d}=this.visualElement;if(d&&d.isPresent===!1)return;const f=w=>{l&&this.snapToCursor(Ts(w).point),this.stopAnimation()},h=(w,A)=>{const{drag:j,dragPropagation:k,onDragStart:D}=this.getProps();if(j&&!k&&(this.openDragLock&&this.openDragLock(),this.openDragLock=oS(j),!this.openDragLock))return;this.latestPointerEvent=w,this.latestPanInfo=A,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Mn(q=>{let W=this.getAxisMotionValue(q).get()||0;if(jn.test(W)){const{projection:E}=this.visualElement;if(E&&E.layout){const T=E.layout.layoutBox[q];T&&(W=De(T)*(parseFloat(W)/100))}}this.originPoint[q]=W}),D&&Jt.update(()=>D(w,A),!1,!0),Tu(this.visualElement,"transform");const{animationState:O}=this.visualElement;O&&O.setActive("whileDrag",!0)},p=(w,A)=>{this.latestPointerEvent=w,this.latestPanInfo=A;const{dragPropagation:j,dragDirectionLock:k,onDirectionLock:D,onDrag:O}=this.getProps();if(!j&&!this.openDragLock)return;const{offset:q}=A;if(k&&this.currentDirection===null){this.currentDirection=_A(q),this.currentDirection!==null&&D&&D(this.currentDirection);return}this.updateAxis("x",A.point,q),this.updateAxis("y",A.point,q),this.visualElement.render(),O&&Jt.update(()=>O(w,A),!1,!0)},y=(w,A)=>{this.latestPointerEvent=w,this.latestPanInfo=A,this.stop(w,A),this.latestPointerEvent=null,this.latestPanInfo=null},g=()=>{const{dragSnapToOrigin:w}=this.getProps();(w||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:b}=this.getProps();this.panSession=new tg(a,{onSessionStart:f,onStart:h,onMove:p,onSessionEnd:y,resumeAnimation:g},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:b,distanceThreshold:r,contextWindow:Zm(this.visualElement),element:this.visualElement.current})}stop(a,l){const r=a||this.latestPointerEvent,d=l||this.latestPanInfo,f=this.isDragging;if(this.cancel(),!f||!d||!r)return;const{velocity:h}=d;this.startAnimation(h);const{onDragEnd:p}=this.getProps();p&&Jt.postRender(()=>p(r,d))}cancel(){this.isDragging=!1;const{projection:a,animationState:l}=this.visualElement;a&&(a.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),l&&l.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(a,l,r){const{drag:d}=this.getProps();if(!r||!Jl(a,d,this.currentDirection))return;const f=this.getAxisMotionValue(a);let h=this.originPoint[a]+r[a];this.constraints&&this.constraints[a]&&(h=MA(h,this.constraints[a],this.elastic[a])),f.set(h)}resolveConstraints(){const{dragConstraints:a,dragElastic:l}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,d=this.constraints;a&&va(a)?this.constraints||(this.constraints=this.resolveRefConstraints()):a&&r?this.constraints=kA(r.layoutBox,a):this.constraints=!1,this.elastic=LA(l),d!==this.constraints&&!va(a)&&r&&this.constraints&&!this.hasMutatedConstraints&&Mn(f=>{this.constraints!==!1&&this.getAxisMotionValue(f)&&(this.constraints[f]=zA(r.layoutBox[f],this.constraints[f]))})}resolveRefConstraints(){const{dragConstraints:a,onMeasureDragConstraints:l}=this.getProps();if(!a||!va(a))return!1;const r=a.current,{projection:d}=this.visualElement;if(!d||!d.layout)return!1;const f=_S(r,d.root,this.visualElement.getTransformPagePoint());let h=RA(d.layout.layoutBox,f);if(l){const p=l(OS(h));this.hasMutatedConstraints=!!p,p&&(h=Up(p))}return h}startAnimation(a){const{drag:l,dragMomentum:r,dragElastic:d,dragTransition:f,dragSnapToOrigin:h,onDragTransitionEnd:p}=this.getProps(),y=this.constraints||{},g=Mn(b=>{if(!Jl(b,l,this.currentDirection))return;let w=y&&y[b]||{};(h===!0||h===b)&&(w={min:0,max:0});const A=d?200:1e6,j=d?40:1e7,k={type:"inertia",velocity:r?a[b]:0,bounceStiffness:A,bounceDamping:j,timeConstant:750,restDelta:1,restSpeed:10,...f,...w};return this.startAxisValueAnimation(b,k)});return Promise.all(g).then(p)}startAxisValueAnimation(a,l){const r=this.getAxisMotionValue(a);return Tu(this.visualElement,a),r.start(Su(a,r,0,l,this.visualElement,!1))}stopAnimation(){Mn(a=>this.getAxisMotionValue(a).stop())}getAxisMotionValue(a){const l=`_drag${a.toUpperCase()}`,r=this.visualElement.getProps(),d=r[l];return d||this.visualElement.getValue(a,(r.initial?r.initial[a]:void 0)||0)}snapToCursor(a){Mn(l=>{const{drag:r}=this.getProps();if(!Jl(l,r,this.currentDirection))return;const{projection:d}=this.visualElement,f=this.getAxisMotionValue(l);if(d&&d.layout){const{min:h,max:p}=d.layout.layoutBox[l],y=f.get()||0;f.set(a[l]-ee(h,p,.5)+y)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:a,dragConstraints:l}=this.getProps(),{projection:r}=this.visualElement;if(!va(l)||!r||!this.constraints)return;this.stopAnimation();const d={x:0,y:0};Mn(h=>{const p=this.getAxisMotionValue(h);if(p&&this.constraints!==!1){const y=p.get();d[h]=DA({min:y,max:y},this.constraints[h])}});const{transformTemplate:f}=this.visualElement.getProps();this.visualElement.current.style.transform=f?f({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),Mn(h=>{if(!Jl(h,a,null))return;const p=this.getAxisMotionValue(h),{min:y,max:g}=this.constraints[h];p.set(ee(y,g,d[h]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;OA.set(this.visualElement,this);const a=this.visualElement.current,l=Es(a,"pointerdown",g=>{const{drag:b,dragListener:w=!0}=this.getProps(),A=g.target,j=A!==a&&pS(A);b&&w&&!j&&this.start(g)});let r;const d=()=>{const{dragConstraints:g}=this.getProps();va(g)&&g.current&&(this.constraints=this.resolveRefConstraints(),r||(r=NA(a,g.current,()=>this.scalePositionWithinConstraints())))},{projection:f}=this.visualElement,h=f.addEventListener("measure",d);f&&!f.layout&&(f.root&&f.root.updateScroll(),f.updateLayout()),Jt.read(d);const p=As(window,"resize",()=>this.scalePositionWithinConstraints()),y=f.addEventListener("didUpdate",(({delta:g,hasLayoutChanged:b})=>{this.isDragging&&b&&(Mn(w=>{const A=this.getAxisMotionValue(w);A&&(this.originPoint[w]+=g[w].translate,A.set(A.get()+g[w].translate))}),this.visualElement.render())}));return()=>{p(),l(),h(),y&&y(),r&&r()}}getProps(){const a=this.visualElement.getProps(),{drag:l=!1,dragDirectionLock:r=!1,dragPropagation:d=!1,dragConstraints:f=!1,dragElastic:h=$u,dragMomentum:p=!0}=a;return{...a,drag:l,dragDirectionLock:r,dragPropagation:d,dragConstraints:f,dragElastic:h,dragMomentum:p}}}function rg(n){let a=!0;return()=>{if(a){a=!1;return}n()}}function NA(n,a,l){const r=Rp(n,rg(l)),d=Rp(a,rg(l));return()=>{r(),d()}}function Jl(n,a,l){return(a===!0||a===n)&&(l===null||l===n)}function _A(n,a=10){let l=null;return Math.abs(n.y)>a?l="y":Math.abs(n.x)>a&&(l="x"),l}class UA extends ri{constructor(a){super(a),this.removeGroupControls=tn,this.removeListeners=tn,this.controls=new BA(a)}mount(){const{dragControls:a}=this.node.getProps();a&&(this.removeGroupControls=a.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||tn}update(){const{dragControls:a}=this.node.getProps(),{dragControls:l}=this.node.prevProps||{};a!==l&&(this.removeGroupControls(),a&&(this.removeGroupControls=a.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Ju=n=>(a,l)=>{n&&Jt.update(()=>n(a,l),!1,!0)};class HA extends ri{constructor(){super(...arguments),this.removePointerDownListener=tn}onPointerDown(a){this.session=new tg(a,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Zm(this.node)})}createPanHandlers(){const{onPanSessionStart:a,onPanStart:l,onPan:r,onPanEnd:d}=this.node.getProps();return{onSessionStart:Ju(a),onStart:Ju(l),onMove:Ju(r),onEnd:(f,h)=>{delete this.session,d&&Jt.postRender(()=>d(f,h))}}}mount(){this.removePointerDownListener=Es(this.node.current,"pointerdown",a=>this.onPointerDown(a))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let tc=!1;class VA extends v.Component{componentDidMount(){const{visualElement:a,layoutGroup:l,switchLayoutGroup:r,layoutId:d}=this.props,{projection:f}=a;f&&(l.group&&l.group.add(f),r&&r.register&&d&&r.register(f),tc&&f.root.didUpdate(),f.addEventListener("animationComplete",()=>{this.safeToRemove()}),f.setOptions({...f.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Kl.hasEverUpdated=!0}getSnapshotBeforeUpdate(a){const{layoutDependency:l,visualElement:r,drag:d,isPresent:f}=this.props,{projection:h}=r;return h&&(h.isPresent=f,a.layoutDependency!==l&&h.setOptions({...h.options,layoutDependency:l}),tc=!0,d||a.layoutDependency!==l||l===void 0||a.isPresent!==f?h.willUpdate():this.safeToRemove(),a.isPresent!==f&&(f?h.promote():h.relegate()||Jt.postRender(()=>{const p=h.getStack();(!p||!p.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:a,layoutAnchor:l}=this.props,{projection:r}=a;r&&(r.options.layoutAnchor=l,r.root.didUpdate(),Ru.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:a,layoutGroup:l,switchLayoutGroup:r}=this.props,{projection:d}=a;tc=!0,d&&(d.scheduleCheckAfterUnmount(),l&&l.group&&l.group.remove(d),r&&r.deregister&&r.deregister(d))}safeToRemove(){const{safeToRemove:a}=this.props;a&&a()}render(){return null}}function og(n){const[a,l]=Um(),r=v.useContext(Yo);return u.jsx(VA,{...n,layoutGroup:r,switchLayoutGroup:v.useContext(Wm),isPresent:a,safeToRemove:l})}const IA={pan:{Feature:HA},drag:{Feature:UA,ProjectionNode:Nm,MeasureLayout:og}};function ug(n,a,l){const{props:r}=n;n.animationState&&r.whileHover&&n.animationState.setActive("whileHover",l==="Start");const d="onHover"+l,f=r[d];f&&Jt.postRender(()=>f(a,Ts(a)))}class YA extends ri{mount(){const{current:a}=this.node;a&&(this.unmount=cS(a,(l,r)=>(ug(this.node,r,"Start"),d=>ug(this.node,d,"End"))))}unmount(){}}class GA extends ri{constructor(){super(...arguments),this.isActive=!1}onFocus(){let a=!1;try{a=this.node.current.matches(":focus-visible")}catch{a=!0}!a||!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=fs(As(this.node.current,"focus",()=>this.onFocus()),As(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function cg(n,a,l){const{props:r}=n;if(n.current instanceof HTMLButtonElement&&n.current.disabled)return;n.animationState&&r.whileTap&&n.animationState.setActive("whileTap",l==="Start");const d="onTap"+(l==="End"?"":l),f=r[d];f&&Jt.postRender(()=>f(a,Ts(a)))}class FA extends ri{mount(){const{current:a}=this.node;if(!a)return;const{globalTapTarget:l,propagate:r}=this.node.props;this.unmount=gS(a,(d,f)=>(cg(this.node,f,"Start"),(h,{success:p})=>cg(this.node,h,p?"End":"Cancel")),{useGlobalTarget:l,stopPropagation:r?.tap===!1})}unmount(){}}const ec=new WeakMap,nc=new WeakMap,qA=n=>{const a=ec.get(n.target);a&&a(n)},XA=n=>{n.forEach(qA)};function PA({root:n,...a}){const l=n||document;nc.has(l)||nc.set(l,{});const r=nc.get(l),d=JSON.stringify(a);return r[d]||(r[d]=new IntersectionObserver(XA,{root:n,...a})),r[d]}function KA(n,a,l){const r=PA(a);return ec.set(n,l),r.observe(n),()=>{ec.delete(n),r.unobserve(n)}}const WA={some:0,all:1};class QA extends ri{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:a={}}=this.node.getProps(),{root:l,margin:r,amount:d="some",once:f}=a,h={root:l?l.current:void 0,rootMargin:r,threshold:typeof d=="number"?d:WA[d]},p=y=>{const{isIntersecting:g}=y;if(this.isInView===g||(this.isInView=g,f&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:b,onViewportLeave:w}=this.node.getProps(),A=g?b:w;A&&A(y)};this.stopObserver=KA(this.node.current,h,p)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:a,prevProps:l}=this.node;["amount","margin","root"].some(ZA(a,l))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function ZA({viewport:n={}},{viewport:a={}}={}){return l=>n[l]!==a[l]}const $A={...AA,...{inView:{Feature:QA},tap:{Feature:FA},focus:{Feature:GA},hover:{Feature:YA}},...IA,...{layout:{ProjectionNode:Nm,MeasureLayout:og}}},Be=xA($A,bA),gt="'Geist', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",tr="https://cdn.jsdelivr.net/npm/geist@1.3.1/dist/fonts/geist-sans",JA=` @font-face { font-family: 'Geist'; font-style: normal; font-weight: 400; font-display: swap; - src: url('${Kl}/Geist-Regular.woff2') format('woff2'); + src: url('${tr}/Geist-Regular.woff2') format('woff2'); } @font-face { font-family: 'Geist'; font-style: normal; font-weight: 500; font-display: swap; - src: url('${Kl}/Geist-Medium.woff2') format('woff2'); + src: url('${tr}/Geist-Medium.woff2') format('woff2'); } @font-face { font-family: 'Geist'; font-style: normal; font-weight: 600; font-display: swap; - src: url('${Kl}/Geist-SemiBold.woff2') format('woff2'); + src: url('${tr}/Geist-SemiBold.woff2') format('woff2'); } @font-face { font-family: 'Geist'; font-style: normal; font-weight: 700; font-display: swap; - src: url('${Kl}/Geist-Bold.woff2') format('woff2'); + src: url('${tr}/Geist-Bold.woff2') format('woff2'); } -`,Zu="linear-gradient(145deg, #24386D 0%, #0B1735 58%, #071021 100%)",Cn={send:"#2f80ed",badge:"#12203f",ring:"#4B83C4",inputBorder:"rgba(28, 30, 38, 0.25)",inputGlow:"0 0 0 3px rgba(75, 131, 196, 0.10)"},ga={bg:"#12203f",fg:"#FFFFFF",border:"rgba(18, 32, 63, 0.22)",borderActive:"rgba(75, 131, 196, 0.45)",activeRing:"0 0 0 2px rgba(75, 131, 196, 0.18)",radius:"50%"},li={badgeSize:24,glyphSize:13},x={bg:"#FFFFFF",headerBg:"#FFFFFF",surfaceMuted:"#F4F4F2",surfaceBubble:"#FFFFFF",surfaceSunken:"#F4F4F2",border:"#d6d3d1",borderStrong:"#a8a29e",divider:"rgba(28, 30, 38, 0.07)",shadow:"0 1px 2px rgba(28, 30, 38, 0.06)",shadowOuter:"0 22px 70px -42px rgba(28, 30, 38, 0.38)",shadowSoft:"none",text:"#1C1E26",textMuted:"#78716c",textLight:"#78716c",accent:"#1C1E26",link:"#4B83C4",hoverBg:"rgba(28, 30, 38, 0.045)",toneSelectedBg:"#F4F4F2",radius:14,radiusMd:10,radiusSm:8,radiusPill:9999,toggleOn:"#2f80ed",toggleOff:"#d6d3d1",inputBg:"#FFFFFF"},_t={bg:"#FFFFFF",border:"#d6d3d1",divider:"rgba(28, 30, 38, 0.09)",shadow:"0 14px 40px -8px rgba(28, 30, 38, 0.34), 0 6px 18px -4px rgba(28, 30, 38, 0.2)",text:"#78716c",textStrong:"#1C1E26",textMuted:"#78716c",hover:"rgba(28, 30, 38, 0.045)",active:"rgba(28, 30, 38, 0.08)",radius:10,radiusInner:8},eg=[{name:"Yellow",value:"rgba(250, 204, 21, 0.45)"},{name:"Green",value:"rgba(34, 197, 94, 0.38)"},{name:"Blue",value:"rgba(75, 131, 196, 0.28)"},{name:"Pink",value:"rgba(236, 72, 153, 0.32)"},{name:"Orange",value:"rgba(245, 158, 11, 0.40)"},{name:"Purple",value:"rgba(168, 85, 247, 0.32)"}],NA={floatingOverlay:2147483648},_A=80,ng="https://useinline.vercel.app",$u=ng;function ig({size:i=li.badgeSize,background:a=Cn.badge,children:l}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:i,height:i,borderRadius:"50%",background:a,color:"#fff",flexShrink:0},children:l})}function Ju({size:i=18,strokeWidth:a=1.75,color:l="currentColor"}){return u.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:l,strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:u.jsx("path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"})})}function ag({size:i=li.badgeSize,iconSize:a=li.glyphSize,background:l=Cn.badge}){return u.jsx(ig,{size:i,background:l,children:u.jsx(Ju,{size:a,strokeWidth:2,color:"#fff"})})}function Ge({size:i=18,children:a}){return u.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a})}function sg({size:i=18}){return u.jsx(Ge,{size:i,children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}function tc({size:i=18}){return u.jsx(Ju,{size:i,strokeWidth:1.75})}function lg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"}),u.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),u.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"}),u.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]})}function rg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),u.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),u.jsx("path",{d:"M2 2l7.586 7.586"}),u.jsx("circle",{cx:"11",cy:"11",r:"2"})]})}function og({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]})}function ug({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("circle",{cx:"12",cy:"12",r:"3"}),u.jsx("path",{d:"M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"})]})}function cg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),u.jsx("polyline",{points:"2 17 12 22 22 17"}),u.jsx("polyline",{points:"2 12 12 17 22 12"})]})}function dg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M5 21h14"}),u.jsx("path",{d:"M8 21v-6l4-9 4 9v6"}),u.jsx("path",{d:"M9.5 12h5"})]})}function fg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function hg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"}),u.jsx("circle",{cx:"12",cy:"13",r:"4"})]})}function pg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor",stroke:"none"}),u.jsx("path",{d:"M12 2v4M12 18v4M2 12h4M18 12h4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"})]})}function mg({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"}),u.jsx("path",{d:"M2 22c2-2 4-3.5 6-3.5s3 1 5 1 4-1.5 6-3.5"})]})}function VA({size:i=18}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),u.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"})]})}function UA({size:i=18}){return u.jsxs("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[u.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),u.jsx("circle",{cx:"19",cy:"12",r:"1.5"}),u.jsx("circle",{cx:"5",cy:"12",r:"1.5"})]})}function HA({size:i=17}){return u.jsxs(Ge,{size:i,children:[u.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),u.jsx("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),u.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),u.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}const IA={rewrite:sg,ai:tc,notes:lg,settings:ug,highlighter:og,draw:rg,layers:cg,stamps:dg,search:fg,screenshot:hg,laser:pg,handwriting:mg};function YA(i,a=18){const l=IA[i];return u.jsx(l,{size:a})}function gg({children:i,size:a=28,active:l}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:a,height:a,borderRadius:x.radiusSm,background:l?x.toneSelectedBg:x.surfaceMuted,border:`1px solid ${l?x.borderStrong:x.border}`,color:l?x.text:x.textMuted,flexShrink:0},children:i})}function GA({children:i,size:a=24,active:l,style:r}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:a,height:a,borderRadius:ga.radius,background:ga.bg,border:`1px solid ${l?ga.borderActive:ga.border}`,color:ga.fg,flexShrink:0,boxShadow:l?ga.activeRing:"none",...r},children:i})}function yg({tool:i,size:a=li.badgeSize}){const l=Math.round(a*(li.glyphSize/li.badgeSize));return u.jsx(ig,{size:a,children:i==="ai"?u.jsx(Ju,{size:l,strokeWidth:2,color:"#fff"}):YA(i,l)})}function ec({size:i=24,radius:a}){return u.jsx("span",{style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:i,height:i,flexShrink:0,borderRadius:a??"50%",background:Zu,border:"1px solid rgba(255,255,255,0.08)"},children:u.jsx("span",{style:{width:Math.max(2,Math.round(i*.13)),height:Math.round(i*.48),borderRadius:2,background:"#FFFFFF",transform:"rotate(-12deg)"}})})}const qA=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",children:u.jsx("path",{d:"M4 4l8 8M12 4l-8 8"})});function xg({onClose:i,label:a="Close"}){const[l,r]=v.useState(!1);return u.jsx("button",{type:"button",onClick:i,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),"aria-label":a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusSm,border:"none",padding:0,background:l?x.hoverBg:"transparent",color:l?x.text:x.textMuted,cursor:"pointer",transition:"background 0.14s, color 0.14s",flexShrink:0},children:u.jsx(qA,{})})}function mn({title:i,subtitle:a,chip:l,width:r=360,onClose:d,footer:f,headerActions:h,headerLeading:p,useChatBrand:y,tool:g,children:b,style:S}){return u.jsxs("div",{style:{width:r,maxWidth:"min(94vw, 388px)",maxHeight:"calc(100vh - 64px)",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,overflow:"hidden",display:"flex",flexDirection:"column",...S},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:56,padding:"0 16px 0 20px",background:x.headerBg,flexShrink:0},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:0,flex:1},children:[p,y?u.jsx(ag,{}):g?u.jsx(yg,{tool:g}):u.jsx(ec,{size:li.badgeSize}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),a&&u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a})]}),l&&u.jsx(WA,{children:l})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:8},children:[h,u.jsx(xg,{onClose:d})]})]}),u.jsx("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flex:1,overflowY:"auto",overflowX:"hidden"},children:b}),f&&u.jsx("div",{style:{background:"rgba(255,255,255,0.95)",flexShrink:0},children:f})]})}const XA={background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,overflow:"hidden",display:"flex",flexDirection:"column"};function nc({title:i,subtitle:a,width:l=360,onClose:r,footer:d,children:f,position:h,zIndex:p,className:y,tool:g,useChatBrand:b,onHeaderMouseDown:S,headerCursor:A,bareBody:j}){const k=h??{right:_A,top:16};return u.jsxs("div",{className:y,style:{position:"fixed",...k,width:l,maxWidth:"min(94vw, 388px)",maxHeight:"70vh",zIndex:p??NA.floatingOverlay,pointerEvents:"auto",...XA},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:56,padding:"0 16px 0 20px",background:x.headerBg,flexShrink:0},children:[u.jsxs("div",{onMouseDown:S,style:{display:"flex",alignItems:"center",gap:10,minWidth:0,flex:1,cursor:A,userSelect:S?"none":void 0},children:[b?u.jsx(ag,{}):g?u.jsx(yg,{tool:g}):u.jsx(ec,{size:li.badgeSize}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),a&&u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a})]})]}),u.jsx(xg,{onClose:r})]}),u.jsx("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flex:1,overflowY:"auto",overflowX:"hidden",...j?{}:{padding:"16px 20px",fontSize:14,lineHeight:1.55,color:x.text}},children:f}),d&&u.jsx("div",{style:{background:x.bg,flexShrink:0},children:d})]})}const Wl={removedBg:"#FEE2E2",removedText:"#991B1B",addedBg:"#DCFCE7",addedText:"#166534"};function FA({children:i}){return u.jsx("p",{style:{margin:0,padding:"4px 8px",borderRadius:x.radiusSm,background:Wl.removedBg,color:Wl.removedText,textDecoration:"line-through",fontSize:12,lineHeight:1.45},children:i})}function bg({children:i}){return u.jsx("p",{style:{margin:0,padding:"4px 8px",borderRadius:x.radiusSm,background:Wl.addedBg,color:Wl.addedText,fontSize:12,lineHeight:1.45},children:i})}function vg({original:i,updated:a}){const l=i.trim(),r=a.trim();return l?u.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[u.jsx(FA,{children:l}),u.jsx(bg,{children:r})]}):u.jsx(bg,{children:r})}function ic({children:i,style:a}){return u.jsx("div",{style:{minHeight:48,maxHeight:280,overflowY:"auto",...a},children:i})}const PA=()=>u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:u.jsx("path",{d:"M20 6L9 17l-5-5"})});function Ql({label:i,onClick:a,disabled:l}){const[r,d]=v.useState(!1);return u.jsx("button",{type:"button",onClick:a,disabled:l,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{padding:"6px 12px",borderRadius:x.radiusPill,border:"none",background:r&&!l?x.hoverBg:"transparent",color:x.textMuted,fontSize:12,fontWeight:500,fontFamily:gt,cursor:l?"not-allowed":"pointer",opacity:l?.55:1},children:i})}function KA({label:i="Approve",onClick:a,disabled:l}){const[r,d]=v.useState(!1);return u.jsxs("button",{type:"button",onClick:a,disabled:l,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"6px 12px",borderRadius:x.radiusPill,border:"none",background:Cn.send,color:"#fff",fontSize:12,fontWeight:500,fontFamily:gt,cursor:l?"not-allowed":"pointer",opacity:l?.55:1,filter:r&&!l?"brightness(1.05)":void 0},children:[u.jsx(PA,{})," ",i]})}function Zl({onBack:i,onReject:a,onApprove:l,approveLabel:r="Approve",approveDisabled:d,showReject:f=!0,showApprove:h=!0}){return u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"12px 16px",flexWrap:"wrap"},children:[u.jsx(Ql,{label:"Back",onClick:i}),u.jsxs("div",{style:{display:"flex",gap:8,marginLeft:"auto"},children:[f&&a&&u.jsx(Ql,{label:"Reject",onClick:a}),h&&l&&u.jsx(KA,{label:r,onClick:l,disabled:d})]})]})}function WA({children:i,tone:a="neutral"}){const l=a==="accent";return u.jsx("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:x.radiusPill,background:l?"rgba(75,131,196,0.12)":x.surfaceMuted,border:`1px solid ${l?"rgba(75,131,196,0.22)":x.divider}`,color:l?Cn.ring:x.textMuted,fontSize:10,fontWeight:600,letterSpacing:"0.01em",maxWidth:140,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})}function ye({children:i,style:a}){return u.jsx("div",{style:{margin:"0 2px 8px",fontSize:12,fontWeight:500,color:x.textMuted,letterSpacing:0,textTransform:"none",lineHeight:1.25,...a},children:i})}const ya={padding:"20px 20px 16px",display:"flex",flexDirection:"column",gap:16},QA={border:`1px solid ${x.border}`,borderRadius:x.radiusMd,background:x.surfaceBubble,boxShadow:"none"};function Mn({children:i,style:a,list:l}){return u.jsx("div",{style:{...QA,...l?{overflow:"hidden",padding:0}:{padding:12},...a},children:i})}function ac({icon:i,label:a,desc:l,disabled:r,onClick:d}){const[f,h]=v.useState(!1);return u.jsxs("button",{type:"button",disabled:r,onClick:d,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),"aria-label":a,style:{display:"flex",alignItems:"center",gap:10,textAlign:"left",padding:"10px 12px",borderRadius:x.radiusMd,width:"100%",boxSizing:"border-box",border:`1px solid ${r?x.divider:f?x.borderStrong:x.border}`,background:r?x.surfaceMuted:x.surfaceBubble,color:r?x.textLight:x.text,cursor:r?"not-allowed":"pointer",opacity:r?.55:1,transition:"background 0.14s, border-color 0.14s",fontFamily:gt},children:[i&&u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusSm,flexShrink:0,background:r?x.surfaceSunken:x.surfaceMuted,color:r?x.textLight:x.text},children:i}),u.jsxs("span",{style:{minWidth:0,display:"flex",flexDirection:"column",gap:1},children:[u.jsx("span",{style:{fontSize:12,fontWeight:500,letterSpacing:"-0.01em",lineHeight:1.2},children:a}),l&&u.jsx("span",{style:{fontSize:11,color:x.textMuted,lineHeight:1.3},children:l})]})]})}function Sg({label:i,active:a,disabled:l,onClick:r}){const[d,f]=v.useState(!1);return u.jsx("button",{type:"button",disabled:l,onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),"aria-label":i,"aria-pressed":a,style:{padding:"7px 13px",borderRadius:x.radiusPill,border:`1px solid ${a?x.accent:l?x.divider:d?x.borderStrong:x.border}`,background:a?x.accent:l?x.surfaceMuted:d?x.hoverBg:x.surfaceBubble,color:a?"#fff":l?x.textLight:x.text,fontSize:12,fontWeight:500,fontFamily:gt,letterSpacing:"-0.01em",cursor:l?"not-allowed":"pointer",opacity:l?.7:1,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:i})}function sc({options:i,value:a,onChange:l}){return u.jsx("div",{style:{display:"flex",gap:3,padding:4,borderRadius:x.radiusMd,background:x.surfaceSunken,border:`1px solid ${x.divider}`},children:i.map(r=>{const d=r.value===a;return u.jsx("button",{type:"button",onClick:()=>l(r.value),"aria-pressed":d,style:{flex:1,padding:"7px 4px",borderRadius:x.radiusSm,border:"none",background:d?x.surfaceBubble:"transparent",color:d?x.text:x.textMuted,fontSize:12,fontWeight:d?600:500,fontFamily:gt,letterSpacing:"-0.01em",cursor:"pointer",transition:"background 0.14s, color 0.14s"},children:r.label},r.value)})})}function $l({checked:i,onChange:a,label:l}){return u.jsx("button",{type:"button",role:"switch","aria-checked":i,"aria-label":l?`${i?"Disable":"Enable"} ${l}`:void 0,onClick:()=>a(!i),style:{position:"relative",width:44,height:26,borderRadius:x.radiusPill,background:i?x.toggleOn:x.toggleOff,border:"none",cursor:"pointer",padding:0,transition:"background 0.22s cubic-bezier(0.4,0,0.2,1)",flexShrink:0},children:u.jsx("span",{style:{position:"absolute",top:3,left:i?21:3,width:20,height:20,borderRadius:"50%",background:"#fff",display:"block",boxShadow:"none",transition:"left 0.22s cubic-bezier(0.4,0,0.2,1)"}})})}const ZA=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})});function lc({value:i,onChange:a,onSubmit:l,placeholder:r,disabled:d,modeLabel:f="Smart mode",sendDisabled:h}){const[p,y]=v.useState(!1),g=!h&&!d&&i.trim().length>0;return u.jsxs("div",{style:{overflow:"hidden",border:`1px solid ${p?Cn.ring:Cn.inputBorder}`,borderRadius:x.radiusMd,background:d?x.surfaceMuted:x.inputBg,boxShadow:p?Cn.inputGlow:"none",transition:"border-color 0.14s, box-shadow 0.14s"},children:[i.trim()&&u.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid rgba(28, 30, 38, 0.10)",background:"rgba(28, 30, 38, 0.05)",padding:"8px 16px",fontSize:12,color:x.accent},children:u.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.trim()})}),u.jsxs("div",{style:{display:"flex",minHeight:78,flexDirection:"column",padding:"12px 16px"},children:[u.jsx("textarea",{value:i,onChange:b=>a(b.target.value),onFocus:()=>y(!0),onBlur:()=>y(!1),onKeyDown:b=>{b.key==="Enter"&&!b.shiftKey&&g&&(b.preventDefault(),l())},disabled:d,placeholder:r,rows:2,style:{width:"100%",border:"none",outline:"none",resize:"none",background:"transparent",fontSize:14,lineHeight:1.5,color:x.text,fontFamily:gt,padding:"0 0 8px",minHeight:34,boxSizing:"border-box"}}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:"auto"},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 10px",borderRadius:x.radiusSm,background:x.surfaceMuted,fontSize:12,fontWeight:500,color:x.text},children:f}),u.jsx("button",{type:"button",onClick:()=>{g&&l()},disabled:!g,"aria-label":"Send",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusPill,border:"none",background:g?Cn.send:x.surfaceMuted,color:g?"#fff":x.textMuted,cursor:g?"pointer":"not-allowed",flexShrink:0,opacity:g?1:.35,transition:"background 0.14s, opacity 0.14s"},children:u.jsx(ZA,{})})]})]})]})}function xa({size:i=18}){return u.jsx("span",{style:{display:"inline-block",width:i,height:i,border:`2px solid ${x.divider}`,borderTopColor:x.accent,borderRadius:"50%",animation:"inline-spin 0.7s linear infinite"}})}function $A({label:i="Working…"}){return u.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:"38px 20px",color:x.textMuted,fontFamily:gt},children:[u.jsx(xa,{size:24}),u.jsx("span",{style:{fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em"},children:i})]})}function wg({icon:i,title:a,hint:l}){return u.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:9,padding:"34px 24px",textAlign:"center",fontFamily:gt},children:[i&&u.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:46,height:46,borderRadius:16,marginBottom:2,background:x.surfaceMuted,color:x.textMuted,border:`1px solid ${x.divider}`},children:i}),u.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:x.text,letterSpacing:"-0.01em"},children:a}),l&&u.jsx("div",{style:{fontSize:12,color:x.textMuted,maxWidth:240,lineHeight:1.5},children:l})]})}let Ag=!1;function JA(i){if(!(Ag||!i))try{const a=document.createElement("style");a.textContent="@keyframes inline-spin{to{transform:rotate(360deg)}}",i.appendChild(a),Ag=!0}catch{}}const t5=["Inline only works when you use it — highlights, notes, drawings, screenshots, or AI on the page you are viewing.","Without an account, your captures stay in this browser only.",`When you sign in, captures sync to your workspace at ${ng}.`,"Guest AI is limited to 10 prompts on this device. We never sell your data or use it for ads."];function e5({onAccept:i,onPrivacyPolicy:a}){return u.jsx(Oe.div,{"data-inline-interactive":"",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.18},style:{position:"fixed",inset:0,zIndex:2147483647,pointerEvents:"auto",display:"flex",justifyContent:"center",padding:"18px 16px 0",background:"rgba(28, 30, 38, 0.28)",backdropFilter:"blur(2px)",fontFamily:gt},children:u.jsxs(Oe.div,{role:"dialog","aria-labelledby":"inline-privacy-title","aria-describedby":"inline-privacy-desc",initial:{opacity:0,y:-8,scale:.97},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.97},transition:{duration:.18,ease:"easeOut"},style:{width:"min(388px, 100%)",height:"fit-content",borderRadius:x.radius,border:`1px solid ${x.border}`,background:x.bg,boxShadow:x.shadowOuter,color:x.text,overflow:"hidden",display:"flex",flexDirection:"column"},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",gap:10,minHeight:56,padding:"0 20px",background:x.headerBg,flexShrink:0},children:[u.jsx(ec,{size:24}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{id:"inline-privacy-title",style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2},children:"Before you capture"}),u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2},children:"Review how Inline handles page content."})]})]}),u.jsxs("div",{id:"inline-privacy-desc",style:{padding:"16px 18px 18px"},children:[u.jsx(ye,{children:"What to know"}),u.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",display:"grid",gap:8},children:t5.map(l=>u.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",borderRadius:x.radiusMd,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12,lineHeight:1.45,color:x.textMuted},children:[u.jsx("span",{"aria-hidden":!0,style:{marginTop:5,width:6,height:6,borderRadius:"50%",background:x.link,flexShrink:0}}),u.jsx("span",{children:l})]},l))})]}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:`1px solid ${x.divider}`,background:"rgba(255,255,255,0.95)",flexShrink:0},children:[u.jsx("button",{type:"button",onClick:a,style:{border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text,borderRadius:x.radiusPill,padding:"9px 14px",fontSize:12.5,fontWeight:650,cursor:"pointer",fontFamily:gt,boxShadow:"none",letterSpacing:"-0.01em"},children:"Privacy policy"}),u.jsx("button",{type:"button",onClick:i,style:{border:"none",background:x.accent,color:"#FFFFFF",borderRadius:x.radiusPill,padding:"9px 16px",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none",letterSpacing:"-0.01em"},children:"I agree"})]})]})})}const Tg=[{id:"JBFqnCBsd6RMkjVDRZzb",name:"George",subtitle:"Warm, captivating storyteller",gender:"male",tier:"free"},{id:"EXAVITQu4vr4xnSDxMaL",name:"Sarah",subtitle:"Mature, reassuring, confident",gender:"female",tier:"free"},{id:"Xb7hH8MSUJpSbSDYk0k2",name:"Alice",subtitle:"Clear, engaging educator",gender:"female",tier:"free"},{id:"onwK4e9ZLuTAKqWW03F9",name:"Daniel",subtitle:"Steady broadcaster",gender:"male",tier:"free"},{id:"A9hvW90SK1w1iyI1xxf9",name:"Lilian",subtitle:"Warm, clear & hybrid (paid)",gender:"female",tier:"paid"},{id:"sNKKDngZymUvjZVKvNU1",name:"Tyler",subtitle:"Primary teaching voice (paid)",gender:"male",tier:"paid"},{id:"klfRFkxouVP3bt55Whp3",name:"Joseph",subtitle:"Clear, smooth & friendly (paid)",gender:"male",tier:"paid"},{id:"UQoLnPXvf18gaKpLzfb8",name:"Sawyer",subtitle:"Calm, measured & serious (paid)",gender:"male",tier:"paid"}],n5=Tg[0].id,i5=new Set(Tg.map(i=>i.id));function Eg(i){return i&&i5.has(i)?i:n5}const a5=new Set(["localhost","127.0.0.1","::1"]);function jg(i){try{const a=new URL(i);if(a.protocol==="https:"||a.protocol==="wss:"||(a.protocol==="http:"||a.protocol==="ws:")&&a5.has(a.hostname))return!0}catch{return!1}return!1}function s5(i){if(!jg(i))throw new Error("Inline blocks non-local insecure network requests. Use HTTPS for synced workspace and AI requests.")}const Cg=$u;function l5(i){if(typeof i!="string"||!i)return Cg;const a=i.replace(/\/$/,"");return jg(a)?a:Cg}async function gn(){return new Promise(i=>{chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineBlockedDomains","inlineFocusMode","inlineVoiceId","inlineScreenReader"],a=>{let l=[];try{const r=a.inlineBlockedDomains;typeof r=="string"&&(l=JSON.parse(r))}catch{}i({apiBaseUrl:l5(a.inlineApiBase),accessToken:typeof a.inlineAccessToken=="string"?a.inlineAccessToken:"",blockedDomains:Array.isArray(l)?l:[],focusMode:a.inlineFocusMode==="true"||a.inlineFocusMode===!0,voiceId:Eg(typeof a.inlineVoiceId=="string"?a.inlineVoiceId:void 0),screenReader:a.inlineScreenReader==="true"||a.inlineScreenReader===!0})})})}let yn=null;function Ss(){if(yn){if(yn.kind==="audio")try{yn.el.pause()}catch{}else if(yn.kind==="utterance")try{window.speechSynthesis.cancel()}catch{}yn=null}}function r5(i,a){const l=new Audio(i);yn={kind:"audio",el:l},l.onended=()=>{URL.revokeObjectURL(i),yn=null,a?.onEnd?.()},l.onerror=()=>{URL.revokeObjectURL(i),yn=null,a?.onEnd?.()},l.play()}function o5(i,a,l){return new Promise(r=>{if(typeof chrome>"u"||!chrome.runtime?.sendMessage){r(!1);return}chrome.runtime.sendMessage({type:"INLINE_TTS",payload:{text:i,voiceId:a}},d=>{if(chrome.runtime.lastError){r(!1);return}if(!d?.ok||!d.audioBase64){r(!1);return}try{l?.onStart?.();const f=atob(d.audioBase64),h=new Uint8Array(f.length);for(let g=0;g"u"||!window.speechSynthesis)return!1;const l=window.speechSynthesis,r=new SpeechSynthesisUtterance(i);r.rate=1,r.pitch=1;const f=l.getVoices().find(h=>/en(-|_)?(US|GB)?/i.test(h.lang));return f&&(r.voice=f),r.onstart=()=>{a?.onStart?.()},r.onend=()=>{yn=null,a?.onEnd?.()},r.onerror=()=>{yn=null,a?.onEnd?.()},yn={kind:"utterance",utterance:r},l.speak(r),!0}catch{return!1}}async function Jl(i,a){Ss();const l=i.slice(0,2e3);if(!l.trim())return;const{voiceId:r}=await gn(),d=Eg(r);await o5(l,d,a)||(a?.onFallback?.(),!u5(l,a)&&a?.onEnd?.())}const rc=[{id:"tldr",label:"TL;DR for exec",prompt:"Summarize this in 2-3 bullet points suitable for an executive briefing."},{id:"bug-report",label:"Bug report",prompt:"Rewrite this as a structured bug report with: Summary, Steps to Reproduce, Expected Behavior, Actual Behavior."},{id:"meeting-notes",label:"Meeting notes",prompt:"Reformat this as structured meeting notes with: Key Decisions, Action Items, and Follow-ups."},{id:"eli5",label:"Explain simply",prompt:"Explain this in simple terms that a non-technical person could understand."},{id:"pros-cons",label:"Pros & Cons",prompt:"Analyze this and list the pros and cons in a balanced way."},{id:"action-items",label:"Action items",prompt:"Extract all action items and to-dos from this text as a numbered list."}];async function ri(i,a={}){if(s5(i),typeof chrome>"u"||!chrome.runtime?.sendMessage)throw new Error("Background service worker unavailable");const l=await new Promise((r,d)=>{chrome.runtime.sendMessage({type:"INLINE_PROXY_FETCH",payload:{url:i,method:a.method??"GET",headers:a.headers??{},body:a.body}},f=>{if(chrome.runtime.lastError){d(new Error(chrome.runtime.lastError.message));return}if(!f){d(new Error("No response from background"));return}r(f)})});if(l.error&&!l.ok)throw new Error(l.error);return{ok:l.ok,status:l.status,bodyText:l.bodyText,json:async()=>JSON.parse(l.bodyText),text:async()=>l.bodyText}}const tr="inlineGuestDeviceId",oc="inlineGuestAiUsage",xn=10;function uc(i){if(typeof i!="string")return!1;const a=i.split(".");return a.length===3&&a.every(l=>l.length>0)}function c5(){try{return crypto.randomUUID()}catch{return`guest-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}async function d5(){const i=await chrome.storage.local.get([tr]),a=typeof i[tr]=="string"?i[tr]:"";if(a)return a;const l=c5();return await chrome.storage.local.set({[tr]:l}),l}function f5(i){if(!i||typeof i!="object")return{used:0,updatedAt:0};const a=i;return{used:typeof a.used=="number"&&Number.isFinite(a.used)?Math.max(0,a.used):0,updatedAt:typeof a.updatedAt=="number"?a.updatedAt:0}}async function Mg(){const[i,a]=await Promise.all([chrome.storage.local.get(["inlineAccessToken",oc]),d5()]),l=uc(i.inlineAccessToken),r=f5(i[oc]);return{allowed:l||r.used"u"?{pageUrl:"",pageTitle:""}:{pageUrl:window.location?.href??"",pageTitle:document?.title??""}}async function kg(i){try{const{pageUrl:a,pageTitle:l}=h5(),{apiBaseUrl:r,accessToken:d}=await gn(),f=await new Promise(A=>{chrome.storage.local.get(["inlineActiveWorkspaceId","inlineUserId"],j=>{A(j)})}),h=i.workspaceId??f.inlineActiveWorkspaceId??"",p=f.inlineUserId??"";if(!uc(d)||!h)return;const y={"ai-rephrase":["ai","rephrase"],"ai-shorten":["ai","shorten"],"ai-summarize":["ai","summary"],"ai-rewrite":["ai","rewrite"],"ai-custom":["ai","custom"],clip:["clip"]},g={"ai-rephrase":"ai-summary","ai-shorten":"ai-summary","ai-summarize":"ai-summary","ai-rewrite":"ai-summary","ai-custom":"ai-summary",clip:"clip"},b={pageUrl:i.pageUrl??a,pageTitle:i.pageTitle??l,workspaceId:h,userId:p,type:g[i.kind],tags:y[i.kind],content:i.selection?`**${i.kind}** +`,ic="linear-gradient(145deg, #24386D 0%, #0B1735 58%, #071021 100%)",kn={send:"#2f80ed",badge:"#12203f",ring:"#4B83C4",inputBorder:"rgba(28, 30, 38, 0.25)",inputGlow:"0 0 0 3px rgba(75, 131, 196, 0.10)"},Sa={bg:"#12203f",fg:"#FFFFFF",border:"rgba(18, 32, 63, 0.22)",borderActive:"rgba(75, 131, 196, 0.45)",activeRing:"0 0 0 2px rgba(75, 131, 196, 0.18)",radius:"50%"},oi={badgeSize:24,glyphSize:13},x={bg:"#FFFFFF",headerBg:"#FFFFFF",surfaceMuted:"#F4F4F2",surfaceBubble:"#FFFFFF",surfaceSunken:"#F4F4F2",border:"#d6d3d1",borderStrong:"#a8a29e",divider:"rgba(28, 30, 38, 0.07)",shadow:"0 1px 2px rgba(28, 30, 38, 0.06)",shadowOuter:"0 22px 70px -42px rgba(28, 30, 38, 0.38)",shadowSoft:"none",text:"#1C1E26",textMuted:"#78716c",textLight:"#78716c",accent:"#1C1E26",link:"#4B83C4",hoverBg:"rgba(28, 30, 38, 0.045)",toneSelectedBg:"#F4F4F2",radius:14,radiusMd:10,radiusSm:8,radiusPill:9999,toggleOn:"#2f80ed",toggleOff:"#d6d3d1",inputBg:"#FFFFFF"},Ht={bg:"#FFFFFF",border:"#d6d3d1",divider:"rgba(28, 30, 38, 0.09)",shadow:"0 14px 40px -8px rgba(28, 30, 38, 0.34), 0 6px 18px -4px rgba(28, 30, 38, 0.2)",text:"#78716c",textStrong:"#1C1E26",textMuted:"#78716c",hover:"rgba(28, 30, 38, 0.045)",active:"rgba(28, 30, 38, 0.08)",radius:10,radiusInner:8},dg=[{name:"Yellow",value:"rgba(250, 204, 21, 0.45)"},{name:"Green",value:"rgba(34, 197, 94, 0.38)"},{name:"Blue",value:"rgba(75, 131, 196, 0.28)"},{name:"Pink",value:"rgba(236, 72, 153, 0.32)"},{name:"Orange",value:"rgba(245, 158, 11, 0.40)"},{name:"Purple",value:"rgba(168, 85, 247, 0.32)"}],t5={floatingOverlay:2147483648},e5=80,fg="https://useinline.vercel.app",ac=fg;function hg({size:n=oi.badgeSize,background:a=kn.badge,children:l}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:n,height:n,borderRadius:"50%",background:a,color:"#fff",flexShrink:0},children:l})}function sc({size:n=18,strokeWidth:a=1.75,color:l="currentColor"}){return u.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:l,strokeWidth:a,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:u.jsx("path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"})})}function pg({size:n=oi.badgeSize,iconSize:a=oi.glyphSize,background:l=kn.badge}){return u.jsx(hg,{size:n,background:l,children:u.jsx(sc,{size:a,strokeWidth:2,color:"#fff"})})}function n5(n){return n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(new RegExp("(?\s*/gm,"").replace(/\s+/g," ").trim()}const i5=/(\*\*[^*]+\*\*|__[^_]+__|\*[^*]+\*|_[^_]+_|`[^`]+`)/g;function js(n){if(!n)return[];const a=n.split(i5),l=[];for(const r of a){if(!r)continue;const d=/^\*\*([^*]+)\*\*$/.exec(r);if(d){l.push({type:"bold",value:d[1]});continue}const f=/^__([^_]+)__$/.exec(r);if(f){l.push({type:"underline",value:f[1]});continue}const h=/^\*([^*]+)\*$/.exec(r);if(h){l.push({type:"italic",value:h[1]});continue}const p=/^_([^_]+)_$/.exec(r);if(p){l.push({type:"italic",value:p[1]});continue}const y=/^`([^`]+)`$/.exec(r);if(y){l.push({type:"code",value:y[1]});continue}l.push({type:"text",value:r})}return l}const lc=/^[-*•]\s+/,rc=/^\d+[.)]\s+/;function a5(n){const a=n.replace(/\r\n/g,` +`).trim();if(!a)return[];const l=a.split(/\n\n+/),r=[];for(const d of l){const f=d.trim();if(!f)continue;const h=f.split(` +`).map(b=>b.trim()).filter(Boolean),p=h.filter(b=>lc.test(b)),y=h.filter(b=>rc.test(b)),g=h.filter(b=>!lc.test(b)&&!rc.test(b));if(p.length>0){g.length>0&&r.push({type:"paragraph",inline:js(g.join(" "))}),r.push({type:"bullet-list",items:p.map(b=>js(b.replace(lc,"")))});continue}if(y.length>0&&g.length===0){r.push({type:"numbered-list",items:y.map(b=>js(b.replace(rc,"")))});continue}if(h.every(b=>b.startsWith(">"))){r.push({type:"blockquote",inline:js(h.map(b=>b.replace(/^>\s?/,"")).join(" "))});continue}r.push({type:"paragraph",inline:js(f.replace(/\n/g," "))})}return r}function er({segments:n}){return u.jsx(u.Fragment,{children:n.map((a,l)=>{switch(a.type){case"bold":return u.jsx("strong",{style:{fontWeight:600},children:a.value},l);case"italic":return u.jsx("em",{children:a.value},l);case"underline":return u.jsx("u",{children:a.value},l);case"code":return u.jsx("code",{style:{fontFamily:"ui-monospace, monospace",fontSize:"0.85em",background:x.surfaceMuted,borderRadius:4,padding:"0 4px"},children:a.value},l);default:return u.jsx("span",{children:a.value},l)}})})}function ui({text:n,style:a}){const l={fontSize:14,lineHeight:1.625,color:x.text,...a},r=a5(n);return r.length===0?null:u.jsx("div",{style:l,children:r.map((d,f)=>{const h=fu.jsx("li",{style:{marginBottom:gu.jsx("li",{style:{marginBottom:gu.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",children:u.jsx("path",{d:"M4 4l8 8M12 4l-8 8"})});function Mg({onClose:n,label:a="Close"}){const[l,r]=v.useState(!1);return u.jsx("button",{type:"button",onClick:n,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),"aria-label":a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusSm,border:"none",padding:0,background:l?x.hoverBg:"transparent",color:l?x.text:x.textMuted,cursor:"pointer",transition:"background 0.14s, color 0.14s",flexShrink:0},children:u.jsx(d5,{})})}function gn({title:n,subtitle:a,chip:l,width:r=360,onClose:d,footer:f,headerActions:h,headerLeading:p,useChatBrand:y,tool:g,children:b,style:w}){return u.jsxs("div",{style:{width:r,maxWidth:"min(94vw, 388px)",maxHeight:"calc(100vh - 64px)",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,overflow:"hidden",display:"flex",flexDirection:"column",...w},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:56,padding:"0 16px 0 20px",background:x.headerBg,flexShrink:0},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:0,flex:1},children:[p,y?u.jsx(pg,{}):g?u.jsx(Cg,{tool:g}):u.jsx(uc,{size:oi.badgeSize}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n}),a&&u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a})]}),l&&u.jsx(g5,{children:l})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:8},children:[h,u.jsx(Mg,{onClose:d})]})]}),u.jsx("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flex:1,overflowY:"auto",overflowX:"hidden"},children:b}),f&&u.jsx("div",{style:{background:"rgba(255,255,255,0.95)",flexShrink:0},children:f})]})}const f5={background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,overflow:"hidden",display:"flex",flexDirection:"column"};function cc({title:n,subtitle:a,width:l=360,onClose:r,footer:d,children:f,position:h,zIndex:p,className:y,tool:g,useChatBrand:b,onHeaderMouseDown:w,headerCursor:A,bareBody:j}){const k=h??{right:e5,top:16};return u.jsxs("div",{className:y,style:{position:"fixed",...k,width:l,maxWidth:"min(94vw, 388px)",maxHeight:"70vh",zIndex:p??t5.floatingOverlay,pointerEvents:"auto",...f5},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:56,padding:"0 16px 0 20px",background:x.headerBg,flexShrink:0},children:[u.jsxs("div",{onMouseDown:w,style:{display:"flex",alignItems:"center",gap:10,minWidth:0,flex:1,cursor:A,userSelect:w?"none":void 0},children:[b?u.jsx(pg,{}):g?u.jsx(Cg,{tool:g}):u.jsx(uc,{size:oi.badgeSize}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n}),a&&u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a})]})]}),u.jsx(Mg,{onClose:r})]}),u.jsx("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flex:1,overflowY:"auto",overflowX:"hidden",...j?{}:{padding:"16px 20px",fontSize:14,lineHeight:1.55,color:x.text}},children:f}),d&&u.jsx("div",{style:{background:x.bg,flexShrink:0},children:d})]})}const nr={removedBg:"#FEE2E2",removedText:"#991B1B",addedBg:"#DCFCE7",addedText:"#166534"};function h5({children:n}){return u.jsx("div",{style:{margin:0,padding:"4px 8px",borderRadius:x.radiusSm,background:nr.removedBg,color:nr.removedText,textDecoration:"line-through",fontSize:12,lineHeight:1.45},children:n})}function kg({children:n}){return u.jsx("div",{style:{margin:0,padding:"4px 8px",borderRadius:x.radiusSm,background:nr.addedBg,color:nr.addedText,fontSize:12,lineHeight:1.45},children:n})}function Rg({original:n,updated:a}){const l=n.trim(),r=a.trim();return l?u.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[u.jsx(h5,{children:u.jsx(ui,{text:l,style:{fontSize:12,lineHeight:1.45}})}),u.jsx(kg,{children:u.jsx(ui,{text:r,style:{fontSize:12,lineHeight:1.45}})})]}):u.jsx(kg,{children:u.jsx(ui,{text:r,style:{fontSize:12,lineHeight:1.45}})})}function dc({children:n,style:a}){return u.jsx("div",{style:{minHeight:48,maxHeight:280,overflowY:"auto",...a},children:n})}const p5=()=>u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:u.jsx("path",{d:"M20 6L9 17l-5-5"})});function ir({label:n,onClick:a,disabled:l}){const[r,d]=v.useState(!1);return u.jsx("button",{type:"button",onClick:a,disabled:l,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{padding:"6px 12px",borderRadius:x.radiusPill,border:"none",background:r&&!l?x.hoverBg:"transparent",color:x.textMuted,fontSize:12,fontWeight:500,fontFamily:gt,cursor:l?"not-allowed":"pointer",opacity:l?.55:1},children:n})}function m5({label:n="Approve",onClick:a,disabled:l}){const[r,d]=v.useState(!1);return u.jsxs("button",{type:"button",onClick:a,disabled:l,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"6px 12px",borderRadius:x.radiusPill,border:"none",background:kn.send,color:"#fff",fontSize:12,fontWeight:500,fontFamily:gt,cursor:l?"not-allowed":"pointer",opacity:l?.55:1,filter:r&&!l?"brightness(1.05)":void 0},children:[u.jsx(p5,{})," ",n]})}function ar({onBack:n,onReject:a,onApprove:l,approveLabel:r="Approve",approveDisabled:d,showReject:f=!0,showApprove:h=!0}){return u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"12px 16px",flexWrap:"wrap"},children:[u.jsx(ir,{label:"Back",onClick:n}),u.jsxs("div",{style:{display:"flex",gap:8,marginLeft:"auto"},children:[f&&a&&u.jsx(ir,{label:"Reject",onClick:a}),h&&l&&u.jsx(m5,{label:r,onClick:l,disabled:d})]})]})}function g5({children:n,tone:a="neutral"}){const l=a==="accent";return u.jsx("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:x.radiusPill,background:l?"rgba(75,131,196,0.12)":x.surfaceMuted,border:`1px solid ${l?"rgba(75,131,196,0.22)":x.divider}`,color:l?kn.ring:x.textMuted,fontSize:10,fontWeight:600,letterSpacing:"0.01em",maxWidth:140,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})}function ye({children:n,style:a}){return u.jsx("div",{style:{margin:"0 2px 8px",fontSize:12,fontWeight:500,color:x.textMuted,letterSpacing:0,textTransform:"none",lineHeight:1.25,...a},children:n})}const wa={padding:"20px 20px 16px",display:"flex",flexDirection:"column",gap:16},y5={border:`1px solid ${x.border}`,borderRadius:x.radiusMd,background:x.surfaceBubble,boxShadow:"none"};function Rn({children:n,style:a,list:l}){return u.jsx("div",{style:{...y5,...l?{overflow:"hidden",padding:0}:{padding:12},...a},children:n})}function fc({icon:n,label:a,desc:l,disabled:r,onClick:d}){const[f,h]=v.useState(!1);return u.jsxs("button",{type:"button",disabled:r,onClick:d,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),"aria-label":a,style:{display:"flex",alignItems:"center",gap:10,textAlign:"left",padding:"10px 12px",borderRadius:x.radiusMd,width:"100%",boxSizing:"border-box",border:`1px solid ${r?x.divider:f?x.borderStrong:x.border}`,background:r?x.surfaceMuted:x.surfaceBubble,color:r?x.textLight:x.text,cursor:r?"not-allowed":"pointer",opacity:r?.55:1,transition:"background 0.14s, border-color 0.14s",fontFamily:gt},children:[n&&u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusSm,flexShrink:0,background:r?x.surfaceSunken:x.surfaceMuted,color:r?x.textLight:x.text},children:n}),u.jsxs("span",{style:{minWidth:0,display:"flex",flexDirection:"column",gap:1},children:[u.jsx("span",{style:{fontSize:12,fontWeight:500,letterSpacing:"-0.01em",lineHeight:1.2},children:a}),l&&u.jsx("span",{style:{fontSize:11,color:x.textMuted,lineHeight:1.3},children:l})]})]})}function Dg({label:n,active:a,disabled:l,onClick:r}){const[d,f]=v.useState(!1);return u.jsx("button",{type:"button",disabled:l,onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),"aria-label":n,"aria-pressed":a,style:{padding:"7px 13px",borderRadius:x.radiusPill,border:`1px solid ${a?x.accent:l?x.divider:d?x.borderStrong:x.border}`,background:a?x.accent:l?x.surfaceMuted:d?x.hoverBg:x.surfaceBubble,color:a?"#fff":l?x.textLight:x.text,fontSize:12,fontWeight:500,fontFamily:gt,letterSpacing:"-0.01em",cursor:l?"not-allowed":"pointer",opacity:l?.7:1,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:n})}function hc({options:n,value:a,onChange:l}){return u.jsx("div",{style:{display:"flex",gap:3,padding:4,borderRadius:x.radiusMd,background:x.surfaceSunken,border:`1px solid ${x.divider}`},children:n.map(r=>{const d=r.value===a;return u.jsx("button",{type:"button",onClick:()=>l(r.value),"aria-pressed":d,style:{flex:1,padding:"7px 4px",borderRadius:x.radiusSm,border:"none",background:d?x.surfaceBubble:"transparent",color:d?x.text:x.textMuted,fontSize:12,fontWeight:d?600:500,fontFamily:gt,letterSpacing:"-0.01em",cursor:"pointer",transition:"background 0.14s, color 0.14s"},children:r.label},r.value)})})}function sr({checked:n,onChange:a,label:l}){return u.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":l?`${n?"Disable":"Enable"} ${l}`:void 0,onClick:()=>a(!n),style:{position:"relative",width:44,height:26,borderRadius:x.radiusPill,background:n?x.toggleOn:x.toggleOff,border:"none",cursor:"pointer",padding:0,transition:"background 0.22s cubic-bezier(0.4,0,0.2,1)",flexShrink:0},children:u.jsx("span",{style:{position:"absolute",top:3,left:n?21:3,width:20,height:20,borderRadius:"50%",background:"#fff",display:"block",boxShadow:"none",transition:"left 0.22s cubic-bezier(0.4,0,0.2,1)"}})})}const x5=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})});function pc({value:n,onChange:a,onSubmit:l,placeholder:r,disabled:d,modeLabel:f="Smart mode",sendDisabled:h}){const[p,y]=v.useState(!1),g=!h&&!d&&n.trim().length>0;return u.jsxs("div",{style:{overflow:"hidden",border:`1px solid ${p?kn.ring:kn.inputBorder}`,borderRadius:x.radiusMd,background:d?x.surfaceMuted:x.inputBg,boxShadow:p?kn.inputGlow:"none",transition:"border-color 0.14s, box-shadow 0.14s"},children:[n.trim()&&u.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid rgba(28, 30, 38, 0.10)",background:"rgba(28, 30, 38, 0.05)",padding:"8px 16px",fontSize:12,color:x.accent},children:u.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.trim()})}),u.jsxs("div",{style:{display:"flex",minHeight:78,flexDirection:"column",padding:"12px 16px"},children:[u.jsx("textarea",{value:n,onChange:b=>a(b.target.value),onFocus:()=>y(!0),onBlur:()=>y(!1),onKeyDown:b=>{b.key==="Enter"&&!b.shiftKey&&g&&(b.preventDefault(),l())},disabled:d,placeholder:r,rows:2,style:{width:"100%",border:"none",outline:"none",resize:"none",background:"transparent",fontSize:14,lineHeight:1.5,color:x.text,fontFamily:gt,padding:"0 0 8px",minHeight:34,boxSizing:"border-box"}}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:"auto"},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 10px",borderRadius:x.radiusSm,background:x.surfaceMuted,fontSize:12,fontWeight:500,color:x.text},children:f}),u.jsx("button",{type:"button",onClick:()=>{g&&l()},disabled:!g,"aria-label":"Send",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radiusPill,border:"none",background:g?kn.send:x.surfaceMuted,color:g?"#fff":x.textMuted,cursor:g?"pointer":"not-allowed",flexShrink:0,opacity:g?1:.35,transition:"background 0.14s, opacity 0.14s"},children:u.jsx(x5,{})})]})]})]})}function Aa({size:n=18}){return u.jsx("span",{style:{display:"inline-block",width:n,height:n,border:`2px solid ${x.divider}`,borderTopColor:x.accent,borderRadius:"50%",animation:"inline-spin 0.7s linear infinite"}})}function b5({label:n="Working…"}){return u.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:"38px 20px",color:x.textMuted,fontFamily:gt},children:[u.jsx(Aa,{size:24}),u.jsx("span",{style:{fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em"},children:n})]})}function zg({icon:n,title:a,hint:l}){return u.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:9,padding:"34px 24px",textAlign:"center",fontFamily:gt},children:[n&&u.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:46,height:46,borderRadius:16,marginBottom:2,background:x.surfaceMuted,color:x.textMuted,border:`1px solid ${x.divider}`},children:n}),u.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:x.text,letterSpacing:"-0.01em"},children:a}),l&&u.jsx("div",{style:{fontSize:12,color:x.textMuted,maxWidth:240,lineHeight:1.5},children:l})]})}let Lg=!1;function v5(n){if(!(Lg||!n))try{const a=document.createElement("style");a.textContent="@keyframes inline-spin{to{transform:rotate(360deg)}}",n.appendChild(a),Lg=!0}catch{}}const S5=["Inline only works when you use it — highlights, notes, drawings, screenshots, or AI on the page you are viewing.","Without an account, your captures stay in this browser only.",`When you sign in, captures sync to your workspace at ${fg}.`,"Guest AI is limited to 10 prompts on this device. We never sell your data or use it for ads."];function w5({onAccept:n,onPrivacyPolicy:a}){return u.jsx(Be.div,{"data-inline-interactive":"",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.18},style:{position:"fixed",inset:0,zIndex:2147483647,pointerEvents:"auto",display:"flex",justifyContent:"center",padding:"18px 16px 0",background:"rgba(28, 30, 38, 0.28)",backdropFilter:"blur(2px)",fontFamily:gt},children:u.jsxs(Be.div,{role:"dialog","aria-labelledby":"inline-privacy-title","aria-describedby":"inline-privacy-desc",initial:{opacity:0,y:-8,scale:.97},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.97},transition:{duration:.18,ease:"easeOut"},style:{width:"min(388px, 100%)",height:"fit-content",borderRadius:x.radius,border:`1px solid ${x.border}`,background:x.bg,boxShadow:x.shadowOuter,color:x.text,overflow:"hidden",display:"flex",flexDirection:"column"},children:[u.jsxs("header",{style:{display:"flex",alignItems:"center",gap:10,minHeight:56,padding:"0 20px",background:x.headerBg,flexShrink:0},children:[u.jsx(uc,{size:24}),u.jsxs("div",{style:{minWidth:0,flex:1},children:[u.jsx("div",{id:"inline-privacy-title",style:{fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",lineHeight:1.2},children:"Before you capture"}),u.jsx("div",{style:{marginTop:2,fontSize:12,color:x.textMuted,lineHeight:1.2},children:"Review how Inline handles page content."})]})]}),u.jsxs("div",{id:"inline-privacy-desc",style:{padding:"16px 18px 18px"},children:[u.jsx(ye,{children:"What to know"}),u.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",display:"grid",gap:8},children:S5.map(l=>u.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",borderRadius:x.radiusMd,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12,lineHeight:1.45,color:x.textMuted},children:[u.jsx("span",{"aria-hidden":!0,style:{marginTop:5,width:6,height:6,borderRadius:"50%",background:x.link,flexShrink:0}}),u.jsx("span",{children:l})]},l))})]}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:`1px solid ${x.divider}`,background:"rgba(255,255,255,0.95)",flexShrink:0},children:[u.jsx("button",{type:"button",onClick:a,style:{border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text,borderRadius:x.radiusPill,padding:"9px 14px",fontSize:12.5,fontWeight:650,cursor:"pointer",fontFamily:gt,boxShadow:"none",letterSpacing:"-0.01em"},children:"Privacy policy"}),u.jsx("button",{type:"button",onClick:n,style:{border:"none",background:x.accent,color:"#FFFFFF",borderRadius:x.radiusPill,padding:"9px 16px",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none",letterSpacing:"-0.01em"},children:"I agree"})]})]})})}const Og=[{id:"JBFqnCBsd6RMkjVDRZzb",name:"George",subtitle:"Warm, captivating storyteller",gender:"male",tier:"free"},{id:"EXAVITQu4vr4xnSDxMaL",name:"Sarah",subtitle:"Mature, reassuring, confident",gender:"female",tier:"free"},{id:"Xb7hH8MSUJpSbSDYk0k2",name:"Alice",subtitle:"Clear, engaging educator",gender:"female",tier:"free"},{id:"onwK4e9ZLuTAKqWW03F9",name:"Daniel",subtitle:"Steady broadcaster",gender:"male",tier:"free"},{id:"A9hvW90SK1w1iyI1xxf9",name:"Lilian",subtitle:"Warm, clear & hybrid (paid)",gender:"female",tier:"paid"},{id:"sNKKDngZymUvjZVKvNU1",name:"Tyler",subtitle:"Primary teaching voice (paid)",gender:"male",tier:"paid"},{id:"klfRFkxouVP3bt55Whp3",name:"Joseph",subtitle:"Clear, smooth & friendly (paid)",gender:"male",tier:"paid"},{id:"UQoLnPXvf18gaKpLzfb8",name:"Sawyer",subtitle:"Calm, measured & serious (paid)",gender:"male",tier:"paid"}],A5=Og[0].id,T5=new Set(Og.map(n=>n.id));function Bg(n){return n&&T5.has(n)?n:A5}const E5=new Set(["localhost","127.0.0.1","::1"]);function Ng(n){try{const a=new URL(n);if(a.protocol==="https:"||a.protocol==="wss:"||(a.protocol==="http:"||a.protocol==="ws:")&&E5.has(a.hostname))return!0}catch{return!1}return!1}function j5(n){if(!Ng(n))throw new Error("Inline blocks non-local insecure network requests. Use HTTPS for synced workspace and AI requests.")}const _g=ac;function C5(n){if(typeof n!="string"||!n)return _g;const a=n.replace(/\/$/,"");return Ng(a)?a:_g}async function yn(){return new Promise(n=>{chrome.storage.local.get(["inlineApiBase","inlineAccessToken","inlineBlockedDomains","inlineFocusMode","inlineVoiceId","inlineScreenReader"],a=>{let l=[];try{const r=a.inlineBlockedDomains;typeof r=="string"&&(l=JSON.parse(r))}catch{}n({apiBaseUrl:C5(a.inlineApiBase),accessToken:typeof a.inlineAccessToken=="string"?a.inlineAccessToken:"",blockedDomains:Array.isArray(l)?l:[],focusMode:a.inlineFocusMode==="true"||a.inlineFocusMode===!0,voiceId:Bg(typeof a.inlineVoiceId=="string"?a.inlineVoiceId:void 0),screenReader:a.inlineScreenReader==="true"||a.inlineScreenReader===!0})})})}let xn=null;function Cs(){if(xn){if(xn.kind==="audio")try{xn.el.pause()}catch{}else if(xn.kind==="utterance")try{window.speechSynthesis.cancel()}catch{}xn=null}}function M5(n,a){const l=new Audio(n);xn={kind:"audio",el:l},l.onended=()=>{URL.revokeObjectURL(n),xn=null,a?.onEnd?.()},l.onerror=()=>{URL.revokeObjectURL(n),xn=null,a?.onEnd?.()},l.play()}function k5(n,a,l){return new Promise(r=>{if(typeof chrome>"u"||!chrome.runtime?.sendMessage){r(!1);return}chrome.runtime.sendMessage({type:"INLINE_TTS",payload:{text:n,voiceId:a}},d=>{if(chrome.runtime.lastError){r(!1);return}if(!d?.ok||!d.audioBase64){r(!1);return}try{l?.onStart?.();const f=atob(d.audioBase64),h=new Uint8Array(f.length);for(let g=0;g"u"||!window.speechSynthesis)return!1;const l=window.speechSynthesis,r=new SpeechSynthesisUtterance(n);r.rate=1,r.pitch=1;const f=l.getVoices().find(h=>/en(-|_)?(US|GB)?/i.test(h.lang));return f&&(r.voice=f),r.onstart=()=>{a?.onStart?.()},r.onend=()=>{xn=null,a?.onEnd?.()},r.onerror=()=>{xn=null,a?.onEnd?.()},xn={kind:"utterance",utterance:r},l.speak(r),!0}catch{return!1}}async function lr(n,a){Cs();const l=n.slice(0,2e3);if(!l.trim())return;const{voiceId:r}=await yn(),d=Bg(r);await k5(l,d,a)||(a?.onFallback?.(),!R5(l,a)&&a?.onEnd?.())}const mc=[{id:"tldr",label:"TL;DR for exec",prompt:"Summarize this in 2-3 bullet points suitable for an executive briefing."},{id:"bug-report",label:"Bug report",prompt:"Rewrite this as a structured bug report with: Summary, Steps to Reproduce, Expected Behavior, Actual Behavior."},{id:"meeting-notes",label:"Meeting notes",prompt:"Reformat this as structured meeting notes with: Key Decisions, Action Items, and Follow-ups."},{id:"eli5",label:"Explain simply",prompt:"Explain this in simple terms that a non-technical person could understand."},{id:"pros-cons",label:"Pros & Cons",prompt:"Analyze this and list the pros and cons in a balanced way."},{id:"action-items",label:"Action items",prompt:"Extract all action items and to-dos from this text as a numbered list."}];async function ci(n,a={}){if(j5(n),typeof chrome>"u"||!chrome.runtime?.sendMessage)throw new Error("Background service worker unavailable");const l=await new Promise((r,d)=>{chrome.runtime.sendMessage({type:"INLINE_PROXY_FETCH",payload:{url:n,method:a.method??"GET",headers:a.headers??{},body:a.body}},f=>{if(chrome.runtime.lastError){d(new Error(chrome.runtime.lastError.message));return}if(!f){d(new Error("No response from background"));return}r(f)})});if(l.error&&!l.ok)throw new Error(l.error);return{ok:l.ok,status:l.status,bodyText:l.bodyText,json:async()=>JSON.parse(l.bodyText),text:async()=>l.bodyText}}const rr="inlineGuestDeviceId",gc="inlineGuestAiUsage",bn=10;function yc(n){if(typeof n!="string")return!1;const a=n.split(".");return a.length===3&&a.every(l=>l.length>0)}function D5(){try{return crypto.randomUUID()}catch{return`guest-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}async function z5(){const n=await chrome.storage.local.get([rr]),a=typeof n[rr]=="string"?n[rr]:"";if(a)return a;const l=D5();return await chrome.storage.local.set({[rr]:l}),l}function L5(n){if(!n||typeof n!="object")return{used:0,updatedAt:0};const a=n;return{used:typeof a.used=="number"&&Number.isFinite(a.used)?Math.max(0,a.used):0,updatedAt:typeof a.updatedAt=="number"?a.updatedAt:0}}async function Ug(){const[n,a]=await Promise.all([chrome.storage.local.get(["inlineAccessToken",gc]),z5()]),l=yc(n.inlineAccessToken),r=L5(n[gc]);return{allowed:l||r.used"u"?{pageUrl:"",pageTitle:""}:{pageUrl:window.location?.href??"",pageTitle:document?.title??""}}async function Hg(n){try{const{pageUrl:a,pageTitle:l}=O5(),{apiBaseUrl:r,accessToken:d}=await yn(),f=await new Promise(A=>{chrome.storage.local.get(["inlineActiveWorkspaceId","inlineUserId"],j=>{A(j)})}),h=n.workspaceId??f.inlineActiveWorkspaceId??"",p=f.inlineUserId??"";if(!yc(d)||!h)return;const y={"ai-rephrase":["ai","rephrase"],"ai-shorten":["ai","shorten"],"ai-summarize":["ai","summary"],"ai-rewrite":["ai","rewrite"],"ai-custom":["ai","custom"],"manual-rewrite":["manual","rewrite"],clip:["clip"]},g={"ai-rephrase":"ai-summary","ai-shorten":"ai-summary","ai-summarize":"ai-summary","ai-rewrite":"ai-summary","ai-custom":"ai-summary","manual-rewrite":"text",clip:"clip"},b={pageUrl:n.pageUrl??a,pageTitle:n.pageTitle??l,workspaceId:h,userId:p,type:g[n.kind],tags:y[n.kind],content:n.selection?`> ${n.selection} -> ${i.selection} - -${i.result}`:i.result},S={"Content-Type":"application/json"};S.Authorization=`Bearer ${d}`,await ri(`${r}/api/clip`,{method:"POST",headers:S,body:JSON.stringify(b)})}catch{}}const Rg={rephrase:{bg:"rgba(167, 139, 250, 0.25)",border:"rgba(139, 92, 246, 0.5)"},shorten:{bg:"rgba(251, 191, 36, 0.3)",border:"rgba(217, 119, 6, 0.5)"},summarize:{bg:"rgba(110, 231, 183, 0.3)",border:"rgba(5, 150, 105, 0.5)"},rewrite:{bg:"rgba(147, 197, 253, 0.3)",border:"rgba(37, 99, 235, 0.55)"},custom:{bg:"rgba(248, 180, 217, 0.35)",border:"rgba(236, 72, 153, 0.55)"},default:{bg:"rgba(244, 231, 211, 0.4)",border:"rgba(161, 98, 7, 0.4)"}},p5={rephrase:"Rephrased by Inline AI",shorten:"Shortened by Inline AI",summarize:"Summarized by Inline AI",rewrite:"Rewritten by Inline AI",custom:"Custom AI prompt applied"};function er(i,a,l){const r=Rg[a]?a:"default",d=Rg[r],f=p5[a]??"Inline AI edit",h=l?` — ${l.slice(0,120)}`:"",p=document.createElement("mark");return p.setAttribute("data-inline-ai",a||"edit"),p.setAttribute("title",`${f}${h}`),p.setAttribute("aria-label",f),p.style.background=d.bg,p.style.borderBottom=`1.5px solid ${d.border}`,p.style.borderRadius="3px",p.style.padding="0 2px",p.style.color="inherit",p.style.transition="background 120ms ease",p.textContent=i,p.addEventListener("mouseenter",()=>{p.style.boxShadow=`0 0 0 2px ${d.border}`}),p.addEventListener("mouseleave",()=>{p.style.boxShadow="none"}),p}let Dg=[];function m5(){return`air-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ba(){return Dg}function cc(i){Dg=i}function zg(i){try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"aiReplacements",data:i,pageTitle:document.title,domain:window.location.hostname,clearedAt:i.length===0?Date.now():null}},()=>{chrome.runtime.lastError})}catch{}}function Lg(i,a,l,r,d){const f=m5();i.setAttribute("data-inline-ai-id",f);const h={id:f,originalText:a,aiText:l,task:r,instruction:d,timestamp:Date.now()},p=[...ba(),h];return cc(p),zg(p),Og(i,f),f}function g5(i){const a=ba().filter(l=>l.id!==i);cc(a),zg(a)}function Og(i,a){i.style.cursor="pointer";const l=d=>{if(!d.target?.classList.contains("inline-ai-remove-badge")&&!d.altKey)return;d.preventDefault(),d.stopPropagation();const p=ba().find(b=>b.id===a);g5(a);const y=i.parentNode;if(!y)return;const g=document.createTextNode(p?.originalText??i.textContent??"");y.replaceChild(g,i)};i.addEventListener("click",l);const r=document.createElement("span");r.className="inline-ai-remove-badge",r.textContent="×",r.setAttribute("aria-label","Remove this AI edit"),r.title="Remove this AI edit",r.style.cssText=["display:none","position:absolute","top:-10px","right:-8px","width:18px","height:18px","border-radius:9999px","background:#1C1E26","color:#fff","font:600 11px/18px system-ui,sans-serif","text-align:center","cursor:pointer","user-select:none","box-shadow:none","z-index:2147483646"].join(";"),i.style.position||(i.style.position="relative"),i.appendChild(r),i.addEventListener("mouseenter",()=>{r.style.display="inline-block"}),i.addEventListener("mouseleave",()=>{r.style.display="none"})}function y5(){const i=ba();i.length>0&&Bg(i);try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},a=>{if(chrome.runtime.lastError||!a?.ok)return;const l=a.data?.elements?.aiReplacements;if(!Array.isArray(l)||l.length===0)return;const r=new Set(ba().map(h=>h.id)),d=l.filter(h=>!r.has(h.id));if(d.length===0)return;const f=[...ba(),...d];cc(f),Bg(d)})}catch{}}function Bg(i){const a=document.body;if(a)for(const l of i){if(!l.originalText||l.originalText.length<3||document.querySelector(`[data-inline-ai-id="${CSS.escape(l.id)}"]`))continue;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,{acceptNode(f){const h=f.parentElement;if(!h||h.closest("[data-inline-ai-id]")||h.closest("#inline-extension-root"))return NodeFilter.FILTER_REJECT;const p=h.tagName;return p==="SCRIPT"||p==="STYLE"||p==="NOSCRIPT"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let d;for(;d=r.nextNode();){const f=d.textContent?.indexOf(l.originalText)??-1;if(f!==-1){try{const h=document.createRange();h.setStart(d,f),h.setEnd(d,f+l.originalText.length);const p=er(l.aiText,l.task,l.instruction);p.setAttribute("data-inline-ai-id",l.id),h.deleteContents(),h.insertNode(p),Og(p,l.id)}catch{}break}}}}const Ng=/^[*•\-]\s+/,_g=/^\d+[.)]\s+/;function Vg(i){return i.replace(/^[*•\-]\s+/,"").replace(/^\d+[.)]\s+/,"")}function dc({text:i,style:a}){const l={fontSize:14,lineHeight:1.625,color:x.text,...a};if(!i.trim())return null;const r=i.split(/\n\n+/);return u.jsx("div",{style:l,children:r.map((d,f)=>{const h=d.trim();if(!h)return null;const p=h.split(` -`).map(A=>A.trim()).filter(Boolean),y=p.filter(A=>Ng.test(A)),g=p.filter(A=>_g.test(A)),b=p.filter(A=>!Ng.test(A)&&!_g.test(A)),S=f0?u.jsxs("div",{style:{marginBottom:S},children:[b.length>0&&u.jsx("p",{style:{margin:"0 0 8px"},children:b.join(" ")}),u.jsx("ul",{style:{margin:0,paddingLeft:20,listStyleType:"disc"},children:y.map((A,j)=>u.jsx("li",{style:{marginBottom:j0?u.jsxs("div",{style:{marginBottom:S},children:[b.length>0&&u.jsx("p",{style:{margin:"0 0 8px"},children:b.join(" ")}),u.jsx("ol",{style:{margin:0,paddingLeft:20},children:g.map((A,j)=>u.jsx("li",{style:{marginBottom:ju.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),u.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),b5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]}),v5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),u.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),S5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5"})}),w5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M8 7l-4 5 4 5M16 7l4 5-4 5M14 4l-4 16"})}),A5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:u.jsx("path",{d:"M4 6h16M4 10h16M4 14h10M4 18h7"})}),T5=["Formal","Casual","Concise"],E5=[{label:"Rephrase",desc:"Reword while keeping the meaning",task:"rephrase",icon:u.jsx(S5,{})},{label:"Shorten",desc:"Trim it down without losing the point",task:"shorten",icon:u.jsx(w5,{})},{label:"Summarize",desc:"Condense to the essentials",task:"summarize",icon:u.jsx(A5,{})}];function j5(i,a){const l=i.split(/(\s+)/),r=a.split(/(\s+)/);let d=0;for(;d=d&&h>=d&&l[f]===r[h];)f--,h--;const p=[];d>0&&p.push({type:"same",text:l.slice(0,d).join("")});const y=l.slice(d,f+1).join(""),g=r.slice(d,h+1).join("");y&&p.push({type:"del",text:y}),g&&p.push({type:"add",text:g});const b=f+1;return b0;function $(){if(D){Ss(),O(!1);return}f&&Jl(f,{onStart:()=>O(!0),onEnd:()=>O(!1)})}const tt=v.useCallback(async(it,rt)=>{y(!0),va(!0),h(null),Q(it),T(rt);try{const mt=await ws();if(!mt.allowed){h(`Sign in to keep using AI. Guest mode includes ${xn} free prompts on this browser.`);return}const kt=i.slice(0,8e3),{apiBaseUrl:B,accessToken:at}=await gn(),G={"Content-Type":"application/json"};mt.signedIn&&at&&(G.Authorization=`Bearer ${at}`),mt.signedIn||(G["X-Inline-Device-Id"]=mt.deviceId);const ct=await ri(`${B}/api/ai/extension-light`,{method:"POST",headers:G,body:JSON.stringify({task:it,text:kt,instruction:rt,guest:!mt.signedIn,deviceId:mt.signedIn?void 0:mt.deviceId})});if(ct.ok){const bt=await ct.json(),M=bt.result??"No result returned.";h(M),bt.result&&kg({kind:{rephrase:"ai-rephrase",shorten:"ai-shorten",summarize:"ai-summarize",rewrite:rt?"ai-custom":"ai-rewrite"}[it]??"ai-custom",selection:kt,result:M})}else h("AI request failed. Check your API settings.")}catch{h("Could not reach AI server.")}finally{y(!1),va(!1)}},[i]);function P(){if(!(!f||!a))try{const it=a.toString();L.current=it,a.deleteContents();const rt=er(f,F,E);rt.style.display="inline-block",rt.style.lineHeight="1.55";const mt=document.createElement("span");mt.className="inline-cite-attr",mt.style.cssText="display:block;font-size:10px;color:#78716c;margin-top:4px;font-style:italic;",mt.textContent=`via Inline · ${new Date().toLocaleString()}`,rt.appendChild(document.createElement("br")),rt.appendChild(mt),a.insertNode(rt),k(!0),Lg(rt,it,f,F,E)}catch{}}function W(){if(!(!L.current||!a))try{a.deleteContents(),a.insertNode(document.createTextNode(L.current)),L.current=null,k(!1)}catch{}}function lt(){f&&navigator.clipboard.writeText(f)}return!f&&!p?u.jsx(mn,{title:"Rewrite",subtitle:"Reword your selection with AI",chip:U?"Selection":void 0,tool:"rewrite",width:342,onClose:l,footer:u.jsx("div",{style:{padding:"10px 14px 12px"},children:u.jsx(lc,{value:g,onChange:b,onSubmit:()=>{g.trim()&&tt("rewrite",g)},placeholder:U?"Describe how to rewrite it...":"Select text to rewrite",sendDisabled:!U,modeLabel:r})}),children:u.jsxs("div",{style:{padding:16,display:"flex",flexDirection:"column",gap:16},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tone"}),u.jsx(sc,{options:T5.map(it=>({value:it,label:it})),value:r,onChange:d})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Rewrite as"}),u.jsx("div",{style:{display:"flex",flexDirection:"column",gap:9},children:E5.map(it=>u.jsx(ac,{icon:it.icon,label:it.label,desc:it.desc,disabled:!U,onClick:()=>tt(it.task,`Tone: ${r}`)},it.label))}),!U&&u.jsx("p",{style:{margin:"10px 2px 0",fontSize:11.5,color:x.textLight,lineHeight:1.5},children:"Select text on the page to rewrite it."})]}),rc.length>0&&u.jsxs("div",{children:[u.jsx(ye,{children:"Quick prompts"}),u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:rc.map(it=>u.jsx(Sg,{label:it.label,disabled:!U,onClick:()=>tt("rewrite",it.prompt)},it.id))})]})]})}):u.jsx(mn,{title:"Rewrite",subtitle:p?"Rewriting...":"Review & apply",chip:E?"Custom":F||void 0,tool:"rewrite",width:342,onClose:l,footer:p?void 0:u.jsxs("div",{style:{padding:"10px 14px",display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[u.jsx("button",{type:"button",onClick:()=>{h(null),A(!1),k(!1)},"aria-label":"Back",style:Ig,children:"Back"}),u.jsx("button",{type:"button",onClick:()=>A(it=>!it),"aria-label":S?"Hide diff":"Show diff",style:Ig,children:S?"Hide diff":"Diff"}),j?u.jsx("button",{type:"button",onClick:W,"aria-label":"Undo insert",style:{...Yg,background:"#DC2626",boxShadow:"none"},children:"Undo"}):u.jsx("button",{type:"button",onClick:P,"aria-label":"Insert into page",style:Yg,children:"Insert"}),u.jsx("button",{type:"button",onClick:$,"aria-label":D?"Stop speaking":"Speak",style:{...Gg,marginLeft:"auto"},children:D?u.jsx(v5,{}):u.jsx(b5,{})}),u.jsx("button",{type:"button",onClick:lt,"aria-label":"Copy",style:Gg,children:u.jsx(x5,{})})]}),children:u.jsxs("div",{style:{padding:18,display:"flex",flexDirection:"column",gap:14},children:[u.jsx("div",{style:{padding:15,border:`1px solid ${x.border}`,borderRadius:16,minHeight:80,background:x.surfaceBubble,boxShadow:"none",maxHeight:280,overflowY:"auto"},children:p?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:13.5,lineHeight:1.7},children:[u.jsx(xa,{size:16}),u.jsx("span",{style:{fontStyle:"italic"},children:"Generating..."})]}):S&&f?u.jsx("span",{style:{fontSize:13.5,lineHeight:1.7,color:x.text},children:j5(i,f).map((it,rt)=>it.type==="del"?u.jsx("span",{style:{color:"#ef4444",textDecoration:"line-through",background:"rgba(239,68,68,0.1)"},children:it.text},rt):it.type==="add"?u.jsx("span",{style:{color:"#16a34a",background:"rgba(34,197,94,0.12)"},children:it.text},rt):u.jsx("span",{children:it.text},rt))}):f?u.jsx(dc,{text:f,style:{fontSize:13.5,lineHeight:1.7}}):null}),!p&&u.jsx(lc,{value:g,onChange:b,onSubmit:()=>{g.trim()&&tt("rewrite",g)},placeholder:"Refine with another instruction...",sendDisabled:!U,modeLabel:r})]})})}const Ig={padding:"8px 13px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12.5,fontWeight:600,cursor:"pointer",color:x.text,fontFamily:gt,boxShadow:"none"},Yg={padding:"8px 16px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none"},Gg={display:"inline-flex",alignItems:"center",justifyContent:"center",width:34,height:34,border:`1px solid ${x.border}`,borderRadius:11,background:x.surfaceBubble,cursor:"pointer",padding:0,color:x.textMuted,boxShadow:"none"};function nr(i){if(!i?.ok&&!i?.queued)return;const a=i.storageMode==="workspace";document.dispatchEvent(new CustomEvent("inline:toast",{detail:a?{message:"Saved to Workspace",tone:"success",action:"dashboard"}:{message:"Saved to browser.",tone:"local"}}))}const M5={summarize:{bg:"rgba(187,247,208,0.92)",title:"Summarized via Inline"},rephrase:{bg:"rgba(196,181,253,0.92)",title:"Rephrased via Inline"},rewrite:{bg:"rgba(191,219,254,0.92)",title:"Rewritten via Inline"},shorten:{bg:"rgba(254,215,170,0.92)",title:"Shortened via Inline"},extract:{bg:"rgba(233,213,255,0.92)",title:"Extracted via Inline"},risk:{bg:"rgba(254,202,202,0.92)",title:"Risk-flagged via Inline"},"selection-hold":{bg:"rgba(147,197,253,0.55)",title:"Selected for Inline"}};function k5(){return`hl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}let ir=[];function R5(i){ir=[...ir,i];try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"highlights",data:ir,pageTitle:document.title,domain:window.location.hostname}},a=>{chrome.runtime.lastError||nr(a)})}catch{}}function D5(i){const a=i.commonAncestorContainer;return!!(a.nodeType===Node.ELEMENT_NODE?a:a.parentElement)?.closest("[data-inline-highlight]")}function qg(i,a,l){const r=i.toString();if(!r.trim()||D5(i))return null;const d=M5[a]??{bg:"rgba(226,232,240,0.95)",title:"Highlighted by Inline"},f=l??d.bg,h=i.cloneRange(),p=document.createElement("span");p.setAttribute("data-inline-highlight",a),p.style.backgroundColor=f,p.style.borderRadius="4px",p.style.padding="0 3px",p.title=d.title;try{h.surroundContents(p)}catch{const g=h.extractContents();p.appendChild(g),h.insertNode(p)}R5({id:k5(),text:r.trim(),action:a,bg:f,title:d.title,timestamp:Date.now()});const y=document.createRange();return y.selectNode(p),document.dispatchEvent(new CustomEvent("inline:highlightAdded")),{text:r,title:d.title,span:p,range:y}}function oi(i,a){const l=window.getSelection();if(!l||l.rangeCount===0||l.isCollapsed)return null;const r=qg(l.getRangeAt(0),i,a);return r?(l.removeAllRanges(),{text:r.text,title:r.title,span:r.span}):null}function z5(i){const a=document.body;if(a)for(const l of i){if(!l.text||l.text.length<3)continue;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);let d;for(;d=r.nextNode();){const f=d.textContent?.indexOf(l.text)??-1;if(!(f===-1||d.parentElement?.hasAttribute("data-inline-highlight"))){try{const p=document.createRange();p.setStart(d,f),p.setEnd(d,f+l.text.length);const y=document.createElement("span");y.setAttribute("data-inline-highlight",l.action),y.style.backgroundColor=l.bg,y.style.borderRadius="4px",y.style.padding="0 3px",y.title=l.title,p.surroundContents(y)}catch{}break}}}}function L5(){try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},i=>{if(chrome.runtime.lastError||!i?.ok)return;const a=i.data?.elements?.highlights;!Array.isArray(a)||a.length===0||(ir=a,z5(a),document.dispatchEvent(new CustomEvent("inline:highlightsRestored")))})}catch{}}const Xg=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]}),O5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:u.jsx("path",{d:"M4 6h16M4 10h16M4 14h10M4 18h7"})}),B5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5"})}),N5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M8 7l-4 5 4 5M16 7l4 5-4 5M14 4l-4 16"})}),_5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M9 11l2 2 4-4M4 6h.01M4 12h.01M4 18h.01M9 18h11M9 6h11"})}),V5=[{label:"Summarize",desc:"Key points",task:"summarize",icon:u.jsx(O5,{})},{label:"Rephrase",desc:"Same meaning",task:"rephrase",icon:u.jsx(B5,{})},{label:"Shorten",desc:"Make it tight",task:"shorten",icon:u.jsx(N5,{})},{label:"Action items",desc:"Checklist",task:"rewrite",instruction:"Extract the key takeaways as a short, clear checklist of action items.",icon:u.jsx(_5,{})}];function U5(i){if(!i)return!1;const a=i.commonAncestorContainer;return!!(a.nodeType===Node.ELEMENT_NODE?a:a.parentElement)?.closest('textarea,input,[contenteditable="true"],[contenteditable="plaintext-only"],[role="textbox"]')}function H5({selectedText:i,originalRange:a,onClose:l}){const[r,d]=v.useState(""),[f,h]=v.useState(null),[p,y]=v.useState(!1),[g,b]=v.useState(""),[S,A]=v.useState(void 0),[j,k]=v.useState("idle"),[D,O]=v.useState({title:"",domain:""}),[F,Q]=v.useState(!1);v.useEffect(()=>{O({title:document.title||"Untitled page",domain:window.location.hostname})},[]);const E=i.trim().length>0,T=U5(a),L=rc.filter(W=>!["eli5","pros-cons","action-items"].includes(W.id)),U=v.useCallback(async()=>{k("loading"),va(!0);try{const{apiBaseUrl:W,accessToken:lt}=await gn(),it=await new Promise(B=>{chrome.storage.local.get(["inlineActiveWorkspaceId"],at=>{B(typeof at.inlineActiveWorkspaceId=="string"&&at.inlineActiveWorkspaceId?at.inlineActiveWorkspaceId:"")})});if(!lt||!it){k("error");return}const rt={"Content-Type":"application/json"};lt&&(rt.Authorization=`Bearer ${lt}`);const mt=await ri(`${W}/api/ai/page-recap`,{method:"POST",headers:rt,body:JSON.stringify({workspaceId:it,pageUrl:window.location.href})});if(!mt.ok){k("error");return}const kt=await mt.json();k(kt.skipped?"empty":"done")}catch{k("error")}finally{va(!1)}},[]),$=v.useCallback(async(W,lt)=>{E&&oi(W),y(!0),va(!0),h(null),Q(!1),b(W),A(lt);try{const it=await ws();if(!it.allowed){h(`Sign in to keep using AI. Guest mode includes ${xn} free prompts on this browser.`);return}const rt=document.body?.innerText??"",mt=(E?i:rt).slice(0,8e3),{apiBaseUrl:kt,accessToken:B}=await gn(),at={"Content-Type":"application/json"};it.signedIn&&B&&(at.Authorization=`Bearer ${B}`),it.signedIn||(at["X-Inline-Device-Id"]=it.deviceId);const G=await ri(`${kt}/api/ai/extension-light`,{method:"POST",headers:at,body:JSON.stringify({task:W,text:mt,instruction:lt,guest:!it.signedIn,deviceId:it.signedIn?void 0:it.deviceId})});if(G.ok){const ct=await G.json(),bt=ct.result??"No result returned.";h(bt),ct.result&&kg({kind:{rephrase:"ai-rephrase",shorten:"ai-shorten",summarize:"ai-summarize",rewrite:lt?"ai-custom":"ai-rewrite"}[W]??"ai-custom",selection:mt,result:bt})}else h("AI request failed. Check settings.")}catch{h("Could not reach AI server.")}finally{y(!1),va(!1)}},[E,i]);function tt(){if(!(!f||!a)){try{a.deleteContents();const W=er(f,g,S);a.insertNode(W)}catch{}l()}}function P(){f&&(navigator.clipboard.writeText(f),Q(!0),window.setTimeout(()=>Q(!1),1400))}return!f&&!p?u.jsx(mn,{title:"Ask",subtitle:E?"Working with your selection":"Working with this page",chip:E?"Selection":"Page",width:342,onClose:l,tool:"ai",children:u.jsxs("div",{style:ya,children:[u.jsxs(Mn,{children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:x.radiusSm,background:x.surfaceMuted,color:x.textMuted,flexShrink:0},children:u.jsx(Xg,{})}),u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.title||"This page"}),u.jsx("span",{style:{display:"block",fontSize:12,color:x.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.domain})]})]}),E&&u.jsxs("p",{style:{margin:"9px 0 0",padding:"8px 10px",borderRadius:x.radiusSm,background:x.surfaceMuted,fontSize:14,lineHeight:1.55,color:x.textMuted,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:['"',i.trim(),'"']})]}),u.jsx(lc,{value:r,onChange:d,onSubmit:()=>{$("rewrite",r)},placeholder:E?"Ask about the selected text…":"Ask about this page…",modeLabel:"Smart mode"}),u.jsxs("div",{children:[u.jsx(ye,{children:"Quick actions"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:V5.map(W=>u.jsx(ac,{icon:W.icon,label:W.label,desc:W.desc,onClick:()=>{$(W.task,W.instruction)}},W.label))}),u.jsx("p",{style:{margin:"9px 2px 0",fontSize:12,color:x.textMuted,lineHeight:1.5},children:E?"Actions use your highlighted selection first.":"Actions use visible page text when nothing is selected."})]}),L.length>0&&u.jsxs("div",{children:[u.jsx(ye,{children:"Suggestions"}),u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:L.map(W=>u.jsx(Sg,{label:W.label,onClick:()=>{$("rewrite",W.prompt)}},W.id))})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Page tools"}),u.jsx(ac,{icon:j==="loading"?u.jsx(xa,{size:15}):u.jsx(Xg,{}),label:j==="loading"?"Generating recap...":"Page recap",desc:"Save a clean summary to your library",disabled:j==="loading",onClick:()=>{U()}}),j==="done"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:"#0f766e"},children:"Recap saved to your workspace library."}),j==="empty"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:x.textMuted},children:"No captures on this page yet. Highlight or clip something first."}),j==="error"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:"#b91c1c"},children:"Recap needs cloud sync. Sign in or open the dashboard to connect your workspace."})]})]})}):u.jsx(mn,{title:"Ask",subtitle:p?"Thinking…":E?g==="summarize"?"Summary update":g==="rephrase"?"Rephrase update":g==="shorten"?"Shorten update":"Rewrite update":"Here is your result",chip:g?S?"Custom":g:void 0,width:342,onClose:l,tool:"ai",footer:p?void 0:u.jsx(Zl,{onBack:()=>{h(null),Q(!1)},onReject:()=>{h(null),Q(!1)},onApprove:T?tt:P,approveLabel:T?"Approve":F?"Copied":"Copy",showReject:!!f}),children:u.jsx("div",{style:{padding:"16px 20px"},children:u.jsx(ic,{children:p?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14,fontStyle:"italic"},children:[u.jsx(xa,{size:16})," Putting together the best answer — one moment, Inline…"]}):f&&E?u.jsx(vg,{original:i,updated:f}):f?u.jsx(dc,{text:f,style:{fontSize:13.5,lineHeight:1.55}}):null})})})}const I5={Plain:"none",Ruled:"repeating-linear-gradient(to bottom, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px)",Grid:"repeating-linear-gradient(to bottom, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px), repeating-linear-gradient(to right, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px)",Dotted:"radial-gradient(circle, rgba(180,170,160,0.3) 1px, transparent 1px)"},Y5={Plain:"auto",Ruled:"auto",Grid:"auto",Dotted:"20px 20px"},G5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#1C1E26",children:[u.jsx("path",{d:"M5 0h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2 2 2 0 0 1-2 2H3a2 2 0 0 1-2-2h1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1H1a2 2 0 0 1 2-2h2V1a1 1 0 0 0-1 1H3a2 2 0 0 1 2-2z"}),u.jsx("path",{d:"M1 6v-.5a.5.5 0 0 1 1 0V6h.5a.5.5 0 0 1 0 1H2v.5a.5.5 0 0 1-1 0V7h-.5a.5.5 0 0 1 0-1H1z"})]}),q5=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#78716c",children:u.jsx("path",{d:"M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854z"})}),Fg={Normal:{tag:"div",size:13,weight:400},Subheading:{tag:"h3",size:15,weight:500},Heading:{tag:"h2",size:18,weight:500}};function X5({onClose:i,initialX:a=100,initialY:l=100,initialW:r=320,initialH:d=260,initialContent:f="",initialPaperStyle:h="Plain",onUpdate:p}){const[y,g]=v.useState("Normal"),[b,S]=v.useState(!1),[A,j]=v.useState(h),[k,D]=v.useState(!1),[O,F]=v.useState({x:a,y:l}),[Q,E]=v.useState({w:r,h:d}),T=v.useRef(null),L=v.useRef(null),U=v.useRef(O),$=v.useRef(Q),tt="You",P=new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"})+", "+new Date().toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),W=v.useCallback(G=>{G.preventDefault(),L.current={ox:G.clientX-O.x,oy:G.clientY-O.y},G.target.setPointerCapture(G.pointerId)},[O]),lt=v.useCallback(G=>{if(!L.current)return;const ct={x:Math.max(8,Math.min(window.innerWidth-48,G.clientX-L.current.ox)),y:Math.max(8,Math.min(window.innerHeight-48,G.clientY-L.current.oy))};U.current=ct,F(ct)},[]),it=v.useCallback(()=>{L.current&&(L.current=null,p?.(U.current))},[p]),rt=v.useCallback(G=>{G.preventDefault(),G.stopPropagation();const ct=G.clientX,bt=G.clientY,M=Q.w,K=Q.h;let nt={w:M,h:K};const dt=Y=>{nt={w:Math.max(240,M+Y.clientX-ct),h:Math.max(180,K+Y.clientY-bt)},$.current=nt,E(nt)},vt=()=>{window.removeEventListener("mousemove",dt),window.removeEventListener("mouseup",vt),p?.($.current)};window.addEventListener("mousemove",dt),window.addEventListener("mouseup",vt)},[Q,p]);function mt(G){T.current?.focus(),document.execCommand(G,!1,void 0)}function kt(G){g(G),S(!1),T.current?.focus(),G==="Heading"?document.execCommand("formatBlock",!1,"h2"):G==="Subheading"?document.execCommand("formatBlock",!1,"h3"):document.execCommand("formatBlock",!1,"div")}v.useEffect(()=>{T.current&&f&&(T.current.innerHTML=f),T.current?.focus()},[]);const B=v.useRef(null),at=v.useCallback(()=>{p&&(B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{p({content:T.current?.innerHTML??""})},400))},[p]);return u.jsxs("div",{style:{position:"fixed",left:O.x,top:O.y,width:Q.w,height:Q.h,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadow,fontFamily:gt,display:"flex",flexDirection:"column",overflow:"hidden",zIndex:2147483646,pointerEvents:"auto"},children:[u.jsxs("div",{onPointerDown:W,onPointerMove:lt,onPointerUp:it,style:{display:"flex",alignItems:"center",gap:2,padding:"8px 12px",background:x.headerBg,borderBottom:`1px solid ${x.divider}`,cursor:"grab",flexShrink:0,touchAction:"none"},children:[u.jsx(G5,{}),u.jsxs("div",{style:{position:"relative",marginLeft:6},children:[u.jsxs("button",{onPointerDown:G=>G.stopPropagation(),onClick:()=>S(G=>!G),style:{display:"flex",alignItems:"center",gap:3,padding:"5px 12px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,background:x.surfaceBubble,fontSize:11,fontWeight:500,color:x.text,cursor:"pointer",boxShadow:x.shadowSoft},children:["Aa ",u.jsx("span",{style:{fontSize:8,color:x.textLight},children:"▼"})]}),b&&u.jsx("div",{style:{position:"absolute",top:"100%",left:0,marginTop:6,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusMd,boxShadow:x.shadow,zIndex:10,overflow:"hidden",minWidth:128},children:["Normal","Subheading","Heading"].map(G=>u.jsx("button",{onPointerDown:ct=>ct.stopPropagation(),onClick:()=>kt(G),style:{display:"block",width:"100%",textAlign:"left",padding:"7px 12px",border:"none",borderRadius:0,background:y===G?x.headerBg:"transparent",fontSize:Fg[G].size*.75,fontWeight:Fg[G].weight,color:x.text,cursor:"pointer"},children:G},G))})]}),u.jsxs("div",{style:{position:"relative",marginLeft:2},children:[u.jsxs("button",{onPointerDown:G=>G.stopPropagation(),onClick:()=>{D(G=>!G),S(!1)},style:{display:"flex",alignItems:"center",gap:3,padding:"5px 10px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,background:x.surfaceBubble,fontSize:11,fontWeight:500,color:x.text,cursor:"pointer",boxShadow:x.shadowSoft},children:[u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm2-1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H4z"})}),u.jsx("span",{style:{fontSize:8,color:x.textLight},children:"▼"})]}),k&&u.jsx("div",{style:{position:"absolute",top:"100%",left:0,marginTop:6,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusMd,boxShadow:x.shadow,zIndex:10,overflow:"hidden",minWidth:110},children:["Plain","Ruled","Grid","Dotted"].map(G=>u.jsx("button",{onPointerDown:ct=>ct.stopPropagation(),onClick:()=>{j(G),D(!1),p?.({paperStyle:G})},style:{display:"block",width:"100%",textAlign:"left",padding:"7px 12px",border:"none",borderRadius:0,background:A===G?x.headerBg:"transparent",fontSize:12,fontWeight:500,color:x.text,cursor:"pointer",fontFamily:gt},children:G},G))})]}),u.jsx("div",{style:{width:1,height:18,background:x.divider,margin:"0 4px",flexShrink:0}}),u.jsx(As,{onPointerDown:G=>G.stopPropagation(),onClick:()=>mt("bold"),"aria-label":"Bold",children:u.jsx("b",{style:{fontSize:12},children:"B"})}),u.jsx(As,{onPointerDown:G=>G.stopPropagation(),onClick:()=>mt("italic"),"aria-label":"Italic",children:u.jsx("i",{style:{fontSize:12},children:"I"})}),u.jsx(As,{onPointerDown:G=>G.stopPropagation(),onClick:()=>mt("underline"),"aria-label":"Underline",children:u.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#1C1E26"},children:"A"})}),u.jsx("div",{style:{width:1,height:18,background:x.divider,margin:"0 4px",flexShrink:0}}),u.jsx(As,{onPointerDown:G=>G.stopPropagation(),onClick:()=>mt("insertUnorderedList"),"aria-label":"Bullet list",children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-8a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"})})}),u.jsx(As,{onPointerDown:G=>G.stopPropagation(),onClick:()=>mt("insertOrderedList"),"aria-label":"Numbered list",children:u.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:[u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z"}),u.jsx("path",{d:"M1.713 11.865v-.474H2c.217 0 .363-.137.363-.317 0-.185-.158-.31-.361-.31-.223 0-.367.152-.373.31h-.59c.016-.467.373-.787.986-.787.588-.002.954.291.957.703a.595.595 0 0 1-.492.594v.015a.63.63 0 0 1 .569.631c0 .438-.395.744-1.017.744-.564 0-.954-.303-.965-.754h.6c.01.175.155.303.376.303.218 0 .38-.152.38-.347 0-.227-.186-.347-.437-.347h-.215v-.468z"}),u.jsx("path",{d:"M2 1a1 1 0 0 0-1 1v.217l.652-.33.348.667L.5 3.476V5h2V4H1.5v-.39l1.217-.66L2 1.5V2z"})]})}),u.jsx("div",{style:{flex:1}}),u.jsx("button",{onPointerDown:G=>G.stopPropagation(),onClick:i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:999,background:"transparent",cursor:"pointer",padding:0},children:u.jsx(q5,{})})]}),u.jsx("div",{ref:T,contentEditable:!0,suppressContentEditableWarning:!0,onInput:at,"data-placeholder":"Start typing…",style:{flex:1,padding:"10px 14px",fontSize:13,lineHeight:1.65,color:x.text,outline:"none",overflowY:"auto",cursor:"text",userSelect:"text",backgroundImage:I5[A],backgroundSize:Y5[A]}}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 14px",borderTop:`1px solid ${x.divider}`,background:x.surfaceMuted,flexShrink:0},children:[u.jsxs("span",{style:{fontSize:10,color:x.textLight},children:["By ",tt," | ",P]}),u.jsx("div",{onMouseDown:rt,role:"separator","aria-label":"Resize note",style:{cursor:"nwse-resize",color:x.textLight,fontSize:10,userSelect:"none"},children:"⠿"})]})]})}function As({children:i,...a}){return u.jsx("button",{type:"button",...a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,border:"none",borderRadius:x.radiusSm,background:"rgba(255,255,255,0.35)",cursor:"pointer",color:x.textMuted,padding:0,...a.style},children:i})}const F5=()=>u.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),u.jsx("polyline",{points:"15 3 21 3 21 9"}),u.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),P5=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"currentColor",children:[u.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1.4"}),u.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1.4"})]}),K5=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})});function W5({onClose:i,onOpenDashboard:a}){const[l,r]=v.useState(!1),[d,f]=v.useState(!1),[h,p]=v.useState(!1),[y,g]=v.useState("en-US"),[b,S]=v.useState(!1),[A,j]=v.useState([]),[k,D]=v.useState(""),[O,F]=v.useState({signedIn:!1,hasWorkspace:!1,name:"",email:"",avatarUrl:"",guestRemaining:xn});v.useEffect(()=>{chrome.storage.local.get(["inlineBlockedDomains","inlineScreenReader","inlineFocusMode","inlineAccessToken","inlineActiveWorkspaceId","inlineUserId","inlineUserName","inlineUserEmail","inlineUserAvatarUrl"],P=>{try{const W=P.inlineBlockedDomains;if(typeof W=="string"){const lt=JSON.parse(W);Array.isArray(lt)&&j(lt)}}catch{}r(P.inlineScreenReader==="true"||P.inlineScreenReader===!0),p(P.inlineFocusMode==="true"||P.inlineFocusMode===!0),Mg().then(W=>{F({signedIn:uc(P.inlineAccessToken),hasWorkspace:typeof P.inlineActiveWorkspaceId=="string"&&P.inlineActiveWorkspaceId.length>0,name:typeof P.inlineUserName=="string"?P.inlineUserName:"",email:typeof P.inlineUserEmail=="string"?P.inlineUserEmail:"",avatarUrl:typeof P.inlineUserAvatarUrl=="string"?P.inlineUserAvatarUrl:"",guestRemaining:Number.isFinite(W.remaining)?W.remaining:xn})})})},[]);const Q=v.useCallback(P=>{r(P),chrome.storage.local.set({inlineScreenReader:String(P)}),document.dispatchEvent(new CustomEvent("inline:screenReader",{detail:{enabled:P}}))},[]),E=v.useCallback(P=>{j(P),chrome.storage.local.set({inlineBlockedDomains:JSON.stringify(P)})},[]),T=v.useCallback(()=>{const P=k.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"");!P||A.includes(P)||(E([...A,P]),D(""))},[k,A,E]),L=v.useCallback(P=>{E(A.filter(W=>W!==P))},[A,E]),U=v.useCallback(P=>{f(P);try{const W=document.body??document.documentElement;W.style.filter=P?"contrast(150%)":""}catch{}},[]),$=O.name||O.email||"Connected account",tt=($.trim()[0]||"I").toUpperCase();return u.jsx(mn,{title:"Settings",subtitle:"Global preferences",width:340,tool:"settings",onClose:i,footer:u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px"},children:[u.jsxs("button",{type:"button",onClick:a,style:{display:"flex",alignItems:"center",gap:7,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:12.5,fontWeight:650,color:x.text,padding:"9px 14px",borderRadius:x.radiusPill,fontFamily:gt,boxShadow:"none"},children:["All settings ",u.jsx(F5,{})]}),u.jsx("button",{type:"button",onClick:()=>S(P=>!P),"aria-label":b?"Resume Inline":"Pause Inline",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:40,height:40,borderRadius:13,border:`1px solid ${b?"rgba(220,38,38,0.25)":x.border}`,background:b?"#FEF2F2":x.surfaceBubble,cursor:"pointer",color:b?"#DC2626":x.textMuted,boxShadow:"none"},children:u.jsx(P5,{})})]}),children:u.jsxs("div",{style:{...ya,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Account"}),u.jsx(Mn,{children:u.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[u.jsxs("span",{style:{display:"flex",alignItems:"flex-start",gap:10,minWidth:0},children:[O.signedIn?u.jsx("span",{style:{width:32,height:32,borderRadius:10,overflow:"hidden",background:x.accent,color:"#FFFFFF",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:800,flexShrink:0},children:O.avatarUrl?u.jsx("img",{src:O.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):tt}):u.jsx("span",{style:{width:9,height:9,borderRadius:"50%",marginTop:5,background:"#D97706",boxShadow:"0 0 0 3px rgba(217, 119, 6, 0.13)",flexShrink:0}}),u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:700,color:x.text,letterSpacing:"-0.01em"},children:O.signedIn?$:"Guest mode"}),u.jsx("span",{style:{display:"block",marginTop:2,fontSize:11.5,color:x.textLight,lineHeight:1.45},children:O.signedIn?O.hasWorkspace?"Workspace sync is on. AI is fully unlocked.":"Open the dashboard to finish workspace sync.":`Saved to this browser. ${O.guestRemaining} of ${xn} guest AI prompts left.`})]})]}),u.jsx("button",{type:"button",onClick:a,style:{border:`1px solid ${x.border}`,background:O.signedIn?x.surfaceSunken:x.accent,color:O.signedIn?x.text:"#FFFFFF",borderRadius:x.radiusPill,padding:"7px 11px",fontSize:11.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none",flexShrink:0},children:O.signedIn?"Dashboard":"Sign in"})]})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Accessibility"}),u.jsxs(Mn,{list:!0,children:[u.jsx(fc,{label:"Screen reader",desc:"Announce captured text",right:u.jsx($l,{checked:l,onChange:Q,label:"screen reader"})}),u.jsx(fc,{label:"High contrast",desc:"Boost page contrast",border:!0,right:u.jsx($l,{checked:d,onChange:U,label:"high contrast"})}),u.jsx(fc,{label:"Immersive reader",desc:"Distraction-free reading",border:!0,right:u.jsx($l,{checked:h,onChange:P=>{p(P),chrome.storage.local.set({inlineFocusMode:String(P)}),document.dispatchEvent(new CustomEvent("inline:focusMode",{detail:{enabled:P}}))},label:"immersive reader"})})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Language"}),u.jsxs(Mn,{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px"},children:[u.jsx("span",{style:{fontSize:13,fontWeight:650,color:x.text},children:"Interface language"}),u.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center"},children:[u.jsxs("select",{value:y,onChange:P=>g(P.target.value),"aria-label":"Interface language",style:{appearance:"none",WebkitAppearance:"none",MozAppearance:"none",padding:"8px 30px 8px 14px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,fontSize:12,color:x.text,background:x.surfaceSunken,cursor:"pointer",outline:"none",fontFamily:gt,fontWeight:600},children:[u.jsx("option",{value:"en-US",children:"English (US)"}),u.jsx("option",{value:"en-GB",children:"English (UK)"}),u.jsx("option",{value:"es",children:"Espanol"}),u.jsx("option",{value:"fr",children:"Francais"}),u.jsx("option",{value:"de",children:"Deutsch"}),u.jsx("option",{value:"pt",children:"Portugues"})]}),u.jsx("span",{style:{position:"absolute",right:10,pointerEvents:"none",color:x.textMuted,display:"inline-flex"},children:u.jsx(K5,{})})]})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Blocked sites"}),u.jsxs(Mn,{children:[A.length>0&&u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:11},children:A.map(P=>u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"5px 6px 5px 11px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceSunken,fontSize:11.5,fontWeight:600,color:x.text,fontFamily:gt},children:[P,u.jsx("button",{type:"button",onClick:()=>L(P),"aria-label":`Unblock ${P}`,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,border:"none",background:x.hoverBg,cursor:"pointer",padding:0,lineHeight:1,fontSize:12,color:x.textMuted,fontWeight:700,borderRadius:"50%"},children:"×"})]},P))}),u.jsxs("div",{style:{display:"flex",gap:8},children:[u.jsx("input",{value:k,onChange:P=>D(P.target.value),onKeyDown:P=>{P.key==="Enter"&&T()},placeholder:"example.com","aria-label":"Domain to block",style:{flex:1,padding:"9px 14px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,fontSize:12.5,outline:"none",color:x.text,background:x.surfaceSunken,fontFamily:gt}}),u.jsx("button",{type:"button",onClick:T,"aria-label":"Block domain",style:{padding:"9px 16px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none"},children:"Add"})]})]})]})]})})}function fc({label:i,desc:a,right:l,border:r}){return u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",...r?{borderTop:`1px solid ${x.divider}`}:{}},children:[u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:650,color:x.text,letterSpacing:"-0.01em"},children:i}),a&&u.jsx("span",{style:{display:"block",fontSize:11,color:x.textLight},children:a})]}),l]})}const hc=[{value:"#FDE68A",name:"Yellow"},{value:"#A7F3D0",name:"Mint"},{value:"#BFDBFE",name:"Sky"},{value:"#FBCFE8",name:"Pink"},{value:"#FDBA74",name:"Orange"},{value:"#C4B5FD",name:"Violet"},{value:"#99F6E4",name:"Teal"},{value:"#FCA5A5",name:"Coral"},{value:"#D9F99D",name:"Lime"},{value:"#E9D5FF",name:"Lilac"}];function Q5({onClose:i}){const[a,l]=v.useState(hc[0].value),r=v.useCallback(f=>{l(f),oi("color",f)},[]),d=hc.find(f=>f.value===a)?.name??"Yellow";return u.jsx(mn,{title:"Highlight",subtitle:"Select text, then pick a colour",chip:d,width:296,tool:"highlighter",onClose:i,children:u.jsxs("div",{style:{padding:"18px 18px 20px",fontFamily:gt},children:[u.jsx(ye,{children:"Highlight colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:12},children:hc.map(({value:f,name:h})=>{const p=a===f;return u.jsx("button",{type:"button",onClick:()=>r(f),"aria-label":`Highlight ${h}`,"aria-pressed":p,style:{height:44,borderRadius:x.radius,background:f,cursor:"pointer",border:p?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.15s",padding:0}},f)})}),u.jsxs("p",{style:{margin:"16px 2px 0",fontSize:11.5,color:x.textLight,lineHeight:1.5,display:"flex",alignItems:"center",gap:7},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#5BE49B",flexShrink:0}}),"Highlight mode is on — drag across any text to colour it."]})]})})}const Bn="http://www.w3.org/2000/svg",ar="inline-draw-canvas",pc="inline-draw-hit-area";function Pg(){const i=document.getElementById(ar);if(i){const l=i;return mc(l),l}const a=document.createElementNS(Bn,"svg");return a.id=ar,a.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483640;pointer-events:none;touch-action:none;",a.setAttribute("width",String(window.innerWidth)),a.setAttribute("height",String(window.innerHeight)),a.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),mc(a),document.body.appendChild(a),window.addEventListener("resize",()=>{a.setAttribute("width",String(window.innerWidth)),a.setAttribute("height",String(window.innerHeight)),a.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`)}),a}function mc(i){if(i.setAttribute("width",String(window.innerWidth)),i.setAttribute("height",String(window.innerHeight)),i.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),i.querySelector(`#${pc}`))return;const a=document.createElementNS(Bn,"rect");a.id=pc,a.setAttribute("x","0"),a.setAttribute("y","0"),a.setAttribute("width","100%"),a.setAttribute("height","100%"),a.setAttribute("fill","transparent"),a.setAttribute("pointer-events","none"),i.insertBefore(a,i.firstChild)}function Kg(i){const a=document.getElementById(ar);if(!a)return;mc(a);const l=a.querySelector(`#${pc}`);l&&l.setAttribute("pointer-events",i?"all":"none")}function Ts(i,a){typeof a.id=="string"&&a.id&&i.setAttribute("data-inline-id",a.id)}function Z5(i,a){if(a.type==="path"){const l=document.createElementNS(Bn,"path");l.setAttribute("d",String(a.d)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill",String(a.fill??"none")),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),a.opacity&&l.setAttribute("opacity",String(a.opacity)),l.setAttribute("data-inline-draw","true"),Ts(l,a),i.appendChild(l)}else if(a.type==="rect"){const l=document.createElementNS(Bn,"rect");l.setAttribute("x",String(a.x)),l.setAttribute("y",String(a.y)),l.setAttribute("width",String(a.width)),l.setAttribute("height",String(a.height)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill","none"),l.setAttribute("rx","2"),l.setAttribute("data-inline-draw","true"),Ts(l,a),i.appendChild(l)}else if(a.type==="ellipse"){const l=document.createElementNS(Bn,"ellipse");l.setAttribute("cx",String(a.cx)),l.setAttribute("cy",String(a.cy)),l.setAttribute("rx",String(a.rx)),l.setAttribute("ry",String(a.ry)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill","none"),l.setAttribute("data-inline-draw","true"),Ts(l,a),i.appendChild(l)}else if(a.type==="arrow"){const l=document.createElementNS(Bn,"g");l.setAttribute("data-inline-draw","true"),Ts(l,a);const r=document.createElementNS(Bn,"line");r.setAttribute("x1",String(a.x1)),r.setAttribute("y1",String(a.y1)),r.setAttribute("x2",String(a.x2)),r.setAttribute("y2",String(a.y2)),r.setAttribute("stroke",String(a.stroke)),r.setAttribute("stroke-width",String(a.strokeWidth)),r.setAttribute("stroke-linecap","round");const d=document.createElementNS(Bn,"polygon");d.setAttribute("fill",String(a.fill)),d.setAttribute("points",String(a.points)),l.appendChild(r),l.appendChild(d),i.appendChild(l)}else if(a.type==="line"){const l=document.createElementNS(Bn,"line");l.setAttribute("x1",String(a.x1)),l.setAttribute("y1",String(a.y1)),l.setAttribute("x2",String(a.x2)),l.setAttribute("y2",String(a.y2)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("stroke-linecap","round"),l.setAttribute("data-inline-draw","true"),Ts(l,a),i.appendChild(l)}}function $5(){const i=document.getElementById(ar);i&&i.querySelectorAll("[data-inline-draw]").forEach(a=>a.remove());try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"drawPaths",data:[],pageTitle:document.title,domain:window.location.hostname,clearedAt:Date.now()}},()=>{chrome.runtime.lastError})}catch{}}function Wg(){try{if(!chrome.runtime?.id)return;const i=Pg();chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},a=>{if(chrome.runtime.lastError||!a?.ok)return;const l=a.data?.elements?.drawPaths;if(!(!Array.isArray(l)||l.length===0))for(const r of l){const d=typeof r.id=="string"?r.id:"";d&&i.querySelector(`[data-inline-id="${CSS.escape(d)}"]`)||Z5(i,r)}})}catch{}}const Qg=["#1C1E26","#b42318","#315a9f","#0f7b6c","#b7791f","#7c3aed","#ec4899","#06b6d4","#ea580c","#78716c"],J5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5z"})}),tT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:[u.jsx("path",{d:"M8.5 1a.5.5 0 0 0-1 0v5.7L5.354 4.354a.5.5 0 1 0-.708.708L7.5 7.916V11.5a.5.5 0 0 0 1 0V7.916l2.854-2.854a.5.5 0 0 0-.708-.708L8.5 6.7V1z"}),u.jsx("path",{d:"M3 13.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z"})]}),eT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"5"}),u.jsx("polyline",{points:"12 5 19 5 19 12"})]}),nT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"})}),iT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"7"})}),aT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 0 2.828l-5.5 5.5A2 2 0 0 1 7.879 15H5.12a2 2 0 0 1-1.414-.586l-2.5-2.5a2 2 0 0 1 0-2.828l5.88-5.879zm2.121.707a1 1 0 0 0-1.414 0L4.16 7.547l5.293 5.293 4.633-4.633a1 1 0 0 0 0-1.414l-3.879-3.879zM8.746 13.547 3.453 8.254 1.914 9.793a1 1 0 0 0 0 1.414l2.5 2.5a1 1 0 0 0 .707.293H7.88a1 1 0 0 0 .707-.293l.16-.16z"})}),sT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M7 22a5 5 0 0 1-2-4"}),u.jsx("path",{d:"M7 16.93c.96.43 1.96.74 2.99.91"}),u.jsx("path",{d:"M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8-4.48 8-10 8a12 12 0 0 1-3-.38"}),u.jsx("circle",{cx:"7",cy:"22",r:"2"})]});function lT({onClose:i}){const[a,l]=v.useState("pen"),[r,d]=v.useState(Qg[0]),[f,h]=v.useState(3),[p,y]=v.useState("object"),[g,b]=v.useState(!1),S=v.useRef(null),A=v.useRef(!1),j=v.useRef(""),k=v.useRef(null),D=v.useRef({x:0,y:0}),O=v.useRef(null),F=v.useRef(0),Q=v.useRef([]),E=v.useRef(null),T=v.useRef(null),L=v.useRef(!1),U=v.useRef({x:0,y:0}),$=v.useRef({x:0,y:0}),tt=v.useRef(!1);v.useEffect(()=>{S.current=Pg(),Wg()},[]);const P=v.useCallback(()=>{S.current&&(S.current.style.pointerEvents="all",Kg(!0),S.current.style.cursor=a==="eraser"?"cell":"crosshair")},[a]),W=v.useCallback(()=>{S.current&&(Kg(!1),S.current.style.pointerEvents="none",S.current.style.cursor="")},[]);v.useEffect(()=>(P(),W),[P,W,a]),v.useEffect(()=>{if(!S.current)return;const rt=S.current;function mt(){if(!T.current||!rt)return;const Y=T.current,H=Y.querySelector(".inline-lasso-border");for(H&&H.remove();Y.firstChild;)rt.insertBefore(Y.firstChild,Y);Y.remove(),T.current=null}function kt(Y,H,st,ht,Tt,Vt){const ut=Y-st,It=H-ht,Et=Tt-st,jt=Vt-ht,X=Et*Et+jt*jt;if(X===0)return Math.hypot(ut,It);const ot=Math.max(0,Math.min(1,(ut*Et+It*jt)/X));return Math.hypot(Y-(st+ot*Et),H-(ht+ot*jt))}function B(Y,H){if(Y.length<2||Y.length>50||H<300)return null;const st=Y.map(Ft=>Ft.x),ht=Y.map(Ft=>Ft.y),Tt=Math.min(...st),Vt=Math.max(...st),ut=Math.min(...ht),It=Math.max(...ht),Et=Vt-Tt,jt=It-ut,X=Y[0],ot=Y[Y.length-1],zt=Math.hypot(ot.x-X.x,ot.y-X.y)20&&Math.max(...Y.map(le=>kt(le.x,le.y,X.x,X.y,ot.x,ot.y)))<15)return{type:"line",x1:X.x,y1:X.y,x2:ot.x,y2:ot.y};if(!zt||Et<15||jt<15)return null;const ze=Math.max(Et,jt)*.2;if(Y.filter(Ft=>{const le=Math.abs(Ft.x-Tt),cr=Math.abs(Ft.x-Vt),bn=Math.abs(Ft.y-ut),ui=Math.abs(Ft.y-It);return Math.min(le,cr)Y.length*.7){const Ft=Et/jt;if(Ft>.3&&Ft<3.5)return{type:"rect",x:Tt,y:ut,width:Et,height:jt}}const ft=(Tt+Vt)/2,Ct=(ut+It)/2,Ut=Et/2,Wt=jt/2;if(Ut>5&&Wt>5){const Ft=Y.map(bn=>{const ui=(bn.x-ft)/Ut,dr=(bn.y-Ct)/Wt;return Math.sqrt(ui*ui+dr*dr)}),le=Ft.reduce((bn,ui)=>bn+ui,0)/Ft.length;if(Math.max(...Ft.map(bn=>Math.abs(bn-le)))<.4)return{type:"ellipse",cx:ft,cy:Ct,rx:Ut,ry:Wt}}return null}function at(Y,H){const st=Math.max(8,f*2);rt.querySelectorAll("[data-inline-draw]").forEach(Tt=>{if(Tt.tagName.toLowerCase()==="path"){const It=(Tt.getAttribute("d")??"").match(/[ML][^ML]*/g);if(!It)return;const Et=[[]];let jt=!1;for(const ot of It){const pt=ot.trim().substring(1).trim().split(/[\s,]+/).map(Number);if(pt.length<2)continue;const zt=pt[0],Xt=pt[1];if(Math.hypot(zt-Y,Xt-H)0&&Et.push([]),jt=!0;else{const I=ot.trim()[0];jt||Et[Et.length-1].length===0?Et[Et.length-1].push(`M${zt} ${Xt}`):Et[Et.length-1].push(`${I}${zt} ${Xt}`),jt=!1}}const X=Et.filter(ot=>ot.length>1);if(X.length===0)Tt.remove();else if(X.length===1)Tt.setAttribute("d",X[0].join(" "));else{const ot=Tt.getAttribute("stroke")??"",pt=Tt.getAttribute("stroke-width")??"",zt=Tt.getAttribute("opacity"),Xt=Tt.getAttribute("fill")??"none";Tt.remove();for(const ze of X){const I=document.createElementNS("http://www.w3.org/2000/svg","path");I.setAttribute("d",ze.join(" ")),I.setAttribute("stroke",ot),I.setAttribute("stroke-width",pt),I.setAttribute("fill",Xt),I.setAttribute("stroke-linecap","round"),I.setAttribute("stroke-linejoin","round"),zt&&I.setAttribute("opacity",zt),I.setAttribute("data-inline-draw","true"),rt.appendChild(I)}}}else try{const ut=Tt.getBBox?.();if(ut){const It=ut.x+ut.width/2,Et=ut.y+ut.height/2;Math.hypot(It-Y,Et-H){const ht=st.tagName.toLowerCase(),Tt=bt(st);if(ht==="path")H.push({id:Tt,type:"path",d:st.getAttribute("d")??"",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??"",opacity:st.getAttribute("opacity")??void 0,fill:st.getAttribute("fill")??"none"});else if(ht==="rect")H.push({id:Tt,type:"rect",x:st.getAttribute("x")??"0",y:st.getAttribute("y")??"0",width:st.getAttribute("width")??"0",height:st.getAttribute("height")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(ht==="ellipse")H.push({id:Tt,type:"ellipse",cx:st.getAttribute("cx")??"0",cy:st.getAttribute("cy")??"0",rx:st.getAttribute("rx")??"0",ry:st.getAttribute("ry")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(ht==="line")H.push({id:Tt,type:"line",x1:st.getAttribute("x1")??"0",y1:st.getAttribute("y1")??"0",x2:st.getAttribute("x2")??"0",y2:st.getAttribute("y2")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(ht==="g"&&!st.classList.contains("inline-lasso-group")){const Vt=st.querySelector("line"),ut=st.querySelector("polygon");Vt&&ut&&H.push({id:Tt,type:"arrow",x1:Vt.getAttribute("x1")??"0",y1:Vt.getAttribute("y1")??"0",x2:Vt.getAttribute("x2")??"0",y2:Vt.getAttribute("y2")??"0",stroke:Vt.getAttribute("stroke")??"",strokeWidth:Vt.getAttribute("stroke-width")??"",points:ut.getAttribute("points")??"",fill:ut.getAttribute("fill")??""})}}),H}function K(){const Y=M();try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"drawPaths",data:Y,pageTitle:document.title,domain:window.location.hostname,clearedAt:Y.length===0?Date.now():null}},H=>{chrome.runtime.lastError||nr(H)})}catch{}}function nt(){if(a==="eraser"&&p==="pixel"){tt.current=!1,K();return}if(L.current){L.current=!1;const H=T.current?.getAttribute("transform")?.match(/translate\(([-\d.]+)[, ]+([-\d.]+)\)/);H&&($.current={x:parseFloat(H[1]),y:parseFloat(H[2])});return}if(a==="lasso"&&A.current&&E.current){A.current=!1;const Y=Q.current;if(Y.length>2){const H=Y.map(jt=>jt.x),st=Y.map(jt=>jt.y),ht=Math.min(...H),Tt=Math.max(...H),Vt=Math.min(...st),ut=Math.max(...st),It=rt.querySelectorAll("[data-inline-draw]"),Et=[];if(It.forEach(jt=>{if(jt!==E.current&&!jt.classList.contains("inline-lasso-group"))try{const X=jt.getBBox(),ot=X.x+X.width/2,pt=X.y+X.height/2;ot>=ht&&ot<=Tt&&pt>=Vt&&pt<=ut&&Et.push(jt)}catch{}}),E.current.remove(),E.current=null,Et.length>0){const jt=document.createElementNS("http://www.w3.org/2000/svg","g");jt.classList.add("inline-lasso-group"),jt.setAttribute("data-inline-draw","true"),rt.appendChild(jt);let X=1/0,ot=1/0,pt=-1/0,zt=-1/0;for(const ze of Et){try{const I=ze.getBBox();X=Math.min(X,I.x),ot=Math.min(ot,I.y),pt=Math.max(pt,I.x+I.width),zt=Math.max(zt,I.y+I.height)}catch{}jt.appendChild(ze)}const Xt=document.createElementNS("http://www.w3.org/2000/svg","rect");Xt.classList.add("inline-lasso-border"),Xt.setAttribute("x",String(X-4)),Xt.setAttribute("y",String(ot-4)),Xt.setAttribute("width",String(pt-X+8)),Xt.setAttribute("height",String(zt-ot+8)),Xt.setAttribute("stroke","#315a9f"),Xt.setAttribute("stroke-width","1.5"),Xt.setAttribute("stroke-dasharray","5 3"),Xt.setAttribute("fill","none"),Xt.setAttribute("rx","3"),jt.insertBefore(Xt,jt.firstChild),T.current=jt,$.current={x:0,y:0}}}else E.current.remove(),E.current=null;Q.current=[];return}if(a==="pen"&&A.current&&k.current){const Y=Q.current,H=Date.now()-F.current,st=B(Y,H);if(st){const ht=k.current,Tt=ht.getAttribute("stroke")??r,Vt=ht.getAttribute("stroke-width")??String(f);if(ht.remove(),st.type==="line"){const ut=document.createElementNS("http://www.w3.org/2000/svg","line");ut.setAttribute("x1",String(st.x1)),ut.setAttribute("y1",String(st.y1)),ut.setAttribute("x2",String(st.x2)),ut.setAttribute("y2",String(st.y2)),ut.setAttribute("stroke",Tt),ut.setAttribute("stroke-width",Vt),ut.setAttribute("stroke-linecap","round"),ut.setAttribute("data-inline-draw","true"),rt.appendChild(ut)}else if(st.type==="rect"){const ut=document.createElementNS("http://www.w3.org/2000/svg","rect");ut.setAttribute("x",String(st.x)),ut.setAttribute("y",String(st.y)),ut.setAttribute("width",String(st.width)),ut.setAttribute("height",String(st.height)),ut.setAttribute("stroke",Tt),ut.setAttribute("stroke-width",Vt),ut.setAttribute("fill","none"),ut.setAttribute("rx","2"),ut.setAttribute("data-inline-draw","true"),rt.appendChild(ut)}else if(st.type==="ellipse"){const ut=document.createElementNS("http://www.w3.org/2000/svg","ellipse");ut.setAttribute("cx",String(st.cx)),ut.setAttribute("cy",String(st.cy)),ut.setAttribute("rx",String(st.rx)),ut.setAttribute("ry",String(st.ry)),ut.setAttribute("stroke",Tt),ut.setAttribute("stroke-width",Vt),ut.setAttribute("fill","none"),ut.setAttribute("data-inline-draw","true"),rt.appendChild(ut)}}}A.current=!1,k.current=null,O.current=null,Q.current=[],K()}function dt(Y){if(a!=="eraser"||p!=="object")return;Y.preventDefault(),Y.stopPropagation();const H=document.elementFromPoint(Y.clientX,Y.clientY);H&&H.hasAttribute("data-inline-draw")&&H.remove(),H?.parentElement&&H.parentElement.hasAttribute("data-inline-draw")&&H.parentElement.remove(),K()}function vt(Y){(Y.key==="Delete"||Y.key==="Backspace")&&T.current&&(T.current.remove(),T.current=null,K())}return rt.addEventListener("pointerdown",G),rt.addEventListener("pointermove",ct),rt.addEventListener("pointerup",nt),rt.addEventListener("click",dt),document.addEventListener("keydown",vt),()=>{rt.removeEventListener("pointerdown",G),rt.removeEventListener("pointermove",ct),rt.removeEventListener("pointerup",nt),rt.removeEventListener("click",dt),document.removeEventListener("keydown",vt)}},[a,r,f,p]);const lt=[{id:"pen",icon:u.jsx(J5,{}),label:"Pen"},{id:"marker",icon:u.jsx(tT,{}),label:"Marker"},{id:"arrow",icon:u.jsx(eT,{}),label:"Arrow"},{id:"rectangle",icon:u.jsx(nT,{}),label:"Rectangle"},{id:"ellipse",icon:u.jsx(iT,{}),label:"Ellipse"},{id:"eraser",icon:u.jsx(aT,{}),label:"Eraser"},{id:"lasso",icon:u.jsx(sT,{}),label:"Lasso"}],it=lt.find(rt=>rt.id===a)?.label??"Pen";return u.jsx(mn,{title:"Draw",subtitle:"Annotate directly on the page",chip:it,width:290,tool:"draw",onClose:i,children:u.jsxs("div",{style:{...ya,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tools"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:9},children:lt.map(rt=>{const mt=a===rt.id;return u.jsx("button",{type:"button",onClick:()=>l(rt.id),"aria-label":rt.label,"aria-pressed":mt,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:46,borderRadius:x.radius,border:`1px solid ${mt?x.accent:x.border}`,background:mt?x.accent:x.surfaceBubble,color:mt?"#fff":x.textMuted,cursor:"pointer",boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:rt.icon},rt.id)})}),a==="eraser"&&u.jsx("div",{style:{marginTop:10},children:u.jsx(sc,{options:[{value:"object",label:"Object"},{value:"pixel",label:"Pixel"}],value:p,onChange:y})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Stroke weight"}),u.jsxs(Mn,{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px"},children:[u.jsx("button",{type:"button",onClick:()=>h(rt=>Math.max(1,rt-1)),"aria-label":"Thinner",style:Zg,children:"−"}),u.jsx("input",{type:"range",min:1,max:12,value:f,onChange:rt=>h(Number(rt.target.value)),"aria-label":"Stroke weight",style:{flex:1,accentColor:x.accent,height:6,cursor:"pointer"}}),u.jsx("button",{type:"button",onClick:()=>h(rt=>Math.min(12,rt+1)),"aria-label":"Thicker",style:Zg,children:"+"}),u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:26,height:26,borderRadius:8,background:x.surfaceSunken,fontSize:12,fontWeight:700,color:x.text},children:f})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:11},children:Qg.map(rt=>{const mt=r===rt;return u.jsx("button",{type:"button",onClick:()=>d(rt),"aria-label":`Colour ${rt}`,"aria-pressed":mt,style:{height:34,borderRadius:x.radius,background:rt,cursor:"pointer",padding:0,border:mt?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.13s"}},rt)})})]}),g?u.jsxs(Mn,{style:{padding:14},children:[u.jsx("p",{style:{margin:"0 0 3px",fontSize:13,fontWeight:700,color:x.text},children:"Clear all drawings?"}),u.jsx("p",{style:{margin:"0 0 12px",fontSize:11.5,lineHeight:1.5,color:x.textMuted},children:"This removes every drawing on this page and can't be undone."}),u.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[u.jsx("button",{type:"button",onClick:()=>b(!1),style:{padding:"8px 14px",fontSize:12,fontWeight:600,borderRadius:x.radiusPill,cursor:"pointer",border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text},children:"Cancel"}),u.jsx("button",{type:"button",onClick:()=>{$5(),b(!1)},style:{padding:"8px 16px",fontSize:12,fontWeight:700,borderRadius:x.radiusPill,cursor:"pointer",border:"none",background:"#DC2626",color:"#fff"},children:"Clear all"})]})]}):u.jsx("button",{type:"button",onClick:()=>b(!0),"aria-label":"Clear all drawings on this page",style:{padding:"11px 0",fontSize:12.5,fontWeight:700,borderRadius:x.radius,cursor:"pointer",width:"100%",border:"1px solid rgba(220,38,38,0.28)",background:"#FEF2F2",color:"#DC2626",transition:"background 0.15s",letterSpacing:"-0.01em",fontFamily:"inherit"},children:"Clear all drawings"})]})})}const Zg={display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radius,flexShrink:0,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:16,fontWeight:600,color:x.textMuted,boxShadow:x.shadowSoft},rT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),oT=()=>u.jsx(tc,{}),uT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"}),u.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),u.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"}),u.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),cT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),u.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),u.jsx("path",{d:"M2 2l7.586 7.586"}),u.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),dT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),fT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"3"}),u.jsx("path",{d:"M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"})]}),hT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polyline",{points:"4 14 10 14 10 20"}),u.jsx("polyline",{points:"20 10 14 10 14 4"}),u.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),u.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}),pT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"6",y:"4",width:"4",height:"16"}),u.jsx("rect",{x:"14",y:"4",width:"4",height:"16"})]}),mT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),gT={action:"Actions",annotate:"Annotate",app:"Workspace",toolbar:"Toolbar"},yT=[{id:"ai",label:"Ask AI",hint:"Chat about the page or selection",icon:u.jsx(oT,{}),category:"action",shortcut:"A"},{id:"rewrite",label:"Rewrite",hint:"Rephrase, shorten, summarize",icon:u.jsx(rT,{}),category:"action",shortcut:"R"},{id:"highlighter",label:"Highlighter",hint:"Highlight passages",icon:u.jsx(dT,{}),category:"annotate",shortcut:"H"},{id:"notes",label:"Sticky note",hint:"Drop a note on the page",icon:u.jsx(uT,{}),category:"annotate",shortcut:"N"},{id:"draw",label:"Draw",hint:"Sketch over the page",icon:u.jsx(cT,{}),category:"annotate"},{id:"settings",label:"Settings",hint:"Preferences & blocked sites",icon:u.jsx(fT,{}),category:"app"},{id:"collapse",label:"Toggle tools dock",hint:"Show or hide the launcher dock",icon:u.jsx(hT,{}),category:"toolbar"},{id:"pause",label:"Hide Inline",hint:"Tuck the launcher away on this page",icon:u.jsx(pT,{}),category:"toolbar"}],xT=[{id:"all",label:"All"},{id:"action",label:"Actions"},{id:"annotate",label:"Annotate"},{id:"toolbar",label:"Toolbar"}];function bT({onClose:i,onAction:a}){const[l,r]=v.useState(""),[d,f]=v.useState("all"),[h,p]=v.useState(0),y=v.useRef(null),g=v.useRef(null),b=yT.filter(j=>(d==="all"||j.category===d)&&(j.label.toLowerCase().includes(l.toLowerCase())||(j.hint?.toLowerCase().includes(l.toLowerCase())??!1)));v.useEffect(()=>{p(0)},[l,d]),v.useEffect(()=>{y.current?.focus()},[]),v.useEffect(()=>{g.current?.querySelector(`[data-cmd-idx="${h}"]`)?.scrollIntoView({block:"nearest"})},[h]);const S=v.useCallback(j=>{a(j),i()},[a,i]),A=v.useCallback(j=>{j.key==="ArrowDown"?(j.preventDefault(),p(k=>Math.min(k+1,b.length-1))):j.key==="ArrowUp"?(j.preventDefault(),p(k=>Math.max(k-1,0))):j.key==="Enter"?(j.preventDefault(),b[h]&&S(b[h].id)):j.key==="Escape"&&(j.preventDefault(),i())},[b,h,S,i]);return u.jsx("div",{onClick:i,style:{position:"fixed",inset:0,zIndex:2147483647,pointerEvents:"auto",background:"rgba(15,18,23,0.28)",backdropFilter:"blur(2px)",display:"flex",justifyContent:"center",alignItems:"flex-start",paddingTop:"16vh",fontFamily:gt},children:u.jsxs("div",{onClick:j=>j.stopPropagation(),onKeyDown:A,style:{width:480,maxWidth:"calc(100vw - 32px)",maxHeight:460,background:x.bg,borderRadius:x.radius,boxShadow:x.shadowOuter,border:`1px solid ${x.border}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[u.jsx("div",{style:{padding:"14px 16px 10px"},children:u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,border:`1px solid ${Cn.inputBorder}`,borderRadius:x.radiusMd,background:x.bg,boxShadow:Cn.inputGlow,padding:"10px 14px"},children:[u.jsx("span",{style:{color:x.textMuted,display:"flex"},children:u.jsx(mT,{})}),u.jsx("input",{ref:y,type:"text",value:l,onChange:j=>r(j.target.value),placeholder:"Search for actions and tools…",style:{flex:1,border:"none",background:"transparent",fontSize:14,fontFamily:gt,color:x.text,outline:"none"}})]})}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 12px",flexWrap:"wrap"},children:[u.jsx("span",{style:{fontSize:12,color:x.textMuted,marginRight:2},children:"I'm looking for…"}),xT.map(j=>{const k=d===j.id;return u.jsx("button",{type:"button",onClick:()=>f(j.id),style:{padding:"5px 12px",borderRadius:x.radiusPill,border:`1px solid ${k?x.text:x.border}`,background:k?x.text:x.bg,color:k?"#fff":x.text,fontSize:12,fontWeight:500,cursor:"pointer",fontFamily:gt,transition:"background 0.13s, border-color 0.13s, color 0.13s"},children:j.label},j.id)})]}),u.jsx("div",{style:{height:1,background:x.divider}}),u.jsxs("div",{ref:g,style:{flex:1,overflowY:"auto",padding:"8px 8px 10px"},children:[b.length===0&&u.jsx("div",{style:{padding:"22px 12px",textAlign:"center",color:x.textMuted,fontSize:13},children:"No matching commands"}),b.map((j,k)=>{const D=k===0||b[k-1].category!==j.category,O=k===h;return u.jsxs("div",{children:[D&&u.jsx("p",{style:{margin:k===0?"4px 10px 4px":"10px 10px 4px",fontSize:12,fontWeight:500,letterSpacing:0,textTransform:"none",color:x.textMuted},children:gT[j.category]}),u.jsxs("button",{"data-cmd-idx":k,onClick:()=>S(j.id),onMouseEnter:()=>p(k),style:{display:"flex",alignItems:"center",gap:12,width:"100%",padding:"9px 10px",border:"none",borderRadius:x.radiusSm,background:O?x.hoverBg:"transparent",color:x.text,cursor:"pointer",fontFamily:gt,textAlign:"left",transition:"background 0.1s"},children:[u.jsx(GA,{size:30,active:O,children:j.icon}),u.jsxs("span",{style:{flex:1,minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:14,fontWeight:500,color:x.text},children:j.label}),j.hint&&u.jsx("span",{style:{display:"block",fontSize:12,color:x.textMuted,marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.hint})]}),j.shortcut&&u.jsx("span",{style:{fontSize:11,fontWeight:600,color:x.textMuted,background:x.surfaceMuted,border:`1px solid ${x.border}`,padding:"2px 7px",borderRadius:6,flexShrink:0},children:j.shortcut})]})]},j.id)})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 14px",borderTop:`1px solid ${x.divider}`,background:x.surfaceBubble},children:[u.jsxs("span",{style:{display:"flex",alignItems:"center",gap:7,fontSize:11,color:x.textLight},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,borderRadius:"50%",background:"#0B1735"},children:u.jsx("span",{style:{display:"block",width:2,height:8,borderRadius:2,background:"#fff",transform:"rotate(-12deg)"}})}),"Inline"]}),u.jsxs("span",{style:{fontSize:11,color:x.textLight},children:[u.jsx("kbd",{style:gc,children:"↑"})," ",u.jsx("kbd",{style:gc,children:"↓"})," to navigate · ",u.jsx("kbd",{style:gc,children:"↵"})," to run"]})]})]})})}const gc={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:16,height:16,padding:"0 4px",borderRadius:5,background:x.surfaceMuted,border:`1px solid ${x.border}`,fontSize:10,color:x.textMuted,fontFamily:gt},sr="inlineLayerVisibility",$g={highlights:!0,drawings:!0,stickies:!0,stamps:!0};async function Jg(){return new Promise(i=>{chrome.storage.local.get(sr,a=>{i(a[sr]?{...$g,...a[sr]}:$g)})})}async function vT(i){await chrome.storage.local.set({[sr]:i})}const ST=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),wT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),u.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),u.jsx("path",{d:"M2 2l7.586 7.586"}),u.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),AT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h9l7-7V5a2 2 0 0 0-2-2z"}),u.jsx("path",{d:"M15 21v-5a1 1 0 0 1 1-1h5"})]}),TT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),ET=[{key:"highlights",label:"Highlights",desc:"Coloured text marks",icon:u.jsx(ST,{})},{key:"drawings",label:"Drawings",desc:"Pen, shapes & arrows",icon:u.jsx(wT,{})},{key:"stickies",label:"Stickies",desc:"Sticky & paper notes",icon:u.jsx(AT,{})},{key:"stamps",label:"Stamps",desc:"Symbol stamps",icon:u.jsx(TT,{})}];function jT({onClose:i}){const[a,l]=v.useState({highlights:!0,drawings:!0,stickies:!0,stamps:!0});v.useEffect(()=>{Jg().then(l)},[]);const r=v.useCallback((d,f)=>{l(h=>{const p={...h,[d]:f};return vT(p),document.dispatchEvent(new CustomEvent("inline:layerToggle",{detail:p})),p})},[]);return u.jsx(mn,{title:"Layers",subtitle:"Show or hide annotation types",width:308,tool:"layers",onClose:i,children:u.jsx("div",{style:{...ya,fontFamily:gt},children:u.jsx(Mn,{list:!0,children:ET.map((d,f)=>u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 12px",...f>0?{borderTop:`1px solid ${x.divider}`}:{}},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,borderRadius:10,flexShrink:0,background:a[d.key]?x.surfaceMuted:x.surfaceSunken,color:a[d.key]?x.accent:x.textLight,transition:"color 0.15s"},children:d.icon}),u.jsxs("span",{style:{flex:1,minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:650,color:x.text,letterSpacing:"-0.01em"},children:d.label}),u.jsx("span",{style:{display:"block",fontSize:11,color:x.textLight},children:d.desc})]}),u.jsx($l,{checked:a[d.key],onChange:h=>r(d.key,h),label:d.label})]},d.key))})})})}const CT=["✓","✗","?","!","★","♥","+","−","→","•"];function MT({onClose:i}){const[a,l]=v.useState(null),r=v.useCallback(f=>{l(f),document.dispatchEvent(new CustomEvent("inline:stampPlace",{detail:{emoji:f}}));const h=()=>{l(null),document.removeEventListener("inline:stampPlaced",h)};document.addEventListener("inline:stampPlaced",h)},[]),d=v.useCallback(()=>l(null),[]);return u.jsxs(mn,{title:"Stamp",subtitle:"Pick a stamp, then click the page",width:306,tool:"stamps",onClose:i,children:[a&&u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"14px 18px 0",padding:"10px 14px",borderRadius:x.radius,background:x.accent,color:"#fff",fontFamily:gt,boxShadow:"none"},children:[u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8,fontSize:12.5,fontWeight:600},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#5BE49B"}}),"Click anywhere to place ",a]}),u.jsx("button",{type:"button",onClick:d,"aria-label":"Cancel placing",style:{border:"none",background:"rgba(255,255,255,0.16)",cursor:"pointer",fontSize:11,fontWeight:700,color:"#fff",fontFamily:gt,padding:"5px 11px",borderRadius:x.radiusPill},children:"Cancel"})]}),u.jsx("div",{style:{...ya,fontFamily:gt},children:u.jsxs("div",{children:[u.jsx(ye,{children:"Symbols"}),u.jsx(Mn,{style:{padding:12},children:u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:10},children:CT.map(f=>{const h=a===f;return u.jsx("button",{type:"button",onClick:()=>r(f),"aria-label":`Stamp ${f}`,"aria-pressed":h,style:{aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center",fontSize:20,fontWeight:600,border:`1px solid ${h?x.accent:x.border}`,borderRadius:x.radius,background:h?x.accent:x.surfaceBubble,color:h?"#fff":x.text,cursor:"pointer",padding:0,fontFamily:gt,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:f},f)})})})]})})]})}const yc=()=>u.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]});function kT({onClose:i}){const[a,l]=v.useState(""),[r,d]=v.useState([]),[f,h]=v.useState(!1),[p,y]=v.useState("page"),[g,b]=v.useState(!1),S=v.useRef(null),A=v.useRef(void 0);v.useEffect(()=>{S.current?.focus()},[]);const j=v.useCallback(async E=>{if(!E.trim()){d([]);return}h(!0);try{const{apiBaseUrl:T,accessToken:L}=await gn(),U={};L&&(U.Authorization=`Bearer ${L}`);const $=await ri(`${T}/api/search?q=${encodeURIComponent(E)}`,{headers:U});if($.ok){const tt=await $.json();d(tt.results??[])}}catch{}finally{h(!1)}},[]),k=v.useCallback(async E=>{if(!E.trim()){d([]);return}h(!0);try{const T=window.location.href,L=await new Promise(U=>{if(!chrome.runtime?.id){U({ok:!1});return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:T}},$=>U($??{ok:!1}))});if(L.ok&&L.data){const U=L.data,$=[],tt=E.toLowerCase();for(const[P,W]of Object.entries(U))typeof W=="object"&&W!==null&&JSON.stringify(W).toLowerCase().includes(tt)&&$.push({id:P,page_url:T,page_title:document.title,content:typeof W=="string"?W:JSON.stringify(W).slice(0,200),type:"annotation",created_at:new Date().toISOString()});d($)}}catch{}finally{h(!1)}},[]),D=v.useCallback((E,T)=>{T?j(E):k(E)},[j,k]),O=v.useCallback(E=>{l(E),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>D(E,p==="all"),300)},[p,D]),F=v.useCallback(E=>{y(E),a.trim()&&D(a,E==="all")},[a,D]),Q=E=>{if(E.length<=120)return E;const U=E.toLowerCase().indexOf(a.toLowerCase());if(U<0)return E.slice(0,120)+"...";const $=Math.max(0,U-40);return($>0?"...":"")+E.slice($,$+120)+"..."};return u.jsxs(mn,{title:"Search",subtitle:"Find your notes & annotations",width:332,tool:"search",onClose:i,style:{height:"min(520px, calc(100vh - 64px))"},children:[u.jsxs("div",{style:{padding:"16px 18px 12px",flexShrink:0,display:"flex",flexDirection:"column",gap:12},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"0 14px",height:44,borderRadius:14,background:x.surfaceBubble,border:`1.5px solid ${g?x.accent:x.border}`,boxShadow:g?"0 0 0 3px rgba(11,23,53,0.06)":"none",transition:"border-color 0.15s, box-shadow 0.15s"},children:[u.jsx("span",{style:{color:g?x.accent:x.textLight,display:"inline-flex",flexShrink:0},children:u.jsx(yc,{})}),u.jsx("input",{ref:S,value:a,onChange:E=>O(E.target.value),onFocus:()=>b(!0),onBlur:()=>b(!1),placeholder:"Search highlights, notes & clips...",style:{flex:1,minWidth:0,border:"none",outline:"none",background:"transparent",fontSize:13.5,color:x.text,fontFamily:gt}})]}),u.jsx(sc,{options:[{value:"page",label:"This page"},{value:"all",label:"All pages"}],value:p,onChange:F})]}),u.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"2px 16px 16px"},children:[f&&u.jsx($A,{label:"Searching..."}),!f&&a.trim()&&r.length===0&&u.jsx(wg,{icon:u.jsx(yc,{}),title:"No results found",hint:'Try a different keyword, or switch to "All pages".'}),!f&&!a.trim()&&r.length===0&&u.jsx(wg,{icon:u.jsx(yc,{}),title:"Search your captures",hint:"Type to find highlights, notes and clips you've saved."}),!f&&r.map(E=>u.jsxs("button",{type:"button",onClick:()=>{E.page_url&&window.open(E.page_url,"_blank")},"aria-label":E.page_title||"Open result",style:{display:"block",width:"100%",textAlign:"left",padding:"12px 14px",marginBottom:9,border:`1px solid ${x.border}`,borderRadius:16,background:x.surfaceBubble,boxShadow:"none",cursor:"pointer",fontFamily:gt,transition:"box-shadow 0.14s, border-color 0.14s"},onMouseEnter:T=>{T.currentTarget.style.borderColor=x.borderStrong},onMouseLeave:T=>{T.currentTarget.style.borderColor=x.border},children:[u.jsx("p",{style:{margin:0,fontSize:12.5,fontWeight:700,color:x.text,lineHeight:1.4,letterSpacing:"-0.01em"},children:E.page_title||"Untitled"}),u.jsx("p",{style:{margin:"4px 0 0",fontSize:11.5,color:x.textMuted,lineHeight:1.55,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Q(E.content)}),E.page_url&&u.jsx("p",{style:{margin:"6px 0 0",fontSize:10.5,color:x.textLight,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E.page_url})]},E.id))]})]})}function RT({screenshot:i,onClose:a}){const l=v.useRef(null),[r,d]=v.useState(!1),[f,h]=v.useState({x:0,y:0}),[p,y]=v.useState({x:0,y:0}),[g,b]=v.useState(!1),[S,A]=v.useState(!1),[j,k]=v.useState(null),D=g?{x:Math.min(f.x,p.x),y:Math.min(f.y,p.y),w:Math.abs(p.x-f.x),h:Math.abs(p.y-f.y)}:null,O=v.useCallback(T=>{j||(d(!0),b(!1),h({x:T.clientX,y:T.clientY}),y({x:T.clientX,y:T.clientY}))},[j]),F=v.useCallback(T=>{r&&y({x:T.clientX,y:T.clientY})},[r]),Q=v.useCallback(()=>{if(!r)return;d(!1);const T=Math.abs(p.x-f.x),L=Math.abs(p.y-f.y);T>10&&L>10&&b(!0)},[r,f,p]),E=v.useCallback(async()=>{if(D){A(!0);try{const T=new Image;T.src=i,await new Promise((mt,kt)=>{T.onload=()=>mt(),T.onerror=()=>kt()});const L=window.devicePixelRatio||1,U=document.createElement("canvas");U.width=D.w*L,U.height=D.h*L,U.getContext("2d").drawImage(T,D.x*L,D.y*L,D.w*L,D.h*L,0,0,D.w*L,D.h*L);const tt=U.toDataURL("image/png"),P=await ws();if(!P.allowed){k(`Sign in to keep using AI. Guest mode includes ${xn} free prompts on this browser.`);return}const{apiBaseUrl:W,accessToken:lt}=await gn(),it={"Content-Type":"application/json"};P.signedIn&<&&(it.Authorization=`Bearer ${lt}`),P.signedIn||(it["X-Inline-Device-Id"]=P.deviceId);const rt=await ri(`${W}/api/ai/extension-light`,{method:"POST",headers:it,body:JSON.stringify({task:"analyze-image",text:"Analyze this screenshot crop and describe what you see.",image:tt,guest:!P.signedIn,deviceId:P.signedIn?void 0:P.deviceId})});if(rt.ok){const mt=await rt.json();k(mt.result??"No result returned.")}else k("AI analysis failed. Check your API settings.")}catch{k("Could not reach AI server.")}finally{A(!1)}}},[D,i]);return v.useEffect(()=>{const T=L=>{L.key==="Escape"&&a()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[a]),u.jsxs("div",{style:{position:"fixed",inset:0,zIndex:2147483647,cursor:j?"default":"crosshair",pointerEvents:"auto"},onMouseDown:O,onMouseMove:F,onMouseUp:Q,children:[u.jsx("img",{src:i,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",pointerEvents:"none"}}),u.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)",pointerEvents:"none"}}),(r||g)&&D&&D.w>2&&D.h>2&&u.jsx("div",{style:{position:"absolute",left:D.x,top:D.y,width:D.w,height:D.h,border:"2px dashed #fff",background:"rgba(255,255,255,0.1)",borderRadius:4,pointerEvents:"none"}}),g&&!j&&u.jsxs("div",{style:{position:"absolute",left:D.x,top:D.y+D.h+12,display:"flex",gap:8,pointerEvents:"auto"},children:[u.jsx("button",{type:"button",onClick:E,disabled:S,style:{padding:"8px 20px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:gt,boxShadow:x.shadowOuter,opacity:S?.7:1},children:S?"Analyzing…":"Analyze"}),u.jsx("button",{type:"button",onClick:a,style:{padding:"8px 20px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.bg,color:x.text,fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:gt,boxShadow:x.shadowOuter},children:"Cancel"})]}),j&&u.jsxs("div",{style:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)",width:300,maxHeight:420,overflowY:"auto",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,pointerEvents:"auto"},onMouseDown:T=>T.stopPropagation(),children:[u.jsxs("div",{style:{padding:"10px 14px",background:x.headerBg,borderBottom:`1px solid ${x.divider}`,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u.jsx("span",{style:{fontSize:13,fontWeight:500,color:x.accent},children:"Analysis"}),u.jsx("button",{type:"button",onClick:a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,border:"none",borderRadius:8,background:"rgba(255,255,255,0.4)",cursor:"pointer",padding:0},children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"#78716c",children:u.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"})})})]}),u.jsx("div",{style:{padding:18,fontSize:13,lineHeight:1.65,color:x.text,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:j}),u.jsx("div",{style:{padding:"10px 16px",borderTop:`1px solid ${x.divider}`,background:x.surfaceMuted,display:"flex",justifyContent:"flex-end"},children:u.jsx("button",{type:"button",onClick:a,style:{padding:"8px 18px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12,fontWeight:500,cursor:"pointer",color:x.text,fontFamily:gt},children:"Close"})})]}),u.jsx("canvas",{ref:l,style:{display:"none"}})]})}const Es=8,xc=6;function DT({onClose:i}){const a=v.useRef(null),l=v.useRef([]),r=v.useRef({x:-100,y:-100}),d=v.useRef(0),f=v.useRef([]),h=v.useRef(null),p=v.useCallback(()=>{const y=l.current,g=f.current,b=h.current;b&&(b.setAttribute("cx",String(r.current.x)),b.setAttribute("cy",String(r.current.y)));for(let S=0;S{const y=document.getElementById("inline-laser-svg");y&&y.remove();const g=document.createElementNS("http://www.w3.org/2000/svg","svg");g.id="inline-laser-svg",g.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483645;pointer-events:none;";const b=document.createElementNS("http://www.w3.org/2000/svg","defs"),S=document.createElementNS("http://www.w3.org/2000/svg","filter");S.id="inline-laser-glow",S.setAttribute("x","-50%"),S.setAttribute("y","-50%"),S.setAttribute("width","200%"),S.setAttribute("height","200%");const A=document.createElementNS("http://www.w3.org/2000/svg","feGaussianBlur");A.setAttribute("stdDeviation","4"),A.setAttribute("result","blur");const j=document.createElementNS("http://www.w3.org/2000/svg","feMerge"),k=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");k.setAttribute("in","blur");const D=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");D.setAttribute("in","SourceGraphic"),j.appendChild(k),j.appendChild(D),S.appendChild(A),S.appendChild(j),b.appendChild(S),g.appendChild(b);const O=[];for(let E=Es-1;E>=0;E--){const T=document.createElementNS("http://www.w3.org/2000/svg","circle");T.setAttribute("r",String(xc-E*.5)),T.setAttribute("fill",E===0?"#ef4444":"#f87171"),T.setAttribute("opacity","0"),E===0&&T.setAttribute("filter","url(#inline-laser-glow)"),g.appendChild(T),O.push(T)}f.current=O;const F=document.createElementNS("http://www.w3.org/2000/svg","circle");F.setAttribute("r",String(xc+4)),F.setAttribute("fill","rgba(239, 68, 68, 0.25)"),F.setAttribute("filter","url(#inline-laser-glow)"),g.insertBefore(F,g.firstChild?.nextSibling??null),h.current=F,document.body.appendChild(g),a.current=g;const Q=E=>{r.current={x:E.clientX,y:E.clientY},l.current.push({x:E.clientX,y:E.clientY}),l.current.length>Es+2&&(l.current=l.current.slice(-Es-2))};return document.addEventListener("pointermove",Q),d.current=requestAnimationFrame(p),()=>{document.removeEventListener("pointermove",Q),cancelAnimationFrame(d.current),g.remove(),a.current=null}},[p]),u.jsxs("div",{style:{position:"fixed",top:12,left:"50%",transform:"translateX(-50%)",zIndex:2147483647,display:"flex",alignItems:"center",gap:10,padding:"5px 14px 5px 12px",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusPill,boxShadow:x.shadowOuter,fontFamily:gt,userSelect:"none"},children:[u.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#ef4444",boxShadow:"0 0 6px rgba(239,68,68,0.6)",flexShrink:0}}),u.jsx("span",{style:{fontSize:13,fontWeight:500,color:x.text,letterSpacing:"-0.01em"},children:"Laser active"}),u.jsx("button",{type:"button",onClick:i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:24,height:24,border:"none",borderRadius:x.radiusSm,background:"rgba(255,255,255,0.35)",cursor:"pointer",padding:0,color:x.textMuted,fontSize:14,fontWeight:500},children:"×"})]})}const ty="inline-handwriting-canvas";function ey(){const i=document.getElementById(ty);if(i)return i;const a=document.createElement("canvas");return a.id=ty,a.width=window.innerWidth,a.height=window.innerHeight,a.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483639;pointer-events:none;touch-action:none;",document.body.appendChild(a),window.addEventListener("resize",()=>{a.width=window.innerWidth,a.height=window.innerHeight;const l=a.__inlineStrokes;Array.isArray(l)&&ny(a,l)}),a}function zT(i,a){const l=a.points;if(!(!Array.isArray(l)||l.length===0)){if(i.save(),a.tool==="highlighter"?(i.globalCompositeOperation="multiply",i.globalAlpha=.35):a.tool==="eraser"?(i.globalCompositeOperation="destination-out",i.globalAlpha=1):(i.globalCompositeOperation="source-over",i.globalAlpha=1),i.lineCap="round",i.lineJoin="round",i.strokeStyle=a.tool==="eraser"?"rgba(0,0,0,1)":a.color,l.length===1){const r=l[0],d=a.thickness*(r.pressure||.5)*.5;i.beginPath(),i.arc(r.x,r.y,Math.max(d,.5),0,Math.PI*2),i.fillStyle=i.strokeStyle,i.fill(),i.restore();return}for(let r=0;r{if(chrome.runtime.lastError||!a?.ok)return;const l=a.data?.elements?.handwriting;!Array.isArray(l)||l.length===0||(i.__inlineStrokes=l,ny(i,l))})}catch{}}const ay=["#1C1E26","#b42318","#315a9f","#0f7b6c","#b7791f","#7c3aed","#ec4899","#06b6d4","#ea580c","#78716c"];function sy(){return`hw-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}const LT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),OT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),BT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 0 2.828l-5.5 5.5A2 2 0 0 1 7.879 15H5.12a2 2 0 0 1-1.414-.586l-2.5-2.5a2 2 0 0 1 0-2.828l5.88-5.879z"})});function NT({onClose:i}){const[a,l]=v.useState("pen"),[r,d]=v.useState(ay[0]),[f,h]=v.useState(3),p=v.useRef(null),y=v.useRef([]),g=v.useRef(null),b=v.useRef(!1),S=v.useRef(0);v.useEffect(()=>{const E=ey();p.current=E;const T=E.__inlineStrokes;Array.isArray(T)&&(y.current=T),iy();try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},L=>{if(chrome.runtime.lastError||!L?.ok)return;const U=L.data?.elements?.handwriting;Array.isArray(U)&&U.length>0&&(y.current=U,E.__inlineStrokes=U,j())})}catch{}},[]),v.useEffect(()=>{const E=p.current;if(E)return E.style.pointerEvents="auto",E.style.cursor=a==="eraser"?"cell":"crosshair",()=>{E.style.pointerEvents="none",E.style.cursor=""}},[a]);const A=v.useCallback((E,T)=>{const L=T.points;if(L.length!==0){if(E.save(),T.tool==="highlighter"?(E.globalCompositeOperation="multiply",E.globalAlpha=.35):T.tool==="eraser"?(E.globalCompositeOperation="destination-out",E.globalAlpha=1):(E.globalCompositeOperation="source-over",E.globalAlpha=1),E.lineCap="round",E.lineJoin="round",E.strokeStyle=T.tool==="eraser"?"rgba(0,0,0,1)":T.color,L.length===1){const U=L[0],$=T.thickness*(U.pressure||.5)*.5;E.beginPath(),E.arc(U.x,U.y,Math.max($,.5),0,Math.PI*2),E.fillStyle=E.strokeStyle,E.fill(),E.restore();return}for(let U=0;U{const E=p.current;if(!E)return;const T=E.getContext("2d");if(T){T.clearRect(0,0,E.width,E.height);for(const L of y.current)A(T,L)}},[A]),k=v.useCallback(()=>{try{if(!chrome.runtime?.id)return;const E=y.current.map(L=>({...L,id:L.id??sy()}));y.current=E;const T=p.current;T&&(T.__inlineStrokes=E),chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"handwriting",data:E,pageTitle:document.title,domain:window.location.hostname,clearedAt:E.length===0?Date.now():null}},L=>{chrome.runtime.lastError||nr(L)})}catch{}},[]);v.useEffect(()=>{const E=p.current;if(!E)return;const T=E;function L(tt){tt.preventDefault(),tt.stopPropagation();try{T.setPointerCapture(tt.pointerId)}catch{}b.current=!0;const P=tt.pressure>0?tt.pressure:.5;g.current={id:sy(),points:[{x:tt.clientX,y:tt.clientY,pressure:P}],color:r,thickness:f,tool:a}}function U(tt){if(!b.current||!g.current)return;tt.preventDefault(),tt.stopPropagation();const P=tt.pressure>0?tt.pressure:.5;g.current.points.push({x:tt.clientX,y:tt.clientY,pressure:P}),cancelAnimationFrame(S.current),S.current=requestAnimationFrame(()=>{const W=p.current;if(!W)return;const lt=W.getContext("2d");if(lt){lt.clearRect(0,0,W.width,W.height);for(const it of y.current)A(lt,it);g.current&&A(lt,g.current)}})}function $(tt){if(!(!b.current||!g.current)){tt.preventDefault(),tt.stopPropagation();try{T.releasePointerCapture(tt.pointerId)}catch{}b.current=!1,g.current.points.length>0&&(y.current=[...y.current,g.current]),g.current=null,j(),k()}}return T.addEventListener("pointerdown",L),T.addEventListener("pointermove",U),T.addEventListener("pointerup",$),T.addEventListener("pointerleave",$),()=>{T.removeEventListener("pointerdown",L),T.removeEventListener("pointermove",U),T.removeEventListener("pointerup",$),T.removeEventListener("pointerleave",$)}},[a,r,f,A,j,k]);const D=v.useCallback(()=>{y.current=[],g.current=null;const E=p.current;if(E){const T=E.getContext("2d");T&&T.clearRect(0,0,E.width,E.height)}k()},[k]),O=v.useCallback(()=>{const E=p.current;if(!E)return;const T=E.toDataURL("image/png"),L=document.createElement("a");L.download=`handwriting-${Date.now()}.png`,L.href=T,L.click()},[]),F=[{id:"pen",icon:u.jsx(LT,{}),label:"Pen"},{id:"highlighter",icon:u.jsx(OT,{}),label:"Highlighter"},{id:"eraser",icon:u.jsx(BT,{}),label:"Eraser"}],Q=F.find(E=>E.id===a)?.label??"Pen";return u.jsx(mn,{title:"Pen",subtitle:"Handwrite & highlight freely",chip:Q,width:290,tool:"handwriting",onClose:i,children:u.jsxs("div",{style:{...ya,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tool"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:9},children:F.map(E=>{const T=a===E.id;return u.jsx("button",{type:"button",onClick:()=>l(E.id),"aria-label":E.label,"aria-pressed":T,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,height:46,borderRadius:x.radius,border:`1px solid ${T?x.accent:x.border}`,background:T?x.accent:x.surfaceBubble,color:T?"#fff":x.textMuted,cursor:"pointer",fontSize:12,fontWeight:650,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:E.icon},E.id)})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Stroke weight"}),u.jsxs(Mn,{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px"},children:[u.jsx("button",{type:"button",onClick:()=>h(E=>Math.max(1,E-1)),"aria-label":"Thinner",style:ly,children:"−"}),u.jsx("input",{type:"range",min:1,max:16,value:f,onChange:E=>h(Number(E.target.value)),"aria-label":"Stroke weight",style:{flex:1,accentColor:x.accent,height:6,cursor:"pointer"}}),u.jsx("button",{type:"button",onClick:()=>h(E=>Math.min(16,E+1)),"aria-label":"Thicker",style:ly,children:"+"}),u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:26,height:26,borderRadius:8,background:x.surfaceSunken,fontSize:12,fontWeight:700,color:x.text},children:f})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:11},children:ay.map(E=>{const T=r===E;return u.jsx("button",{type:"button",onClick:()=>d(E),"aria-label":`Colour ${E}`,"aria-pressed":T,style:{height:34,borderRadius:x.radius,background:E,cursor:"pointer",padding:0,border:T?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.13s"}},E)})})]}),u.jsxs("div",{style:{display:"flex",gap:9},children:[u.jsx("button",{type:"button",onClick:D,"aria-label":"Clear all",style:ry,children:"Clear all"}),u.jsx("button",{type:"button",onClick:O,"aria-label":"Export PNG",style:{...ry,background:x.accent,color:"#fff",border:"none",boxShadow:"none"},children:"Export PNG"})]})]})})}const ly={display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radius,flexShrink:0,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:16,fontWeight:600,color:x.textMuted,boxShadow:x.shadowSoft},ry={flex:1,padding:"11px 0",fontSize:12.5,fontWeight:700,borderRadius:x.radius,cursor:"pointer",letterSpacing:"-0.01em",border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text,transition:"background 0.15s, border-color 0.15s",fontFamily:"inherit"},De={selectionUiActive:"inline:selectionUiActive",selectionUiDismiss:"inline:selectionUiDismiss",dockPanelDismiss:"inline:dockPanelDismiss",dockPanelOpen:"inline:dockPanelOpen",dockPanelClosed:"inline:dockPanelClosed"};function oy(i){document.dispatchEvent(new CustomEvent(De.selectionUiActive,{detail:{source:i}}))}function Ii(){document.dispatchEvent(new CustomEvent(De.selectionUiDismiss))}function uy(){document.dispatchEvent(new CustomEvent(De.dockPanelDismiss))}function cy(i){document.dispatchEvent(new CustomEvent(De.dockPanelOpen,{detail:{panel:i}}))}function lr(){document.dispatchEvent(new CustomEvent(De.dockPanelClosed))}function _T(i){const a=l=>{const r=l.detail?.source;r&&i(r)};return document.addEventListener(De.selectionUiActive,a),()=>document.removeEventListener(De.selectionUiActive,a)}function VT(i){return document.addEventListener(De.selectionUiDismiss,i),()=>document.removeEventListener(De.selectionUiDismiss,i)}function UT(i){return document.addEventListener(De.dockPanelDismiss,i),()=>document.removeEventListener(De.dockPanelDismiss,i)}function dy(i){const a=l=>{const r=l.detail?.panel;r&&i(r)};return document.addEventListener(De.dockPanelOpen,a),()=>document.removeEventListener(De.dockPanelOpen,a)}function HT(i){return document.addEventListener(De.dockPanelClosed,i),()=>document.removeEventListener(De.dockPanelClosed,i)}function js(i="/app/dashboard"){gn().then(a=>{window.open(`${a.apiBaseUrl}${i}`,"_blank")}).catch(()=>{window.open(`${$u}${i}`,"_blank")})}const bc={type:"spring",stiffness:380,damping:30,mass:.6},fy={type:"spring",stiffness:440,damping:36,mass:.5},IT=()=>u.jsx(sg,{}),YT=()=>u.jsx(tc,{}),GT=()=>u.jsx(lg,{}),qT=()=>u.jsx(rg,{}),hy=()=>u.jsx(og,{}),XT=()=>u.jsx(ug,{}),FT=()=>u.jsx(cg,{}),PT=()=>u.jsx(dg,{}),KT=()=>u.jsx(fg,{}),WT=()=>u.jsx(hg,{}),QT=()=>u.jsx(pg,{}),ZT=()=>u.jsx(mg,{}),$T=()=>u.jsx(VA,{}),JT=()=>u.jsx(HA,{}),tE=()=>u.jsx(UA,{});function py({size:i=22}){return u.jsx("span",{style:{display:"block",width:Math.max(3,Math.round(i*.16)),height:Math.round(i*.58),borderRadius:2,background:"#FFFFFF",transform:"rotate(-12deg)"}})}function vc({children:i}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:15,height:15,padding:"0 3px",borderRadius:4,background:x.surfaceMuted,color:x.textMuted,border:`1px solid ${x.border}`,fontSize:9.5,fontWeight:700,lineHeight:1},children:i})}const my=38,Sc=40,wc=34,gy=5,yy=12,xy=560,Ac={ai:{icon:u.jsx(YT,{}),label:"Ask Inline"},rewrite:{icon:u.jsx(IT,{}),label:"Rewrite"},highlighter:{icon:u.jsx(hy,{}),label:"Highlight"},notes:{icon:u.jsx(GT,{}),label:"Sticky note"},draw:{icon:u.jsx(qT,{}),label:"Draw"},handwriting:{icon:u.jsx(ZT,{}),label:"Pen"},stamps:{icon:u.jsx(PT,{}),label:"Stamp"},search:{icon:u.jsx(KT,{}),label:"Search"},screenshot:{icon:u.jsx(WT,{}),label:"Screenshot"},laser:{icon:u.jsx(QT,{}),label:"Laser pointer"},layers:{icon:u.jsx(FT,{}),label:"Layers"},settings:{icon:u.jsx(XT,{}),label:"Settings"}},eE=[{type:"tool",id:"ai"},{type:"tool",id:"rewrite"},{type:"group",id:"annotate",icon:u.jsx(hy,{}),label:"Annotate"},{type:"tool",id:"search"},{type:"group",id:"utility",icon:u.jsx(tE,{}),label:"More tools"}],by={annotate:["highlighter","notes","draw","handwriting","stamps"],utility:["screenshot","laser","layers","settings"]},nE=new Set(["ai","rewrite","search","settings","highlighter","draw","handwriting","stamps","layers"]),vy={highlighter:"Highlight mode active",draw:"Drawing mode active",handwriting:"Pen mode active",stamps:"Stamp mode active",laser:"Laser pointer active"},iE=new Set(["highlighter","draw","handwriting","stamps"]);function aE(){return`pn-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function sE(){return u.jsx("span",{style:{height:1,width:22,background:x.divider,margin:"4px 0",flexShrink:0}})}function rr(){try{navigator.vibrate?.(12)}catch{}}function or({icon:i,label:a,active:l,onClick:r}){const[d,f]=v.useState(!1),[h,p]=v.useState(!1),y=`inline-rail-tip-${a.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,g=d||h;return u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",flexShrink:0},children:[u.jsx(On,{children:g&&u.jsxs(Oe.span,{id:y,role:"tooltip",initial:{opacity:0,x:5,scale:.94},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:5,scale:.94},transition:{duration:.12,ease:"easeOut"},style:{position:"absolute",right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:12,whiteSpace:"nowrap",pointerEvents:"none",background:x.surfaceBubble,color:x.text,fontSize:11.5,fontWeight:600,padding:"6px 11px",borderRadius:9,letterSpacing:"-0.01em",lineHeight:1,border:`1px solid ${x.border}`},children:[a,u.jsx("span",{style:{position:"absolute",left:"100%",top:"50%",transform:"translateY(-50%)",width:0,height:0,borderTop:"5px solid transparent",borderBottom:"5px solid transparent",borderLeft:`6px solid ${x.surfaceBubble}`}})]})}),u.jsx("button",{type:"button",onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),onFocus:()=>p(!0),onBlur:()=>p(!1),"aria-label":a,"aria-describedby":g?y:void 0,"aria-pressed":l,style:{display:"flex",alignItems:"center",justifyContent:"center",width:wc,height:wc,borderRadius:11,border:"none",padding:0,background:l?x.toneSelectedBg:d?x.hoverBg:"transparent",color:l?x.accent:x.textMuted,cursor:"pointer",transition:"background 0.14s, color 0.14s",boxShadow:l?`inset 0 0 0 1px ${x.borderStrong}${h?", 0 0 0 3px rgba(19, 42, 79, 0.18)":""}`:h?"0 0 0 3px rgba(19, 42, 79, 0.18)":"none"},children:i})]})}function lE({selectedText:i,originalRange:a}){const[l,r]=v.useState(null),[d,f]=v.useState([]),[h,p]=v.useState(!1),y=v.useRef(null),g=v.useRef(!1),[b,S]=v.useState(!1),[A,j]=v.useState(null),[k,D]=v.useState(!1),[O,F]=v.useState(!1),[Q,E]=v.useState(!1),[T,L]=v.useState(null),[U,$]=v.useState(!1),[tt,P]=v.useState(!1),[W,lt]=v.useState(null),it=v.useRef(null),[rt,mt]=v.useState(16+wc+2*gy+yy),[kt,B]=v.useState(typeof window<"u"?window.innerWidth{const X=at.current?.getRootNode();JA(X)},[]);const bt=v.useCallback((X,ot="success",pt,zt)=>{it.current&&clearTimeout(it.current),lt({id:Date.now(),message:X,tone:ot,actionLabel:pt,onAction:zt}),it.current=setTimeout(()=>lt(null),2600)},[]);v.useEffect(()=>()=>{it.current&&clearTimeout(it.current)},[]),v.useEffect(()=>{const X=ot=>{const pt=ot.detail;pt?.message&&bt(pt.message,pt.tone??"success",pt.action==="dashboard"?"Open →":void 0,pt.action==="dashboard"?()=>js():void 0)};return document.addEventListener("inline:toast",X),()=>document.removeEventListener("inline:toast",X)},[bt]),v.useEffect(()=>{if(!chrome.runtime?.id){p(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},X=>{if(chrome.runtime.lastError){p(!0);return}const ot=X?.data?.elements?.paperNotes;Array.isArray(ot)&&f(ot),p(!0)})},[]),v.useEffect(()=>{if(h){if(!g.current){g.current=!0;return}return y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{chrome.runtime?.id&&chrome.storage.local.get(["inlineAccessToken","inlineActiveWorkspaceId"],X=>{const ot=typeof X?.inlineAccessToken=="string"&&X.inlineAccessToken.split(".").length===3&&typeof X?.inlineActiveWorkspaceId=="string"&&X.inlineActiveWorkspaceId.length>0;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"paperNotes",data:d,pageTitle:document.title,domain:window.location.hostname,clearedAt:d.length===0?Date.now():null}},pt=>{if(chrome.runtime.lastError){bt("Could not save. Try again.","error");return}if(pt?.ok){pt.storageMode==="workspace"||pt.storageMode!=="local"&&ot?bt("Saved to Workspace","success","Open →",()=>js()):bt("Saved to browser.","local");return}if(pt?.queued){bt("Saved to browser.","local");return}bt("Could not save. Try again.","error")})})},500),()=>{y.current&&clearTimeout(y.current)}}},[d,h,bt]);const M=v.useCallback((X,ot)=>{f(pt=>pt.map(zt=>zt.id===X?{...zt,...ot,updatedAt:Date.now()}:zt))},[]),K=v.useCallback(X=>{f(ot=>ot.filter(pt=>pt.id!==X))},[]),nt=v.useCallback(()=>{r(null),lr()},[]),dt=v.useCallback(X=>{rr(),T===X||nt(),L(pt=>pt===X?null:X)},[T,nt]),vt=v.useCallback(()=>{f(X=>[...X,{id:aE(),x:120+X.length*20,y:120+X.length*20,w:320,h:260,content:"",paperStyle:"Plain",createdAt:Date.now(),updatedAt:Date.now()}])},[]),Y=v.useCallback(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"CAPTURE_TAB"},X=>{chrome.runtime.lastError||X?.ok&&X.dataUrl&&j(X.dataUrl)})},[]),H=v.useCallback(X=>{if(X){if(rr(),E(!0),L(null),X==="notes"){Ii(),vt();return}if(X==="screenshot"){Ii(),Y();return}if(X==="laser"){D(ot=>(ot||Ii(),!ot));return}nE.has(X)&&r(ot=>{const pt=ot===X?null:X;return pt?(Ii(),cy(pt)):lr(),pt})}},[vt,Y]),st=v.useCallback(()=>{rr(),E(X=>{const ot=!X;return L(null),ot?(Ii(),cy("ai"),r("ai")):(r(null),lr()),ot})},[]),ht=v.useCallback(()=>{F(X=>{const ot=!X;return ot?(nt(),D(!1),j(null),E(!1),L(null),Ii(),document.dispatchEvent(new CustomEvent("inline:hideAll",{detail:{hidden:!0}}))):document.dispatchEvent(new CustomEvent("inline:hideAll",{detail:{hidden:!1}})),ot})},[nt]);v.useEffect(()=>{const X=ot=>{const pt=ot.detail;F(pt.hidden),pt.hidden&&(nt(),D(!1),j(null),E(!1),L(null),Ii())};return document.addEventListener("inline:hideAll",X),()=>document.removeEventListener("inline:hideAll",X)},[nt]),v.useEffect(()=>{const X=()=>{L(null),r(zt=>(zt!==null&&lr(),null))},ot=_T(()=>{X()}),pt=UT(X);return()=>{ot(),pt()}},[]);const Tt=v.useCallback(()=>{const X=at.current;if(!X)return;const ot=X.getBoundingClientRect();mt(Math.max(14,Math.round(window.innerWidth-ot.left+yy)))},[]);v.useLayoutEffect(()=>{Tt()},[Tt,O,l]),v.useEffect(()=>{const X=()=>{B(window.innerWidthwindow.removeEventListener("resize",X)},[Tt]),v.useEffect(()=>{if(!l)return;const X=ot=>{const pt=ot.composedPath?.()??[],zt=G.current?pt.includes(G.current):!1,Xt=at.current?pt.includes(at.current):!1;if(zt||Xt||iE.has(l)||Hg())return;const I=G.current?.getRootNode()?.activeElement;I&&G.current?.contains(I)&&(I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable)||nt()};return document.addEventListener("pointerdown",X,!0),()=>document.removeEventListener("pointerdown",X,!0)},[l,nt]),v.useEffect(()=>{if(!T)return;const X=ot=>{const pt=ot.composedPath?.()??[];ct.current&&pt.includes(ct.current)||at.current&&pt.includes(at.current)||L(null)};return document.addEventListener("pointerdown",X,!0),()=>document.removeEventListener("pointerdown",X,!0)},[T]),v.useEffect(()=>{const X=ot=>{if(ot.key==="Escape"){if(k){ot.stopPropagation(),D(!1);return}if(T){ot.stopPropagation(),L(null);return}l&&(ot.stopPropagation(),nt())}};return document.addEventListener("keydown",X,!0),()=>document.removeEventListener("keydown",X,!0)},[k,T,l,nt]);const Vt=v.useCallback(X=>{switch(X){case"rewrite":case"ai":case"search":case"settings":case"highlighter":case"draw":case"handwriting":case"stamps":case"layers":H(X);break;case"notes":vt();break;case"screenshot":Y();break;case"laser":D(ot=>!ot);break;case"notebooks":js();break;case"collapse":E(ot=>{const pt=!ot;return L(null),r(pt?"ai":null),pt});break;case"pause":ht();break}S(!1)},[H,vt,Y,ht]);v.useEffect(()=>{const X=ot=>{switch(ot.detail.command){case"toggle-command-palette":S(zt=>!zt);break;case"toggle-rewrite":H("rewrite");break;case"toggle-ai":H("ai");break;case"toggle-highlighter":H("highlighter");break;case"new-note":vt();break;case"toggle-pause":ht();break}};return document.addEventListener("inline:command",X),()=>document.removeEventListener("inline:command",X)},[H,vt,ht]),v.useEffect(()=>{const X=ot=>{(ot.ctrlKey||ot.metaKey)&&ot.shiftKey&&ot.key.toLowerCase()==="k"&&(ot.preventDefault(),E(!0),L(null),r("ai"))};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[]);const ut=k?"laser":l&&vy[l]?l:null,It=ut?vy[ut]:null,Et=ut?Ac[ut]?.icon:null,jt=l?u.jsx(On,{mode:"wait",children:u.jsxs(Oe.div,{initial:{opacity:0,x:10,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:10,scale:.985},transition:fy,style:{pointerEvents:"auto"},children:[l==="rewrite"&&u.jsx(C5,{selectedText:i,originalRange:a,onClose:nt}),l==="ai"&&u.jsx(H5,{selectedText:i,originalRange:a,onClose:nt}),l==="search"&&u.jsx(kT,{onClose:nt}),l==="settings"&&u.jsx(W5,{onClose:nt,onOpenDashboard:()=>{js(),nt()}}),l==="highlighter"&&u.jsx(Q5,{onClose:nt}),l==="draw"&&u.jsx(lT,{onClose:nt}),l==="handwriting"&&u.jsx(NT,{onClose:nt}),l==="stamps"&&u.jsx(MT,{onClose:nt}),l==="layers"&&u.jsx(jT,{onClose:nt})]},l)}):null;return u.jsxs(u.Fragment,{children:[u.jsx(On,{children:!O&&It&&u.jsxs(Oe.div,{"data-inline-interactive":"",initial:{opacity:0,y:-6,x:"-50%",scale:.96},animate:{opacity:1,y:0,x:"-50%",scale:1},exit:{opacity:0,y:-6,x:"-50%",scale:.96},transition:{duration:.16,ease:"easeOut"},style:{position:"fixed",top:18,left:"50%",zIndex:2147483647,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,background:x.surfaceBubble,color:x.text,padding:"8px 14px",borderRadius:x.radiusMd,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",whiteSpace:"nowrap",border:`1px solid ${x.border}`,boxShadow:x.shadowOuter,fontFamily:gt},children:[Et&&u.jsx(gg,{size:24,children:Et}),It]},ut??It)}),u.jsx(On,{children:!O&&W&&u.jsxs(Oe.div,{"data-inline-interactive":"",initial:{opacity:0,y:-6,x:"-50%",scale:.96},animate:{opacity:1,y:0,x:"-50%",scale:1},exit:{opacity:0,y:-6,x:"-50%",scale:.96},transition:{duration:.16,ease:"easeOut"},style:{position:"fixed",top:It?56:18,left:"50%",zIndex:2147483647,pointerEvents:W.onAction?"auto":"none",display:"flex",alignItems:"center",gap:7,background:W.tone==="error"?"#FEF2F2":x.surfaceBubble,color:W.tone==="error"?"#991B1B":x.text,padding:"8px 14px",borderRadius:x.radiusMd,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",whiteSpace:"nowrap",border:`1px solid ${W.tone==="error"?"#FECACA":x.border}`,boxShadow:x.shadowOuter,fontFamily:gt},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:W.tone==="error"?"#DC2626":W.tone==="local"?"#D97706":"#16A34A"}}),W.message,W.onAction&&W.actionLabel&&u.jsx("button",{type:"button",onClick:()=>{const X=W?.onAction;X?.(),lt(null)},style:{border:"none",background:"transparent",padding:"0 0 0 2px",color:x.accent,fontSize:12,fontWeight:750,cursor:"pointer",fontFamily:gt},children:W.actionLabel})]},W.id)}),u.jsx(On,{children:!O&&l&&!kt&&u.jsx(Oe.div,{"data-inline-interactive":"",ref:G,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.14},style:{position:"fixed",right:rt,top:my,zIndex:2147483646,pointerEvents:"none",display:"flex",fontFamily:gt},children:jt},"panel-wrap")}),u.jsx(On,{children:!O&&l&&kt&&u.jsxs(u.Fragment,{children:[u.jsx(Oe.div,{"data-inline-interactive":"",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.16},onPointerDown:()=>{Hg()||nt()},style:{position:"fixed",inset:0,zIndex:2147483645,background:"rgba(11,18,33,0.34)",pointerEvents:"auto"}},"scrim"),u.jsx(Oe.div,{"data-inline-interactive":"",ref:G,initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:fy,style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:2147483646,pointerEvents:"none",display:"flex",fontFamily:gt},children:jt},"panel-sheet")]})}),u.jsx("div",{"data-inline-interactive":"",ref:at,style:{position:"fixed",right:16,top:my,zIndex:2147483647,pointerEvents:"none",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:12,fontFamily:gt},children:O?u.jsx(Oe.button,{type:"button",onClick:ht,"aria-label":"Show Inline",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:bc,style:{pointerEvents:"auto",width:40,height:40,borderRadius:13,background:Zu,border:"1px solid rgba(255,255,255,0.14)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#FFFFFF",boxShadow:x.shadowOuter,padding:0},children:u.jsx(py,{size:20})}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",pointerEvents:"auto"},children:[u.jsx(On,{children:(U||tt)&&!Q&&!l&&u.jsxs(Oe.div,{id:"inline-launcher-tooltip",role:"tooltip",initial:{opacity:0,x:8,scale:.94},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:8,scale:.94},transition:{duration:.13,ease:"easeOut"},style:{position:"absolute",right:"100%",marginRight:13,display:"flex",alignItems:"center",gap:8,whiteSpace:"nowrap",background:x.surfaceBubble,color:x.text,padding:"7px 12px",borderRadius:10,fontSize:11.5,fontWeight:600,letterSpacing:"-0.01em",pointerEvents:"none",border:`1px solid ${x.border}`},children:[u.jsx("span",{children:"Open Inline tools"}),u.jsxs("span",{style:{display:"inline-flex",gap:3},children:[u.jsx(vc,{children:"⌘"}),u.jsx(vc,{children:"⇧"}),u.jsx(vc,{children:"K"})]}),u.jsx("span",{style:{position:"absolute",left:"100%",top:"50%",transform:"translateY(-50%)",width:0,height:0,borderTop:"5px solid transparent",borderBottom:"5px solid transparent",borderLeft:`6px solid ${x.surfaceBubble}`}})]})}),u.jsx(Oe.button,{type:"button",onClick:st,onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),onFocus:()=>P(!0),onBlur:()=>P(!1),"aria-label":Q?"Close Inline tools":"Open Inline tools","aria-expanded":Q,"aria-describedby":(U||tt)&&!Q&&!l?"inline-launcher-tooltip":void 0,initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},whileHover:{scale:1.05},whileTap:{scale:.94},transition:bc,style:{position:"relative",width:Sc,height:Sc,borderRadius:13,background:Zu,border:`1px solid ${Q?x.accent:"rgba(17,24,39,0.18)"}`,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,outline:"none",color:"#FFFFFF",boxShadow:`${x.shadowOuter}${tt?", 0 0 0 3px rgba(19, 42, 79, 0.18)":""}`},children:u.jsx(py,{size:21})})]}),u.jsx(On,{children:Q&&u.jsxs(Oe.div,{initial:{opacity:0,y:-8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.98},transition:bc,style:{pointerEvents:"auto",display:"flex",flexDirection:"column",alignItems:"center",gap:2,padding:gy,background:x.bg,border:`1px solid ${x.border}`,borderRadius:17,boxShadow:x.shadowOuter,maxHeight:"min(72vh, 640px)",overflowY:"auto",overflowX:"hidden"},children:[eE.map(X=>{if(X.type==="tool"){const pt=Ac[X.id],zt=X.id==="laser"?k:l===X.id;return u.jsx(or,{icon:pt.icon,label:pt.label,active:zt,onClick:()=>H(X.id)},X.id)}const ot=T===X.id||by[X.id].some(pt=>pt==="laser"?k:l===pt);return u.jsx(or,{icon:X.icon,label:X.label,active:ot,onClick:()=>dt(X.id)},X.id)}),u.jsx(sE,{}),u.jsx(or,{icon:u.jsx($T,{}),label:"Notebooks",active:!1,onClick:()=>{rr(),js()}}),u.jsx(or,{icon:u.jsx(JT,{}),label:"Hide Inline",active:!1,onClick:ht})]})}),u.jsx(On,{children:Q&&T&&u.jsxs(Oe.div,{ref:ct,initial:{opacity:0,x:8,scale:.98},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:8,scale:.98},transition:{duration:.14,ease:"easeOut"},style:{position:"absolute",right:"calc(100% + 10px)",top:Sc+10,pointerEvents:"auto",width:172,padding:6,borderRadius:x.radiusMd,border:`1px solid ${x.border}`,background:x.bg,boxShadow:x.shadowOuter,display:"flex",flexDirection:"column",gap:2,fontFamily:gt},children:[u.jsx("div",{style:{padding:"4px 8px 6px",fontSize:11,fontWeight:500,color:x.textMuted,letterSpacing:"0.01em"},children:T==="annotate"?"Annotate":"More tools"}),by[T].map(X=>{const ot=Ac[X],pt=X==="laser"?k:l===X;return u.jsxs("button",{type:"button",onClick:()=>H(X),"aria-label":ot.label,"aria-pressed":pt,style:{display:"flex",alignItems:"center",gap:10,width:"100%",minHeight:36,padding:"6px 8px",borderRadius:x.radiusSm,border:"none",background:pt?x.toneSelectedBg:"transparent",color:pt?x.text:x.textMuted,cursor:"pointer",fontFamily:gt,fontSize:12,fontWeight:500,textAlign:"left",transition:"background 0.14s"},children:[u.jsx(gg,{size:28,active:pt,children:ot.icon}),u.jsx("span",{children:ot.label})]},X)})]},T)})]})}),!O&&d.map(X=>u.jsx(X5,{initialX:X.x,initialY:X.y,initialW:X.w,initialH:X.h,initialContent:X.content,initialPaperStyle:X.paperStyle,onClose:()=>K(X.id),onUpdate:ot=>M(X.id,ot)},X.id)),b&&u.jsx(bT,{onClose:()=>S(!1),onAction:Vt}),!O&&A&&u.jsx(RT,{screenshot:A,onClose:()=>j(null)}),!O&&k&&u.jsx(DT,{onClose:()=>D(!1)})]})}function rE(){const[i,a]=v.useState(""),[l,r]=v.useState(null),d=v.useRef(null),f=v.useRef("");return v.useEffect(()=>{d.current=l},[l]),v.useEffect(()=>{f.current=i},[i]),v.useEffect(()=>{function h(){const p=window.getSelection();if(p&&!(p.isCollapsed||!p.toString().trim()))try{const y=p.getRangeAt(0).cloneRange();a(p.toString()),r(y)}catch{}}return document.addEventListener("mouseup",h),document.addEventListener("keyup",h),()=>{document.removeEventListener("mouseup",h),document.removeEventListener("keyup",h)}},[]),v.useEffect(()=>dy(h=>{if(h!=="rewrite"&&h!=="ai")return;const p=d.current,y=f.current.trim();if(!(!p||!y))try{const g=qg(p,"selection-hold");if(!g)return;d.current=g.range,f.current=g.text,r(g.range),a(g.text)}catch{}}),[]),u.jsx("div",{"data-panel-host":"",children:u.jsx(lE,{selectedText:i,originalRange:l})})}async function oE(i,a){const l=window;try{const r=l.ai?.languageModel?.create;if(!r)return null;const d=await r.call(l.ai.languageModel),f=i==="summarize"?`Summarize in 3 short bullets: +${n.result}`:n.result},w={"Content-Type":"application/json"};w.Authorization=`Bearer ${d}`,await ci(`${r}/api/clip`,{method:"POST",headers:w,body:JSON.stringify(b)})}catch{}}const Vg={rephrase:{bg:"rgba(167, 139, 250, 0.25)",border:"rgba(139, 92, 246, 0.5)"},shorten:{bg:"rgba(251, 191, 36, 0.3)",border:"rgba(217, 119, 6, 0.5)"},summarize:{bg:"rgba(110, 231, 183, 0.3)",border:"rgba(5, 150, 105, 0.5)"},rewrite:{bg:"rgba(147, 197, 253, 0.3)",border:"rgba(37, 99, 235, 0.55)"},custom:{bg:"rgba(248, 180, 217, 0.35)",border:"rgba(236, 72, 153, 0.55)"},default:{bg:"rgba(244, 231, 211, 0.4)",border:"rgba(161, 98, 7, 0.4)"}},B5={rephrase:"Rephrased by Inline AI",shorten:"Shortened by Inline AI",summarize:"Summarized by Inline AI",rewrite:"Rewritten by Inline AI",custom:"Custom AI prompt applied"};function or(n,a,l){const r=Vg[a]?a:"default",d=Vg[r],f=B5[a]??"Inline AI edit",h=l?` — ${l.slice(0,120)}`:"",p=document.createElement("mark");return p.setAttribute("data-inline-ai",a||"edit"),p.setAttribute("title",`${f}${h}`),p.setAttribute("aria-label",f),p.style.background=d.bg,p.style.borderBottom=`1.5px solid ${d.border}`,p.style.borderRadius="3px",p.style.padding="0 2px",p.style.color="inherit",p.style.transition="background 120ms ease",p.textContent=n,p.addEventListener("mouseenter",()=>{p.style.boxShadow=`0 0 0 2px ${d.border}`}),p.addEventListener("mouseleave",()=>{p.style.boxShadow="none"}),p}const Ig="inline-manual-insert-styles",N5=` +.inline-manual-wrap { + display: inline; + position: relative; + vertical-align: baseline; +} +.inline-manual-wrap .inline-manual-text { + background: rgba(147, 197, 253, 0.3); + border-bottom: 1.5px solid rgba(37, 99, 235, 0.55); + border-radius: 3px; + padding: 0 2px; + color: inherit; + transition: box-shadow 180ms ease, background 180ms ease; +} +.inline-manual-wrap:hover .inline-manual-text, +.inline-manual-wrap:focus-within .inline-manual-text { + background: rgba(147, 197, 253, 0.42); + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.28); +} +.inline-manual-popover { + position: absolute; + top: calc(100% + 5px); + left: 0; + z-index: 2147483640; + pointer-events: none; + min-width: 148px; + max-width: 220px; + padding: 6px 10px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.98); + border: 1px solid rgba(37, 99, 235, 0.22); + box-shadow: 0 4px 16px rgba(28, 30, 38, 0.14); + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + opacity: 0; + visibility: hidden; + transform: translateY(-5px) scale(0.97); + transform-origin: top left; + transition: + opacity 200ms ease, + transform 220ms cubic-bezier(0.22, 1, 0.36, 1), + visibility 0s linear 220ms; +} +.inline-manual-popover--above { + top: auto; + bottom: calc(100% + 5px); + transform-origin: bottom left; + transform: translateY(5px) scale(0.97); +} +.inline-manual-wrap:hover .inline-manual-popover, +.inline-manual-wrap:focus-within .inline-manual-popover { + opacity: 1; + visibility: visible; + transform: translateY(0) scale(1); + transition: + opacity 200ms ease, + transform 220ms cubic-bezier(0.22, 1, 0.36, 1), + visibility 0s linear 0s; +} +.inline-manual-wrap:hover .inline-manual-popover--above, +.inline-manual-wrap:focus-within .inline-manual-popover--above { + transform: translateY(0) scale(1); +} +.inline-manual-popover-label { + display: block; + font-size: 10px; + font-weight: 600; + color: #2563eb; + line-height: 1.3; + letter-spacing: 0.01em; +} +.inline-manual-popover-time { + display: block; + font-size: 10px; + color: #78716c; + font-style: italic; + line-height: 1.35; + margin-top: 2px; +} +`;function _5(){let n=document.getElementById(Ig);n||(n=document.createElement("style"),n.id=Ig,document.head.appendChild(n)),n.textContent=N5}function U5(n){return new Date(n).toLocaleString()}function H5(n,a){a.classList.remove("inline-manual-popover--above");const l=n.getBoundingClientRect(),r=44;l.bottom+r+8>window.innerHeight&&l.top>r+8&&a.classList.add("inline-manual-popover--above")}function Yg(n,a,l){_5();const r=l??Date.now(),d=U5(r),f=document.createElement("span");f.className="inline-manual-wrap",f.setAttribute("data-inline-manual","true"),a&&f.setAttribute("data-inline-manual-id",a),f.setAttribute("tabindex","0"),f.setAttribute("aria-label",`Manual edit via Inline, ${d}`);const h=document.createElement("mark");h.className="inline-manual-text",h.textContent=n;const p=document.createElement("span");p.className="inline-manual-popover",p.setAttribute("role","tooltip");const y=document.createElement("span");y.className="inline-manual-popover-label",y.textContent="Manual edit via Inline";const g=document.createElement("span");g.className="inline-manual-popover-time",g.textContent=d,p.appendChild(y),p.appendChild(g),f.appendChild(h),f.appendChild(p);const b=()=>H5(f,p);return f.addEventListener("mouseenter",b),f.addEventListener("focusin",b),f}function Ta(n){n?.ok&&n.storageMode==="workspace"&&document.dispatchEvent(new CustomEvent("inline:toast",{detail:{message:"Saved to Workspace",tone:"success",action:"dashboard"}}))}const Gg=window.location.href,V5=2500;let Fi=[];function I5(){return`air-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Fg(...n){const a=new Map;for(const l of n)for(const r of l)r?.id&&a.set(r.id,r);return[...a.values()]}function qg(n){Fi=n;try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:Gg,featureKey:"aiReplacements",data:n,pageTitle:document.title,domain:window.location.hostname,clearedAt:n.length===0?Date.now():null}},a=>{Ta(a),chrome.runtime.lastError?console.error("[Inline] Save failed:",chrome.runtime.lastError.message):a?.ok||console.error("[Inline] Backend sync failed:",a?.error)})}catch{}}function Xg(){try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:Gg}},n=>{if(chrome.runtime.lastError||!n?.ok)return;const a=n.data?.elements?.aiReplacements;if(!Array.isArray(a)||a.length===0)return;const l=a.filter(r=>r.task!=="manual");Fi=Fg(Fi,l),F5(Fi)})}catch{}}function Pg(n,a,l,r,d){const f=I5();n.setAttribute("data-inline-ai-id",f);const h={id:f,originalText:a,aiText:l,task:r,instruction:d,timestamp:Date.now()},p=Fg(Fi,[h]);return qg(p),Kg(n,f),f}function Y5(n){const a=Fi.filter(l=>l.id!==n);qg(a)}function Kg(n,a){n.style.cursor="pointer";const l=d=>{if(!d.target?.classList.contains("inline-ai-remove-badge")&&!d.altKey)return;d.preventDefault(),d.stopPropagation();const p=Fi.find(b=>b.id===a);Y5(a);const y=n.parentNode;if(!y)return;const g=document.createTextNode(p?.originalText??n.textContent??"");y.replaceChild(g,n)};n.addEventListener("click",l);const r=document.createElement("span");r.className="inline-ai-remove-badge",r.textContent="×",r.setAttribute("aria-label","Remove this edit"),r.title="Remove this edit",r.style.cssText=["display:none","position:absolute","top:-10px","right:-8px","width:18px","height:18px","border-radius:9999px","background:#1C1E26","color:#fff","font:600 11px/18px system-ui,sans-serif","text-align:center","cursor:pointer","user-select:none","box-shadow:none","z-index:2147483646"].join(";"),n.style.position||(n.style.position="relative"),n.appendChild(r),n.addEventListener("mouseenter",()=>{r.style.display="inline-block"}),n.addEventListener("mouseleave",()=>{r.style.display="none"})}function G5(){Xg(),window.setTimeout(Xg,V5)}function F5(n){const a=document.body;if(a)for(const l of n){if(!l.originalText?.trim()||l.task==="manual"||l.originalText.length<3||document.querySelector(`[data-inline-ai-id="${CSS.escape(l.id)}"]`))continue;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,{acceptNode(f){const h=f.parentElement;if(!h||h.closest("[data-inline-ai-id]")||h.closest("[data-inline-manual-id]")||h.closest("#inline-extension-root"))return NodeFilter.FILTER_REJECT;const p=h.tagName;return p==="SCRIPT"||p==="STYLE"||p==="NOSCRIPT"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let d;for(;d=r.nextNode();){const f=d.textContent?.indexOf(l.originalText)??-1;if(f!==-1){try{const h=document.createRange();h.setStart(d,f),h.setEnd(d,f+l.originalText.length);const p=or(l.aiText,l.task,l.instruction);p.setAttribute("data-inline-ai-id",l.id),h.deleteContents(),h.insertNode(p),Kg(p,l.id)}catch{}break}}}}let Wg=!1;function Ea(n){Wg=n}function Qg(){return Wg}const q5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),u.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),X5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]}),P5=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),u.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),K5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5"})}),W5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M8 7l-4 5 4 5M16 7l4 5-4 5M14 4l-4 16"})}),Q5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:u.jsx("path",{d:"M4 6h16M4 10h16M4 14h10M4 18h7"})}),Z5=["Formal","Casual","Concise"],$5=[{label:"Rephrase",desc:"Reword while keeping the meaning",task:"rephrase",icon:u.jsx(K5,{})},{label:"Shorten",desc:"Trim it down without losing the point",task:"shorten",icon:u.jsx(W5,{})},{label:"Summarize",desc:"Condense to the essentials",task:"summarize",icon:u.jsx(Q5,{})}];function J5(n,a){const l=n.split(/(\s+)/),r=a.split(/(\s+)/);let d=0;for(;d=d&&h>=d&&l[f]===r[h];)f--,h--;const p=[];d>0&&p.push({type:"same",text:l.slice(0,d).join("")});const y=l.slice(d,f+1).join(""),g=r.slice(d,h+1).join("");y&&p.push({type:"del",text:y}),g&&p.push({type:"add",text:g});const b=f+1;return b0;function J(){if(D){Cs(),O(!1);return}f&&lr(f,{onStart:()=>O(!0),onEnd:()=>O(!1)})}const $=v.useCallback(async(it,rt)=>{y(!0),Ea(!0),h(null),W(it),T(rt);try{const ht=await Ms();if(!ht.allowed){h(`Sign in to keep using AI. Guest mode includes ${bn} free prompts on this browser.`);return}const Mt=n.slice(0,8e3),{apiBaseUrl:B,accessToken:at}=await yn(),Y={"Content-Type":"application/json"};ht.signedIn&&at&&(Y.Authorization=`Bearer ${at}`),ht.signedIn||(Y["X-Inline-Device-Id"]=ht.deviceId);const dt=await ci(`${B}/api/ai/extension-light`,{method:"POST",headers:Y,body:JSON.stringify({task:it,text:Mt,instruction:rt,guest:!ht.signedIn,deviceId:ht.signedIn?void 0:ht.deviceId})});if(dt.ok){const bt=await dt.json(),M=bt.result??"No result returned.";h(M),bt.result&&Hg({kind:{rephrase:"ai-rephrase",shorten:"ai-shorten",summarize:"ai-summarize",rewrite:rt?"ai-custom":"ai-rewrite"}[it]??"ai-custom",selection:Mt,result:M})}else h("AI request failed. Check your API settings.")}catch{h("Could not reach AI server.")}finally{y(!1),Ea(!1)}},[n]);function F(){if(!(!f||!a))try{const it=a.toString();L.current=it,a.deleteContents();const rt=or(f,q,E);rt.style.display="inline-block",rt.style.lineHeight="1.55";const ht=document.createElement("span");ht.className="inline-cite-attr",ht.style.cssText="display:block;font-size:10px;color:#78716c;margin-top:4px;font-style:italic;",ht.textContent=`via Inline · ${new Date().toLocaleString()}`,rt.appendChild(document.createElement("br")),rt.appendChild(ht),a.insertNode(rt),k(!0),Pg(rt,it,f,q,E)}catch{}}function K(){if(!(!L.current||!a))try{a.deleteContents(),a.insertNode(document.createTextNode(L.current)),L.current=null,k(!1)}catch{}}function lt(){f&&navigator.clipboard.writeText(f)}return!f&&!p?u.jsx(gn,{title:"Rewrite",subtitle:"Reword your selection with AI",chip:H?"Selection":void 0,tool:"rewrite",width:342,onClose:l,footer:u.jsx("div",{style:{padding:"10px 14px 12px"},children:u.jsx(pc,{value:g,onChange:b,onSubmit:()=>{g.trim()&&$("rewrite",g)},placeholder:H?"Describe how to rewrite it...":"Select text to rewrite",sendDisabled:!H,modeLabel:r})}),children:u.jsxs("div",{style:{padding:16,display:"flex",flexDirection:"column",gap:16},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tone"}),u.jsx(hc,{options:Z5.map(it=>({value:it,label:it})),value:r,onChange:d})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Rewrite as"}),u.jsx("div",{style:{display:"flex",flexDirection:"column",gap:9},children:$5.map(it=>u.jsx(fc,{icon:it.icon,label:it.label,desc:it.desc,disabled:!H,onClick:()=>$(it.task,`Tone: ${r}`)},it.label))}),!H&&u.jsx("p",{style:{margin:"10px 2px 0",fontSize:11.5,color:x.textLight,lineHeight:1.5},children:"Select text on the page to rewrite it."})]}),mc.length>0&&u.jsxs("div",{children:[u.jsx(ye,{children:"Quick prompts"}),u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:mc.map(it=>u.jsx(Dg,{label:it.label,disabled:!H,onClick:()=>$("rewrite",it.prompt)},it.id))})]})]})}):u.jsx(gn,{title:"Rewrite",subtitle:p?"Rewriting...":"Review & apply",chip:E?"Custom":q||void 0,tool:"rewrite",width:342,onClose:l,footer:p?void 0:u.jsxs("div",{style:{padding:"10px 14px",display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[u.jsx("button",{type:"button",onClick:()=>{h(null),A(!1),k(!1)},"aria-label":"Back",style:Zg,children:"Back"}),u.jsx("button",{type:"button",onClick:()=>A(it=>!it),"aria-label":w?"Hide diff":"Show diff",style:Zg,children:w?"Hide diff":"Diff"}),j?u.jsx("button",{type:"button",onClick:K,"aria-label":"Undo insert",style:{...$g,background:"#DC2626",boxShadow:"none"},children:"Undo"}):u.jsx("button",{type:"button",onClick:F,"aria-label":"Insert into page",style:$g,children:"Insert"}),u.jsx("button",{type:"button",onClick:J,"aria-label":D?"Stop speaking":"Speak",style:{...Jg,marginLeft:"auto"},children:D?u.jsx(P5,{}):u.jsx(X5,{})}),u.jsx("button",{type:"button",onClick:lt,"aria-label":"Copy",style:Jg,children:u.jsx(q5,{})})]}),children:u.jsxs("div",{style:{padding:18,display:"flex",flexDirection:"column",gap:14},children:[u.jsx("div",{style:{padding:15,border:`1px solid ${x.border}`,borderRadius:16,minHeight:80,background:x.surfaceBubble,boxShadow:"none",maxHeight:280,overflowY:"auto"},children:p?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:13.5,lineHeight:1.7},children:[u.jsx(Aa,{size:16}),u.jsx("span",{style:{fontStyle:"italic"},children:"Generating..."})]}):w&&f?u.jsx("span",{style:{fontSize:13.5,lineHeight:1.7,color:x.text},children:J5(n,f).map((it,rt)=>it.type==="del"?u.jsx("span",{style:{color:"#ef4444",textDecoration:"line-through",background:"rgba(239,68,68,0.1)"},children:it.text},rt):it.type==="add"?u.jsx("span",{style:{color:"#16a34a",background:"rgba(34,197,94,0.12)"},children:it.text},rt):u.jsx("span",{children:it.text},rt))}):f?u.jsx(ui,{text:f,style:{fontSize:13.5,lineHeight:1.7}}):null}),!p&&u.jsx(pc,{value:g,onChange:b,onSubmit:()=>{g.trim()&&$("rewrite",g)},placeholder:"Refine with another instruction...",sendDisabled:!H,modeLabel:r})]})})}const Zg={padding:"8px 13px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12.5,fontWeight:600,cursor:"pointer",color:x.text,fontFamily:gt,boxShadow:"none"},$g={padding:"8px 16px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none"},Jg={display:"inline-flex",alignItems:"center",justifyContent:"center",width:34,height:34,border:`1px solid ${x.border}`,borderRadius:11,background:x.surfaceBubble,cursor:"pointer",padding:0,color:x.textMuted,boxShadow:"none"},eT={summarize:{bg:"rgba(187,247,208,0.92)",title:"Summarized via Inline"},rephrase:{bg:"rgba(196,181,253,0.92)",title:"Rephrased via Inline"},rewrite:{bg:"rgba(191,219,254,0.92)",title:"Rewritten via Inline"},shorten:{bg:"rgba(254,215,170,0.92)",title:"Shortened via Inline"},extract:{bg:"rgba(233,213,255,0.92)",title:"Extracted via Inline"},risk:{bg:"rgba(254,202,202,0.92)",title:"Risk-flagged via Inline"},"selection-hold":{bg:"rgba(147,197,253,0.55)",title:"Selected for Inline"}};function nT(){return`hl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}let ur=[];function iT(n){ur=[...ur,n];try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"highlights",data:ur,pageTitle:document.title,domain:window.location.hostname}},a=>{chrome.runtime.lastError||Ta(a)})}catch{}}function aT(n){const a=n.commonAncestorContainer;return!!(a.nodeType===Node.ELEMENT_NODE?a:a.parentElement)?.closest("[data-inline-highlight]")}function ty(n,a,l){const r=n.toString();if(!r.trim()||aT(n))return null;const d=eT[a]??{bg:"rgba(226,232,240,0.95)",title:"Highlighted by Inline"},f=l??d.bg,h=n.cloneRange(),p=document.createElement("span");p.setAttribute("data-inline-highlight",a),p.style.backgroundColor=f,p.style.borderRadius="4px",p.style.padding="0 3px",p.title=d.title;try{h.surroundContents(p)}catch{const g=h.extractContents();p.appendChild(g),h.insertNode(p)}iT({id:nT(),text:r.trim(),action:a,bg:f,title:d.title,timestamp:Date.now()});const y=document.createRange();return y.selectNode(p),document.dispatchEvent(new CustomEvent("inline:highlightAdded")),{text:r,title:d.title,span:p,range:y}}function di(n,a){const l=window.getSelection();if(!l||l.rangeCount===0||l.isCollapsed)return null;const r=ty(l.getRangeAt(0),n,a);return r?(l.removeAllRanges(),{text:r.text,title:r.title,span:r.span}):null}function sT(n){const a=document.body;if(a)for(const l of n){if(!l.text||l.text.length<3)continue;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);let d;for(;d=r.nextNode();){const f=d.textContent?.indexOf(l.text)??-1;if(!(f===-1||d.parentElement?.hasAttribute("data-inline-highlight"))){try{const p=document.createRange();p.setStart(d,f),p.setEnd(d,f+l.text.length);const y=document.createElement("span");y.setAttribute("data-inline-highlight",l.action),y.style.backgroundColor=l.bg,y.style.borderRadius="4px",y.style.padding="0 3px",y.title=l.title,p.surroundContents(y)}catch{}break}}}}function lT(){try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},n=>{if(chrome.runtime.lastError||!n?.ok)return;const a=n.data?.elements?.highlights;!Array.isArray(a)||a.length===0||(ur=a,sT(a),document.dispatchEvent(new CustomEvent("inline:highlightsRestored")))})}catch{}}const ey=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]}),rT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:u.jsx("path",{d:"M4 6h16M4 10h16M4 14h10M4 18h7"})}),oT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5"})}),uT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M8 7l-4 5 4 5M16 7l4 5-4 5M14 4l-4 16"})}),cT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M9 11l2 2 4-4M4 6h.01M4 12h.01M4 18h.01M9 18h11M9 6h11"})}),dT=[{label:"Summarize",desc:"Key points",task:"summarize",icon:u.jsx(rT,{})},{label:"Rephrase",desc:"Same meaning",task:"rephrase",icon:u.jsx(oT,{})},{label:"Shorten",desc:"Make it tight",task:"shorten",icon:u.jsx(uT,{})},{label:"Action items",desc:"Checklist",task:"rewrite",instruction:"Extract the key takeaways as a short, clear checklist of action items.",icon:u.jsx(cT,{})}];function fT(n){if(!n)return!1;const a=n.commonAncestorContainer;return!!(a.nodeType===Node.ELEMENT_NODE?a:a.parentElement)?.closest('textarea,input,[contenteditable="true"],[contenteditable="plaintext-only"],[role="textbox"]')}function hT({selectedText:n,originalRange:a,onClose:l}){const[r,d]=v.useState(""),[f,h]=v.useState(null),[p,y]=v.useState(!1),[g,b]=v.useState(""),[w,A]=v.useState(void 0),[j,k]=v.useState("idle"),[D,O]=v.useState({title:"",domain:""}),[q,W]=v.useState(!1);v.useEffect(()=>{O({title:document.title||"Untitled page",domain:window.location.hostname})},[]);const E=n.trim().length>0,T=fT(a),L=mc.filter(K=>!["eli5","pros-cons","action-items"].includes(K.id)),H=v.useCallback(async()=>{k("loading"),Ea(!0);try{const{apiBaseUrl:K,accessToken:lt}=await yn(),it=await new Promise(B=>{chrome.storage.local.get(["inlineActiveWorkspaceId"],at=>{B(typeof at.inlineActiveWorkspaceId=="string"&&at.inlineActiveWorkspaceId?at.inlineActiveWorkspaceId:"")})});if(!lt||!it){k("error");return}const rt={"Content-Type":"application/json"};lt&&(rt.Authorization=`Bearer ${lt}`);const ht=await ci(`${K}/api/ai/page-recap`,{method:"POST",headers:rt,body:JSON.stringify({workspaceId:it,pageUrl:window.location.href})});if(!ht.ok){k("error");return}const Mt=await ht.json();k(Mt.skipped?"empty":"done")}catch{k("error")}finally{Ea(!1)}},[]),J=v.useCallback(async(K,lt)=>{E&&di(K),y(!0),Ea(!0),h(null),W(!1),b(K),A(lt);try{const it=await Ms();if(!it.allowed){h(`Sign in to keep using AI. Guest mode includes ${bn} free prompts on this browser.`);return}const rt=document.body?.innerText??"",ht=(E?n:rt).slice(0,8e3),{apiBaseUrl:Mt,accessToken:B}=await yn(),at={"Content-Type":"application/json"};it.signedIn&&B&&(at.Authorization=`Bearer ${B}`),it.signedIn||(at["X-Inline-Device-Id"]=it.deviceId);const Y=await ci(`${Mt}/api/ai/extension-light`,{method:"POST",headers:at,body:JSON.stringify({task:K,text:ht,instruction:lt,guest:!it.signedIn,deviceId:it.signedIn?void 0:it.deviceId})});if(Y.ok){const dt=await Y.json(),bt=dt.result??"No result returned.";h(bt),dt.result&&Hg({kind:{rephrase:"ai-rephrase",shorten:"ai-shorten",summarize:"ai-summarize",rewrite:lt?"ai-custom":"ai-rewrite"}[K]??"ai-custom",selection:ht,result:bt})}else h("AI request failed. Check settings.")}catch{h("Could not reach AI server.")}finally{y(!1),Ea(!1)}},[E,n]);function $(){if(!(!f||!a)){try{a.deleteContents();const K=or(f,g,w);a.insertNode(K)}catch{}l()}}function F(){f&&(navigator.clipboard.writeText(f),W(!0),window.setTimeout(()=>W(!1),1400))}return!f&&!p?u.jsx(gn,{title:"Ask",subtitle:E?"Working with your selection":"Working with this page",chip:E?"Selection":"Page",width:342,onClose:l,tool:"ai",children:u.jsxs("div",{style:wa,children:[u.jsxs(Rn,{children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:x.radiusSm,background:x.surfaceMuted,color:x.textMuted,flexShrink:0},children:u.jsx(ey,{})}),u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:14,fontWeight:500,color:x.text,letterSpacing:"-0.01em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.title||"This page"}),u.jsx("span",{style:{display:"block",fontSize:12,color:x.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.domain})]})]}),E&&u.jsxs("p",{style:{margin:"9px 0 0",padding:"8px 10px",borderRadius:x.radiusSm,background:x.surfaceMuted,fontSize:14,lineHeight:1.55,color:x.textMuted,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:['"',n.trim(),'"']})]}),u.jsx(pc,{value:r,onChange:d,onSubmit:()=>{J("rewrite",r)},placeholder:E?"Ask about the selected text…":"Ask about this page…",modeLabel:"Smart mode"}),u.jsxs("div",{children:[u.jsx(ye,{children:"Quick actions"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:dT.map(K=>u.jsx(fc,{icon:K.icon,label:K.label,desc:K.desc,onClick:()=>{J(K.task,K.instruction)}},K.label))}),u.jsx("p",{style:{margin:"9px 2px 0",fontSize:12,color:x.textMuted,lineHeight:1.5},children:E?"Actions use your highlighted selection first.":"Actions use visible page text when nothing is selected."})]}),L.length>0&&u.jsxs("div",{children:[u.jsx(ye,{children:"Suggestions"}),u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:L.map(K=>u.jsx(Dg,{label:K.label,onClick:()=>{J("rewrite",K.prompt)}},K.id))})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Page tools"}),u.jsx(fc,{icon:j==="loading"?u.jsx(Aa,{size:15}):u.jsx(ey,{}),label:j==="loading"?"Generating recap...":"Page recap",desc:"Save a clean summary to your library",disabled:j==="loading",onClick:()=>{H()}}),j==="done"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:"#0f766e"},children:"Recap saved to your workspace library."}),j==="empty"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:x.textMuted},children:"No captures on this page yet. Highlight or clip something first."}),j==="error"&&u.jsx("p",{style:{margin:"8px 2px 0",fontSize:11.5,color:"#b91c1c"},children:"Recap needs cloud sync. Sign in or open the dashboard to connect your workspace."})]})]})}):u.jsx(gn,{title:"Ask",subtitle:p?"Thinking…":E?g==="summarize"?"Summary update":g==="rephrase"?"Rephrase update":g==="shorten"?"Shorten update":"Rewrite update":"Here is your result",chip:g?w?"Custom":g:void 0,width:342,onClose:l,tool:"ai",footer:p?void 0:u.jsx(ar,{onBack:()=>{h(null),W(!1)},onReject:()=>{h(null),W(!1)},onApprove:T?$:F,approveLabel:T?"Approve":q?"Copied":"Copy",showReject:!!f}),children:u.jsx("div",{style:{padding:"16px 20px"},children:u.jsx(dc,{children:p?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14,fontStyle:"italic"},children:[u.jsx(Aa,{size:16})," Putting together the best answer — one moment, Inline…"]}):f&&E?u.jsx(Rg,{original:n,updated:f}):f?u.jsx(ui,{text:f,style:{fontSize:13.5,lineHeight:1.55}}):null})})})}const pT={Plain:"none",Ruled:"repeating-linear-gradient(to bottom, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px)",Grid:"repeating-linear-gradient(to bottom, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px), repeating-linear-gradient(to right, transparent, transparent 27px, rgba(180,170,160,0.18) 27px, rgba(180,170,160,0.18) 28px)",Dotted:"radial-gradient(circle, rgba(180,170,160,0.3) 1px, transparent 1px)"},mT={Plain:"auto",Ruled:"auto",Grid:"auto",Dotted:"20px 20px"},gT=()=>u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#1C1E26",children:[u.jsx("path",{d:"M5 0h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2 2 2 0 0 1-2 2H3a2 2 0 0 1-2-2h1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1H1a2 2 0 0 1 2-2h2V1a1 1 0 0 0-1 1H3a2 2 0 0 1 2-2z"}),u.jsx("path",{d:"M1 6v-.5a.5.5 0 0 1 1 0V6h.5a.5.5 0 0 1 0 1H2v.5a.5.5 0 0 1-1 0V7h-.5a.5.5 0 0 1 0-1H1z"})]}),yT=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"#78716c",children:u.jsx("path",{d:"M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854z"})}),ny={Normal:{tag:"div",size:13,weight:400},Subheading:{tag:"h3",size:15,weight:500},Heading:{tag:"h2",size:18,weight:500}};function xT({onClose:n,initialX:a=100,initialY:l=100,initialW:r=320,initialH:d=260,initialContent:f="",initialPaperStyle:h="Plain",onUpdate:p}){const[y,g]=v.useState("Normal"),[b,w]=v.useState(!1),[A,j]=v.useState(h),[k,D]=v.useState(!1),[O,q]=v.useState({x:a,y:l}),[W,E]=v.useState({w:r,h:d}),T=v.useRef(null),L=v.useRef(null),H=v.useRef(O),J=v.useRef(W),$="You",F=new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"})+", "+new Date().toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),K=v.useCallback(Y=>{Y.preventDefault(),L.current={ox:Y.clientX-O.x,oy:Y.clientY-O.y},Y.target.setPointerCapture(Y.pointerId)},[O]),lt=v.useCallback(Y=>{if(!L.current)return;const dt={x:Math.max(8,Math.min(window.innerWidth-48,Y.clientX-L.current.ox)),y:Math.max(8,Math.min(window.innerHeight-48,Y.clientY-L.current.oy))};H.current=dt,q(dt)},[]),it=v.useCallback(()=>{L.current&&(L.current=null,p?.(H.current))},[p]),rt=v.useCallback(Y=>{Y.preventDefault(),Y.stopPropagation();const dt=Y.clientX,bt=Y.clientY,M=W.w,P=W.h;let nt={w:M,h:P};const ft=I=>{nt={w:Math.max(240,M+I.clientX-dt),h:Math.max(180,P+I.clientY-bt)},J.current=nt,E(nt)},vt=()=>{window.removeEventListener("mousemove",ft),window.removeEventListener("mouseup",vt),p?.(J.current)};window.addEventListener("mousemove",ft),window.addEventListener("mouseup",vt)},[W,p]);function ht(Y){T.current?.focus(),document.execCommand(Y,!1,void 0)}function Mt(Y){g(Y),w(!1),T.current?.focus(),Y==="Heading"?document.execCommand("formatBlock",!1,"h2"):Y==="Subheading"?document.execCommand("formatBlock",!1,"h3"):document.execCommand("formatBlock",!1,"div")}v.useEffect(()=>{T.current&&f&&(T.current.innerHTML=f),T.current?.focus()},[]);const B=v.useRef(null),at=v.useCallback(()=>{p&&(B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{p({content:T.current?.innerHTML??""})},400))},[p]);return u.jsxs("div",{style:{position:"fixed",left:O.x,top:O.y,width:W.w,height:W.h,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadow,fontFamily:gt,display:"flex",flexDirection:"column",overflow:"hidden",zIndex:2147483646,pointerEvents:"auto"},children:[u.jsxs("div",{onPointerDown:K,onPointerMove:lt,onPointerUp:it,style:{display:"flex",alignItems:"center",gap:2,padding:"8px 12px",background:x.headerBg,borderBottom:`1px solid ${x.divider}`,cursor:"grab",flexShrink:0,touchAction:"none"},children:[u.jsx(gT,{}),u.jsxs("div",{style:{position:"relative",marginLeft:6},children:[u.jsxs("button",{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>w(Y=>!Y),style:{display:"flex",alignItems:"center",gap:3,padding:"5px 12px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,background:x.surfaceBubble,fontSize:11,fontWeight:500,color:x.text,cursor:"pointer",boxShadow:x.shadowSoft},children:["Aa ",u.jsx("span",{style:{fontSize:8,color:x.textLight},children:"▼"})]}),b&&u.jsx("div",{style:{position:"absolute",top:"100%",left:0,marginTop:6,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusMd,boxShadow:x.shadow,zIndex:10,overflow:"hidden",minWidth:128},children:["Normal","Subheading","Heading"].map(Y=>u.jsx("button",{onPointerDown:dt=>dt.stopPropagation(),onClick:()=>Mt(Y),style:{display:"block",width:"100%",textAlign:"left",padding:"7px 12px",border:"none",borderRadius:0,background:y===Y?x.headerBg:"transparent",fontSize:ny[Y].size*.75,fontWeight:ny[Y].weight,color:x.text,cursor:"pointer"},children:Y},Y))})]}),u.jsxs("div",{style:{position:"relative",marginLeft:2},children:[u.jsxs("button",{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>{D(Y=>!Y),w(!1)},style:{display:"flex",alignItems:"center",gap:3,padding:"5px 10px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,background:x.surfaceBubble,fontSize:11,fontWeight:500,color:x.text,cursor:"pointer",boxShadow:x.shadowSoft},children:[u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm2-1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H4z"})}),u.jsx("span",{style:{fontSize:8,color:x.textLight},children:"▼"})]}),k&&u.jsx("div",{style:{position:"absolute",top:"100%",left:0,marginTop:6,background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusMd,boxShadow:x.shadow,zIndex:10,overflow:"hidden",minWidth:110},children:["Plain","Ruled","Grid","Dotted"].map(Y=>u.jsx("button",{onPointerDown:dt=>dt.stopPropagation(),onClick:()=>{j(Y),D(!1),p?.({paperStyle:Y})},style:{display:"block",width:"100%",textAlign:"left",padding:"7px 12px",border:"none",borderRadius:0,background:A===Y?x.headerBg:"transparent",fontSize:12,fontWeight:500,color:x.text,cursor:"pointer",fontFamily:gt},children:Y},Y))})]}),u.jsx("div",{style:{width:1,height:18,background:x.divider,margin:"0 4px",flexShrink:0}}),u.jsx(ks,{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>ht("bold"),"aria-label":"Bold",children:u.jsx("b",{style:{fontSize:12},children:"B"})}),u.jsx(ks,{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>ht("italic"),"aria-label":"Italic",children:u.jsx("i",{style:{fontSize:12},children:"I"})}),u.jsx(ks,{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>ht("underline"),"aria-label":"Underline",children:u.jsx("span",{style:{fontSize:12,fontWeight:500,color:"#1C1E26"},children:"A"})}),u.jsx("div",{style:{width:1,height:18,background:x.divider,margin:"0 4px",flexShrink:0}}),u.jsx(ks,{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>ht("insertUnorderedList"),"aria-label":"Bullet list",children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-8a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"})})}),u.jsx(ks,{onPointerDown:Y=>Y.stopPropagation(),onClick:()=>ht("insertOrderedList"),"aria-label":"Numbered list",children:u.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:[u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z"}),u.jsx("path",{d:"M1.713 11.865v-.474H2c.217 0 .363-.137.363-.317 0-.185-.158-.31-.361-.31-.223 0-.367.152-.373.31h-.59c.016-.467.373-.787.986-.787.588-.002.954.291.957.703a.595.595 0 0 1-.492.594v.015a.63.63 0 0 1 .569.631c0 .438-.395.744-1.017.744-.564 0-.954-.303-.965-.754h.6c.01.175.155.303.376.303.218 0 .38-.152.38-.347 0-.227-.186-.347-.437-.347h-.215v-.468z"}),u.jsx("path",{d:"M2 1a1 1 0 0 0-1 1v.217l.652-.33.348.667L.5 3.476V5h2V4H1.5v-.39l1.217-.66L2 1.5V2z"})]})}),u.jsx("div",{style:{flex:1}}),u.jsx("button",{onPointerDown:Y=>Y.stopPropagation(),onClick:n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:999,background:"transparent",cursor:"pointer",padding:0},children:u.jsx(yT,{})})]}),u.jsx("div",{ref:T,contentEditable:!0,suppressContentEditableWarning:!0,onInput:at,"data-placeholder":"Start typing…",style:{flex:1,padding:"10px 14px",fontSize:13,lineHeight:1.65,color:x.text,outline:"none",overflowY:"auto",cursor:"text",userSelect:"text",backgroundImage:pT[A],backgroundSize:mT[A]}}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 14px",borderTop:`1px solid ${x.divider}`,background:x.surfaceMuted,flexShrink:0},children:[u.jsxs("span",{style:{fontSize:10,color:x.textLight},children:["By ",$," | ",F]}),u.jsx("div",{onMouseDown:rt,role:"separator","aria-label":"Resize note",style:{cursor:"nwse-resize",color:x.textLight,fontSize:10,userSelect:"none"},children:"⠿"})]})]})}function ks({children:n,...a}){return u.jsx("button",{type:"button",...a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,border:"none",borderRadius:x.radiusSm,background:"rgba(255,255,255,0.35)",cursor:"pointer",color:x.textMuted,padding:0,...a.style},children:n})}const bT=()=>u.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),u.jsx("polyline",{points:"15 3 21 3 21 9"}),u.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),vT=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"currentColor",children:[u.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1.4"}),u.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1.4"})]}),ST=()=>u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})});function wT({onClose:n,onOpenDashboard:a}){const[l,r]=v.useState(!1),[d,f]=v.useState(!1),[h,p]=v.useState(!1),[y,g]=v.useState("en-US"),[b,w]=v.useState(!1),[A,j]=v.useState([]),[k,D]=v.useState(""),[O,q]=v.useState({signedIn:!1,hasWorkspace:!1,name:"",email:"",avatarUrl:"",guestRemaining:bn});v.useEffect(()=>{chrome.storage.local.get(["inlineBlockedDomains","inlineScreenReader","inlineFocusMode","inlineAccessToken","inlineActiveWorkspaceId","inlineUserId","inlineUserName","inlineUserEmail","inlineUserAvatarUrl"],F=>{try{const K=F.inlineBlockedDomains;if(typeof K=="string"){const lt=JSON.parse(K);Array.isArray(lt)&&j(lt)}}catch{}r(F.inlineScreenReader==="true"||F.inlineScreenReader===!0),p(F.inlineFocusMode==="true"||F.inlineFocusMode===!0),Ug().then(K=>{q({signedIn:yc(F.inlineAccessToken),hasWorkspace:typeof F.inlineActiveWorkspaceId=="string"&&F.inlineActiveWorkspaceId.length>0,name:typeof F.inlineUserName=="string"?F.inlineUserName:"",email:typeof F.inlineUserEmail=="string"?F.inlineUserEmail:"",avatarUrl:typeof F.inlineUserAvatarUrl=="string"?F.inlineUserAvatarUrl:"",guestRemaining:Number.isFinite(K.remaining)?K.remaining:bn})})})},[]);const W=v.useCallback(F=>{r(F),chrome.storage.local.set({inlineScreenReader:String(F)}),document.dispatchEvent(new CustomEvent("inline:screenReader",{detail:{enabled:F}}))},[]),E=v.useCallback(F=>{j(F),chrome.storage.local.set({inlineBlockedDomains:JSON.stringify(F)})},[]),T=v.useCallback(()=>{const F=k.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"");!F||A.includes(F)||(E([...A,F]),D(""))},[k,A,E]),L=v.useCallback(F=>{E(A.filter(K=>K!==F))},[A,E]),H=v.useCallback(F=>{f(F);try{const K=document.body??document.documentElement;K.style.filter=F?"contrast(150%)":""}catch{}},[]),J=O.name||O.email||"Connected account",$=(J.trim()[0]||"I").toUpperCase();return u.jsx(gn,{title:"Settings",subtitle:"Global preferences",width:340,tool:"settings",onClose:n,footer:u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px"},children:[u.jsxs("button",{type:"button",onClick:a,style:{display:"flex",alignItems:"center",gap:7,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:12.5,fontWeight:650,color:x.text,padding:"9px 14px",borderRadius:x.radiusPill,fontFamily:gt,boxShadow:"none"},children:["All settings ",u.jsx(bT,{})]}),u.jsx("button",{type:"button",onClick:()=>w(F=>!F),"aria-label":b?"Resume Inline":"Pause Inline",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:40,height:40,borderRadius:13,border:`1px solid ${b?"rgba(220,38,38,0.25)":x.border}`,background:b?"#FEF2F2":x.surfaceBubble,cursor:"pointer",color:b?"#DC2626":x.textMuted,boxShadow:"none"},children:u.jsx(vT,{})})]}),children:u.jsxs("div",{style:{...wa,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Account"}),u.jsx(Rn,{children:u.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[u.jsxs("span",{style:{display:"flex",alignItems:"flex-start",gap:10,minWidth:0},children:[O.signedIn?u.jsx("span",{style:{width:32,height:32,borderRadius:10,overflow:"hidden",background:x.accent,color:"#FFFFFF",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:800,flexShrink:0},children:O.avatarUrl?u.jsx("img",{src:O.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):$}):u.jsx("span",{style:{width:9,height:9,borderRadius:"50%",marginTop:5,background:"#D97706",boxShadow:"0 0 0 3px rgba(217, 119, 6, 0.13)",flexShrink:0}}),u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:700,color:x.text,letterSpacing:"-0.01em"},children:O.signedIn?J:"Guest mode"}),u.jsx("span",{style:{display:"block",marginTop:2,fontSize:11.5,color:x.textLight,lineHeight:1.45},children:O.signedIn?O.hasWorkspace?"Workspace sync is on. AI is fully unlocked.":"Open the dashboard to finish workspace sync.":`Saved to this browser. ${O.guestRemaining} of ${bn} guest AI prompts left.`})]})]}),u.jsx("button",{type:"button",onClick:a,style:{border:`1px solid ${x.border}`,background:O.signedIn?x.surfaceSunken:x.accent,color:O.signedIn?x.text:"#FFFFFF",borderRadius:x.radiusPill,padding:"7px 11px",fontSize:11.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none",flexShrink:0},children:O.signedIn?"Dashboard":"Sign in"})]})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Accessibility"}),u.jsxs(Rn,{list:!0,children:[u.jsx(xc,{label:"Screen reader",desc:"Announce captured text",right:u.jsx(sr,{checked:l,onChange:W,label:"screen reader"})}),u.jsx(xc,{label:"High contrast",desc:"Boost page contrast",border:!0,right:u.jsx(sr,{checked:d,onChange:H,label:"high contrast"})}),u.jsx(xc,{label:"Immersive reader",desc:"Distraction-free reading",border:!0,right:u.jsx(sr,{checked:h,onChange:F=>{p(F),chrome.storage.local.set({inlineFocusMode:String(F)}),document.dispatchEvent(new CustomEvent("inline:focusMode",{detail:{enabled:F}}))},label:"immersive reader"})})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Language"}),u.jsxs(Rn,{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px"},children:[u.jsx("span",{style:{fontSize:13,fontWeight:650,color:x.text},children:"Interface language"}),u.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center"},children:[u.jsxs("select",{value:y,onChange:F=>g(F.target.value),"aria-label":"Interface language",style:{appearance:"none",WebkitAppearance:"none",MozAppearance:"none",padding:"8px 30px 8px 14px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,fontSize:12,color:x.text,background:x.surfaceSunken,cursor:"pointer",outline:"none",fontFamily:gt,fontWeight:600},children:[u.jsx("option",{value:"en-US",children:"English (US)"}),u.jsx("option",{value:"en-GB",children:"English (UK)"}),u.jsx("option",{value:"es",children:"Espanol"}),u.jsx("option",{value:"fr",children:"Francais"}),u.jsx("option",{value:"de",children:"Deutsch"}),u.jsx("option",{value:"pt",children:"Portugues"})]}),u.jsx("span",{style:{position:"absolute",right:10,pointerEvents:"none",color:x.textMuted,display:"inline-flex"},children:u.jsx(ST,{})})]})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Blocked sites"}),u.jsxs(Rn,{children:[A.length>0&&u.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:11},children:A.map(F=>u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"5px 6px 5px 11px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceSunken,fontSize:11.5,fontWeight:600,color:x.text,fontFamily:gt},children:[F,u.jsx("button",{type:"button",onClick:()=>L(F),"aria-label":`Unblock ${F}`,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,border:"none",background:x.hoverBg,cursor:"pointer",padding:0,lineHeight:1,fontSize:12,color:x.textMuted,fontWeight:700,borderRadius:"50%"},children:"×"})]},F))}),u.jsxs("div",{style:{display:"flex",gap:8},children:[u.jsx("input",{value:k,onChange:F=>D(F.target.value),onKeyDown:F=>{F.key==="Enter"&&T()},placeholder:"example.com","aria-label":"Domain to block",style:{flex:1,padding:"9px 14px",border:`1px solid ${x.border}`,borderRadius:x.radiusPill,fontSize:12.5,outline:"none",color:x.text,background:x.surfaceSunken,fontFamily:gt}}),u.jsx("button",{type:"button",onClick:T,"aria-label":"Block domain",style:{padding:"9px 16px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:gt,boxShadow:"none"},children:"Add"})]})]})]})]})})}function xc({label:n,desc:a,right:l,border:r}){return u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",...r?{borderTop:`1px solid ${x.divider}`}:{}},children:[u.jsxs("span",{style:{minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:650,color:x.text,letterSpacing:"-0.01em"},children:n}),a&&u.jsx("span",{style:{display:"block",fontSize:11,color:x.textLight},children:a})]}),l]})}const bc=[{value:"#FDE68A",name:"Yellow"},{value:"#A7F3D0",name:"Mint"},{value:"#BFDBFE",name:"Sky"},{value:"#FBCFE8",name:"Pink"},{value:"#FDBA74",name:"Orange"},{value:"#C4B5FD",name:"Violet"},{value:"#99F6E4",name:"Teal"},{value:"#FCA5A5",name:"Coral"},{value:"#D9F99D",name:"Lime"},{value:"#E9D5FF",name:"Lilac"}];function AT({onClose:n}){const[a,l]=v.useState(bc[0].value),r=v.useCallback(f=>{l(f),di("color",f)},[]),d=bc.find(f=>f.value===a)?.name??"Yellow";return u.jsx(gn,{title:"Highlight",subtitle:"Select text, then pick a colour",chip:d,width:296,tool:"highlighter",onClose:n,children:u.jsxs("div",{style:{padding:"18px 18px 20px",fontFamily:gt},children:[u.jsx(ye,{children:"Highlight colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:12},children:bc.map(({value:f,name:h})=>{const p=a===f;return u.jsx("button",{type:"button",onClick:()=>r(f),"aria-label":`Highlight ${h}`,"aria-pressed":p,style:{height:44,borderRadius:x.radius,background:f,cursor:"pointer",border:p?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.15s",padding:0}},f)})}),u.jsxs("p",{style:{margin:"16px 2px 0",fontSize:11.5,color:x.textLight,lineHeight:1.5,display:"flex",alignItems:"center",gap:7},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#5BE49B",flexShrink:0}}),"Highlight mode is on — drag across any text to colour it."]})]})})}const _n="http://www.w3.org/2000/svg",cr="inline-draw-canvas",vc="inline-draw-hit-area";function iy(){const n=document.getElementById(cr);if(n){const l=n;return Sc(l),l}const a=document.createElementNS(_n,"svg");return a.id=cr,a.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483640;pointer-events:none;touch-action:none;",a.setAttribute("width",String(window.innerWidth)),a.setAttribute("height",String(window.innerHeight)),a.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),Sc(a),document.body.appendChild(a),window.addEventListener("resize",()=>{a.setAttribute("width",String(window.innerWidth)),a.setAttribute("height",String(window.innerHeight)),a.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`)}),a}function Sc(n){if(n.setAttribute("width",String(window.innerWidth)),n.setAttribute("height",String(window.innerHeight)),n.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),n.querySelector(`#${vc}`))return;const a=document.createElementNS(_n,"rect");a.id=vc,a.setAttribute("x","0"),a.setAttribute("y","0"),a.setAttribute("width","100%"),a.setAttribute("height","100%"),a.setAttribute("fill","transparent"),a.setAttribute("pointer-events","none"),n.insertBefore(a,n.firstChild)}function ay(n){const a=document.getElementById(cr);if(!a)return;Sc(a);const l=a.querySelector(`#${vc}`);l&&l.setAttribute("pointer-events",n?"all":"none")}function Rs(n,a){typeof a.id=="string"&&a.id&&n.setAttribute("data-inline-id",a.id)}function TT(n,a){if(a.type==="path"){const l=document.createElementNS(_n,"path");l.setAttribute("d",String(a.d)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill",String(a.fill??"none")),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),a.opacity&&l.setAttribute("opacity",String(a.opacity)),l.setAttribute("data-inline-draw","true"),Rs(l,a),n.appendChild(l)}else if(a.type==="rect"){const l=document.createElementNS(_n,"rect");l.setAttribute("x",String(a.x)),l.setAttribute("y",String(a.y)),l.setAttribute("width",String(a.width)),l.setAttribute("height",String(a.height)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill","none"),l.setAttribute("rx","2"),l.setAttribute("data-inline-draw","true"),Rs(l,a),n.appendChild(l)}else if(a.type==="ellipse"){const l=document.createElementNS(_n,"ellipse");l.setAttribute("cx",String(a.cx)),l.setAttribute("cy",String(a.cy)),l.setAttribute("rx",String(a.rx)),l.setAttribute("ry",String(a.ry)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("fill","none"),l.setAttribute("data-inline-draw","true"),Rs(l,a),n.appendChild(l)}else if(a.type==="arrow"){const l=document.createElementNS(_n,"g");l.setAttribute("data-inline-draw","true"),Rs(l,a);const r=document.createElementNS(_n,"line");r.setAttribute("x1",String(a.x1)),r.setAttribute("y1",String(a.y1)),r.setAttribute("x2",String(a.x2)),r.setAttribute("y2",String(a.y2)),r.setAttribute("stroke",String(a.stroke)),r.setAttribute("stroke-width",String(a.strokeWidth)),r.setAttribute("stroke-linecap","round");const d=document.createElementNS(_n,"polygon");d.setAttribute("fill",String(a.fill)),d.setAttribute("points",String(a.points)),l.appendChild(r),l.appendChild(d),n.appendChild(l)}else if(a.type==="line"){const l=document.createElementNS(_n,"line");l.setAttribute("x1",String(a.x1)),l.setAttribute("y1",String(a.y1)),l.setAttribute("x2",String(a.x2)),l.setAttribute("y2",String(a.y2)),l.setAttribute("stroke",String(a.stroke)),l.setAttribute("stroke-width",String(a.strokeWidth)),l.setAttribute("stroke-linecap","round"),l.setAttribute("data-inline-draw","true"),Rs(l,a),n.appendChild(l)}}function ET(){const n=document.getElementById(cr);n&&n.querySelectorAll("[data-inline-draw]").forEach(a=>a.remove());try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"drawPaths",data:[],pageTitle:document.title,domain:window.location.hostname,clearedAt:Date.now()}},()=>{chrome.runtime.lastError})}catch{}}function sy(){try{if(!chrome.runtime?.id)return;const n=iy();chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},a=>{if(chrome.runtime.lastError||!a?.ok)return;const l=a.data?.elements?.drawPaths;if(!(!Array.isArray(l)||l.length===0))for(const r of l){const d=typeof r.id=="string"?r.id:"";d&&n.querySelector(`[data-inline-id="${CSS.escape(d)}"]`)||TT(n,r)}})}catch{}}const ly=["#1C1E26","#b42318","#315a9f","#0f7b6c","#b7791f","#7c3aed","#ec4899","#06b6d4","#ea580c","#78716c"],jT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5z"})}),CT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:[u.jsx("path",{d:"M8.5 1a.5.5 0 0 0-1 0v5.7L5.354 4.354a.5.5 0 1 0-.708.708L7.5 7.916V11.5a.5.5 0 0 0 1 0V7.916l2.854-2.854a.5.5 0 0 0-.708-.708L8.5 6.7V1z"}),u.jsx("path",{d:"M3 13.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z"})]}),MT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"5"}),u.jsx("polyline",{points:"12 5 19 5 19 12"})]}),kT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"})}),RT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"7"})}),DT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 0 2.828l-5.5 5.5A2 2 0 0 1 7.879 15H5.12a2 2 0 0 1-1.414-.586l-2.5-2.5a2 2 0 0 1 0-2.828l5.88-5.879zm2.121.707a1 1 0 0 0-1.414 0L4.16 7.547l5.293 5.293 4.633-4.633a1 1 0 0 0 0-1.414l-3.879-3.879zM8.746 13.547 3.453 8.254 1.914 9.793a1 1 0 0 0 0 1.414l2.5 2.5a1 1 0 0 0 .707.293H7.88a1 1 0 0 0 .707-.293l.16-.16z"})}),zT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M7 22a5 5 0 0 1-2-4"}),u.jsx("path",{d:"M7 16.93c.96.43 1.96.74 2.99.91"}),u.jsx("path",{d:"M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8-4.48 8-10 8a12 12 0 0 1-3-.38"}),u.jsx("circle",{cx:"7",cy:"22",r:"2"})]});function LT({onClose:n}){const[a,l]=v.useState("pen"),[r,d]=v.useState(ly[0]),[f,h]=v.useState(3),[p,y]=v.useState("object"),[g,b]=v.useState(!1),w=v.useRef(null),A=v.useRef(!1),j=v.useRef(""),k=v.useRef(null),D=v.useRef({x:0,y:0}),O=v.useRef(null),q=v.useRef(0),W=v.useRef([]),E=v.useRef(null),T=v.useRef(null),L=v.useRef(!1),H=v.useRef({x:0,y:0}),J=v.useRef({x:0,y:0}),$=v.useRef(!1);v.useEffect(()=>{w.current=iy(),sy()},[]);const F=v.useCallback(()=>{w.current&&(w.current.style.pointerEvents="all",ay(!0),w.current.style.cursor=a==="eraser"?"cell":"crosshair")},[a]),K=v.useCallback(()=>{w.current&&(ay(!1),w.current.style.pointerEvents="none",w.current.style.cursor="")},[]);v.useEffect(()=>(F(),K),[F,K,a]),v.useEffect(()=>{if(!w.current)return;const rt=w.current;function ht(){if(!T.current||!rt)return;const I=T.current,V=I.querySelector(".inline-lasso-border");for(V&&V.remove();I.firstChild;)rt.insertBefore(I.firstChild,I);I.remove(),T.current=null}function Mt(I,V,st,pt,Tt,Vt){const ct=I-st,It=V-pt,jt=Tt-st,Et=Vt-pt,X=jt*jt+Et*Et;if(X===0)return Math.hypot(ct,It);const ot=Math.max(0,Math.min(1,(ct*jt+It*Et)/X));return Math.hypot(I-(st+ot*jt),V-(pt+ot*Et))}function B(I,V){if(I.length<2||I.length>50||V<300)return null;const st=I.map(kt=>kt.x),pt=I.map(kt=>kt.y),Tt=Math.min(...st),Vt=Math.max(...st),ct=Math.min(...pt),It=Math.max(...pt),jt=Vt-Tt,Et=It-ct,X=I[0],ot=I[I.length-1],Nt=Math.hypot(ot.x-X.x,ot.y-X.y)20&&Math.max(...I.map(oe=>Mt(oe.x,oe.y,X.x,X.y,ot.x,ot.y)))<15)return{type:"line",x1:X.x,y1:X.y,x2:ot.x,y2:ot.y};if(!Nt||jt<15||Et<15)return null;const be=Math.max(jt,Et)*.2;if(I.filter(kt=>{const oe=Math.abs(kt.x-Tt),Le=Math.abs(kt.x-Vt),Sn=Math.abs(kt.y-ct),fi=Math.abs(kt.y-It);return Math.min(oe,Le)I.length*.7){const kt=jt/Et;if(kt>.3&&kt<3.5)return{type:"rect",x:Tt,y:ct,width:jt,height:Et}}const Q=(Tt+Vt)/2,ut=(ct+It)/2,zt=jt/2,Lt=Et/2;if(zt>5&&Lt>5){const kt=I.map(Sn=>{const fi=(Sn.x-Q)/zt,yr=(Sn.y-ut)/Lt;return Math.sqrt(fi*fi+yr*yr)}),oe=kt.reduce((Sn,fi)=>Sn+fi,0)/kt.length;if(Math.max(...kt.map(Sn=>Math.abs(Sn-oe)))<.4)return{type:"ellipse",cx:Q,cy:ut,rx:zt,ry:Lt}}return null}function at(I,V){const st=Math.max(8,f*2);rt.querySelectorAll("[data-inline-draw]").forEach(Tt=>{if(Tt.tagName.toLowerCase()==="path"){const It=(Tt.getAttribute("d")??"").match(/[ML][^ML]*/g);if(!It)return;const jt=[[]];let Et=!1;for(const ot of It){const mt=ot.trim().substring(1).trim().split(/[\s,]+/).map(Number);if(mt.length<2)continue;const Nt=mt[0],Xt=mt[1];if(Math.hypot(Nt-I,Xt-V)0&&jt.push([]),Et=!0;else{const Pt=ot.trim()[0];Et||jt[jt.length-1].length===0?jt[jt.length-1].push(`M${Nt} ${Xt}`):jt[jt.length-1].push(`${Pt}${Nt} ${Xt}`),Et=!1}}const X=jt.filter(ot=>ot.length>1);if(X.length===0)Tt.remove();else if(X.length===1)Tt.setAttribute("d",X[0].join(" "));else{const ot=Tt.getAttribute("stroke")??"",mt=Tt.getAttribute("stroke-width")??"",Nt=Tt.getAttribute("opacity"),Xt=Tt.getAttribute("fill")??"none";Tt.remove();for(const be of X){const Pt=document.createElementNS("http://www.w3.org/2000/svg","path");Pt.setAttribute("d",be.join(" ")),Pt.setAttribute("stroke",ot),Pt.setAttribute("stroke-width",mt),Pt.setAttribute("fill",Xt),Pt.setAttribute("stroke-linecap","round"),Pt.setAttribute("stroke-linejoin","round"),Nt&&Pt.setAttribute("opacity",Nt),Pt.setAttribute("data-inline-draw","true"),rt.appendChild(Pt)}}}else try{const ct=Tt.getBBox?.();if(ct){const It=ct.x+ct.width/2,jt=ct.y+ct.height/2;Math.hypot(It-I,jt-V){const pt=st.tagName.toLowerCase(),Tt=bt(st);if(pt==="path")V.push({id:Tt,type:"path",d:st.getAttribute("d")??"",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??"",opacity:st.getAttribute("opacity")??void 0,fill:st.getAttribute("fill")??"none"});else if(pt==="rect")V.push({id:Tt,type:"rect",x:st.getAttribute("x")??"0",y:st.getAttribute("y")??"0",width:st.getAttribute("width")??"0",height:st.getAttribute("height")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(pt==="ellipse")V.push({id:Tt,type:"ellipse",cx:st.getAttribute("cx")??"0",cy:st.getAttribute("cy")??"0",rx:st.getAttribute("rx")??"0",ry:st.getAttribute("ry")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(pt==="line")V.push({id:Tt,type:"line",x1:st.getAttribute("x1")??"0",y1:st.getAttribute("y1")??"0",x2:st.getAttribute("x2")??"0",y2:st.getAttribute("y2")??"0",stroke:st.getAttribute("stroke")??"",strokeWidth:st.getAttribute("stroke-width")??""});else if(pt==="g"&&!st.classList.contains("inline-lasso-group")){const Vt=st.querySelector("line"),ct=st.querySelector("polygon");Vt&&ct&&V.push({id:Tt,type:"arrow",x1:Vt.getAttribute("x1")??"0",y1:Vt.getAttribute("y1")??"0",x2:Vt.getAttribute("x2")??"0",y2:Vt.getAttribute("y2")??"0",stroke:Vt.getAttribute("stroke")??"",strokeWidth:Vt.getAttribute("stroke-width")??"",points:ct.getAttribute("points")??"",fill:ct.getAttribute("fill")??""})}}),V}function P(){const I=M();try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"drawPaths",data:I,pageTitle:document.title,domain:window.location.hostname,clearedAt:I.length===0?Date.now():null}},V=>{chrome.runtime.lastError||Ta(V)})}catch{}}function nt(){if(a==="eraser"&&p==="pixel"){$.current=!1,P();return}if(L.current){L.current=!1;const V=T.current?.getAttribute("transform")?.match(/translate\(([-\d.]+)[, ]+([-\d.]+)\)/);V&&(J.current={x:parseFloat(V[1]),y:parseFloat(V[2])});return}if(a==="lasso"&&A.current&&E.current){A.current=!1;const I=W.current;if(I.length>2){const V=I.map(Et=>Et.x),st=I.map(Et=>Et.y),pt=Math.min(...V),Tt=Math.max(...V),Vt=Math.min(...st),ct=Math.max(...st),It=rt.querySelectorAll("[data-inline-draw]"),jt=[];if(It.forEach(Et=>{if(Et!==E.current&&!Et.classList.contains("inline-lasso-group"))try{const X=Et.getBBox(),ot=X.x+X.width/2,mt=X.y+X.height/2;ot>=pt&&ot<=Tt&&mt>=Vt&&mt<=ct&&jt.push(Et)}catch{}}),E.current.remove(),E.current=null,jt.length>0){const Et=document.createElementNS("http://www.w3.org/2000/svg","g");Et.classList.add("inline-lasso-group"),Et.setAttribute("data-inline-draw","true"),rt.appendChild(Et);let X=1/0,ot=1/0,mt=-1/0,Nt=-1/0;for(const be of jt){try{const Pt=be.getBBox();X=Math.min(X,Pt.x),ot=Math.min(ot,Pt.y),mt=Math.max(mt,Pt.x+Pt.width),Nt=Math.max(Nt,Pt.y+Pt.height)}catch{}Et.appendChild(be)}const Xt=document.createElementNS("http://www.w3.org/2000/svg","rect");Xt.classList.add("inline-lasso-border"),Xt.setAttribute("x",String(X-4)),Xt.setAttribute("y",String(ot-4)),Xt.setAttribute("width",String(mt-X+8)),Xt.setAttribute("height",String(Nt-ot+8)),Xt.setAttribute("stroke","#315a9f"),Xt.setAttribute("stroke-width","1.5"),Xt.setAttribute("stroke-dasharray","5 3"),Xt.setAttribute("fill","none"),Xt.setAttribute("rx","3"),Et.insertBefore(Xt,Et.firstChild),T.current=Et,J.current={x:0,y:0}}}else E.current.remove(),E.current=null;W.current=[];return}if(a==="pen"&&A.current&&k.current){const I=W.current,V=Date.now()-q.current,st=B(I,V);if(st){const pt=k.current,Tt=pt.getAttribute("stroke")??r,Vt=pt.getAttribute("stroke-width")??String(f);if(pt.remove(),st.type==="line"){const ct=document.createElementNS("http://www.w3.org/2000/svg","line");ct.setAttribute("x1",String(st.x1)),ct.setAttribute("y1",String(st.y1)),ct.setAttribute("x2",String(st.x2)),ct.setAttribute("y2",String(st.y2)),ct.setAttribute("stroke",Tt),ct.setAttribute("stroke-width",Vt),ct.setAttribute("stroke-linecap","round"),ct.setAttribute("data-inline-draw","true"),rt.appendChild(ct)}else if(st.type==="rect"){const ct=document.createElementNS("http://www.w3.org/2000/svg","rect");ct.setAttribute("x",String(st.x)),ct.setAttribute("y",String(st.y)),ct.setAttribute("width",String(st.width)),ct.setAttribute("height",String(st.height)),ct.setAttribute("stroke",Tt),ct.setAttribute("stroke-width",Vt),ct.setAttribute("fill","none"),ct.setAttribute("rx","2"),ct.setAttribute("data-inline-draw","true"),rt.appendChild(ct)}else if(st.type==="ellipse"){const ct=document.createElementNS("http://www.w3.org/2000/svg","ellipse");ct.setAttribute("cx",String(st.cx)),ct.setAttribute("cy",String(st.cy)),ct.setAttribute("rx",String(st.rx)),ct.setAttribute("ry",String(st.ry)),ct.setAttribute("stroke",Tt),ct.setAttribute("stroke-width",Vt),ct.setAttribute("fill","none"),ct.setAttribute("data-inline-draw","true"),rt.appendChild(ct)}}}A.current=!1,k.current=null,O.current=null,W.current=[],P()}function ft(I){if(a!=="eraser"||p!=="object")return;I.preventDefault(),I.stopPropagation();const V=document.elementFromPoint(I.clientX,I.clientY);V&&V.hasAttribute("data-inline-draw")&&V.remove(),V?.parentElement&&V.parentElement.hasAttribute("data-inline-draw")&&V.parentElement.remove(),P()}function vt(I){(I.key==="Delete"||I.key==="Backspace")&&T.current&&(T.current.remove(),T.current=null,P())}return rt.addEventListener("pointerdown",Y),rt.addEventListener("pointermove",dt),rt.addEventListener("pointerup",nt),rt.addEventListener("click",ft),document.addEventListener("keydown",vt),()=>{rt.removeEventListener("pointerdown",Y),rt.removeEventListener("pointermove",dt),rt.removeEventListener("pointerup",nt),rt.removeEventListener("click",ft),document.removeEventListener("keydown",vt)}},[a,r,f,p]);const lt=[{id:"pen",icon:u.jsx(jT,{}),label:"Pen"},{id:"marker",icon:u.jsx(CT,{}),label:"Marker"},{id:"arrow",icon:u.jsx(MT,{}),label:"Arrow"},{id:"rectangle",icon:u.jsx(kT,{}),label:"Rectangle"},{id:"ellipse",icon:u.jsx(RT,{}),label:"Ellipse"},{id:"eraser",icon:u.jsx(DT,{}),label:"Eraser"},{id:"lasso",icon:u.jsx(zT,{}),label:"Lasso"}],it=lt.find(rt=>rt.id===a)?.label??"Pen";return u.jsx(gn,{title:"Draw",subtitle:"Annotate directly on the page",chip:it,width:290,tool:"draw",onClose:n,children:u.jsxs("div",{style:{...wa,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tools"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:9},children:lt.map(rt=>{const ht=a===rt.id;return u.jsx("button",{type:"button",onClick:()=>l(rt.id),"aria-label":rt.label,"aria-pressed":ht,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:46,borderRadius:x.radius,border:`1px solid ${ht?x.accent:x.border}`,background:ht?x.accent:x.surfaceBubble,color:ht?"#fff":x.textMuted,cursor:"pointer",boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:rt.icon},rt.id)})}),a==="eraser"&&u.jsx("div",{style:{marginTop:10},children:u.jsx(hc,{options:[{value:"object",label:"Object"},{value:"pixel",label:"Pixel"}],value:p,onChange:y})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Stroke weight"}),u.jsxs(Rn,{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px"},children:[u.jsx("button",{type:"button",onClick:()=>h(rt=>Math.max(1,rt-1)),"aria-label":"Thinner",style:ry,children:"−"}),u.jsx("input",{type:"range",min:1,max:12,value:f,onChange:rt=>h(Number(rt.target.value)),"aria-label":"Stroke weight",style:{flex:1,accentColor:x.accent,height:6,cursor:"pointer"}}),u.jsx("button",{type:"button",onClick:()=>h(rt=>Math.min(12,rt+1)),"aria-label":"Thicker",style:ry,children:"+"}),u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:26,height:26,borderRadius:8,background:x.surfaceSunken,fontSize:12,fontWeight:700,color:x.text},children:f})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:11},children:ly.map(rt=>{const ht=r===rt;return u.jsx("button",{type:"button",onClick:()=>d(rt),"aria-label":`Colour ${rt}`,"aria-pressed":ht,style:{height:34,borderRadius:x.radius,background:rt,cursor:"pointer",padding:0,border:ht?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.13s"}},rt)})})]}),g?u.jsxs(Rn,{style:{padding:14},children:[u.jsx("p",{style:{margin:"0 0 3px",fontSize:13,fontWeight:700,color:x.text},children:"Clear all drawings?"}),u.jsx("p",{style:{margin:"0 0 12px",fontSize:11.5,lineHeight:1.5,color:x.textMuted},children:"This removes every drawing on this page and can't be undone."}),u.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[u.jsx("button",{type:"button",onClick:()=>b(!1),style:{padding:"8px 14px",fontSize:12,fontWeight:600,borderRadius:x.radiusPill,cursor:"pointer",border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text},children:"Cancel"}),u.jsx("button",{type:"button",onClick:()=>{ET(),b(!1)},style:{padding:"8px 16px",fontSize:12,fontWeight:700,borderRadius:x.radiusPill,cursor:"pointer",border:"none",background:"#DC2626",color:"#fff"},children:"Clear all"})]})]}):u.jsx("button",{type:"button",onClick:()=>b(!0),"aria-label":"Clear all drawings on this page",style:{padding:"11px 0",fontSize:12.5,fontWeight:700,borderRadius:x.radius,cursor:"pointer",width:"100%",border:"1px solid rgba(220,38,38,0.28)",background:"#FEF2F2",color:"#DC2626",transition:"background 0.15s",letterSpacing:"-0.01em",fontFamily:"inherit"},children:"Clear all drawings"})]})})}const ry={display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radius,flexShrink:0,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:16,fontWeight:600,color:x.textMuted,boxShadow:x.shadowSoft},OT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),BT=()=>u.jsx(oc,{}),NT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"}),u.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),u.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"}),u.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),_T=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),u.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),u.jsx("path",{d:"M2 2l7.586 7.586"}),u.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),UT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),HT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"3"}),u.jsx("path",{d:"M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"})]}),VT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polyline",{points:"4 14 10 14 10 20"}),u.jsx("polyline",{points:"20 10 14 10 14 4"}),u.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),u.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}),IT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"6",y:"4",width:"4",height:"16"}),u.jsx("rect",{x:"14",y:"4",width:"4",height:"16"})]}),YT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),GT={action:"Actions",annotate:"Annotate",app:"Workspace",toolbar:"Toolbar"},FT=[{id:"ai",label:"Ask AI",hint:"Chat about the page or selection",icon:u.jsx(BT,{}),category:"action",shortcut:"A"},{id:"rewrite",label:"Rewrite",hint:"Rephrase, shorten, summarize",icon:u.jsx(OT,{}),category:"action",shortcut:"R"},{id:"highlighter",label:"Highlighter",hint:"Highlight passages",icon:u.jsx(UT,{}),category:"annotate",shortcut:"H"},{id:"notes",label:"Sticky note",hint:"Drop a note on the page",icon:u.jsx(NT,{}),category:"annotate",shortcut:"N"},{id:"draw",label:"Draw",hint:"Sketch over the page",icon:u.jsx(_T,{}),category:"annotate"},{id:"settings",label:"Settings",hint:"Preferences & blocked sites",icon:u.jsx(HT,{}),category:"app"},{id:"collapse",label:"Toggle tools dock",hint:"Show or hide the launcher dock",icon:u.jsx(VT,{}),category:"toolbar"},{id:"pause",label:"Hide Inline",hint:"Tuck the launcher away on this page",icon:u.jsx(IT,{}),category:"toolbar"}],qT=[{id:"all",label:"All"},{id:"action",label:"Actions"},{id:"annotate",label:"Annotate"},{id:"toolbar",label:"Toolbar"}];function XT({onClose:n,onAction:a}){const[l,r]=v.useState(""),[d,f]=v.useState("all"),[h,p]=v.useState(0),y=v.useRef(null),g=v.useRef(null),b=FT.filter(j=>(d==="all"||j.category===d)&&(j.label.toLowerCase().includes(l.toLowerCase())||(j.hint?.toLowerCase().includes(l.toLowerCase())??!1)));v.useEffect(()=>{p(0)},[l,d]),v.useEffect(()=>{y.current?.focus()},[]),v.useEffect(()=>{g.current?.querySelector(`[data-cmd-idx="${h}"]`)?.scrollIntoView({block:"nearest"})},[h]);const w=v.useCallback(j=>{a(j),n()},[a,n]),A=v.useCallback(j=>{j.key==="ArrowDown"?(j.preventDefault(),p(k=>Math.min(k+1,b.length-1))):j.key==="ArrowUp"?(j.preventDefault(),p(k=>Math.max(k-1,0))):j.key==="Enter"?(j.preventDefault(),b[h]&&w(b[h].id)):j.key==="Escape"&&(j.preventDefault(),n())},[b,h,w,n]);return u.jsx("div",{onClick:n,style:{position:"fixed",inset:0,zIndex:2147483647,pointerEvents:"auto",background:"rgba(15,18,23,0.28)",backdropFilter:"blur(2px)",display:"flex",justifyContent:"center",alignItems:"flex-start",paddingTop:"16vh",fontFamily:gt},children:u.jsxs("div",{onClick:j=>j.stopPropagation(),onKeyDown:A,style:{width:480,maxWidth:"calc(100vw - 32px)",maxHeight:460,background:x.bg,borderRadius:x.radius,boxShadow:x.shadowOuter,border:`1px solid ${x.border}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[u.jsx("div",{style:{padding:"14px 16px 10px"},children:u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,border:`1px solid ${kn.inputBorder}`,borderRadius:x.radiusMd,background:x.bg,boxShadow:kn.inputGlow,padding:"10px 14px"},children:[u.jsx("span",{style:{color:x.textMuted,display:"flex"},children:u.jsx(YT,{})}),u.jsx("input",{ref:y,type:"text",value:l,onChange:j=>r(j.target.value),placeholder:"Search for actions and tools…",style:{flex:1,border:"none",background:"transparent",fontSize:14,fontFamily:gt,color:x.text,outline:"none"}})]})}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 12px",flexWrap:"wrap"},children:[u.jsx("span",{style:{fontSize:12,color:x.textMuted,marginRight:2},children:"I'm looking for…"}),qT.map(j=>{const k=d===j.id;return u.jsx("button",{type:"button",onClick:()=>f(j.id),style:{padding:"5px 12px",borderRadius:x.radiusPill,border:`1px solid ${k?x.text:x.border}`,background:k?x.text:x.bg,color:k?"#fff":x.text,fontSize:12,fontWeight:500,cursor:"pointer",fontFamily:gt,transition:"background 0.13s, border-color 0.13s, color 0.13s"},children:j.label},j.id)})]}),u.jsx("div",{style:{height:1,background:x.divider}}),u.jsxs("div",{ref:g,style:{flex:1,overflowY:"auto",padding:"8px 8px 10px"},children:[b.length===0&&u.jsx("div",{style:{padding:"22px 12px",textAlign:"center",color:x.textMuted,fontSize:13},children:"No matching commands"}),b.map((j,k)=>{const D=k===0||b[k-1].category!==j.category,O=k===h;return u.jsxs("div",{children:[D&&u.jsx("p",{style:{margin:k===0?"4px 10px 4px":"10px 10px 4px",fontSize:12,fontWeight:500,letterSpacing:0,textTransform:"none",color:x.textMuted},children:GT[j.category]}),u.jsxs("button",{"data-cmd-idx":k,onClick:()=>w(j.id),onMouseEnter:()=>p(k),style:{display:"flex",alignItems:"center",gap:12,width:"100%",padding:"9px 10px",border:"none",borderRadius:x.radiusSm,background:O?x.hoverBg:"transparent",color:x.text,cursor:"pointer",fontFamily:gt,textAlign:"left",transition:"background 0.1s"},children:[u.jsx(c5,{size:30,active:O,children:j.icon}),u.jsxs("span",{style:{flex:1,minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:14,fontWeight:500,color:x.text},children:j.label}),j.hint&&u.jsx("span",{style:{display:"block",fontSize:12,color:x.textMuted,marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.hint})]}),j.shortcut&&u.jsx("span",{style:{fontSize:11,fontWeight:600,color:x.textMuted,background:x.surfaceMuted,border:`1px solid ${x.border}`,padding:"2px 7px",borderRadius:6,flexShrink:0},children:j.shortcut})]})]},j.id)})]}),u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 14px",borderTop:`1px solid ${x.divider}`,background:x.surfaceBubble},children:[u.jsxs("span",{style:{display:"flex",alignItems:"center",gap:7,fontSize:11,color:x.textLight},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,borderRadius:"50%",background:"#0B1735"},children:u.jsx("span",{style:{display:"block",width:2,height:8,borderRadius:2,background:"#fff",transform:"rotate(-12deg)"}})}),"Inline"]}),u.jsxs("span",{style:{fontSize:11,color:x.textLight},children:[u.jsx("kbd",{style:wc,children:"↑"})," ",u.jsx("kbd",{style:wc,children:"↓"})," to navigate · ",u.jsx("kbd",{style:wc,children:"↵"})," to run"]})]})]})})}const wc={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:16,height:16,padding:"0 4px",borderRadius:5,background:x.surfaceMuted,border:`1px solid ${x.border}`,fontSize:10,color:x.textMuted,fontFamily:gt},dr="inlineLayerVisibility",oy={highlights:!0,drawings:!0,stickies:!0,stamps:!0};async function uy(){return new Promise(n=>{chrome.storage.local.get(dr,a=>{n(a[dr]?{...oy,...a[dr]}:oy)})})}async function PT(n){await chrome.storage.local.set({[dr]:n})}const KT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),WT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 19l7-7 3 3-7 7-3-3z"}),u.jsx("path",{d:"M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"}),u.jsx("path",{d:"M2 2l7.586 7.586"}),u.jsx("circle",{cx:"11",cy:"11",r:"2"})]}),QT=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h9l7-7V5a2 2 0 0 0-2-2z"}),u.jsx("path",{d:"M15 21v-5a1 1 0 0 1 1-1h5"})]}),ZT=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),$T=[{key:"highlights",label:"Highlights",desc:"Coloured text marks",icon:u.jsx(KT,{})},{key:"drawings",label:"Drawings",desc:"Pen, shapes & arrows",icon:u.jsx(WT,{})},{key:"stickies",label:"Stickies",desc:"Sticky & paper notes",icon:u.jsx(QT,{})},{key:"stamps",label:"Stamps",desc:"Symbol stamps",icon:u.jsx(ZT,{})}];function JT({onClose:n}){const[a,l]=v.useState({highlights:!0,drawings:!0,stickies:!0,stamps:!0});v.useEffect(()=>{uy().then(l)},[]);const r=v.useCallback((d,f)=>{l(h=>{const p={...h,[d]:f};return PT(p),document.dispatchEvent(new CustomEvent("inline:layerToggle",{detail:p})),p})},[]);return u.jsx(gn,{title:"Layers",subtitle:"Show or hide annotation types",width:308,tool:"layers",onClose:n,children:u.jsx("div",{style:{...wa,fontFamily:gt},children:u.jsx(Rn,{list:!0,children:$T.map((d,f)=>u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 12px",...f>0?{borderTop:`1px solid ${x.divider}`}:{}},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,borderRadius:10,flexShrink:0,background:a[d.key]?x.surfaceMuted:x.surfaceSunken,color:a[d.key]?x.accent:x.textLight,transition:"color 0.15s"},children:d.icon}),u.jsxs("span",{style:{flex:1,minWidth:0},children:[u.jsx("span",{style:{display:"block",fontSize:13,fontWeight:650,color:x.text,letterSpacing:"-0.01em"},children:d.label}),u.jsx("span",{style:{display:"block",fontSize:11,color:x.textLight},children:d.desc})]}),u.jsx(sr,{checked:a[d.key],onChange:h=>r(d.key,h),label:d.label})]},d.key))})})})}const tE=["✓","✗","?","!","★","♥","+","−","→","•"];function eE({onClose:n}){const[a,l]=v.useState(null),r=v.useCallback(f=>{l(f),document.dispatchEvent(new CustomEvent("inline:stampPlace",{detail:{emoji:f}}));const h=()=>{l(null),document.removeEventListener("inline:stampPlaced",h)};document.addEventListener("inline:stampPlaced",h)},[]),d=v.useCallback(()=>l(null),[]);return u.jsxs(gn,{title:"Stamp",subtitle:"Pick a stamp, then click the page",width:306,tool:"stamps",onClose:n,children:[a&&u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"14px 18px 0",padding:"10px 14px",borderRadius:x.radius,background:x.accent,color:"#fff",fontFamily:gt,boxShadow:"none"},children:[u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8,fontSize:12.5,fontWeight:600},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#5BE49B"}}),"Click anywhere to place ",a]}),u.jsx("button",{type:"button",onClick:d,"aria-label":"Cancel placing",style:{border:"none",background:"rgba(255,255,255,0.16)",cursor:"pointer",fontSize:11,fontWeight:700,color:"#fff",fontFamily:gt,padding:"5px 11px",borderRadius:x.radiusPill},children:"Cancel"})]}),u.jsx("div",{style:{...wa,fontFamily:gt},children:u.jsxs("div",{children:[u.jsx(ye,{children:"Symbols"}),u.jsx(Rn,{style:{padding:12},children:u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:10},children:tE.map(f=>{const h=a===f;return u.jsx("button",{type:"button",onClick:()=>r(f),"aria-label":`Stamp ${f}`,"aria-pressed":h,style:{aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center",fontSize:20,fontWeight:600,border:`1px solid ${h?x.accent:x.border}`,borderRadius:x.radius,background:h?x.accent:x.surfaceBubble,color:h?"#fff":x.text,cursor:"pointer",padding:0,fontFamily:gt,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:f},f)})})})]})})]})}const Ac=()=>u.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]});function nE({onClose:n}){const[a,l]=v.useState(""),[r,d]=v.useState([]),[f,h]=v.useState(!1),[p,y]=v.useState("page"),[g,b]=v.useState(!1),w=v.useRef(null),A=v.useRef(void 0);v.useEffect(()=>{w.current?.focus()},[]);const j=v.useCallback(async E=>{if(!E.trim()){d([]);return}h(!0);try{const{apiBaseUrl:T,accessToken:L}=await yn(),H={};L&&(H.Authorization=`Bearer ${L}`);const J=await ci(`${T}/api/search?q=${encodeURIComponent(E)}`,{headers:H});if(J.ok){const $=await J.json();d($.results??[])}}catch{}finally{h(!1)}},[]),k=v.useCallback(async E=>{if(!E.trim()){d([]);return}h(!0);try{const T=window.location.href,L=await new Promise(H=>{if(!chrome.runtime?.id){H({ok:!1});return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:T}},J=>H(J??{ok:!1}))});if(L.ok&&L.data){const H=L.data,J=[],$=E.toLowerCase();for(const[F,K]of Object.entries(H))typeof K=="object"&&K!==null&&JSON.stringify(K).toLowerCase().includes($)&&J.push({id:F,page_url:T,page_title:document.title,content:typeof K=="string"?K:JSON.stringify(K).slice(0,200),type:"annotation",created_at:new Date().toISOString()});d(J)}}catch{}finally{h(!1)}},[]),D=v.useCallback((E,T)=>{T?j(E):k(E)},[j,k]),O=v.useCallback(E=>{l(E),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>D(E,p==="all"),300)},[p,D]),q=v.useCallback(E=>{y(E),a.trim()&&D(a,E==="all")},[a,D]),W=E=>{const T=n5(E),L=120;if(T.length<=L)return T;const J=T.toLowerCase().indexOf(a.toLowerCase());if(J<0)return T.slice(0,L)+"...";const $=Math.max(0,J-40);return($>0?"...":"")+T.slice($,$+L)+"..."};return u.jsxs(gn,{title:"Search",subtitle:"Find your notes & annotations",width:332,tool:"search",onClose:n,style:{height:"min(520px, calc(100vh - 64px))"},children:[u.jsxs("div",{style:{padding:"16px 18px 12px",flexShrink:0,display:"flex",flexDirection:"column",gap:12},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"0 14px",height:44,borderRadius:14,background:x.surfaceBubble,border:`1.5px solid ${g?x.accent:x.border}`,boxShadow:g?"0 0 0 3px rgba(11,23,53,0.06)":"none",transition:"border-color 0.15s, box-shadow 0.15s"},children:[u.jsx("span",{style:{color:g?x.accent:x.textLight,display:"inline-flex",flexShrink:0},children:u.jsx(Ac,{})}),u.jsx("input",{ref:w,value:a,onChange:E=>O(E.target.value),onFocus:()=>b(!0),onBlur:()=>b(!1),placeholder:"Search highlights, notes & clips...",style:{flex:1,minWidth:0,border:"none",outline:"none",background:"transparent",fontSize:13.5,color:x.text,fontFamily:gt}})]}),u.jsx(hc,{options:[{value:"page",label:"This page"},{value:"all",label:"All pages"}],value:p,onChange:q})]}),u.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"2px 16px 16px"},children:[f&&u.jsx(b5,{label:"Searching..."}),!f&&a.trim()&&r.length===0&&u.jsx(zg,{icon:u.jsx(Ac,{}),title:"No results found",hint:'Try a different keyword, or switch to "All pages".'}),!f&&!a.trim()&&r.length===0&&u.jsx(zg,{icon:u.jsx(Ac,{}),title:"Search your captures",hint:"Type to find highlights, notes and clips you've saved."}),!f&&r.map(E=>u.jsxs("button",{type:"button",onClick:()=>{E.page_url&&window.open(E.page_url,"_blank")},"aria-label":E.page_title||"Open result",style:{display:"block",width:"100%",textAlign:"left",padding:"12px 14px",marginBottom:9,border:`1px solid ${x.border}`,borderRadius:16,background:x.surfaceBubble,boxShadow:"none",cursor:"pointer",fontFamily:gt,transition:"box-shadow 0.14s, border-color 0.14s"},onMouseEnter:T=>{T.currentTarget.style.borderColor=x.borderStrong},onMouseLeave:T=>{T.currentTarget.style.borderColor=x.border},children:[u.jsx("p",{style:{margin:0,fontSize:12.5,fontWeight:700,color:x.text,lineHeight:1.4,letterSpacing:"-0.01em"},children:E.page_title||"Untitled"}),u.jsx("p",{style:{margin:"4px 0 0",fontSize:11.5,color:x.textMuted,lineHeight:1.55,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:W(E.content)}),E.page_url&&u.jsx("p",{style:{margin:"6px 0 0",fontSize:10.5,color:x.textLight,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E.page_url})]},E.id))]})]})}function iE({screenshot:n,onClose:a}){const l=v.useRef(null),[r,d]=v.useState(!1),[f,h]=v.useState({x:0,y:0}),[p,y]=v.useState({x:0,y:0}),[g,b]=v.useState(!1),[w,A]=v.useState(!1),[j,k]=v.useState(null),D=g?{x:Math.min(f.x,p.x),y:Math.min(f.y,p.y),w:Math.abs(p.x-f.x),h:Math.abs(p.y-f.y)}:null,O=v.useCallback(T=>{j||(d(!0),b(!1),h({x:T.clientX,y:T.clientY}),y({x:T.clientX,y:T.clientY}))},[j]),q=v.useCallback(T=>{r&&y({x:T.clientX,y:T.clientY})},[r]),W=v.useCallback(()=>{if(!r)return;d(!1);const T=Math.abs(p.x-f.x),L=Math.abs(p.y-f.y);T>10&&L>10&&b(!0)},[r,f,p]),E=v.useCallback(async()=>{if(D){A(!0);try{const T=new Image;T.src=n,await new Promise((ht,Mt)=>{T.onload=()=>ht(),T.onerror=()=>Mt()});const L=window.devicePixelRatio||1,H=document.createElement("canvas");H.width=D.w*L,H.height=D.h*L,H.getContext("2d").drawImage(T,D.x*L,D.y*L,D.w*L,D.h*L,0,0,D.w*L,D.h*L);const $=H.toDataURL("image/png"),F=await Ms();if(!F.allowed){k(`Sign in to keep using AI. Guest mode includes ${bn} free prompts on this browser.`);return}const{apiBaseUrl:K,accessToken:lt}=await yn(),it={"Content-Type":"application/json"};F.signedIn&<&&(it.Authorization=`Bearer ${lt}`),F.signedIn||(it["X-Inline-Device-Id"]=F.deviceId);const rt=await ci(`${K}/api/ai/extension-light`,{method:"POST",headers:it,body:JSON.stringify({task:"analyze-image",text:"Analyze this screenshot crop and describe what you see.",image:$,guest:!F.signedIn,deviceId:F.signedIn?void 0:F.deviceId})});if(rt.ok){const ht=await rt.json();k(ht.result??"No result returned.")}else k("AI analysis failed. Check your API settings.")}catch{k("Could not reach AI server.")}finally{A(!1)}}},[D,n]);return v.useEffect(()=>{const T=L=>{L.key==="Escape"&&a()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[a]),u.jsxs("div",{style:{position:"fixed",inset:0,zIndex:2147483647,cursor:j?"default":"crosshair",pointerEvents:"auto"},onMouseDown:O,onMouseMove:q,onMouseUp:W,children:[u.jsx("img",{src:n,alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",pointerEvents:"none"}}),u.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)",pointerEvents:"none"}}),(r||g)&&D&&D.w>2&&D.h>2&&u.jsx("div",{style:{position:"absolute",left:D.x,top:D.y,width:D.w,height:D.h,border:"2px dashed #fff",background:"rgba(255,255,255,0.1)",borderRadius:4,pointerEvents:"none"}}),g&&!j&&u.jsxs("div",{style:{position:"absolute",left:D.x,top:D.y+D.h+12,display:"flex",gap:8,pointerEvents:"auto"},children:[u.jsx("button",{type:"button",onClick:E,disabled:w,style:{padding:"8px 20px",borderRadius:x.radiusPill,border:"none",background:x.accent,color:"#fff",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:gt,boxShadow:x.shadowOuter,opacity:w?.7:1},children:w?"Analyzing…":"Analyze"}),u.jsx("button",{type:"button",onClick:a,style:{padding:"8px 20px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.bg,color:x.text,fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:gt,boxShadow:x.shadowOuter},children:"Cancel"})]}),j&&u.jsxs("div",{style:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)",width:300,maxHeight:420,overflowY:"auto",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radius,boxShadow:x.shadowOuter,fontFamily:gt,pointerEvents:"auto"},onMouseDown:T=>T.stopPropagation(),children:[u.jsxs("div",{style:{padding:"10px 14px",background:x.headerBg,borderBottom:`1px solid ${x.divider}`,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u.jsx("span",{style:{fontSize:13,fontWeight:500,color:x.accent},children:"Analysis"}),u.jsx("button",{type:"button",onClick:a,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,border:"none",borderRadius:8,background:"rgba(255,255,255,0.4)",cursor:"pointer",padding:0},children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"#78716c",children:u.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"})})})]}),u.jsx("div",{style:{padding:18,fontSize:13,lineHeight:1.65,color:x.text,wordBreak:"break-word"},children:u.jsx(ui,{text:j,style:{fontSize:13,lineHeight:1.65}})}),u.jsx("div",{style:{padding:"10px 16px",borderTop:`1px solid ${x.divider}`,background:x.surfaceMuted,display:"flex",justifyContent:"flex-end"},children:u.jsx("button",{type:"button",onClick:a,style:{padding:"8px 18px",borderRadius:x.radiusPill,border:`1px solid ${x.border}`,background:x.surfaceBubble,fontSize:12,fontWeight:500,cursor:"pointer",color:x.text,fontFamily:gt},children:"Close"})})]}),u.jsx("canvas",{ref:l,style:{display:"none"}})]})}const Ds=8,Tc=6;function aE({onClose:n}){const a=v.useRef(null),l=v.useRef([]),r=v.useRef({x:-100,y:-100}),d=v.useRef(0),f=v.useRef([]),h=v.useRef(null),p=v.useCallback(()=>{const y=l.current,g=f.current,b=h.current;b&&(b.setAttribute("cx",String(r.current.x)),b.setAttribute("cy",String(r.current.y)));for(let w=0;w{const y=document.getElementById("inline-laser-svg");y&&y.remove();const g=document.createElementNS("http://www.w3.org/2000/svg","svg");g.id="inline-laser-svg",g.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483645;pointer-events:none;";const b=document.createElementNS("http://www.w3.org/2000/svg","defs"),w=document.createElementNS("http://www.w3.org/2000/svg","filter");w.id="inline-laser-glow",w.setAttribute("x","-50%"),w.setAttribute("y","-50%"),w.setAttribute("width","200%"),w.setAttribute("height","200%");const A=document.createElementNS("http://www.w3.org/2000/svg","feGaussianBlur");A.setAttribute("stdDeviation","4"),A.setAttribute("result","blur");const j=document.createElementNS("http://www.w3.org/2000/svg","feMerge"),k=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");k.setAttribute("in","blur");const D=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");D.setAttribute("in","SourceGraphic"),j.appendChild(k),j.appendChild(D),w.appendChild(A),w.appendChild(j),b.appendChild(w),g.appendChild(b);const O=[];for(let E=Ds-1;E>=0;E--){const T=document.createElementNS("http://www.w3.org/2000/svg","circle");T.setAttribute("r",String(Tc-E*.5)),T.setAttribute("fill",E===0?"#ef4444":"#f87171"),T.setAttribute("opacity","0"),E===0&&T.setAttribute("filter","url(#inline-laser-glow)"),g.appendChild(T),O.push(T)}f.current=O;const q=document.createElementNS("http://www.w3.org/2000/svg","circle");q.setAttribute("r",String(Tc+4)),q.setAttribute("fill","rgba(239, 68, 68, 0.25)"),q.setAttribute("filter","url(#inline-laser-glow)"),g.insertBefore(q,g.firstChild?.nextSibling??null),h.current=q,document.body.appendChild(g),a.current=g;const W=E=>{r.current={x:E.clientX,y:E.clientY},l.current.push({x:E.clientX,y:E.clientY}),l.current.length>Ds+2&&(l.current=l.current.slice(-Ds-2))};return document.addEventListener("pointermove",W),d.current=requestAnimationFrame(p),()=>{document.removeEventListener("pointermove",W),cancelAnimationFrame(d.current),g.remove(),a.current=null}},[p]),u.jsxs("div",{style:{position:"fixed",top:12,left:"50%",transform:"translateX(-50%)",zIndex:2147483647,display:"flex",alignItems:"center",gap:10,padding:"5px 14px 5px 12px",background:x.bg,border:`1px solid ${x.border}`,borderRadius:x.radiusPill,boxShadow:x.shadowOuter,fontFamily:gt,userSelect:"none"},children:[u.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#ef4444",boxShadow:"0 0 6px rgba(239,68,68,0.6)",flexShrink:0}}),u.jsx("span",{style:{fontSize:13,fontWeight:500,color:x.text,letterSpacing:"-0.01em"},children:"Laser active"}),u.jsx("button",{type:"button",onClick:n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:24,height:24,border:"none",borderRadius:x.radiusSm,background:"rgba(255,255,255,0.35)",cursor:"pointer",padding:0,color:x.textMuted,fontSize:14,fontWeight:500},children:"×"})]})}const cy="inline-handwriting-canvas";function dy(){const n=document.getElementById(cy);if(n)return n;const a=document.createElement("canvas");return a.id=cy,a.width=window.innerWidth,a.height=window.innerHeight,a.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483639;pointer-events:none;touch-action:none;",document.body.appendChild(a),window.addEventListener("resize",()=>{a.width=window.innerWidth,a.height=window.innerHeight;const l=a.__inlineStrokes;Array.isArray(l)&&fy(a,l)}),a}function sE(n,a){const l=a.points;if(!(!Array.isArray(l)||l.length===0)){if(n.save(),a.tool==="highlighter"?(n.globalCompositeOperation="multiply",n.globalAlpha=.35):a.tool==="eraser"?(n.globalCompositeOperation="destination-out",n.globalAlpha=1):(n.globalCompositeOperation="source-over",n.globalAlpha=1),n.lineCap="round",n.lineJoin="round",n.strokeStyle=a.tool==="eraser"?"rgba(0,0,0,1)":a.color,l.length===1){const r=l[0],d=a.thickness*(r.pressure||.5)*.5;n.beginPath(),n.arc(r.x,r.y,Math.max(d,.5),0,Math.PI*2),n.fillStyle=n.strokeStyle,n.fill(),n.restore();return}for(let r=0;r{if(chrome.runtime.lastError||!a?.ok)return;const l=a.data?.elements?.handwriting;!Array.isArray(l)||l.length===0||(n.__inlineStrokes=l,fy(n,l))})}catch{}}const py=["#1C1E26","#b42318","#315a9f","#0f7b6c","#b7791f","#7c3aed","#ec4899","#06b6d4","#ea580c","#78716c"];function my(){return`hw-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}const lE=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),rE=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),oE=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 0 2.828l-5.5 5.5A2 2 0 0 1 7.879 15H5.12a2 2 0 0 1-1.414-.586l-2.5-2.5a2 2 0 0 1 0-2.828l5.88-5.879z"})});function uE({onClose:n}){const[a,l]=v.useState("pen"),[r,d]=v.useState(py[0]),[f,h]=v.useState(3),p=v.useRef(null),y=v.useRef([]),g=v.useRef(null),b=v.useRef(!1),w=v.useRef(0);v.useEffect(()=>{const E=dy();p.current=E;const T=E.__inlineStrokes;Array.isArray(T)&&(y.current=T),hy();try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},L=>{if(chrome.runtime.lastError||!L?.ok)return;const H=L.data?.elements?.handwriting;Array.isArray(H)&&H.length>0&&(y.current=H,E.__inlineStrokes=H,j())})}catch{}},[]),v.useEffect(()=>{const E=p.current;if(E)return E.style.pointerEvents="auto",E.style.cursor=a==="eraser"?"cell":"crosshair",()=>{E.style.pointerEvents="none",E.style.cursor=""}},[a]);const A=v.useCallback((E,T)=>{const L=T.points;if(L.length!==0){if(E.save(),T.tool==="highlighter"?(E.globalCompositeOperation="multiply",E.globalAlpha=.35):T.tool==="eraser"?(E.globalCompositeOperation="destination-out",E.globalAlpha=1):(E.globalCompositeOperation="source-over",E.globalAlpha=1),E.lineCap="round",E.lineJoin="round",E.strokeStyle=T.tool==="eraser"?"rgba(0,0,0,1)":T.color,L.length===1){const H=L[0],J=T.thickness*(H.pressure||.5)*.5;E.beginPath(),E.arc(H.x,H.y,Math.max(J,.5),0,Math.PI*2),E.fillStyle=E.strokeStyle,E.fill(),E.restore();return}for(let H=0;H{const E=p.current;if(!E)return;const T=E.getContext("2d");if(T){T.clearRect(0,0,E.width,E.height);for(const L of y.current)A(T,L)}},[A]),k=v.useCallback(()=>{try{if(!chrome.runtime?.id)return;const E=y.current.map(L=>({...L,id:L.id??my()}));y.current=E;const T=p.current;T&&(T.__inlineStrokes=E),chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"handwriting",data:E,pageTitle:document.title,domain:window.location.hostname,clearedAt:E.length===0?Date.now():null}},L=>{chrome.runtime.lastError||Ta(L)})}catch{}},[]);v.useEffect(()=>{const E=p.current;if(!E)return;const T=E;function L($){$.preventDefault(),$.stopPropagation();try{T.setPointerCapture($.pointerId)}catch{}b.current=!0;const F=$.pressure>0?$.pressure:.5;g.current={id:my(),points:[{x:$.clientX,y:$.clientY,pressure:F}],color:r,thickness:f,tool:a}}function H($){if(!b.current||!g.current)return;$.preventDefault(),$.stopPropagation();const F=$.pressure>0?$.pressure:.5;g.current.points.push({x:$.clientX,y:$.clientY,pressure:F}),cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{const K=p.current;if(!K)return;const lt=K.getContext("2d");if(lt){lt.clearRect(0,0,K.width,K.height);for(const it of y.current)A(lt,it);g.current&&A(lt,g.current)}})}function J($){if(!(!b.current||!g.current)){$.preventDefault(),$.stopPropagation();try{T.releasePointerCapture($.pointerId)}catch{}b.current=!1,g.current.points.length>0&&(y.current=[...y.current,g.current]),g.current=null,j(),k()}}return T.addEventListener("pointerdown",L),T.addEventListener("pointermove",H),T.addEventListener("pointerup",J),T.addEventListener("pointerleave",J),()=>{T.removeEventListener("pointerdown",L),T.removeEventListener("pointermove",H),T.removeEventListener("pointerup",J),T.removeEventListener("pointerleave",J)}},[a,r,f,A,j,k]);const D=v.useCallback(()=>{y.current=[],g.current=null;const E=p.current;if(E){const T=E.getContext("2d");T&&T.clearRect(0,0,E.width,E.height)}k()},[k]),O=v.useCallback(()=>{const E=p.current;if(!E)return;const T=E.toDataURL("image/png"),L=document.createElement("a");L.download=`handwriting-${Date.now()}.png`,L.href=T,L.click()},[]),q=[{id:"pen",icon:u.jsx(lE,{}),label:"Pen"},{id:"highlighter",icon:u.jsx(rE,{}),label:"Highlighter"},{id:"eraser",icon:u.jsx(oE,{}),label:"Eraser"}],W=q.find(E=>E.id===a)?.label??"Pen";return u.jsx(gn,{title:"Pen",subtitle:"Handwrite & highlight freely",chip:W,width:290,tool:"handwriting",onClose:n,children:u.jsxs("div",{style:{...wa,fontFamily:gt},children:[u.jsxs("div",{children:[u.jsx(ye,{children:"Tool"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:9},children:q.map(E=>{const T=a===E.id;return u.jsx("button",{type:"button",onClick:()=>l(E.id),"aria-label":E.label,"aria-pressed":T,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,height:46,borderRadius:x.radius,border:`1px solid ${T?x.accent:x.border}`,background:T?x.accent:x.surfaceBubble,color:T?"#fff":x.textMuted,cursor:"pointer",fontSize:12,fontWeight:650,boxShadow:"none",transition:"background 0.14s, border-color 0.14s, color 0.14s"},children:E.icon},E.id)})})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Stroke weight"}),u.jsxs(Rn,{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px"},children:[u.jsx("button",{type:"button",onClick:()=>h(E=>Math.max(1,E-1)),"aria-label":"Thinner",style:gy,children:"−"}),u.jsx("input",{type:"range",min:1,max:16,value:f,onChange:E=>h(Number(E.target.value)),"aria-label":"Stroke weight",style:{flex:1,accentColor:x.accent,height:6,cursor:"pointer"}}),u.jsx("button",{type:"button",onClick:()=>h(E=>Math.min(16,E+1)),"aria-label":"Thicker",style:gy,children:"+"}),u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:26,height:26,borderRadius:8,background:x.surfaceSunken,fontSize:12,fontWeight:700,color:x.text},children:f})]})]}),u.jsxs("div",{children:[u.jsx(ye,{children:"Colour"}),u.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:11},children:py.map(E=>{const T=r===E;return u.jsx("button",{type:"button",onClick:()=>d(E),"aria-label":`Colour ${E}`,"aria-pressed":T,style:{height:34,borderRadius:x.radius,background:E,cursor:"pointer",padding:0,border:T?`2.5px solid ${x.accent}`:"1px solid rgba(17,19,33,0.08)",boxShadow:"none",transform:"none",transition:"border-color 0.13s"}},E)})})]}),u.jsxs("div",{style:{display:"flex",gap:9},children:[u.jsx("button",{type:"button",onClick:D,"aria-label":"Clear all",style:yy,children:"Clear all"}),u.jsx("button",{type:"button",onClick:O,"aria-label":"Export PNG",style:{...yy,background:x.accent,color:"#fff",border:"none",boxShadow:"none"},children:"Export PNG"})]})]})})}const gy={display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,borderRadius:x.radius,flexShrink:0,border:`1px solid ${x.border}`,background:x.surfaceBubble,cursor:"pointer",fontSize:16,fontWeight:600,color:x.textMuted,boxShadow:x.shadowSoft},yy={flex:1,padding:"11px 0",fontSize:12.5,fontWeight:700,borderRadius:x.radius,cursor:"pointer",letterSpacing:"-0.01em",border:`1px solid ${x.border}`,background:x.surfaceBubble,color:x.text,transition:"background 0.15s, border-color 0.15s",fontFamily:"inherit"},ze={selectionUiActive:"inline:selectionUiActive",selectionUiDismiss:"inline:selectionUiDismiss",dockPanelDismiss:"inline:dockPanelDismiss",dockPanelOpen:"inline:dockPanelOpen",dockPanelClosed:"inline:dockPanelClosed"};function xy(n){document.dispatchEvent(new CustomEvent(ze.selectionUiActive,{detail:{source:n}}))}function qi(){document.dispatchEvent(new CustomEvent(ze.selectionUiDismiss))}function by(){document.dispatchEvent(new CustomEvent(ze.dockPanelDismiss))}function vy(n){document.dispatchEvent(new CustomEvent(ze.dockPanelOpen,{detail:{panel:n}}))}function fr(){document.dispatchEvent(new CustomEvent(ze.dockPanelClosed))}function cE(n){const a=l=>{const r=l.detail?.source;r&&n(r)};return document.addEventListener(ze.selectionUiActive,a),()=>document.removeEventListener(ze.selectionUiActive,a)}function dE(n){return document.addEventListener(ze.selectionUiDismiss,n),()=>document.removeEventListener(ze.selectionUiDismiss,n)}function fE(n){return document.addEventListener(ze.dockPanelDismiss,n),()=>document.removeEventListener(ze.dockPanelDismiss,n)}function Sy(n){const a=l=>{const r=l.detail?.panel;r&&n(r)};return document.addEventListener(ze.dockPanelOpen,a),()=>document.removeEventListener(ze.dockPanelOpen,a)}function hE(n){return document.addEventListener(ze.dockPanelClosed,n),()=>document.removeEventListener(ze.dockPanelClosed,n)}function zs(n="/app/dashboard"){yn().then(a=>{window.open(`${a.apiBaseUrl}${n}`,"_blank")}).catch(()=>{window.open(`${ac}${n}`,"_blank")})}const Ec={type:"spring",stiffness:380,damping:30,mass:.6},wy={type:"spring",stiffness:440,damping:36,mass:.5},pE=()=>u.jsx(mg,{}),mE=()=>u.jsx(oc,{}),gE=()=>u.jsx(gg,{}),yE=()=>u.jsx(yg,{}),Ay=()=>u.jsx(xg,{}),xE=()=>u.jsx(bg,{}),bE=()=>u.jsx(vg,{}),vE=()=>u.jsx(Sg,{}),SE=()=>u.jsx(wg,{}),wE=()=>u.jsx(Ag,{}),AE=()=>u.jsx(Tg,{}),TE=()=>u.jsx(Eg,{}),EE=()=>u.jsx(s5,{}),jE=()=>u.jsx(r5,{}),CE=()=>u.jsx(l5,{});function Ty({size:n=22}){return u.jsx("span",{style:{display:"block",width:Math.max(3,Math.round(n*.16)),height:Math.round(n*.58),borderRadius:2,background:"#FFFFFF",transform:"rotate(-12deg)"}})}function jc({children:n}){return u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:15,height:15,padding:"0 3px",borderRadius:4,background:x.surfaceMuted,color:x.textMuted,border:`1px solid ${x.border}`,fontSize:9.5,fontWeight:700,lineHeight:1},children:n})}const Ey=38,Cc=40,Mc=34,jy=5,Cy=12,My=560,kc={ai:{icon:u.jsx(mE,{}),label:"Ask Inline"},rewrite:{icon:u.jsx(pE,{}),label:"Rewrite"},highlighter:{icon:u.jsx(Ay,{}),label:"Highlight"},notes:{icon:u.jsx(gE,{}),label:"Sticky note"},draw:{icon:u.jsx(yE,{}),label:"Draw"},handwriting:{icon:u.jsx(TE,{}),label:"Pen"},stamps:{icon:u.jsx(vE,{}),label:"Stamp"},search:{icon:u.jsx(SE,{}),label:"Search"},screenshot:{icon:u.jsx(wE,{}),label:"Screenshot"},laser:{icon:u.jsx(AE,{}),label:"Laser pointer"},layers:{icon:u.jsx(bE,{}),label:"Layers"},settings:{icon:u.jsx(xE,{}),label:"Settings"}},ME=[{type:"tool",id:"ai"},{type:"tool",id:"rewrite"},{type:"group",id:"annotate",icon:u.jsx(Ay,{}),label:"Annotate"},{type:"tool",id:"search"},{type:"group",id:"utility",icon:u.jsx(CE,{}),label:"More tools"}],ky={annotate:["highlighter","notes","draw","handwriting","stamps"],utility:["screenshot","laser","layers","settings"]},kE=new Set(["ai","rewrite","search","settings","highlighter","draw","handwriting","stamps","layers"]),Ry={highlighter:"Highlight mode active",draw:"Drawing mode active",handwriting:"Pen mode active",stamps:"Stamp mode active",laser:"Laser pointer active"},RE=new Set(["highlighter","draw","handwriting","stamps"]);function DE(){return`pn-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function zE(){return u.jsx("span",{style:{height:1,width:22,background:x.divider,margin:"4px 0",flexShrink:0}})}function hr(){try{navigator.vibrate?.(12)}catch{}}function pr({icon:n,label:a,active:l,onClick:r}){const[d,f]=v.useState(!1),[h,p]=v.useState(!1),y=`inline-rail-tip-${a.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,g=d||h;return u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",flexShrink:0},children:[u.jsx(Nn,{children:g&&u.jsxs(Be.span,{id:y,role:"tooltip",initial:{opacity:0,x:5,scale:.94},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:5,scale:.94},transition:{duration:.12,ease:"easeOut"},style:{position:"absolute",right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:12,whiteSpace:"nowrap",pointerEvents:"none",background:x.surfaceBubble,color:x.text,fontSize:11.5,fontWeight:600,padding:"6px 11px",borderRadius:9,letterSpacing:"-0.01em",lineHeight:1,border:`1px solid ${x.border}`},children:[a,u.jsx("span",{style:{position:"absolute",left:"100%",top:"50%",transform:"translateY(-50%)",width:0,height:0,borderTop:"5px solid transparent",borderBottom:"5px solid transparent",borderLeft:`6px solid ${x.surfaceBubble}`}})]})}),u.jsx("button",{type:"button",onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),onFocus:()=>p(!0),onBlur:()=>p(!1),"aria-label":a,"aria-describedby":g?y:void 0,"aria-pressed":l,style:{display:"flex",alignItems:"center",justifyContent:"center",width:Mc,height:Mc,borderRadius:11,border:"none",padding:0,background:l?x.toneSelectedBg:d?x.hoverBg:"transparent",color:l?x.accent:x.textMuted,cursor:"pointer",transition:"background 0.14s, color 0.14s",boxShadow:l?`inset 0 0 0 1px ${x.borderStrong}${h?", 0 0 0 3px rgba(19, 42, 79, 0.18)":""}`:h?"0 0 0 3px rgba(19, 42, 79, 0.18)":"none"},children:n})]})}function LE({selectedText:n,originalRange:a}){const[l,r]=v.useState(null),[d,f]=v.useState([]),[h,p]=v.useState(!1),y=v.useRef(null),g=v.useRef(!1),[b,w]=v.useState(!1),[A,j]=v.useState(null),[k,D]=v.useState(!1),[O,q]=v.useState(!1),[W,E]=v.useState(!1),[T,L]=v.useState(null),[H,J]=v.useState(!1),[$,F]=v.useState(!1),[K,lt]=v.useState(null),it=v.useRef(null),[rt,ht]=v.useState(16+Mc+2*jy+Cy),[Mt,B]=v.useState(typeof window<"u"?window.innerWidth{const X=at.current?.getRootNode();v5(X)},[]);const bt=v.useCallback((X,ot="success",mt,Nt)=>{it.current&&clearTimeout(it.current),lt({id:Date.now(),message:X,tone:ot,actionLabel:mt,onAction:Nt}),it.current=setTimeout(()=>lt(null),2600)},[]);v.useEffect(()=>()=>{it.current&&clearTimeout(it.current)},[]),v.useEffect(()=>{const X=ot=>{const mt=ot.detail;mt?.message&&bt(mt.message,mt.tone??"success",mt.action==="dashboard"?"Open →":void 0,mt.action==="dashboard"?()=>zs():void 0)};return document.addEventListener("inline:toast",X),()=>document.removeEventListener("inline:toast",X)},[bt]),v.useEffect(()=>{if(!chrome.runtime?.id){p(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},X=>{if(chrome.runtime.lastError){p(!0);return}const ot=X?.data?.elements?.paperNotes;Array.isArray(ot)&&f(ot),p(!0)})},[]),v.useEffect(()=>{if(h){if(!g.current){g.current=!0;return}return y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{chrome.runtime?.id&&chrome.storage.local.get(["inlineAccessToken","inlineActiveWorkspaceId"],X=>{const ot=typeof X?.inlineAccessToken=="string"&&X.inlineAccessToken.split(".").length===3&&typeof X?.inlineActiveWorkspaceId=="string"&&X.inlineActiveWorkspaceId.length>0;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"paperNotes",data:d,pageTitle:document.title,domain:window.location.hostname,clearedAt:d.length===0?Date.now():null}},mt=>{if(chrome.runtime.lastError){bt("Could not save. Try again.","error");return}if(mt?.ok){mt.storageMode==="workspace"||mt.storageMode!=="local"&&ot?bt("Saved to Workspace","success","Open →",()=>zs()):bt("Saved to browser.","local");return}if(mt?.queued){bt("Saved to browser.","local");return}bt("Could not save. Try again.","error")})})},500),()=>{y.current&&clearTimeout(y.current)}}},[d,h,bt]);const M=v.useCallback((X,ot)=>{f(mt=>mt.map(Nt=>Nt.id===X?{...Nt,...ot,updatedAt:Date.now()}:Nt))},[]),P=v.useCallback(X=>{f(ot=>ot.filter(mt=>mt.id!==X))},[]),nt=v.useCallback(()=>{r(null),fr()},[]),ft=v.useCallback(X=>{hr(),T===X||nt(),L(mt=>mt===X?null:X)},[T,nt]),vt=v.useCallback(()=>{f(X=>[...X,{id:DE(),x:120+X.length*20,y:120+X.length*20,w:320,h:260,content:"",paperStyle:"Plain",createdAt:Date.now(),updatedAt:Date.now()}])},[]),I=v.useCallback(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"CAPTURE_TAB"},X=>{chrome.runtime.lastError||X?.ok&&X.dataUrl&&j(X.dataUrl)})},[]),V=v.useCallback(X=>{if(X){if(hr(),E(!0),L(null),X==="notes"){qi(),vt();return}if(X==="screenshot"){qi(),I();return}if(X==="laser"){D(ot=>(ot||qi(),!ot));return}kE.has(X)&&r(ot=>{const mt=ot===X?null:X;return mt?(qi(),vy(mt)):fr(),mt})}},[vt,I]),st=v.useCallback(()=>{hr(),E(X=>{const ot=!X;return L(null),ot?(qi(),vy("ai"),r("ai")):(r(null),fr()),ot})},[]),pt=v.useCallback(()=>{q(X=>{const ot=!X;return ot?(nt(),D(!1),j(null),E(!1),L(null),qi(),document.dispatchEvent(new CustomEvent("inline:hideAll",{detail:{hidden:!0}}))):document.dispatchEvent(new CustomEvent("inline:hideAll",{detail:{hidden:!1}})),ot})},[nt]);v.useEffect(()=>{const X=ot=>{const mt=ot.detail;q(mt.hidden),mt.hidden&&(nt(),D(!1),j(null),E(!1),L(null),qi())};return document.addEventListener("inline:hideAll",X),()=>document.removeEventListener("inline:hideAll",X)},[nt]),v.useEffect(()=>{const X=()=>{L(null),r(Nt=>(Nt!==null&&fr(),null))},ot=cE(()=>{X()}),mt=fE(X);return()=>{ot(),mt()}},[]);const Tt=v.useCallback(()=>{const X=at.current;if(!X)return;const ot=X.getBoundingClientRect();ht(Math.max(14,Math.round(window.innerWidth-ot.left+Cy)))},[]);v.useLayoutEffect(()=>{Tt()},[Tt,O,l]),v.useEffect(()=>{const X=()=>{B(window.innerWidthwindow.removeEventListener("resize",X)},[Tt]),v.useEffect(()=>{if(!l)return;const X=ot=>{const mt=ot.composedPath?.()??[],Nt=Y.current?mt.includes(Y.current):!1,Xt=at.current?mt.includes(at.current):!1;if(Nt||Xt||RE.has(l)||Qg())return;const Pt=Y.current?.getRootNode()?.activeElement;Pt&&Y.current?.contains(Pt)&&(Pt.tagName==="INPUT"||Pt.tagName==="TEXTAREA"||Pt.isContentEditable)||nt()};return document.addEventListener("pointerdown",X,!0),()=>document.removeEventListener("pointerdown",X,!0)},[l,nt]),v.useEffect(()=>{if(!T)return;const X=ot=>{const mt=ot.composedPath?.()??[];dt.current&&mt.includes(dt.current)||at.current&&mt.includes(at.current)||L(null)};return document.addEventListener("pointerdown",X,!0),()=>document.removeEventListener("pointerdown",X,!0)},[T]),v.useEffect(()=>{const X=ot=>{if(ot.key==="Escape"){if(k){ot.stopPropagation(),D(!1);return}if(T){ot.stopPropagation(),L(null);return}l&&(ot.stopPropagation(),nt())}};return document.addEventListener("keydown",X,!0),()=>document.removeEventListener("keydown",X,!0)},[k,T,l,nt]);const Vt=v.useCallback(X=>{switch(X){case"rewrite":case"ai":case"search":case"settings":case"highlighter":case"draw":case"handwriting":case"stamps":case"layers":V(X);break;case"notes":vt();break;case"screenshot":I();break;case"laser":D(ot=>!ot);break;case"notebooks":zs();break;case"collapse":E(ot=>{const mt=!ot;return L(null),r(mt?"ai":null),mt});break;case"pause":pt();break}w(!1)},[V,vt,I,pt]);v.useEffect(()=>{const X=ot=>{switch(ot.detail.command){case"toggle-command-palette":w(Nt=>!Nt);break;case"toggle-rewrite":V("rewrite");break;case"toggle-ai":V("ai");break;case"toggle-highlighter":V("highlighter");break;case"new-note":vt();break;case"toggle-pause":pt();break}};return document.addEventListener("inline:command",X),()=>document.removeEventListener("inline:command",X)},[V,vt,pt]),v.useEffect(()=>{const X=ot=>{(ot.ctrlKey||ot.metaKey)&&ot.shiftKey&&ot.key.toLowerCase()==="k"&&(ot.preventDefault(),E(!0),L(null),r("ai"))};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[]);const ct=k?"laser":l&&Ry[l]?l:null,It=ct?Ry[ct]:null,jt=ct?kc[ct]?.icon:null,Et=l?u.jsx(Nn,{mode:"wait",children:u.jsxs(Be.div,{initial:{opacity:0,x:10,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:10,scale:.985},transition:wy,style:{pointerEvents:"auto"},children:[l==="rewrite"&&u.jsx(tT,{selectedText:n,originalRange:a,onClose:nt}),l==="ai"&&u.jsx(hT,{selectedText:n,originalRange:a,onClose:nt}),l==="search"&&u.jsx(nE,{onClose:nt}),l==="settings"&&u.jsx(wT,{onClose:nt,onOpenDashboard:()=>{zs(),nt()}}),l==="highlighter"&&u.jsx(AT,{onClose:nt}),l==="draw"&&u.jsx(LT,{onClose:nt}),l==="handwriting"&&u.jsx(uE,{onClose:nt}),l==="stamps"&&u.jsx(eE,{onClose:nt}),l==="layers"&&u.jsx(JT,{onClose:nt})]},l)}):null;return u.jsxs(u.Fragment,{children:[u.jsx(Nn,{children:!O&&It&&u.jsxs(Be.div,{"data-inline-interactive":"",initial:{opacity:0,y:-6,x:"-50%",scale:.96},animate:{opacity:1,y:0,x:"-50%",scale:1},exit:{opacity:0,y:-6,x:"-50%",scale:.96},transition:{duration:.16,ease:"easeOut"},style:{position:"fixed",top:18,left:"50%",zIndex:2147483647,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,background:x.surfaceBubble,color:x.text,padding:"8px 14px",borderRadius:x.radiusMd,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",whiteSpace:"nowrap",border:`1px solid ${x.border}`,boxShadow:x.shadowOuter,fontFamily:gt},children:[jt&&u.jsx(jg,{size:24,children:jt}),It]},ct??It)}),u.jsx(Nn,{children:!O&&K&&u.jsxs(Be.div,{"data-inline-interactive":"",initial:{opacity:0,y:-6,x:"-50%",scale:.96},animate:{opacity:1,y:0,x:"-50%",scale:1},exit:{opacity:0,y:-6,x:"-50%",scale:.96},transition:{duration:.16,ease:"easeOut"},style:{position:"fixed",top:It?56:18,left:"50%",zIndex:2147483647,pointerEvents:K.onAction?"auto":"none",display:"flex",alignItems:"center",gap:7,background:K.tone==="error"?"#FEF2F2":x.surfaceBubble,color:K.tone==="error"?"#991B1B":x.text,padding:"8px 14px",borderRadius:x.radiusMd,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",whiteSpace:"nowrap",border:`1px solid ${K.tone==="error"?"#FECACA":x.border}`,boxShadow:x.shadowOuter,fontFamily:gt},children:[u.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:K.tone==="error"?"#DC2626":K.tone==="local"?"#D97706":"#16A34A"}}),K.message,K.onAction&&K.actionLabel&&u.jsx("button",{type:"button",onClick:()=>{const X=K?.onAction;X?.(),lt(null)},style:{border:"none",background:"transparent",padding:"0 0 0 2px",color:x.accent,fontSize:12,fontWeight:750,cursor:"pointer",fontFamily:gt},children:K.actionLabel})]},K.id)}),u.jsx(Nn,{children:!O&&l&&!Mt&&u.jsx(Be.div,{"data-inline-interactive":"",ref:Y,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.14},style:{position:"fixed",right:rt,top:Ey,zIndex:2147483646,pointerEvents:"none",display:"flex",fontFamily:gt},children:Et},"panel-wrap")}),u.jsx(Nn,{children:!O&&l&&Mt&&u.jsxs(u.Fragment,{children:[u.jsx(Be.div,{"data-inline-interactive":"",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.16},onPointerDown:()=>{Qg()||nt()},style:{position:"fixed",inset:0,zIndex:2147483645,background:"rgba(11,18,33,0.34)",pointerEvents:"auto"}},"scrim"),u.jsx(Be.div,{"data-inline-interactive":"",ref:Y,initial:{opacity:0,y:24,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:24,scale:.98},transition:wy,style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:2147483646,pointerEvents:"none",display:"flex",fontFamily:gt},children:Et},"panel-sheet")]})}),u.jsx("div",{"data-inline-interactive":"",ref:at,style:{position:"fixed",right:16,top:Ey,zIndex:2147483647,pointerEvents:"none",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:12,fontFamily:gt},children:O?u.jsx(Be.button,{type:"button",onClick:pt,"aria-label":"Show Inline",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:Ec,style:{pointerEvents:"auto",width:40,height:40,borderRadius:13,background:ic,border:"1px solid rgba(255,255,255,0.14)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#FFFFFF",boxShadow:x.shadowOuter,padding:0},children:u.jsx(Ty,{size:20})}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",pointerEvents:"auto"},children:[u.jsx(Nn,{children:(H||$)&&!W&&!l&&u.jsxs(Be.div,{id:"inline-launcher-tooltip",role:"tooltip",initial:{opacity:0,x:8,scale:.94},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:8,scale:.94},transition:{duration:.13,ease:"easeOut"},style:{position:"absolute",right:"100%",marginRight:13,display:"flex",alignItems:"center",gap:8,whiteSpace:"nowrap",background:x.surfaceBubble,color:x.text,padding:"7px 12px",borderRadius:10,fontSize:11.5,fontWeight:600,letterSpacing:"-0.01em",pointerEvents:"none",border:`1px solid ${x.border}`},children:[u.jsx("span",{children:"Open Inline tools"}),u.jsxs("span",{style:{display:"inline-flex",gap:3},children:[u.jsx(jc,{children:"⌘"}),u.jsx(jc,{children:"⇧"}),u.jsx(jc,{children:"K"})]}),u.jsx("span",{style:{position:"absolute",left:"100%",top:"50%",transform:"translateY(-50%)",width:0,height:0,borderTop:"5px solid transparent",borderBottom:"5px solid transparent",borderLeft:`6px solid ${x.surfaceBubble}`}})]})}),u.jsx(Be.button,{type:"button",onClick:st,onMouseEnter:()=>J(!0),onMouseLeave:()=>J(!1),onFocus:()=>F(!0),onBlur:()=>F(!1),"aria-label":W?"Close Inline tools":"Open Inline tools","aria-expanded":W,"aria-describedby":(H||$)&&!W&&!l?"inline-launcher-tooltip":void 0,initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},whileHover:{scale:1.05},whileTap:{scale:.94},transition:Ec,style:{position:"relative",width:Cc,height:Cc,borderRadius:13,background:ic,border:`1px solid ${W?x.accent:"rgba(17,24,39,0.18)"}`,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,outline:"none",color:"#FFFFFF",boxShadow:`${x.shadowOuter}${$?", 0 0 0 3px rgba(19, 42, 79, 0.18)":""}`},children:u.jsx(Ty,{size:21})})]}),u.jsx(Nn,{children:W&&u.jsxs(Be.div,{initial:{opacity:0,y:-8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.98},transition:Ec,style:{pointerEvents:"auto",display:"flex",flexDirection:"column",alignItems:"center",gap:2,padding:jy,background:x.bg,border:`1px solid ${x.border}`,borderRadius:17,boxShadow:x.shadowOuter,maxHeight:"min(72vh, 640px)",overflowY:"auto",overflowX:"hidden"},children:[ME.map(X=>{if(X.type==="tool"){const mt=kc[X.id],Nt=X.id==="laser"?k:l===X.id;return u.jsx(pr,{icon:mt.icon,label:mt.label,active:Nt,onClick:()=>V(X.id)},X.id)}const ot=T===X.id||ky[X.id].some(mt=>mt==="laser"?k:l===mt);return u.jsx(pr,{icon:X.icon,label:X.label,active:ot,onClick:()=>ft(X.id)},X.id)}),u.jsx(zE,{}),u.jsx(pr,{icon:u.jsx(EE,{}),label:"Notebooks",active:!1,onClick:()=>{hr(),zs()}}),u.jsx(pr,{icon:u.jsx(jE,{}),label:"Hide Inline",active:!1,onClick:pt})]})}),u.jsx(Nn,{children:W&&T&&u.jsxs(Be.div,{ref:dt,initial:{opacity:0,x:8,scale:.98},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:8,scale:.98},transition:{duration:.14,ease:"easeOut"},style:{position:"absolute",right:"calc(100% + 10px)",top:Cc+10,pointerEvents:"auto",width:172,padding:6,borderRadius:x.radiusMd,border:`1px solid ${x.border}`,background:x.bg,boxShadow:x.shadowOuter,display:"flex",flexDirection:"column",gap:2,fontFamily:gt},children:[u.jsx("div",{style:{padding:"4px 8px 6px",fontSize:11,fontWeight:500,color:x.textMuted,letterSpacing:"0.01em"},children:T==="annotate"?"Annotate":"More tools"}),ky[T].map(X=>{const ot=kc[X],mt=X==="laser"?k:l===X;return u.jsxs("button",{type:"button",onClick:()=>V(X),"aria-label":ot.label,"aria-pressed":mt,style:{display:"flex",alignItems:"center",gap:10,width:"100%",minHeight:36,padding:"6px 8px",borderRadius:x.radiusSm,border:"none",background:mt?x.toneSelectedBg:"transparent",color:mt?x.text:x.textMuted,cursor:"pointer",fontFamily:gt,fontSize:12,fontWeight:500,textAlign:"left",transition:"background 0.14s"},children:[u.jsx(jg,{size:28,active:mt,children:ot.icon}),u.jsx("span",{children:ot.label})]},X)})]},T)})]})}),!O&&d.map(X=>u.jsx(xT,{initialX:X.x,initialY:X.y,initialW:X.w,initialH:X.h,initialContent:X.content,initialPaperStyle:X.paperStyle,onClose:()=>P(X.id),onUpdate:ot=>M(X.id,ot)},X.id)),b&&u.jsx(XT,{onClose:()=>w(!1),onAction:Vt}),!O&&A&&u.jsx(iE,{screenshot:A,onClose:()=>j(null)}),!O&&k&&u.jsx(aE,{onClose:()=>D(!1)})]})}function OE(){const[n,a]=v.useState(""),[l,r]=v.useState(null),d=v.useRef(null),f=v.useRef("");return v.useEffect(()=>{d.current=l},[l]),v.useEffect(()=>{f.current=n},[n]),v.useEffect(()=>{function h(){const p=window.getSelection();if(p&&!(p.isCollapsed||!p.toString().trim()))try{const y=p.getRangeAt(0).cloneRange();a(p.toString()),r(y)}catch{}}return document.addEventListener("mouseup",h),document.addEventListener("keyup",h),()=>{document.removeEventListener("mouseup",h),document.removeEventListener("keyup",h)}},[]),v.useEffect(()=>Sy(h=>{if(h!=="rewrite"&&h!=="ai")return;const p=d.current,y=f.current.trim();if(!(!p||!y))try{const g=ty(p,"selection-hold");if(!g)return;d.current=g.range,f.current=g.text,r(g.range),a(g.text)}catch{}}),[]),u.jsx("div",{"data-panel-host":"",children:u.jsx(LE,{selectedText:n,originalRange:l})})}const BE=2500;function mr(){return window.location.href}function NE(){return`mwr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}let vn=[],Dy=!1;const Xi=new Set;function Rc(...n){const a=new Map;for(const l of n)for(const r of l)r?.id&&a.set(r.id,r);return[...a.values()]}function zy(n){if(!n||typeof n!="object")return null;const a=n,l=typeof a.id=="string"&&a.id?a.id:null;if(!l)return null;const r=typeof a.text=="string"?a.text:typeof a.aiText=="string"?a.aiText:"";if(!r.trim())return null;const d=typeof a.originalText=="string"?a.originalText:"",f=typeof a.timestamp=="number"&&Number.isFinite(a.timestamp)?a.timestamp:Date.now();return{id:l,originalText:d,text:r,aiText:r,task:"manual",timestamp:f}}function Dc(n){vn=n;for(const a of n)Xi.add(a.id);try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:mr(),featureKey:"manualRewrites",data:n,pageTitle:document.title,domain:window.location.hostname,clearedAt:n.length===0?Date.now():null}},a=>{if(chrome.runtime.lastError){console.error("[Inline] Manual rewrite save failed:",chrome.runtime.lastError.message);return}if(a?.ok)for(const l of n)Xi.delete(l.id);Ta(a),a?.ok||console.error("[Inline] Manual rewrite backend sync failed:",a?.error)})}catch{}}function Ly(n){return n.querySelector(".inline-manual-text")?.textContent??""}function Oy(n,a){const l=n.parentNode;l&&l.replaceChild(document.createTextNode(a),n)}function _E(n,a){const l=vn.find(d=>d.id===n),r=a??document.querySelector(`[data-inline-manual-id="${CSS.escape(n)}"]`);r&&Oy(r,l?.originalText??Ly(r)),Xi.delete(n),Dc(vn.filter(d=>d.id!==n))}function zc(n,a){if(n.getAttribute("data-inline-manual-remove")==="true")return;n.setAttribute("data-inline-manual-remove","true");const l=n.querySelector(".inline-manual-text");l instanceof HTMLElement&&(l.style.cursor="pointer",l.title="Double-click to restore original text",l.addEventListener("dblclick",r=>{r.preventDefault(),r.stopPropagation(),_E(a,n)}))}function UE(n,a,l){const r=NE();n.setAttribute("data-inline-manual-id",r);const d={id:r,originalText:a,text:l,aiText:l,task:"manual",timestamp:Date.now()},f=Rc(vn,[d]);return Dc(f),zc(n,r),r}function HE(n){const a=n.parentElement;if(!a||a.closest("[data-inline-manual-id]")||a.closest("[data-inline-ai-id]")||a.closest("#inline-extension-root"))return NodeFilter.FILTER_REJECT;const l=a.tagName;return l==="SCRIPT"||l==="STYLE"||l==="NOSCRIPT"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}function VE(){const n=document.body,a=[];if(!n)return{full:"",segments:a};const l=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode:HE});let r="",d;for(;d=l.nextNode();){const f=d.textContent??"",h=r.length;r+=f,a.push({node:d,start:h,end:r.length})}return{full:r,segments:a}}function By(n,a,l){if(n.length===0)return null;for(let d=0;df.start&&ar.trim().length>0);for(const r of l){const d=IE(r);if(d)try{const f=Yg(n.text,n.id,n.timestamp);return d.deleteContents(),d.insertNode(f),zc(f,n.id),!0}catch{}}return!1}function GE(n){if(document.body)for(const a of n)YE(a)}function FE(n){document.querySelectorAll("[data-inline-manual-id]").forEach(a=>{if(!(a instanceof HTMLElement))return;const l=a.getAttribute("data-inline-manual-id");if(!l||n.has(l)||Xi.has(l))return;const r=vn.find(d=>d.id===l);Oy(a,r?.originalText??Ly(a))})}function qE(n){return Array.isArray(n)?n.map(zy).filter(a=>a!==null):[]}function XE(n){return Array.isArray(n)?n.filter(a=>!a||typeof a!="object"?!1:a.task==="manual").map(zy).filter(a=>a!==null):[]}function PE(n){for(const l of n)Xi.delete(l.id);vn=Rc(vn,n);const a=new Set(vn.map(l=>l.id));for(const l of Xi)a.add(l);FE(a),GE(vn)}function Ny(){try{if(!chrome.runtime?.id)return;chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:mr()}},n=>{if(chrome.runtime.lastError||!n?.ok){console.error("[Inline] Manual rewrite load failed:",chrome.runtime.lastError?.message??n?.error);return}const a=n.data?.elements??{},l=qE(a.manualRewrites),r=XE(a.aiReplacements),d=Rc(l,r);PE(d),r.length>0&&l.length===0&&Dc(vn),document.dispatchEvent(new CustomEvent("inline:manualRewritesRestored"))})}catch{}}function KE(){if(Dy)return;Dy=!0;let n=mr();const a=()=>{const r=mr();r!==n&&(n=r,vn=[],Xi.clear(),_y())};window.addEventListener("popstate",a),window.addEventListener("hashchange",a);const l=r=>((...d)=>{r.apply(history,d),a()});try{history.pushState=l(history.pushState),history.replaceState=l(history.replaceState)}catch{}}function _y(){KE(),Ny(),window.setTimeout(Ny,BE)}async function WE(n,a){const l=window;try{const r=l.ai?.languageModel?.create;if(!r)return null;const d=await r.call(l.ai.languageModel),f=n==="summarize"?`Summarize in 3 short bullets: -${a}`:i==="rephrase"?`Rephrase clearly, same meaning: +${a}`:n==="rephrase"?`Rephrase clearly, same meaning: -${a}`:i==="shorten"?`Shorten by ~40%, keep meaning: +${a}`:n==="shorten"?`Shorten by ~40%, keep meaning: ${a}`:`Rewrite clearly, same meaning: -${a}`;return await d.prompt(f.slice(0,8e3))}catch{return null}}async function uE(i,a,l,r,d){const f=await ws();if(!f.allowed)return`[Error] Sign in to keep using AI. Guest mode includes ${xn} free prompts on this browser.`;const h={"Content-Type":"application/json"};f.signedIn&&a&&(h.Authorization=`Bearer ${a}`),f.signedIn||(h["X-Inline-Device-Id"]=f.deviceId);try{const p=await ri(`${i}/api/ai/extension-light`,{method:"POST",headers:h,body:JSON.stringify({task:l,text:r,instruction:d,guest:!f.signedIn,deviceId:f.signedIn?void 0:f.deviceId})});if(!p.ok){try{const g=await p.json();if(g.error)return`[Error] ${g.error}`}catch{}return null}return(await p.json()).result??null}catch(p){return`[Error] ${p instanceof Error?p.message:"AI request failed"}`}}const Nn=x.text,Sy=x.bg,wy=x.border,Ay=x.border,Yi=x.textMuted,cE=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),Tc=()=>u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),Ty=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"3",y:"3",width:"7",height:"7"}),u.jsx("rect",{x:"14",y:"3",width:"7",height:"7"}),u.jsx("rect",{x:"3",y:"14",width:"7",height:"7"}),u.jsx("rect",{x:"14",y:"14",width:"7",height:"7"})]}),Ey=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),u.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),u.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),dE=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"}),u.jsx("line",{x1:"7",y1:"7",x2:"7.01",y2:"7"})]}),jy=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]}),fE=()=>u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3z"})}),hE=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"})]}),Ec=()=>u.jsx("div",{style:{width:1,height:20,background:wy,margin:"0 4px",flexShrink:0}});function pE({label:i,show:a}){return u.jsxs("span",{role:"tooltip",style:{position:"absolute",bottom:"calc(100% + 8px)",left:"50%",transform:`translateX(-50%) translateY(${a?"0":"3px"})`,background:x.text,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:8,padding:"5px 9px",fontSize:11,fontWeight:600,lineHeight:1,letterSpacing:"0.01em",whiteSpace:"nowrap",fontFamily:gt,pointerEvents:"none",opacity:a?1:0,transition:"opacity 0.12s ease, transform 0.12s ease",boxShadow:"none",zIndex:2147483647},children:[i,u.jsx("span",{style:{position:"absolute",top:"100%",left:"50%",transform:"translateX(-50%) rotate(45deg)",marginTop:-3,width:6,height:6,background:"#0B1735",borderRight:"1px solid rgba(255,255,255,0.16)",borderBottom:"1px solid rgba(255,255,255,0.16)"}})]})}function kn({children:i,active:a,onClick:l,title:r,isText:d}){const[f,h]=v.useState(!1);return u.jsxs("button",{type:"button","aria-label":r,onClick:l,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onFocus:()=>h(!0),onBlur:()=>h(!1),style:d?{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"6px 11px",border:"none",borderRadius:_t.radiusInner,background:f?_t.hover:"transparent",color:f?_t.textStrong:_t.text,fontSize:12.5,fontWeight:500,fontFamily:gt,cursor:"pointer",lineHeight:1,whiteSpace:"nowrap",transition:"background 0.13s, color 0.13s",letterSpacing:"-0.01em"}:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"7px",border:"none",borderRadius:_t.radiusInner,background:a?_t.active:f?_t.hover:"transparent",color:a||f?_t.textStrong:_t.text,cursor:"pointer",lineHeight:1,transition:"background 0.13s, color 0.13s"},children:[i,r&&u.jsx(pE,{label:r,show:f})]})}function mE({item:i}){const[a,l]=v.useState(!1);return u.jsxs("button",{type:"button",onMouseDown:r=>r.preventDefault(),onClick:i.action,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"8px 10px",border:"none",borderRadius:7,background:a?i.danger?"rgba(239,68,68,0.08)":_t.hover:"transparent",color:i.danger?"#ef4444":a?Nn:"#4B5563",fontSize:12.5,fontWeight:500,cursor:"pointer",fontFamily:gt,textAlign:"left",transition:"background 0.12s, color 0.12s"},children:[u.jsx("span",{style:{display:"flex",color:i.danger?"#ef4444":Yi},children:i.icon}),i.label]})}function gE(){const[i,a]=v.useState(null),[l,r]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(""),[y,g]=v.useState(!1),[b,S]=v.useState(""),[A,j]=v.useState(!1),[k,D]=v.useState([]),[O,F]=v.useState(!1),[Q,E]=v.useState(null),[T,L]=v.useState(null),[U,$]=v.useState(""),tt=v.useRef(null),P=v.useRef(null),W=v.useRef(null),[lt,it]=v.useState(null),rt=v.useRef(null),mt=v.useRef(null),kt=v.useRef(""),B=v.useRef(""),at=v.useRef(null),G=v.useRef(null),ct=v.useRef(!1),bt=v.useRef(!1),M=v.useRef(!1),K=v.useCallback(()=>{a(null),f(null),r(!1),E(null),L(null),$("")},[]),nt=v.useCallback(()=>{K(),it(null),g(!1),S(""),j(!1),M.current=!1,B.current="",P.current=null},[K]);v.useEffect(()=>{if(!chrome.runtime?.id){F(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},I=>{if(chrome.runtime.lastError){F(!0);return}const ft=I?.data?.elements?.anchorNotes;Array.isArray(ft)&&D(ft),F(!0)})},[]),v.useEffect(()=>{if(O)return G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"anchorNotes",data:k,pageTitle:document.title,domain:window.location.hostname,clearedAt:k.length===0?Date.now():null}},()=>{chrome.runtime.lastError})},500),()=>{G.current&&clearTimeout(G.current)}},[k,O]);const dt=v.useCallback(()=>{const I=window.getSelection();if(!(I&&!I.isCollapsed&&I.toString().trim().length>0)){if(W.current)return;M.current=!1,a(null),f(null),r(!1),B.current="",P.current=null;return}const Ct=I.getRangeAt(0),Ut=Ct.getBoundingClientRect();if(!Ut.width&&!Ut.height){a(null);return}B.current=I.toString();try{P.current=Ct.cloneRange()}catch{}ct.current||bt.current||M.current||(E(null),L(null),a(Wt=>(Wt||(uy(),oy("toolbar")),{x:Ut.left+Ut.width/2,y:Ut.top+window.scrollY})))},[]);v.useEffect(()=>{const I=()=>requestAnimationFrame(dt);return document.addEventListener("mouseup",I),document.addEventListener("keyup",I),()=>{document.removeEventListener("mouseup",I),document.removeEventListener("keyup",I)}},[dt]),v.useEffect(()=>{const I=Ct=>{const Ut=window.getSelection();if(!(!Ut||Ut.isCollapsed||!Ut.toString().trim())){Ct.preventDefault(),B.current=Ut.toString();try{P.current=Ut.getRangeAt(0).cloneRange()}catch{P.current=null}M.current=!1,ct.current=!0,a(null),f(null),r(!1),uy(),oy("contextMenu"),E({x:Ct.clientX,y:Ct.clientY})}},ft=()=>{ct.current=!1,E(null)};return document.addEventListener("contextmenu",I),document.addEventListener("click",ft),()=>{document.removeEventListener("contextmenu",I),document.removeEventListener("click",ft)}},[]),v.useEffect(()=>{const I=VT(()=>{K()}),ft=dy(()=>{M.current=!0,K()}),Ct=HT(()=>{M.current=!1,requestAnimationFrame(()=>{if(M.current||ct.current||bt.current)return;const Wt=window.getSelection();if(!(!Wt||Wt.isCollapsed||!Wt.toString().trim()))try{const Ft=Wt.getRangeAt(0),le=Ft.getBoundingClientRect();if(!le.width&&!le.height)return;B.current=Wt.toString(),P.current=Ft.cloneRange(),a({x:le.left+le.width/2,y:le.top+window.scrollY})}catch{}})}),Ut=Wt=>{Wt.detail?.hidden&&nt()};return document.addEventListener("inline:hideAll",Ut),()=>{I(),ft(),Ct(),document.removeEventListener("inline:hideAll",Ut)}},[K,nt]),v.useEffect(()=>{ct.current=!!Q},[Q]),v.useEffect(()=>{bt.current=!!T},[T]),v.useEffect(()=>{T&&setTimeout(()=>tt.current?.focus(),60)},[T]);function vt(){const I=P.current;if(!I)return!1;const ft=window.getSelection();if(!ft)return!1;try{return ft.removeAllRanges(),ft.addRange(I),!ft.isCollapsed&&ft.toString().trim().length>0}catch{return!1}}function Y(){const I=U.trim();I&&vt()&&(bt.current=!1,L(null),$(""),P.current=null,Et("rewrite",I))}v.useEffect(()=>{const I=ft=>{ft?.type==="INLINE_PAGE_RISK"&&X()};return chrome.runtime.onMessage.addListener(I),()=>chrome.runtime.onMessage.removeListener(I)},[]),v.useEffect(()=>{W.current=d,d&&setTimeout(()=>at.current?.focus(),60)},[d]);function H(I){if(!P.current){const ft=window.getSelection();if(ft&&!ft.isCollapsed&&ft.rangeCount>0){try{P.current=ft.getRangeAt(0).cloneRange()}catch{}B.current=ft.toString()}}r(!1),f(ft=>ft===I?null:I),p("")}function st(I,ft){vt(),ct.current=!1,E(null),Et(I,ft)}function ht(I,ft){vt(),Et(I,ft)}function Tt(I){return I==="summarize"?"Summary":I==="rephrase"?"Rephrased":I==="rewrite"?"Rewritten":"Shortened"}function Vt(I){return I==="summarize"?"Summary update":I==="rephrase"?"Rephrase update":I==="rewrite"?"Rewrite update":"Shorten update"}function ut(){it(null)}function It(){const I=mt.current,ft=kt.current;if(I?.parentNode){const Ct=document.createTextNode(ft||I.textContent||"");I.parentNode.replaceChild(Ct,I)}mt.current=null,kt.current="",it(null)}async function Et(I,ft){vt();const Ct=oi(I);if(!Ct){ct.current=!1,bt.current=!1,K(),it({title:"Selection lost",body:"Highlight the paragraph you want to change, then try again.",loading:!1});return}mt.current=Ct.span,kt.current=Ct.text,ct.current=!1,bt.current=!1,K();const Ut=Tt(I);it({title:Ut,body:"",loading:!0,task:I,instruction:ft});let Wt=await oE(I,Ct.text);if(!Wt){const{apiBaseUrl:Ft,accessToken:le}=await gn();Wt=await uE(Ft,le,I,Ct.text,ft)}it({title:Ut,body:Wt??"AI unavailable — set API URL + token in the popup.",loading:!1,task:I,instruction:ft})}function jt(){const I=mt.current,ft=kt.current;if(!(!I||!lt||!lt.body||!lt.task)&&!lt.body.startsWith("[Error]"))try{const Ct=er(lt.body,lt.task,lt.instruction),Ut=I.parentNode;if(!Ut)return;Ut.replaceChild(Ct,I),Lg(Ct,ft,lt.body,lt.task,lt.instruction),it(Wt=>Wt&&{...Wt,inserted:!0}),mt.current=null,kt.current=""}catch{}}function X(){g(!0),j(!0),S(""),(async()=>{const I=(document.body?.innerText??"").slice(0,12e3),ft=await ws();if(!ft.allowed){S(`Sign in to keep using AI. Guest mode includes ${xn} free prompts on this browser.`),j(!1);return}const{apiBaseUrl:Ct,accessToken:Ut}=await gn(),Wt={"Content-Type":"application/json"};ft.signedIn&&Ut&&(Wt.Authorization=`Bearer ${Ut}`),ft.signedIn||(Wt["X-Inline-Device-Id"]=ft.deviceId);try{const le=await(await ri(`${Ct}/api/ai/page-risk`,{method:"POST",headers:Wt,body:JSON.stringify({pageTextSample:I,guest:!ft.signedIn,deviceId:ft.signedIn?void 0:ft.deviceId})})).json();S(le.analysis??le.error??"No response")}catch(Ft){S(Ft instanceof Error?Ft.message:"Failed")}finally{j(!1)}})()}function ot(I){oi("extract",I),a(null),r(!1),f(null)}function pt(){a(null),f(null),E(null);const I=k.length*16;D(ft=>[...ft,{id:`an-${Date.now()}`,x:Math.min(window.innerWidth-252,40+I),y:Math.min(window.innerHeight-200,140+I),text:B.current?`"${B.current.slice(0,120)}"`:""}])}if(!i&&!y&&!Q&&!T&&!lt&&k.length===0)return null;const zt=i?Math.max(8,Math.min(window.innerWidth-500,i.x-230)):0,Xt=i?Math.max(8,i.y-50):0,ze=[{label:"Highlight",icon:u.jsx(cE,{}),action:()=>{vt(),oi("extract"),E(null)}},{label:"Summarize",icon:u.jsx(fE,{}),action:()=>st("summarize")},{label:"Rephrase",icon:u.jsx(Tc,{}),action:()=>st("rephrase")},{label:"Shorten",icon:u.jsx(Ty,{}),action:()=>st("shorten")},{label:"Custom Rewrite…",icon:u.jsx(Tc,{}),action:()=>{const I=Q;ct.current=!1,E(null),I&&(bt.current=!0,$(""),L(I))}},{label:"Add Note",icon:u.jsx(hE,{}),action:pt},{label:"Read Aloud",icon:u.jsx(jy,{}),action:()=>{Jl(B.current.slice(0,800)),E(null)}},{label:"Page Risk",icon:u.jsx(Ey,{}),action:()=>{E(null),X()}}];return u.jsxs(u.Fragment,{children:[i&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"inline-toolbar",onMouseDown:I=>{I.preventDefault()},style:{position:"fixed",left:zt,top:Xt,zIndex:2147483646,background:_t.bg,border:`1px solid ${_t.border}`,borderRadius:_t.radius,pointerEvents:"auto",width:"max-content",fontFamily:gt,display:"flex",alignItems:"center",gap:1,padding:"5px 6px",boxShadow:_t.shadow},children:[u.jsx(kn,{isText:!0,active:l,onClick:()=>{f(null),r(I=>!I)},title:"Highlight",children:u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:7},children:["Highlight",u.jsx("span",{style:{width:15,height:15,borderRadius:5,background:eg[0].value,border:`1px solid ${_t.divider}`}}),u.jsx("span",{style:{color:_t.textMuted,fontSize:9,marginLeft:-2},children:l?"▴":"▾"})]})}),u.jsx(Ec,{}),u.jsx(kn,{isText:!0,onClick:()=>ht("summarize"),title:"Summarize",children:"Summarize"}),u.jsx(kn,{isText:!0,onClick:()=>ht("rephrase"),title:"Rephrase",children:"Rephrase"}),u.jsx(kn,{isText:!0,onClick:()=>ht("shorten"),title:"Shorten",children:"Shorten"}),u.jsx(kn,{active:d==="rewrite",onClick:()=>H("rewrite"),title:"Custom rewrite",children:u.jsx(Tc,{})}),u.jsx(Ec,{}),u.jsx(kn,{onClick:()=>{oi("extract"),a(null)},title:"Extract data",children:u.jsx(Ty,{})}),u.jsx(kn,{onClick:()=>{a(null),X()},title:"Page risk",children:u.jsx(Ey,{})}),u.jsx(Ec,{}),u.jsx(kn,{active:d==="insight",onClick:()=>H("insight"),title:"Tag insight",children:u.jsx(dE,{})}),u.jsx(kn,{onClick:()=>{Jl(B.current.slice(0,800))},title:"Read aloud",children:u.jsx(jy,{})}),u.jsx(kn,{isText:!0,onClick:pt,title:"Pin a note here",children:"Note"})]}),l&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:I=>{I.preventDefault()},style:{position:"fixed",left:zt,top:Xt+50,zIndex:2147483646,background:_t.bg,border:`1px solid ${_t.border}`,borderRadius:_t.radius,pointerEvents:"auto",fontFamily:gt,display:"flex",alignItems:"center",gap:6,padding:"6px 10px",boxShadow:_t.shadow},children:[u.jsxs("button",{type:"button",onClick:()=>r(!1),"aria-label":"Back",style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"transparent",cursor:"pointer",color:_t.text,fontSize:12.5,fontWeight:500,fontFamily:gt,padding:"4px 6px",borderRadius:_t.radiusInner},children:[u.jsx("span",{style:{fontSize:13,lineHeight:1},children:"‹"})," Highlight"]}),u.jsx("div",{style:{width:1,height:18,background:_t.divider,margin:"0 2px"}}),eg.map(I=>u.jsx("button",{type:"button",onClick:()=>ot(I.value),"aria-label":`Highlight ${I.name}`,title:I.name,style:{width:22,height:22,borderRadius:7,background:I.value,border:`1px solid ${_t.divider}`,cursor:"pointer",padding:0,flexShrink:0,transition:"transform 0.1s"},onMouseEnter:ft=>ft.currentTarget.style.transform="scale(1.12)",onMouseLeave:ft=>ft.currentTarget.style.transform="scale(1)"},I.name))]}),d==="rewrite"&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:I=>{const ft=I.target;ft.tagName!=="INPUT"&&ft.tagName!=="TEXTAREA"&&I.preventDefault()},style:{position:"fixed",left:zt,top:Xt+50,zIndex:2147483645,background:_t.bg,border:`1px solid ${_t.border}`,borderRadius:_t.radius,pointerEvents:"auto",width:320,display:"flex",alignItems:"center",gap:6,padding:"7px 8px 7px 10px",fontFamily:gt,boxShadow:_t.shadow},children:[u.jsx("input",{ref:at,value:h,onChange:I=>p(I.target.value),onKeyDown:I=>{I.key==="Enter"&&h.trim()&&ht("rewrite",h.trim()),I.key==="Escape"&&f(null)},placeholder:"How should I rewrite this?",style:{flex:1,padding:"8px 10px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Nn,background:"transparent"}}),u.jsx("button",{type:"button",disabled:!h.trim(),onClick:()=>{h.trim()&&ht("rewrite",h.trim())},style:{padding:"7px 16px",borderRadius:9999,border:"none",background:h.trim()?Nn:"#E5E3DF",color:h.trim()?"#fff":Yi,fontWeight:600,fontSize:12,cursor:h.trim()?"pointer":"default",whiteSpace:"nowrap"},children:"Go"}),u.jsx("button",{type:"button",onClick:()=>f(null),style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Yi,fontSize:15,cursor:"pointer"},children:"×"})]}),d==="insight"&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:I=>{const ft=I.target;ft.tagName!=="INPUT"&&ft.tagName!=="TEXTAREA"&&I.preventDefault()},style:{position:"fixed",left:zt,top:Xt+50,zIndex:2147483645,background:_t.bg,border:`1px solid ${_t.border}`,borderRadius:_t.radius,pointerEvents:"auto",width:300,display:"flex",alignItems:"center",gap:6,padding:"7px 8px 7px 10px",fontFamily:gt,boxShadow:_t.shadow},children:[u.jsx("input",{ref:at,value:h,onChange:I=>p(I.target.value),onKeyDown:I=>{if(I.key==="Enter"&&h.trim()){oi("extract");const ft=h;f(null),a(null),p(""),it({title:"Insight saved",body:ft,loading:!1})}},placeholder:"Add insight…",style:{flex:1,padding:"8px 10px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Nn,background:"transparent"}}),u.jsx("button",{type:"button",onClick:()=>{h.trim()&&(oi("extract"),it({title:"Insight saved",body:h,loading:!1})),f(null),a(null),p("")},style:{padding:"7px 16px",borderRadius:9999,border:"none",background:Nn,color:"#fff",fontWeight:600,fontSize:12,cursor:"pointer",whiteSpace:"nowrap"},children:"Save"}),u.jsx("button",{type:"button",onClick:()=>f(null),style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Yi,fontSize:15,cursor:"pointer"},children:"×"})]})]}),Q&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:I=>I.preventDefault(),style:{position:"fixed",left:Math.min(Q.x,window.innerWidth-200),top:Math.min(Q.y,window.innerHeight-360),zIndex:2147483647,background:Sy,border:`1px solid ${Ay}`,borderRadius:x.radius,pointerEvents:"auto",width:192,padding:"6px",fontFamily:gt,boxShadow:x.shadowOuter},onClick:I=>I.stopPropagation(),children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px 8px",borderBottom:`1px solid ${wy}`,marginBottom:4},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:18,height:18,borderRadius:6,background:Nn,flexShrink:0},children:u.jsx("span",{style:{display:"block",width:2.5,height:9,borderRadius:2,background:"#fff",transform:"rotate(-12deg)"}})}),u.jsx("span",{style:{fontSize:11,fontWeight:700,color:Yi,letterSpacing:"0.06em"},children:"INLINE"})]}),ze.map(I=>u.jsx(mE,{item:I},I.label))]}),T&&u.jsxs("div",{className:"inline-toolbar",style:{position:"fixed",left:Math.min(T.x,window.innerWidth-340),top:Math.min(T.y,window.innerHeight-80),zIndex:2147483647,background:Sy,border:`1px solid ${Ay}`,borderRadius:_t.radius,pointerEvents:"auto",width:340,display:"flex",alignItems:"center",gap:6,padding:"8px 8px 8px 12px",fontFamily:gt,boxShadow:_t.shadow},onClick:I=>I.stopPropagation(),children:[u.jsx("input",{ref:tt,value:U,onChange:I=>$(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Y(),I.key==="Escape"&&(L(null),$(""))},placeholder:"How should I rewrite this?",style:{flex:1,padding:"8px 6px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Nn,background:"transparent"}}),u.jsx("button",{type:"button",onClick:Y,disabled:!U.trim(),style:{padding:"7px 16px",borderRadius:9999,border:"none",background:U.trim()?Nn:"#E5E3DF",color:U.trim()?"#fff":Yi,fontWeight:600,fontSize:12,cursor:U.trim()?"pointer":"default",whiteSpace:"nowrap"},children:"Go"}),u.jsx("button",{type:"button",onClick:()=>{L(null),$(""),P.current=null},style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Yi,fontSize:15,cursor:"pointer"},children:"×"})]}),k.map(I=>u.jsx(yE,{note:I,dragRef:rt,onChange:ft=>D(Ct=>Ct.map(Ut=>Ut.id===I.id?{...Ut,text:ft}:Ut)),onClose:()=>D(ft=>ft.filter(Ct=>Ct.id!==I.id))},I.id)),y&&u.jsx(nc,{title:"Ask",subtitle:"Page risk analysis",width:342,tool:"ai",onClose:()=>g(!1),footer:!A&&b?u.jsx(Zl,{onBack:()=>g(!1),showReject:!1,showApprove:!1}):void 0,children:u.jsx(ic,{children:A?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14},children:[u.jsx(xa,{size:16})," Analysing…"]}):u.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0,fontFamily:gt,fontSize:13.5,lineHeight:1.55},children:b})})}),lt&&(()=>{const I=!lt.loading&<.body.startsWith("[Error]"),ft=!!lt.task&&!I&&!lt.loading,Ct=kt.current,Ut=ft&&!lt.inserted&&!!mt.current;return u.jsx(nc,{className:"inline-toolbar",title:"Ask",subtitle:lt.loading?"Thinking…":I?"Something went wrong":lt.task?Vt(lt.task):lt.title,width:342,tool:"ai",onClose:ut,footer:!lt.loading&<.body?ft?u.jsx(Zl,{onBack:ut,onReject:It,onApprove:jt,approveLabel:lt.inserted?"Approved":"Approve",approveDisabled:!Ut}):I?u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"12px 16px"},children:[u.jsx(Ql,{label:"Back",onClick:ut}),u.jsx(Ql,{label:"Copy",onClick:()=>{navigator.clipboard.writeText(lt.body).catch(()=>{})}})]}):u.jsx(Zl,{onBack:ut,showReject:!1,showApprove:!1}):void 0,children:u.jsx(ic,{children:lt.loading?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14,fontStyle:"italic"},children:[u.jsx(xa,{size:16})," Putting together the best answer…"]}):I?u.jsx("p",{style:{margin:0,fontSize:13.5,lineHeight:1.55,color:"#991B1B"},children:lt.body.replace(/^\[Error\]\s*/,"")}):ft&&Ct?u.jsx(vg,{original:Ct,updated:lt.body}):u.jsx(dc,{text:lt.body,style:{fontSize:13.5,lineHeight:1.55}})})})})(),u.jsx(xE,{setAnchors:D,dragRef:rt})]})}function yE({note:i,dragRef:a,onChange:l,onClose:r}){return u.jsx(nc,{className:"inline-anchor",title:"Note",subtitle:"Drag header to move",width:260,bareBody:!0,position:{left:i.x,top:i.y},zIndex:2147483645,onClose:r,onHeaderMouseDown:d=>{a.current={id:i.id,ox:d.clientX-i.x,oy:d.clientY-i.y},d.preventDefault()},headerCursor:"grab",children:u.jsx("div",{style:{padding:"12px 14px"},children:u.jsx("textarea",{value:i.text,onChange:d=>l(d.target.value),placeholder:"Start typing…",style:{display:"block",width:"100%",boxSizing:"border-box",border:`1px solid ${x.border}`,borderRadius:x.radiusSm,padding:"8px 10px",fontSize:12,resize:"vertical",minHeight:90,outline:"none",fontFamily:gt,color:Nn,background:x.inputBg}})})})}function xE({setAnchors:i,dragRef:a}){return v.useEffect(()=>{const l=d=>{const f=a.current;f&&i(h=>h.map(p=>p.id===f.id?{...p,x:Math.max(0,d.clientX-f.ox),y:Math.max(0,d.clientY-f.oy)}:p))},r=()=>{a.current=null};return window.addEventListener("mousemove",l),window.addEventListener("mouseup",r),()=>{window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",r)}},[a,i]),null}function Cy(){const i=[];return document.querySelectorAll("video").forEach(r=>{r.duration>0&&!isNaN(r.duration)&&i.push({element:r,type:"video",currentTime:r.currentTime,duration:r.duration,title:document.title})}),document.querySelectorAll("audio").forEach(r=>{r.duration>0&&!isNaN(r.duration)&&i.push({element:r,type:"audio",currentTime:r.currentTime,duration:r.duration,title:document.title})}),i}function My(i){const a=Math.floor(i/3600),l=Math.floor(i%3600/60),r=Math.floor(i%60);return a>0?`${a}:${String(l).padStart(2,"0")}:${String(r).padStart(2,"0")}`:`${l}:${String(r).padStart(2,"0")}`}function bE(i){const a=Cy();a.length>0&&(a[0].element.currentTime=i,a[0].element.play().catch(()=>{}))}const Cs=[{bg:"#ede9fe",header:"#ddd6fe"},{bg:"#fef9c3",header:"#fef08a"},{bg:"#fce7f3",header:"#fbcfe8"},{bg:"#dcfce7",header:"#bbf7d0"},{bg:"#dbeafe",header:"#bfdbfe"},{bg:"#ffedd5",header:"#fed7aa"}];function vE(i){return Cs.find(a=>a.bg===i)??Cs[0]}function jc(i,a){const l=parseInt(i.slice(1,3),16),r=parseInt(i.slice(3,5),16),d=parseInt(i.slice(5,7),16);return`rgba(${l},${r},${d},${a})`}const SE=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.21 13c2.106 0 3.412-1.087 3.412-2.823 0-1.306-.984-2.283-2.324-2.386v-.055a2.176 2.176 0 0 0 1.852-2.14c0-1.51-1.162-2.46-3.014-2.46H3.843V13H8.21zM5.908 4.674h1.696c.963 0 1.517.451 1.517 1.244 0 .834-.629 1.32-1.73 1.32H5.908V4.674zm0 6.788V8.598h1.73c1.217 0 1.88.492 1.88 1.415 0 .943-.643 1.449-1.832 1.449H5.907z"})}),wE=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M7.991 11.674 9.53 4.455c.123-.595.246-.71 1.347-.807l.11-.52H7.211l-.11.52c1.06.096 1.128.212 1.005.807L6.57 11.674c-.123.595-.246.71-1.346.806l-.11.52h3.774l.11-.52c-1.06-.095-1.129-.211-1.006-.806z"})}),AE=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-8a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"})}),TE=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8 5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm4 3a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM5.5 7a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm.25 2.9a2.5 2.5 0 0 1 3.5 0 .5.5 0 0 0 .5.1 2 2 0 0 0 1.834-2.165 8 8 0 1 0-11.996.946 8 8 0 0 0 .914.48A2 2 0 0 0 2 9.5a2 2 0 0 0 3.75-.6z"})});function Cc({children:i,onClick:a}){const[l,r]=v.useState(!1);return u.jsx("button",{type:"button",onMouseDown:d=>{d.preventDefault(),a()},onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:5,background:l?"rgba(0,0,0,0.08)":"transparent",color:"#374151",cursor:"pointer"},children:i})}function EE({note:i,onUpdate:a,onDelete:l}){const[r,d]=v.useState(!1),[f,h]=v.useState(!1),[p,y]=v.useState(i.title??"Note"),[g,b]=v.useState(!1),S=v.useRef({x:0,y:0}),A=v.useRef(null),j=v.useRef(null),k=vE(i.color),D=v.useCallback(U=>{U.preventDefault(),d(!0),S.current={x:U.clientX-i.x,y:U.clientY-i.y},U.target.setPointerCapture(U.pointerId)},[i.x,i.y]),O=v.useCallback(U=>{r&&a(i.id,{x:U.clientX-S.current.x,y:U.clientY-S.current.y})},[r,i.id,a]),F=v.useCallback(()=>d(!1),[]),Q=v.useCallback(U=>{U.preventDefault(),U.stopPropagation();const $=U.clientX,tt=U.clientY,P=i.width,W=i.height,lt=rt=>a(i.id,{width:Math.max(200,P+rt.clientX-$),height:Math.max(140,W+rt.clientY-tt)}),it=()=>{window.removeEventListener("mousemove",lt),window.removeEventListener("mouseup",it)};window.addEventListener("mousemove",lt),window.addEventListener("mouseup",it)},[i.id,i.width,i.height,a]),E=v.useCallback(()=>{A.current&&a(i.id,{content:A.current.innerHTML})},[i.id,a]);v.useEffect(()=>{A.current&&A.current.innerHTML!==i.content&&(A.current.innerHTML=i.content||""),!i.content&&Date.now()-i.createdAt<1e3&&A.current?.focus()},[]),v.useEffect(()=>{y(i.title??"Note")},[i.title]),v.useEffect(()=>{f&&j.current?.select()},[f]);function T(){const U=p.trim()||"Note";y(U),a(i.id,{title:U}),h(!1)}function L(U){A.current?.focus(),document.execCommand(U,!1,void 0),A.current&&a(i.id,{content:A.current.innerHTML})}return u.jsxs("div",{className:"sticky-note",style:{position:"fixed",left:i.x,top:i.y,width:i.width,height:i.height,zIndex:r?2147483647:2147483646,background:jc(k.bg,.82),backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",borderColor:k.header},children:[u.jsxs("div",{className:"sticky-note-header",onPointerDown:D,onPointerMove:O,onPointerUp:F,style:{background:jc(k.header,.9),cursor:r?"grabbing":"grab"},children:[u.jsx("span",{className:"sticky-drag-handle",children:"⠿"}),f?u.jsx("input",{ref:j,value:p,onChange:U=>y(U.target.value),onBlur:T,onKeyDown:U=>{(U.key==="Enter"||U.key==="Escape")&&T()},onPointerDown:U=>U.stopPropagation(),style:{flex:1,border:"none",background:"transparent",outline:"none",fontSize:12,fontWeight:500,color:"#1c1e26",fontFamily:"'Geist', ui-sans-serif, system-ui, sans-serif"}}):u.jsx("span",{className:"sticky-note-title",onDoubleClick:U=>{U.stopPropagation(),h(!0)},"aria-label":"Double-click to rename",children:i.title??"Note"}),i.mediaTimestamp!=null&&u.jsxs("button",{type:"button",onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),bE(i.mediaTimestamp)},"aria-label":`Jump to ${My(i.mediaTimestamp)}`,style:{display:"inline-flex",alignItems:"center",gap:3,padding:"2px 8px",border:"none",borderRadius:10,background:"rgba(99,102,241,0.15)",color:"#4f46e5",fontSize:10,fontWeight:700,cursor:"pointer",fontFamily:"'Geist', ui-sans-serif, system-ui, sans-serif",lineHeight:1,whiteSpace:"nowrap"},children:[u.jsx("svg",{width:"8",height:"8",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M6.271 5.055a.5.5 0 0 1 .52.038l3.5 2.5a.5.5 0 0 1 0 .814l-3.5 2.5A.5.5 0 0 1 6 10.5v-5a.5.5 0 0 1 .271-.445z"})}),My(i.mediaTimestamp)]}),u.jsx("button",{type:"button",onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),b($=>!$)},className:"sticky-palette-btn","aria-label":"Change color",children:u.jsx(TE,{})}),u.jsx("span",{className:"sticky-dot",style:{background:"#6366f1"}}),u.jsx("button",{className:"sticky-note-delete",onClick:()=>l(i.id),"aria-label":"Delete",children:"×"})]}),g&&u.jsx("div",{style:{display:"flex",gap:6,padding:"6px 10px",background:jc(k.header,.7),borderBottom:`1px solid ${k.header}`},children:Cs.map(U=>u.jsx("button",{type:"button",onMouseDown:$=>{$.preventDefault(),$.stopPropagation(),a(i.id,{color:U.bg}),b(!1)},style:{width:20,height:20,borderRadius:"50%",border:i.color===U.bg?"2px solid #6366f1":"2px solid rgba(0,0,0,0.1)",background:U.bg,cursor:"pointer"}},U.bg))}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",background:"rgba(255,255,255,0.65)",borderBottom:`1px solid ${k.header}`},children:[u.jsx(Cc,{onClick:()=>L("bold"),children:u.jsx(SE,{})}),u.jsx(Cc,{onClick:()=>L("italic"),children:u.jsx(wE,{})}),u.jsx(Cc,{onClick:()=>L("insertUnorderedList"),children:u.jsx(AE,{})})]}),u.jsx("div",{ref:A,className:"sticky-note-body",contentEditable:!0,suppressContentEditableWarning:!0,onInput:E,"data-placeholder":"Start typing…",style:{background:"rgba(255,255,255,0.55)"}}),u.jsx("div",{className:"sticky-resize",onMouseDown:Q,children:u.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"rgba(0,0,0,0.3)",children:[u.jsx("path",{d:"M8 2L2 8M5 2L2 5M8 5L5 8"}),u.jsx("path",{d:"M8 2L2 8",strokeWidth:"1",stroke:"rgba(0,0,0,0.3)",fill:"none"}),u.jsx("path",{d:"M10 4L4 10M10 7L7 10",strokeWidth:"1.2",stroke:"rgba(0,0,0,0.25)",fill:"none"})]})})]})}function jE(){return crypto.randomUUID()}const Mc=window.location.href,CE=500,ME=(()=>{let i=0;return()=>{const a=Cs[i%Cs.length].bg;return i++,a}})(),ky=v.createContext(null);function kE(){const i=v.useContext(ky);if(!i)return null;const{notes:a,notesVisible:l,handleUpdateNote:r,handleDeleteNote:d}=i;return u.jsx(u.Fragment,{children:l&&a.map(f=>u.jsx(EE,{note:f,onUpdate:r,onDelete:d},f.id))})}function RE(){const[i,a]=v.useState(!1);return v.useEffect(()=>{const l=r=>{const d=r.detail;a(d.hidden)};return document.addEventListener("inline:hideAll",l),()=>document.removeEventListener("inline:hideAll",l)},[]),i}function DE({children:i}){const[a,l]=v.useState([]),[r,d]=v.useState(!1),[f,h]=v.useState(!0),p=v.useRef(null);v.useEffect(()=>{if(!chrome.runtime?.id){d(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:Mc}},A=>{chrome.runtime.lastError?console.error("[Inline] Load failed:",chrome.runtime.lastError.message):A?.ok&&Array.isArray(A.data?.elements?.stickyNotes)&&l(A.data.elements.stickyNotes),d(!0)})},[]),v.useEffect(()=>{if(r)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:Mc,featureKey:"stickyNotes",data:a}},A=>{if(chrome.runtime.lastError){console.error("[Inline] Message failed:",chrome.runtime.lastError.message);return}if(nr(A),!A?.ok){const j=String(A?.error??"");if(A?.queued||/queued|offline|unreachable/i.test(j))return;console.error("[Inline] Backend sync failed:",A?.error)}})},CE),()=>{p.current&&clearTimeout(p.current)}},[a,r]);const y=v.useCallback(()=>{const A=Date.now(),k=Cy().find(O=>!O.element.paused),D=k?k.currentTime:void 0;l(O=>{const F=O.length*18;return[...O,{id:jE(),pageUrl:Mc,x:Math.min(window.innerWidth-260,window.innerWidth/2-120+F),y:Math.min(window.innerHeight-220,window.innerHeight/2-100+F),width:240,height:190,content:"",color:ME(),title:"Note",createdAt:A,updatedAt:A,...D!==void 0&&{mediaTimestamp:D}}]})},[]),g=v.useCallback((A,j)=>l(k=>k.map(D=>D.id===A?{...D,...j,updatedAt:Date.now()}:D)),[]),b=v.useCallback(A=>l(j=>j.filter(k=>k.id!==A)),[]),S={notes:a,notesVisible:f,setNotesVisible:h,handleAddNote:y,handleUpdateNote:g,handleDeleteNote:b};return u.jsx(ky.Provider,{value:S,children:i})}function zE(){return RE()?null:u.jsx(u.Fragment,{children:u.jsx(kE,{})})}function LE(){return u.jsx(DE,{children:u.jsx(zE,{})})}const ur="inlinePrivacyAccepted";function Ry(){return new Promise(i=>{if(!chrome.runtime?.id){i(!0);return}chrome.storage.local.get([ur],a=>{i(a[ur]==="true"||a[ur]===!0)})})}function OE(){return new Promise((i,a)=>{if(!chrome.runtime?.id){i();return}chrome.storage.local.set({[ur]:"true"},()=>{if(chrome.runtime.lastError){a(new Error(chrome.runtime.lastError.message));return}i()})})}function BE(){const[i,a]=v.useState(!1),[l,r]=v.useState(!1);v.useEffect(()=>{Ry().then(f=>{r(f),a(!0)})},[]);const d=v.useCallback(()=>{r(!0),OE().catch(()=>{r(!1)})},[]);return{ready:i,accepted:l,accept:d}}function NE(){gn().then(i=>{window.open(`${i.apiBaseUrl}/privacy`,"_blank")}).catch(()=>{window.open(`${$u}/privacy`,"_blank")})}function _E(){const{ready:i,accepted:a,accept:l}=BE();return v.useEffect(()=>{a&&document.dispatchEvent(new CustomEvent("inline:privacyAccepted"))},[a]),v.useEffect(()=>{if(!a)return;const r=window.setTimeout(()=>{L5(),Wg(),iy(),y5()},800);return()=>window.clearTimeout(r)},[a]),i?a?u.jsxs(u.Fragment,{children:[u.jsx(gE,{}),u.jsx(LE,{}),u.jsx(rE,{})]}):u.jsx(e5,{onAccept:l,onPrivacyPolicy:NE}):null}const kc="inline-reader-style";function Dy(){if(document.getElementById(kc))return;const i=document.createElement("style");i.id=kc,i.textContent=` +${a}`;return await d.prompt(f.slice(0,8e3))}catch{return null}}async function QE(n,a,l,r,d){const f=await Ms();if(!f.allowed)return`[Error] Sign in to keep using AI. Guest mode includes ${bn} free prompts on this browser.`;const h={"Content-Type":"application/json"};f.signedIn&&a&&(h.Authorization=`Bearer ${a}`),f.signedIn||(h["X-Inline-Device-Id"]=f.deviceId);try{const p=await ci(`${n}/api/ai/extension-light`,{method:"POST",headers:h,body:JSON.stringify({task:l,text:r,instruction:d,guest:!f.signedIn,deviceId:f.signedIn?void 0:f.deviceId})});if(!p.ok){try{const g=await p.json();if(g.error)return`[Error] ${g.error}`}catch{}return null}return(await p.json()).result??null}catch(p){return`[Error] ${p instanceof Error?p.message:"AI request failed"}`}}const Un=x.text,Uy=x.bg,Hy=x.border,Vy=x.border,Pi=x.textMuted,ZE=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M9 11l-6 6v3h9l3-3"}),u.jsx("path",{d:"M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]}),Lc=()=>u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),Iy=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"3",y:"3",width:"7",height:"7"}),u.jsx("rect",{x:"14",y:"3",width:"7",height:"7"}),u.jsx("rect",{x:"3",y:"14",width:"7",height:"7"}),u.jsx("rect",{x:"14",y:"14",width:"7",height:"7"})]}),Yy=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),u.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),u.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),$E=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"}),u.jsx("line",{x1:"7",y1:"7",x2:"7.01",y2:"7"})]}),Gy=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]}),JE=()=>u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3z"})}),tj=()=>u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"})]}),Oc=()=>u.jsx("div",{style:{width:1,height:20,background:Hy,margin:"0 4px",flexShrink:0}});function ej({label:n,show:a}){return u.jsxs("span",{role:"tooltip",style:{position:"absolute",bottom:"calc(100% + 8px)",left:"50%",transform:`translateX(-50%) translateY(${a?"0":"3px"})`,background:x.text,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:8,padding:"5px 9px",fontSize:11,fontWeight:600,lineHeight:1,letterSpacing:"0.01em",whiteSpace:"nowrap",fontFamily:gt,pointerEvents:"none",opacity:a?1:0,transition:"opacity 0.12s ease, transform 0.12s ease",boxShadow:"none",zIndex:2147483647},children:[n,u.jsx("span",{style:{position:"absolute",top:"100%",left:"50%",transform:"translateX(-50%) rotate(45deg)",marginTop:-3,width:6,height:6,background:"#0B1735",borderRight:"1px solid rgba(255,255,255,0.16)",borderBottom:"1px solid rgba(255,255,255,0.16)"}})]})}function Dn({children:n,active:a,onClick:l,title:r,isText:d}){const[f,h]=v.useState(!1);return u.jsxs("button",{type:"button","aria-label":r,onClick:l,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onFocus:()=>h(!0),onBlur:()=>h(!1),style:d?{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"6px 11px",border:"none",borderRadius:Ht.radiusInner,background:f?Ht.hover:"transparent",color:f?Ht.textStrong:Ht.text,fontSize:12.5,fontWeight:500,fontFamily:gt,cursor:"pointer",lineHeight:1,whiteSpace:"nowrap",transition:"background 0.13s, color 0.13s",letterSpacing:"-0.01em"}:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"7px",border:"none",borderRadius:Ht.radiusInner,background:a?Ht.active:f?Ht.hover:"transparent",color:a||f?Ht.textStrong:Ht.text,cursor:"pointer",lineHeight:1,transition:"background 0.13s, color 0.13s"},children:[n,r&&u.jsx(ej,{label:r,show:f})]})}function nj({item:n}){const[a,l]=v.useState(!1);return u.jsxs("button",{type:"button",onMouseDown:r=>r.preventDefault(),onClick:n.action,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"8px 10px",border:"none",borderRadius:7,background:a?n.danger?"rgba(239,68,68,0.08)":Ht.hover:"transparent",color:n.danger?"#ef4444":a?Un:"#4B5563",fontSize:12.5,fontWeight:500,cursor:"pointer",fontFamily:gt,textAlign:"left",transition:"background 0.12s, color 0.12s"},children:[u.jsx("span",{style:{display:"flex",color:n.danger?"#ef4444":Pi},children:n.icon}),n.label]})}function ij(){const[n,a]=v.useState(null),[l,r]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(""),[y,g]=v.useState(!1),[b,w]=v.useState(""),[A,j]=v.useState(!1),[k,D]=v.useState([]),[O,q]=v.useState(!1),[W,E]=v.useState(null),[T,L]=v.useState(null),[H,J]=v.useState(""),$=v.useRef(null),F=v.useRef(null),K=v.useRef(null),[lt,it]=v.useState(null),rt=v.useRef(null),ht=v.useRef(null),Mt=v.useRef(""),B=v.useRef(""),at=v.useRef(null),Y=v.useRef(null),dt=v.useRef(!1),bt=v.useRef(!1),M=v.useRef(!1),P=v.useCallback(()=>{a(null),f(null),r(!1),E(null),L(null),J("")},[]),nt=v.useCallback(()=>{P(),it(null),g(!1),w(""),j(!1),M.current=!1,B.current="",F.current=null},[P]);v.useEffect(()=>{if(!chrome.runtime?.id){q(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},Q=>{if(chrome.runtime.lastError){q(!0);return}const ut=Q?.data?.elements?.anchorNotes;Array.isArray(ut)&&D(ut),q(!0)})},[]),v.useEffect(()=>{if(O)return Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"anchorNotes",data:k,pageTitle:document.title,domain:window.location.hostname,clearedAt:k.length===0?Date.now():null}},()=>{chrome.runtime.lastError})},500),()=>{Y.current&&clearTimeout(Y.current)}},[k,O]);const ft=v.useCallback(()=>{const Q=window.getSelection();if(!(Q&&!Q.isCollapsed&&Q.toString().trim().length>0)){if(K.current)return;M.current=!1,a(null),f(null),r(!1),B.current="",F.current=null;return}const zt=Q.getRangeAt(0),Lt=zt.getBoundingClientRect();if(!Lt.width&&!Lt.height){a(null);return}B.current=Q.toString();try{F.current=zt.cloneRange()}catch{}dt.current||bt.current||M.current||(E(null),L(null),a(kt=>(kt||(by(),xy("toolbar")),{x:Lt.left+Lt.width/2,y:Lt.top+window.scrollY})))},[]);v.useEffect(()=>{const Q=()=>requestAnimationFrame(ft);return document.addEventListener("mouseup",Q),document.addEventListener("keyup",Q),()=>{document.removeEventListener("mouseup",Q),document.removeEventListener("keyup",Q)}},[ft]),v.useEffect(()=>{const Q=zt=>{const Lt=window.getSelection();if(!(!Lt||Lt.isCollapsed||!Lt.toString().trim())){zt.preventDefault(),B.current=Lt.toString();try{F.current=Lt.getRangeAt(0).cloneRange()}catch{F.current=null}M.current=!1,dt.current=!0,a(null),f(null),r(!1),by(),xy("contextMenu"),E({x:zt.clientX,y:zt.clientY})}},ut=()=>{dt.current=!1,E(null)};return document.addEventListener("contextmenu",Q),document.addEventListener("click",ut),()=>{document.removeEventListener("contextmenu",Q),document.removeEventListener("click",ut)}},[]),v.useEffect(()=>{const Q=dE(()=>{P()}),ut=Sy(()=>{M.current=!0,P()}),zt=hE(()=>{M.current=!1,requestAnimationFrame(()=>{if(M.current||dt.current||bt.current)return;const kt=window.getSelection();if(!(!kt||kt.isCollapsed||!kt.toString().trim()))try{const oe=kt.getRangeAt(0),Le=oe.getBoundingClientRect();if(!Le.width&&!Le.height)return;B.current=kt.toString(),F.current=oe.cloneRange(),a({x:Le.left+Le.width/2,y:Le.top+window.scrollY})}catch{}})}),Lt=kt=>{kt.detail?.hidden&&nt()};return document.addEventListener("inline:hideAll",Lt),()=>{Q(),ut(),zt(),document.removeEventListener("inline:hideAll",Lt)}},[P,nt]),v.useEffect(()=>{dt.current=!!W},[W]),v.useEffect(()=>{bt.current=!!T},[T]),v.useEffect(()=>{T&&setTimeout(()=>$.current?.focus(),60)},[T]);function vt(){const Q=F.current;if(!Q)return!1;const ut=window.getSelection();if(!ut)return!1;try{return ut.removeAllRanges(),ut.addRange(Q),!ut.isCollapsed&&ut.toString().trim().length>0}catch{return!1}}function I(){const Q=H.trim();Q&&vt()&&(bt.current=!1,L(null),J(""),F.current=null,Et("rewrite",Q))}v.useEffect(()=>{const Q=ut=>{ut?.type==="INLINE_PAGE_RISK"&&ot()};return chrome.runtime.onMessage.addListener(Q),()=>chrome.runtime.onMessage.removeListener(Q)},[]),v.useEffect(()=>{K.current=d,d&&setTimeout(()=>at.current?.focus(),60)},[d]);function V(Q){if(!F.current){const ut=window.getSelection();if(ut&&!ut.isCollapsed&&ut.rangeCount>0){try{F.current=ut.getRangeAt(0).cloneRange()}catch{}B.current=ut.toString()}}r(!1),f(ut=>ut===Q?null:Q),p("")}function st(Q,ut){vt(),dt.current=!1,E(null),Et(Q,ut)}function pt(Q,ut){vt(),Et(Q,ut)}function Tt(){const Q=h.trim();if(!Q)return;const ut=F.current;if(!ut)return;let zt;try{zt=ut.cloneRange()}catch{return}const Lt=zt.toString();if(Lt.trim()){vt();try{zt.deleteContents();const kt=Yg(Q);zt.insertNode(kt),UE(kt,Lt,Q),f(null),a(null),p(""),F.current=null,B.current="",window.getSelection()?.removeAllRanges()}catch{}}}function Vt(Q){return Q==="summarize"?"Summary":Q==="rephrase"?"Rephrased":Q==="rewrite"?"Rewritten":"Shortened"}function ct(Q){return Q==="summarize"?"Summary update":Q==="rephrase"?"Rephrase update":Q==="rewrite"?"Rewrite update":"Shorten update"}function It(){it(null)}function jt(){const Q=ht.current,ut=Mt.current;if(Q?.parentNode){const zt=document.createTextNode(ut||Q.textContent||"");Q.parentNode.replaceChild(zt,Q)}ht.current=null,Mt.current="",it(null)}async function Et(Q,ut){vt();const zt=di(Q);if(!zt){dt.current=!1,bt.current=!1,P(),it({title:"Selection lost",body:"Highlight the paragraph you want to change, then try again.",loading:!1});return}ht.current=zt.span,Mt.current=zt.text,dt.current=!1,bt.current=!1,P();const Lt=Vt(Q);it({title:Lt,body:"",loading:!0,task:Q,instruction:ut});let kt=await WE(Q,zt.text);if(!kt){const{apiBaseUrl:oe,accessToken:Le}=await yn();kt=await QE(oe,Le,Q,zt.text,ut)}it({title:Lt,body:kt??"AI unavailable — set API URL + token in the popup.",loading:!1,task:Q,instruction:ut})}function X(){const Q=ht.current,ut=Mt.current;if(!(!Q||!lt||!lt.body||!lt.task)&&!lt.body.startsWith("[Error]"))try{const zt=or(lt.body,lt.task,lt.instruction),Lt=Q.parentNode;if(!Lt)return;Lt.replaceChild(zt,Q),Pg(zt,ut,lt.body,lt.task,lt.instruction),it(kt=>kt&&{...kt,inserted:!0}),ht.current=null,Mt.current=""}catch{}}function ot(){g(!0),j(!0),w(""),(async()=>{const Q=(document.body?.innerText??"").slice(0,12e3),ut=await Ms();if(!ut.allowed){w(`Sign in to keep using AI. Guest mode includes ${bn} free prompts on this browser.`),j(!1);return}const{apiBaseUrl:zt,accessToken:Lt}=await yn(),kt={"Content-Type":"application/json"};ut.signedIn&&Lt&&(kt.Authorization=`Bearer ${Lt}`),ut.signedIn||(kt["X-Inline-Device-Id"]=ut.deviceId);try{const Le=await(await ci(`${zt}/api/ai/page-risk`,{method:"POST",headers:kt,body:JSON.stringify({pageTextSample:Q,guest:!ut.signedIn,deviceId:ut.signedIn?void 0:ut.deviceId})})).json();w(Le.analysis??Le.error??"No response")}catch(oe){w(oe instanceof Error?oe.message:"Failed")}finally{j(!1)}})()}function mt(Q){di("extract",Q),a(null),r(!1),f(null)}function Nt(){a(null),f(null),E(null);const Q=k.length*16;D(ut=>[...ut,{id:`an-${Date.now()}`,x:Math.min(window.innerWidth-252,40+Q),y:Math.min(window.innerHeight-200,140+Q),text:B.current?`"${B.current.slice(0,120)}"`:""}])}if(!n&&!y&&!W&&!T&&!lt&&k.length===0)return null;const Xt=n?Math.max(8,Math.min(window.innerWidth-500,n.x-230)):0,be=n?Math.max(8,n.y-50):0,Pt=[{label:"Highlight",icon:u.jsx(ZE,{}),action:()=>{vt(),di("extract"),E(null)}},{label:"Summarize",icon:u.jsx(JE,{}),action:()=>st("summarize")},{label:"Rephrase",icon:u.jsx(Lc,{}),action:()=>st("rephrase")},{label:"Shorten",icon:u.jsx(Iy,{}),action:()=>st("shorten")},{label:"Custom Rewrite…",icon:u.jsx(Lc,{}),action:()=>{const Q=W;dt.current=!1,E(null),Q&&(bt.current=!0,J(""),L(Q))}},{label:"Add Note",icon:u.jsx(tj,{}),action:Nt},{label:"Read Aloud",icon:u.jsx(Gy,{}),action:()=>{lr(B.current.slice(0,800)),E(null)}},{label:"Page Risk",icon:u.jsx(Yy,{}),action:()=>{E(null),ot()}}];return u.jsxs(u.Fragment,{children:[n&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"inline-toolbar",onMouseDown:Q=>{Q.preventDefault()},style:{position:"fixed",left:Xt,top:be,zIndex:2147483646,background:Ht.bg,border:`1px solid ${Ht.border}`,borderRadius:Ht.radius,pointerEvents:"auto",width:"max-content",fontFamily:gt,display:"flex",alignItems:"center",gap:1,padding:"5px 6px",boxShadow:Ht.shadow},children:[u.jsx(Dn,{isText:!0,active:l,onClick:()=>{f(null),r(Q=>!Q)},title:"Highlight",children:u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:7},children:["Highlight",u.jsx("span",{style:{width:15,height:15,borderRadius:5,background:dg[0].value,border:`1px solid ${Ht.divider}`}}),u.jsx("span",{style:{color:Ht.textMuted,fontSize:9,marginLeft:-2},children:l?"▴":"▾"})]})}),u.jsx(Oc,{}),u.jsx(Dn,{isText:!0,onClick:()=>pt("summarize"),title:"Summarize",children:"Summarize"}),u.jsx(Dn,{isText:!0,onClick:()=>pt("rephrase"),title:"Rephrase",children:"Rephrase"}),u.jsx(Dn,{isText:!0,onClick:()=>pt("shorten"),title:"Shorten",children:"Shorten"}),u.jsx(Dn,{active:d==="rewrite",onClick:()=>V("rewrite"),title:"Manual rewrite",children:u.jsx(Lc,{})}),u.jsx(Oc,{}),u.jsx(Dn,{onClick:()=>{di("extract"),a(null)},title:"Extract data",children:u.jsx(Iy,{})}),u.jsx(Dn,{onClick:()=>{a(null),ot()},title:"Page risk",children:u.jsx(Yy,{})}),u.jsx(Oc,{}),u.jsx(Dn,{active:d==="insight",onClick:()=>V("insight"),title:"Tag insight",children:u.jsx($E,{})}),u.jsx(Dn,{onClick:()=>{lr(B.current.slice(0,800))},title:"Read aloud",children:u.jsx(Gy,{})}),u.jsx(Dn,{isText:!0,onClick:Nt,title:"Pin a note here",children:"Note"})]}),l&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:Q=>{Q.preventDefault()},style:{position:"fixed",left:Xt,top:be+50,zIndex:2147483646,background:Ht.bg,border:`1px solid ${Ht.border}`,borderRadius:Ht.radius,pointerEvents:"auto",fontFamily:gt,display:"flex",alignItems:"center",gap:6,padding:"6px 10px",boxShadow:Ht.shadow},children:[u.jsxs("button",{type:"button",onClick:()=>r(!1),"aria-label":"Back",style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"transparent",cursor:"pointer",color:Ht.text,fontSize:12.5,fontWeight:500,fontFamily:gt,padding:"4px 6px",borderRadius:Ht.radiusInner},children:[u.jsx("span",{style:{fontSize:13,lineHeight:1},children:"‹"})," Highlight"]}),u.jsx("div",{style:{width:1,height:18,background:Ht.divider,margin:"0 2px"}}),dg.map(Q=>u.jsx("button",{type:"button",onClick:()=>mt(Q.value),"aria-label":`Highlight ${Q.name}`,title:Q.name,style:{width:22,height:22,borderRadius:7,background:Q.value,border:`1px solid ${Ht.divider}`,cursor:"pointer",padding:0,flexShrink:0,transition:"transform 0.1s"},onMouseEnter:ut=>ut.currentTarget.style.transform="scale(1.12)",onMouseLeave:ut=>ut.currentTarget.style.transform="scale(1)"},Q.name))]}),d==="rewrite"&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:Q=>{const ut=Q.target;ut.tagName!=="INPUT"&&ut.tagName!=="TEXTAREA"&&Q.preventDefault()},style:{position:"fixed",left:Xt,top:be+50,zIndex:2147483645,background:Ht.bg,border:`1px solid ${Ht.border}`,borderRadius:Ht.radius,pointerEvents:"auto",width:320,display:"flex",alignItems:"center",gap:6,padding:"7px 8px 7px 10px",fontFamily:gt,boxShadow:Ht.shadow},children:[u.jsx("input",{ref:at,value:h,onChange:Q=>p(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&h.trim()&&Tt(),Q.key==="Escape"&&f(null)},placeholder:"Replace selection with…",style:{flex:1,padding:"8px 10px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Un,background:"transparent"}}),u.jsx("button",{type:"button",disabled:!h.trim(),onClick:()=>{h.trim()&&Tt()},style:{padding:"7px 16px",borderRadius:9999,border:"none",background:h.trim()?Un:"#E5E3DF",color:h.trim()?"#fff":Pi,fontWeight:600,fontSize:12,cursor:h.trim()?"pointer":"default",whiteSpace:"nowrap"},children:"Go"}),u.jsx("button",{type:"button",onClick:()=>f(null),style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Pi,fontSize:15,cursor:"pointer"},children:"×"})]}),d==="insight"&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:Q=>{const ut=Q.target;ut.tagName!=="INPUT"&&ut.tagName!=="TEXTAREA"&&Q.preventDefault()},style:{position:"fixed",left:Xt,top:be+50,zIndex:2147483645,background:Ht.bg,border:`1px solid ${Ht.border}`,borderRadius:Ht.radius,pointerEvents:"auto",width:300,display:"flex",alignItems:"center",gap:6,padding:"7px 8px 7px 10px",fontFamily:gt,boxShadow:Ht.shadow},children:[u.jsx("input",{ref:at,value:h,onChange:Q=>p(Q.target.value),onKeyDown:Q=>{if(Q.key==="Enter"&&h.trim()){di("extract");const ut=h;f(null),a(null),p(""),it({title:"Insight saved",body:ut,loading:!1})}},placeholder:"Add insight…",style:{flex:1,padding:"8px 10px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Un,background:"transparent"}}),u.jsx("button",{type:"button",onClick:()=>{h.trim()&&(di("extract"),it({title:"Insight saved",body:h,loading:!1})),f(null),a(null),p("")},style:{padding:"7px 16px",borderRadius:9999,border:"none",background:Un,color:"#fff",fontWeight:600,fontSize:12,cursor:"pointer",whiteSpace:"nowrap"},children:"Save"}),u.jsx("button",{type:"button",onClick:()=>f(null),style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Pi,fontSize:15,cursor:"pointer"},children:"×"})]})]}),W&&u.jsxs("div",{className:"inline-toolbar",onMouseDown:Q=>Q.preventDefault(),style:{position:"fixed",left:Math.min(W.x,window.innerWidth-200),top:Math.min(W.y,window.innerHeight-360),zIndex:2147483647,background:Uy,border:`1px solid ${Vy}`,borderRadius:x.radius,pointerEvents:"auto",width:192,padding:"6px",fontFamily:gt,boxShadow:x.shadowOuter},onClick:Q=>Q.stopPropagation(),children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px 8px",borderBottom:`1px solid ${Hy}`,marginBottom:4},children:[u.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:18,height:18,borderRadius:6,background:Un,flexShrink:0},children:u.jsx("span",{style:{display:"block",width:2.5,height:9,borderRadius:2,background:"#fff",transform:"rotate(-12deg)"}})}),u.jsx("span",{style:{fontSize:11,fontWeight:700,color:Pi,letterSpacing:"0.06em"},children:"INLINE"})]}),Pt.map(Q=>u.jsx(nj,{item:Q},Q.label))]}),T&&u.jsxs("div",{className:"inline-toolbar",style:{position:"fixed",left:Math.min(T.x,window.innerWidth-340),top:Math.min(T.y,window.innerHeight-80),zIndex:2147483647,background:Uy,border:`1px solid ${Vy}`,borderRadius:Ht.radius,pointerEvents:"auto",width:340,display:"flex",alignItems:"center",gap:6,padding:"8px 8px 8px 12px",fontFamily:gt,boxShadow:Ht.shadow},onClick:Q=>Q.stopPropagation(),children:[u.jsx("input",{ref:$,value:H,onChange:Q=>J(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&I(),Q.key==="Escape"&&(L(null),J(""))},placeholder:"How should I rewrite this?",style:{flex:1,padding:"8px 6px",border:"none",borderRadius:8,fontSize:12.5,fontFamily:gt,outline:"none",color:Un,background:"transparent"}}),u.jsx("button",{type:"button",onClick:I,disabled:!H.trim(),style:{padding:"7px 16px",borderRadius:9999,border:"none",background:H.trim()?Un:"#E5E3DF",color:H.trim()?"#fff":Pi,fontWeight:600,fontSize:12,cursor:H.trim()?"pointer":"default",whiteSpace:"nowrap"},children:"Go"}),u.jsx("button",{type:"button",onClick:()=>{L(null),J(""),F.current=null},style:{padding:"4px 8px",borderRadius:6,border:"none",background:"transparent",color:Pi,fontSize:15,cursor:"pointer"},children:"×"})]}),k.map(Q=>u.jsx(aj,{note:Q,dragRef:rt,onChange:ut=>D(zt=>zt.map(Lt=>Lt.id===Q.id?{...Lt,text:ut}:Lt)),onClose:()=>D(ut=>ut.filter(zt=>zt.id!==Q.id))},Q.id)),y&&u.jsx(cc,{title:"Ask",subtitle:"Page risk analysis",width:342,tool:"ai",onClose:()=>g(!1),footer:!A&&b?u.jsx(ar,{onBack:()=>g(!1),showReject:!1,showApprove:!1}):void 0,children:u.jsx(dc,{children:A?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14},children:[u.jsx(Aa,{size:16})," Analysing…"]}):u.jsx(ui,{text:b,style:{fontSize:13.5,lineHeight:1.55}})})}),lt&&(()=>{const Q=!lt.loading&<.body.startsWith("[Error]"),ut=!!lt.task&&!Q&&!lt.loading,zt=Mt.current,Lt=ut&&!lt.inserted&&!!ht.current;return u.jsx(cc,{className:"inline-toolbar",title:"Ask",subtitle:lt.loading?"Thinking…":Q?"Something went wrong":lt.task?ct(lt.task):lt.title,width:342,tool:"ai",onClose:It,footer:!lt.loading&<.body?ut?u.jsx(ar,{onBack:It,onReject:jt,onApprove:X,approveLabel:lt.inserted?"Approved":"Approve",approveDisabled:!Lt}):Q?u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"12px 16px"},children:[u.jsx(ir,{label:"Back",onClick:It}),u.jsx(ir,{label:"Copy",onClick:()=>{navigator.clipboard.writeText(lt.body).catch(()=>{})}})]}):u.jsx(ar,{onBack:It,showReject:!1,showApprove:!1}):void 0,children:u.jsx(dc,{children:lt.loading?u.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,color:x.textMuted,fontSize:14,fontStyle:"italic"},children:[u.jsx(Aa,{size:16})," Putting together the best answer…"]}):Q?u.jsx("p",{style:{margin:0,fontSize:13.5,lineHeight:1.55,color:"#991B1B"},children:lt.body.replace(/^\[Error\]\s*/,"")}):ut&&zt?u.jsx(Rg,{original:zt,updated:lt.body}):u.jsx(ui,{text:lt.body,style:{fontSize:13.5,lineHeight:1.55}})})})})(),u.jsx(sj,{setAnchors:D,dragRef:rt})]})}function aj({note:n,dragRef:a,onChange:l,onClose:r}){return u.jsx(cc,{className:"inline-anchor",title:"Note",subtitle:"Drag header to move",width:260,bareBody:!0,position:{left:n.x,top:n.y},zIndex:2147483645,onClose:r,onHeaderMouseDown:d=>{a.current={id:n.id,ox:d.clientX-n.x,oy:d.clientY-n.y},d.preventDefault()},headerCursor:"grab",children:u.jsx("div",{style:{padding:"12px 14px"},children:u.jsx("textarea",{value:n.text,onChange:d=>l(d.target.value),placeholder:"Start typing…",style:{display:"block",width:"100%",boxSizing:"border-box",border:`1px solid ${x.border}`,borderRadius:x.radiusSm,padding:"8px 10px",fontSize:12,resize:"vertical",minHeight:90,outline:"none",fontFamily:gt,color:Un,background:x.inputBg}})})})}function sj({setAnchors:n,dragRef:a}){return v.useEffect(()=>{const l=d=>{const f=a.current;f&&n(h=>h.map(p=>p.id===f.id?{...p,x:Math.max(0,d.clientX-f.ox),y:Math.max(0,d.clientY-f.oy)}:p))},r=()=>{a.current=null};return window.addEventListener("mousemove",l),window.addEventListener("mouseup",r),()=>{window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",r)}},[a,n]),null}function Fy(){const n=[];return document.querySelectorAll("video").forEach(r=>{r.duration>0&&!isNaN(r.duration)&&n.push({element:r,type:"video",currentTime:r.currentTime,duration:r.duration,title:document.title})}),document.querySelectorAll("audio").forEach(r=>{r.duration>0&&!isNaN(r.duration)&&n.push({element:r,type:"audio",currentTime:r.currentTime,duration:r.duration,title:document.title})}),n}function qy(n){const a=Math.floor(n/3600),l=Math.floor(n%3600/60),r=Math.floor(n%60);return a>0?`${a}:${String(l).padStart(2,"0")}:${String(r).padStart(2,"0")}`:`${l}:${String(r).padStart(2,"0")}`}function lj(n){const a=Fy();a.length>0&&(a[0].element.currentTime=n,a[0].element.play().catch(()=>{}))}const Ls=[{bg:"#ede9fe",header:"#ddd6fe"},{bg:"#fef9c3",header:"#fef08a"},{bg:"#fce7f3",header:"#fbcfe8"},{bg:"#dcfce7",header:"#bbf7d0"},{bg:"#dbeafe",header:"#bfdbfe"},{bg:"#ffedd5",header:"#fed7aa"}];function rj(n){return Ls.find(a=>a.bg===n)??Ls[0]}function Bc(n,a){const l=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),d=parseInt(n.slice(5,7),16);return`rgba(${l},${r},${d},${a})`}const oj=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8.21 13c2.106 0 3.412-1.087 3.412-2.823 0-1.306-.984-2.283-2.324-2.386v-.055a2.176 2.176 0 0 0 1.852-2.14c0-1.51-1.162-2.46-3.014-2.46H3.843V13H8.21zM5.908 4.674h1.696c.963 0 1.517.451 1.517 1.244 0 .834-.629 1.32-1.73 1.32H5.908V4.674zm0 6.788V8.598h1.73c1.217 0 1.88.492 1.88 1.415 0 .943-.643 1.449-1.832 1.449H5.907z"})}),uj=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M7.991 11.674 9.53 4.455c.123-.595.246-.71 1.347-.807l.11-.52H7.211l-.11.52c1.06.096 1.128.212 1.005.807L6.57 11.674c-.123.595-.246.71-1.346.806l-.11.52h3.774l.11-.52c-1.06-.095-1.129-.211-1.006-.806z"})}),cj=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-8a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"})}),dj=()=>u.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M8 5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm4 3a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM5.5 7a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm.25 2.9a2.5 2.5 0 0 1 3.5 0 .5.5 0 0 0 .5.1 2 2 0 0 0 1.834-2.165 8 8 0 1 0-11.996.946 8 8 0 0 0 .914.48A2 2 0 0 0 2 9.5a2 2 0 0 0 3.75-.6z"})});function Nc({children:n,onClick:a}){const[l,r]=v.useState(!1);return u.jsx("button",{type:"button",onMouseDown:d=>{d.preventDefault(),a()},onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:5,background:l?"rgba(0,0,0,0.08)":"transparent",color:"#374151",cursor:"pointer"},children:n})}function fj({note:n,onUpdate:a,onDelete:l}){const[r,d]=v.useState(!1),[f,h]=v.useState(!1),[p,y]=v.useState(n.title??"Note"),[g,b]=v.useState(!1),w=v.useRef({x:0,y:0}),A=v.useRef(null),j=v.useRef(null),k=rj(n.color),D=v.useCallback(H=>{H.preventDefault(),d(!0),w.current={x:H.clientX-n.x,y:H.clientY-n.y},H.target.setPointerCapture(H.pointerId)},[n.x,n.y]),O=v.useCallback(H=>{r&&a(n.id,{x:H.clientX-w.current.x,y:H.clientY-w.current.y})},[r,n.id,a]),q=v.useCallback(()=>d(!1),[]),W=v.useCallback(H=>{H.preventDefault(),H.stopPropagation();const J=H.clientX,$=H.clientY,F=n.width,K=n.height,lt=rt=>a(n.id,{width:Math.max(200,F+rt.clientX-J),height:Math.max(140,K+rt.clientY-$)}),it=()=>{window.removeEventListener("mousemove",lt),window.removeEventListener("mouseup",it)};window.addEventListener("mousemove",lt),window.addEventListener("mouseup",it)},[n.id,n.width,n.height,a]),E=v.useCallback(()=>{A.current&&a(n.id,{content:A.current.innerHTML})},[n.id,a]);v.useEffect(()=>{A.current&&A.current.innerHTML!==n.content&&(A.current.innerHTML=n.content||""),!n.content&&Date.now()-n.createdAt<1e3&&A.current?.focus()},[]),v.useEffect(()=>{y(n.title??"Note")},[n.title]),v.useEffect(()=>{f&&j.current?.select()},[f]);function T(){const H=p.trim()||"Note";y(H),a(n.id,{title:H}),h(!1)}function L(H){A.current?.focus(),document.execCommand(H,!1,void 0),A.current&&a(n.id,{content:A.current.innerHTML})}return u.jsxs("div",{className:"sticky-note",style:{position:"fixed",left:n.x,top:n.y,width:n.width,height:n.height,zIndex:r?2147483647:2147483646,background:Bc(k.bg,.82),backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",borderColor:k.header},children:[u.jsxs("div",{className:"sticky-note-header",onPointerDown:D,onPointerMove:O,onPointerUp:q,style:{background:Bc(k.header,.9),cursor:r?"grabbing":"grab"},children:[u.jsx("span",{className:"sticky-drag-handle",children:"⠿"}),f?u.jsx("input",{ref:j,value:p,onChange:H=>y(H.target.value),onBlur:T,onKeyDown:H=>{(H.key==="Enter"||H.key==="Escape")&&T()},onPointerDown:H=>H.stopPropagation(),style:{flex:1,border:"none",background:"transparent",outline:"none",fontSize:12,fontWeight:500,color:"#1c1e26",fontFamily:"'Geist', ui-sans-serif, system-ui, sans-serif"}}):u.jsx("span",{className:"sticky-note-title",onDoubleClick:H=>{H.stopPropagation(),h(!0)},"aria-label":"Double-click to rename",children:n.title??"Note"}),n.mediaTimestamp!=null&&u.jsxs("button",{type:"button",onMouseDown:H=>{H.preventDefault(),H.stopPropagation(),lj(n.mediaTimestamp)},"aria-label":`Jump to ${qy(n.mediaTimestamp)}`,style:{display:"inline-flex",alignItems:"center",gap:3,padding:"2px 8px",border:"none",borderRadius:10,background:"rgba(99,102,241,0.15)",color:"#4f46e5",fontSize:10,fontWeight:700,cursor:"pointer",fontFamily:"'Geist', ui-sans-serif, system-ui, sans-serif",lineHeight:1,whiteSpace:"nowrap"},children:[u.jsx("svg",{width:"8",height:"8",viewBox:"0 0 16 16",fill:"currentColor",children:u.jsx("path",{d:"M6.271 5.055a.5.5 0 0 1 .52.038l3.5 2.5a.5.5 0 0 1 0 .814l-3.5 2.5A.5.5 0 0 1 6 10.5v-5a.5.5 0 0 1 .271-.445z"})}),qy(n.mediaTimestamp)]}),u.jsx("button",{type:"button",onMouseDown:H=>{H.preventDefault(),H.stopPropagation(),b(J=>!J)},className:"sticky-palette-btn","aria-label":"Change color",children:u.jsx(dj,{})}),u.jsx("span",{className:"sticky-dot",style:{background:"#6366f1"}}),u.jsx("button",{className:"sticky-note-delete",onClick:()=>l(n.id),"aria-label":"Delete",children:"×"})]}),g&&u.jsx("div",{style:{display:"flex",gap:6,padding:"6px 10px",background:Bc(k.header,.7),borderBottom:`1px solid ${k.header}`},children:Ls.map(H=>u.jsx("button",{type:"button",onMouseDown:J=>{J.preventDefault(),J.stopPropagation(),a(n.id,{color:H.bg}),b(!1)},style:{width:20,height:20,borderRadius:"50%",border:n.color===H.bg?"2px solid #6366f1":"2px solid rgba(0,0,0,0.1)",background:H.bg,cursor:"pointer"}},H.bg))}),u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",background:"rgba(255,255,255,0.65)",borderBottom:`1px solid ${k.header}`},children:[u.jsx(Nc,{onClick:()=>L("bold"),children:u.jsx(oj,{})}),u.jsx(Nc,{onClick:()=>L("italic"),children:u.jsx(uj,{})}),u.jsx(Nc,{onClick:()=>L("insertUnorderedList"),children:u.jsx(cj,{})})]}),u.jsx("div",{ref:A,className:"sticky-note-body",contentEditable:!0,suppressContentEditableWarning:!0,onInput:E,"data-placeholder":"Start typing…",style:{background:"rgba(255,255,255,0.55)"}}),u.jsx("div",{className:"sticky-resize",onMouseDown:W,children:u.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"rgba(0,0,0,0.3)",children:[u.jsx("path",{d:"M8 2L2 8M5 2L2 5M8 5L5 8"}),u.jsx("path",{d:"M8 2L2 8",strokeWidth:"1",stroke:"rgba(0,0,0,0.3)",fill:"none"}),u.jsx("path",{d:"M10 4L4 10M10 7L7 10",strokeWidth:"1.2",stroke:"rgba(0,0,0,0.25)",fill:"none"})]})})]})}function hj(){return crypto.randomUUID()}const _c=window.location.href,pj=500,mj=(()=>{let n=0;return()=>{const a=Ls[n%Ls.length].bg;return n++,a}})(),Xy=v.createContext(null);function gj(){const n=v.useContext(Xy);if(!n)return null;const{notes:a,notesVisible:l,handleUpdateNote:r,handleDeleteNote:d}=n;return u.jsx(u.Fragment,{children:l&&a.map(f=>u.jsx(fj,{note:f,onUpdate:r,onDelete:d},f.id))})}function yj(){const[n,a]=v.useState(!1);return v.useEffect(()=>{const l=r=>{const d=r.detail;a(d.hidden)};return document.addEventListener("inline:hideAll",l),()=>document.removeEventListener("inline:hideAll",l)},[]),n}function xj({children:n}){const[a,l]=v.useState([]),[r,d]=v.useState(!1),[f,h]=v.useState(!0),p=v.useRef(null);v.useEffect(()=>{if(!chrome.runtime?.id){d(!0);return}chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:_c}},A=>{chrome.runtime.lastError?console.error("[Inline] Load failed:",chrome.runtime.lastError.message):A?.ok&&Array.isArray(A.data?.elements?.stickyNotes)&&l(A.data.elements.stickyNotes),d(!0)})},[]),v.useEffect(()=>{if(r)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:_c,featureKey:"stickyNotes",data:a}},A=>{if(chrome.runtime.lastError){console.error("[Inline] Message failed:",chrome.runtime.lastError.message);return}if(Ta(A),!A?.ok){const j=String(A?.error??"");if(A?.queued||/queued|offline|unreachable/i.test(j))return;console.error("[Inline] Backend sync failed:",A?.error)}})},pj),()=>{p.current&&clearTimeout(p.current)}},[a,r]);const y=v.useCallback(()=>{const A=Date.now(),k=Fy().find(O=>!O.element.paused),D=k?k.currentTime:void 0;l(O=>{const q=O.length*18;return[...O,{id:hj(),pageUrl:_c,x:Math.min(window.innerWidth-260,window.innerWidth/2-120+q),y:Math.min(window.innerHeight-220,window.innerHeight/2-100+q),width:240,height:190,content:"",color:mj(),title:"Note",createdAt:A,updatedAt:A,...D!==void 0&&{mediaTimestamp:D}}]})},[]),g=v.useCallback((A,j)=>l(k=>k.map(D=>D.id===A?{...D,...j,updatedAt:Date.now()}:D)),[]),b=v.useCallback(A=>l(j=>j.filter(k=>k.id!==A)),[]),w={notes:a,notesVisible:f,setNotesVisible:h,handleAddNote:y,handleUpdateNote:g,handleDeleteNote:b};return u.jsx(Xy.Provider,{value:w,children:n})}function bj(){return yj()?null:u.jsx(u.Fragment,{children:u.jsx(gj,{})})}function vj(){return u.jsx(xj,{children:u.jsx(bj,{})})}const gr="inlinePrivacyAccepted";function Py(){return new Promise(n=>{if(!chrome.runtime?.id){n(!0);return}chrome.storage.local.get([gr],a=>{n(a[gr]==="true"||a[gr]===!0)})})}function Sj(){return new Promise((n,a)=>{if(!chrome.runtime?.id){n();return}chrome.storage.local.set({[gr]:"true"},()=>{if(chrome.runtime.lastError){a(new Error(chrome.runtime.lastError.message));return}n()})})}function wj(){const[n,a]=v.useState(!1),[l,r]=v.useState(!1);v.useEffect(()=>{Py().then(f=>{r(f),a(!0)})},[]);const d=v.useCallback(()=>{r(!0),Sj().catch(()=>{r(!1)})},[]);return{ready:n,accepted:l,accept:d}}function Aj(){yn().then(n=>{window.open(`${n.apiBaseUrl}/privacy`,"_blank")}).catch(()=>{window.open(`${ac}/privacy`,"_blank")})}function Tj(){const{ready:n,accepted:a,accept:l}=wj();return v.useEffect(()=>{a&&document.dispatchEvent(new CustomEvent("inline:privacyAccepted"))},[a]),v.useEffect(()=>{if(!a)return;const r=window.setTimeout(()=>{lT(),sy(),hy(),G5(),_y()},800);return()=>window.clearTimeout(r)},[a]),n?a?u.jsxs(u.Fragment,{children:[u.jsx(ij,{}),u.jsx(vj,{}),u.jsx(OE,{})]}):u.jsx(w5,{onAccept:l,onPrivacyPolicy:Aj}):null}const Uc="inline-reader-style";function Ky(){if(document.getElementById(Uc))return;const n=document.createElement("style");n.id=Uc,n.textContent=` body > *:not(#inline-extension-root):not(main):not(article):not([role="main"]) { display: none !important; } @@ -76,14 +153,14 @@ ${a}`;return await d.prompt(f.slice(0,8e3))}catch{return null}}async function uE body { background: #F5EBE3 !important; } - `,document.head.appendChild(i)}function VE(){document.getElementById(kc)?.remove()}const zy="inline-layer-visibility-style",Ly="[data-inline-highlight]",Oy={drawings:["#inline-draw-canvas","#inline-handwriting-canvas"],stickies:["[data-inline-sticky]","[data-inline-anchor]"],stamps:["[data-inline-stamp]"]};function UE(){if(document.getElementById(zy))return;const i=document.createElement("style");i.id=zy,i.textContent=` - html[data-inline-hide-highlights] ${Ly} { + `,document.head.appendChild(n)}function Ej(){document.getElementById(Uc)?.remove()}const Wy="inline-layer-visibility-style",Qy="[data-inline-highlight]",Zy={drawings:["#inline-draw-canvas","#inline-handwriting-canvas"],stickies:["[data-inline-sticky]","[data-inline-anchor]"],stamps:["[data-inline-stamp]"]};function jj(){if(document.getElementById(Wy))return;const n=document.createElement("style");n.id=Wy,n.textContent=` + html[data-inline-hide-highlights] ${Qy} { background-color: transparent !important; border-radius: 0 !important; padding: 0 !important; } - `,document.head.appendChild(i)}function By(i){UE(),document.querySelectorAll(Ly).forEach(a=>{a.style.removeProperty("display")}),i?document.documentElement.removeAttribute("data-inline-hide-highlights"):document.documentElement.setAttribute("data-inline-hide-highlights","")}function HE(i){By(i.highlights),Object.keys(Oy).forEach(a=>{const l=i[a];for(const r of Oy[a])document.querySelectorAll(r).forEach(d=>{d.style.display=l?"":"none"})})}const IE=".sticky-note{display:flex;flex-direction:column;border-radius:12px;overflow:hidden;border:1px solid rgba(17,24,39,.12);font-family:Geist,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;-webkit-user-select:none;user-select:none;transition:border-color .15s,transform .1s;box-shadow:none}.sticky-note:hover{border-color:#11182733;box-shadow:none}.sticky-note-header{display:flex;align-items:center;gap:6px;padding:8px 10px 7px;border-bottom:1px solid rgba(17,24,39,.08);touch-action:none;flex-shrink:0}.sticky-drag-handle{font-size:11px;color:#78716c66;letter-spacing:1px;pointer-events:none;flex-shrink:0}.sticky-note-title{flex:1;font-size:12px;font-weight:700;color:#1c1e26;pointer-events:auto;cursor:pointer;-webkit-user-select:none;user-select:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.sticky-palette-btn{all:unset;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:6px;color:#78716c8c;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-palette-btn:hover{background:#0000000f;color:#57534e}.sticky-dot{display:flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;font-size:14px;font-weight:300;color:#78716c73;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-note-delete{all:unset;display:flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;font-size:16px;font-weight:400;color:#78716c80;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-note-delete:hover{background:#ef44441f;color:#ef4444}.sticky-note-body{flex:1;padding:10px 12px;font-size:12.5px;line-height:1.7;color:#1c1e26;overflow-y:auto;cursor:text;-webkit-user-select:text;user-select:text;word-break:break-word;outline:none}.sticky-note-body:empty:before{content:attr(data-placeholder);color:#0003;font-style:italic;pointer-events:none}.sticky-note-body b,.sticky-note-body strong{font-weight:700}.sticky-note-body ul,.sticky-note-body ol{margin:2px 0;padding-left:18px}.sticky-note-body li{margin-bottom:2px}.sticky-resize{position:absolute;right:2px;bottom:2px;width:14px;height:14px;cursor:nwse-resize;display:flex;align-items:center;justify-content:center;-webkit-user-select:none;user-select:none;flex-shrink:0;background:transparent;opacity:.3;transition:opacity .1s}.sticky-note:hover .sticky-resize{opacity:.6}.add-note-launcher{position:fixed;right:20px;bottom:20px;display:flex;flex-direction:column;align-items:center;gap:10px;z-index:2147483647;pointer-events:auto}.launcher-eye{all:unset;display:flex;align-items:center;justify-content:center;width:42px;height:42px;border-radius:50%;background:#fff;color:#5d6470;border:1px solid rgba(17,24,39,.12);cursor:pointer;transition:background .15s,color .15s,border-color .15s;box-shadow:none}.launcher-eye:hover{background:#fafafa;color:#1c1e26;border-color:#11182733;box-shadow:none}.launcher-add{all:unset;display:flex;align-items:center;justify-content:center;box-sizing:border-box;min-width:48px;height:48px;border-radius:9999px;background:#111318;color:#fff;cursor:pointer;transition:background .15s,width .2s ease;box-shadow:none;font-family:Geist,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.launcher-add:hover{background:#13244d;box-shadow:none}.launcher-add:active{background:#111318}.inline-toolbar,.inline-anchor,.inline-modal-backdrop,.inline-context-menu{pointer-events:auto}[data-inline-citation]{border-left:4px solid #1C1E26;padding:8px 16px;margin:8px 0;background:#fdfbf7f2;border-radius:0 8px 8px 0;font-style:normal;line-height:1.6}[data-inline-citation] .inline-cite-attr{display:block;font-size:10px;color:#78716c;margin-top:6px;font-style:italic}";(async()=>{const i=await new Promise(y=>chrome.storage.local.get(["inlineBlockedDomains","inlineFocusMode"],g=>y(g)));let a=[];try{const y=i.inlineBlockedDomains;typeof y=="string"&&(a=JSON.parse(y))}catch{}const l=window.location.hostname;if(Array.isArray(a)&&a.some(y=>l===y||l.endsWith(`.${y}`)))return;const r=i.inlineFocusMode==="true"||i.inlineFocusMode===!0;r&&Dy();let d=await Ry(),f=!1;const h="inline-extension-root";if(!document.getElementById(h)){const y=document.createElement("div");y.id=h,y.style.cssText="position:fixed; top:0; left:0; width:0; height:0; z-index:2147483647; pointer-events:none;",r&&(y.dataset.inlineFocus="true"),document.body.appendChild(y);const g=y.attachShadow({mode:"open"}),b=document.createElement("style");b.textContent=BA+` -`+IE,g.appendChild(b);const S=document.createElement("div");S.id="inline-mount",S.style.cssText="position:fixed; top:0; left:0; width:100vw; height:100vh; pointer-events:none;",g.appendChild(S);const A=document.createElement("style");A.textContent=` + `,document.head.appendChild(n)}function $y(n){jj(),document.querySelectorAll(Qy).forEach(a=>{a.style.removeProperty("display")}),n?document.documentElement.removeAttribute("data-inline-hide-highlights"):document.documentElement.setAttribute("data-inline-hide-highlights","")}function Cj(n){$y(n.highlights),Object.keys(Zy).forEach(a=>{const l=n[a];for(const r of Zy[a])document.querySelectorAll(r).forEach(d=>{d.style.display=l?"":"none"})})}const Mj=".sticky-note{display:flex;flex-direction:column;border-radius:12px;overflow:hidden;border:1px solid rgba(17,24,39,.12);font-family:Geist,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;-webkit-user-select:none;user-select:none;transition:border-color .15s,transform .1s;box-shadow:none}.sticky-note:hover{border-color:#11182733;box-shadow:none}.sticky-note-header{display:flex;align-items:center;gap:6px;padding:8px 10px 7px;border-bottom:1px solid rgba(17,24,39,.08);touch-action:none;flex-shrink:0}.sticky-drag-handle{font-size:11px;color:#78716c66;letter-spacing:1px;pointer-events:none;flex-shrink:0}.sticky-note-title{flex:1;font-size:12px;font-weight:700;color:#1c1e26;pointer-events:auto;cursor:pointer;-webkit-user-select:none;user-select:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.sticky-palette-btn{all:unset;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:6px;color:#78716c8c;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-palette-btn:hover{background:#0000000f;color:#57534e}.sticky-dot{display:flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;font-size:14px;font-weight:300;color:#78716c73;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-note-delete{all:unset;display:flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;font-size:16px;font-weight:400;color:#78716c80;cursor:pointer;flex-shrink:0;transition:background .1s,color .1s}.sticky-note-delete:hover{background:#ef44441f;color:#ef4444}.sticky-note-body{flex:1;padding:10px 12px;font-size:12.5px;line-height:1.7;color:#1c1e26;overflow-y:auto;cursor:text;-webkit-user-select:text;user-select:text;word-break:break-word;outline:none}.sticky-note-body:empty:before{content:attr(data-placeholder);color:#0003;font-style:italic;pointer-events:none}.sticky-note-body b,.sticky-note-body strong{font-weight:700}.sticky-note-body ul,.sticky-note-body ol{margin:2px 0;padding-left:18px}.sticky-note-body li{margin-bottom:2px}.sticky-resize{position:absolute;right:2px;bottom:2px;width:14px;height:14px;cursor:nwse-resize;display:flex;align-items:center;justify-content:center;-webkit-user-select:none;user-select:none;flex-shrink:0;background:transparent;opacity:.3;transition:opacity .1s}.sticky-note:hover .sticky-resize{opacity:.6}.add-note-launcher{position:fixed;right:20px;bottom:20px;display:flex;flex-direction:column;align-items:center;gap:10px;z-index:2147483647;pointer-events:auto}.launcher-eye{all:unset;display:flex;align-items:center;justify-content:center;width:42px;height:42px;border-radius:50%;background:#fff;color:#5d6470;border:1px solid rgba(17,24,39,.12);cursor:pointer;transition:background .15s,color .15s,border-color .15s;box-shadow:none}.launcher-eye:hover{background:#fafafa;color:#1c1e26;border-color:#11182733;box-shadow:none}.launcher-add{all:unset;display:flex;align-items:center;justify-content:center;box-sizing:border-box;min-width:48px;height:48px;border-radius:9999px;background:#111318;color:#fff;cursor:pointer;transition:background .15s,width .2s ease;box-shadow:none;font-family:Geist,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.launcher-add:hover{background:#13244d;box-shadow:none}.launcher-add:active{background:#111318}.inline-toolbar,.inline-anchor,.inline-modal-backdrop,.inline-context-menu{pointer-events:auto}[data-inline-citation]{border-left:4px solid #1C1E26;padding:8px 16px;margin:8px 0;background:#fdfbf7f2;border-radius:0 8px 8px 0;font-style:normal;line-height:1.6}[data-inline-citation] .inline-cite-attr{display:block;font-size:10px;color:#78716c;margin-top:6px;font-style:italic}",Jy="inline-extension-root";let Hc=null;function kj(){return document.body?Promise.resolve(document.body):new Promise(n=>{const a=()=>{document.body&&(l.disconnect(),n(document.body))},l=new MutationObserver(a);l.observe(document.documentElement,{childList:!0,subtree:!0}),a()})}function Rj(n){const a=n.getElementById("inline-mount"),l=document.createElement("div");return l.id="inline-mount",l.style.cssText="position:fixed; top:0; left:0; width:100vw; height:100vh; pointer-events:none;",a?a.replaceWith(l):n.appendChild(l),l}function Dj(n){let a=document.getElementById(Jy);if(a&&!a.shadowRoot&&(a.remove(),a=null),!a){a=document.createElement("div"),a.id=Jy,a.style.cssText="position:fixed; top:0; left:0; width:0; height:0; z-index:2147483647; pointer-events:none;",n&&(a.dataset.inlineFocus="true");const r=a.attachShadow({mode:"open"}),d=document.createElement("style");d.textContent=JA+` +`+Mj,r.appendChild(d);const f=document.createElement("style");f.textContent=` .sticky-note, .add-note-button, .add-note-launcher, .add-note-launcher *, .launcher-eye, .launcher-add, @@ -95,4 +172,4 @@ ${a}`;return await d.prompt(f.slice(0,8e3))}catch{return null}}async function uE } *::-webkit-scrollbar { display: none; } * { scrollbar-width: none; } - `,g.appendChild(A);const j=document.createElement("div");j.id="inline-offline-badge",j.textContent="Offline",j.style.cssText=["position:fixed","bottom:72px","right:24px","padding:4px 12px","border-radius:9999px","background:#ef4444","color:#fff","font:500 12px/1.4 Geist,ui-sans-serif,system-ui,sans-serif","pointer-events:none","display:none","z-index:2147483647"].join(";"),g.appendChild(j);const k=()=>{j.style.display="block"},D=()=>{j.style.display="none"};window.addEventListener("offline",k),window.addEventListener("online",D),navigator.onLine||k(),Ib.createRoot(S).render(u.jsx(_E,{}))}function p(){if(!d||f)return;f=!0,chrome.runtime.onMessage.addListener(T=>{if(T.action==="addNote"&&document.dispatchEvent(new CustomEvent("inline:addNote")),T.type==="INLINE_COMMAND"&&document.dispatchEvent(new CustomEvent("inline:command",{detail:{command:T.command}})),T.type==="INLINE_FEATURE"&&T.featureId==="clip-to-workspace"){const L=T.selectedText?.trim()??"";if(!L)return;try{chrome.storage.local.get(["inlineActiveWorkspaceId"],U=>{const $=typeof U.inlineActiveWorkspaceId=="string"?U.inlineActiveWorkspaceId:"";chrome.runtime.sendMessage({type:"CLIP_TO_WORKSPACE",payload:{pageUrl:window.location.href,pageTitle:document.title,selection:L,highlights:[],workspaceId:$}},()=>{chrome.runtime.lastError})})}catch{}}});let y=null;function g(T){y=T,HE(T)}Jg().then(g).catch(()=>{}),document.addEventListener("inline:layerToggle",(T=>{T.detail&&g(T.detail)})),document.addEventListener("inline:highlightsRestored",b),document.addEventListener("inline:highlightAdded",b);function b(){y&&By(y.highlights)}let S=null,A=[],j=!1;function k(){return`st-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function D(T){if(document.querySelector(`[data-inline-stamp-id="${T.id}"]`))return;const L=document.createElement("div");L.setAttribute("data-inline-stamp","true"),L.setAttribute("data-inline-stamp-id",T.id),L.textContent=T.emoji,L.style.cssText=["position:absolute",`left:${T.x}px`,`top:${T.y}px`,"font-size:24px","line-height:1","pointer-events:none","z-index:2147483640","user-select:none","transform:translate(-50%,-50%)"].join(";"),document.body.appendChild(L)}function O(){chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"stamps",data:A,pageTitle:document.title,domain:window.location.hostname,clearedAt:A.length===0?Date.now():null}},()=>{chrome.runtime.lastError})}chrome.runtime?.id?chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},T=>{if(j=!0,chrome.runtime.lastError||!T?.ok)return;const L=T.data?.elements?.stamps;if(Array.isArray(L)){A=L;for(const U of A)D(U)}}):j=!0,document.addEventListener("inline:stampPlace",(T=>{S=T.detail?.emoji??null,document.body.style.cursor="crosshair"}));let F=!1;chrome.storage.local.get(["inlineScreenReader"],T=>{F=T.inlineScreenReader==="true"||T.inlineScreenReader===!0}),document.addEventListener("inline:screenReader",(T=>{F=!!T.detail?.enabled,F||Ss()}));function Q(){const T=window.getSelection()?.toString().trim();if(T)return T;const L=document.activeElement;if(L){if("value"in L&&typeof L.value=="string")return L.value.trim();const U=(L.innerText??L.textContent??"").trim();if(U)return U.slice(0,600)}return""}function E(){if(!F)return;const T=Q();T&&Jl(T)}document.addEventListener("keydown",T=>{F&&(T.altKey&&T.shiftKey&&(T.key==="S"||T.key==="s")&&(T.preventDefault(),E()),T.key==="Escape"&&Ss())}),document.addEventListener("inline:speakSelection",()=>{E()}),document.addEventListener("inline:stopSpeaking",()=>{Ss()}),document.addEventListener("click",T=>{if(!S||T.target?.closest?.("#inline-extension-root"))return;const U=T.pageX,$=T.pageY,tt={id:k(),emoji:S,x:U,y:$,createdAt:Date.now()};A=[...A,tt],D(tt),S=null,document.body.style.cursor="",j&&O(),document.dispatchEvent(new CustomEvent("inline:stampPlaced",{detail:tt}))},!0)}document.addEventListener("inline:privacyAccepted",()=>{d=!0,p()}),d&&p(),document.addEventListener("inline:focusMode",(y=>{const g=document.getElementById("inline-extension-root");g&&(y.detail.enabled?(g.dataset.inlineFocus="true",Dy()):(delete g.dataset.inlineFocus,VE()))})),document.addEventListener("inline:saveResult",(y=>{const g=document.getElementById("inline-extension-root")?.shadowRoot?.getElementById("inline-offline-badge");if(!g)return;const b=y.detail?.error??"";/offline|queued/i.test(b)&&(g.style.display="block")}))})()})(); + `,r.appendChild(f);const h=document.createElement("div");h.id="inline-offline-badge",h.textContent="Offline",h.style.cssText=["position:fixed","bottom:72px","right:24px","padding:4px 12px","border-radius:9999px","background:#ef4444","color:#fff","font:500 12px/1.4 Geist,ui-sans-serif,system-ui,sans-serif","pointer-events:none","display:none","z-index:2147483647"].join(";"),r.appendChild(h);const p=()=>{h.style.display="block"},y=()=>{h.style.display="none"};window.addEventListener("offline",p),window.addEventListener("online",y),navigator.onLine||p(),document.body.appendChild(a)}const l=Rj(a.shadowRoot);try{Hc?.unmount()}catch{}Hc=sv.createRoot(l),Hc.render(u.jsx(Tj,{}))}(async()=>{if(!chrome.runtime?.id||!await kj().catch(()=>null))return;const a=await new Promise(y=>chrome.storage.local.get(["inlineBlockedDomains","inlineFocusMode"],g=>y(g)));let l=[];try{const y=a.inlineBlockedDomains;typeof y=="string"&&(l=JSON.parse(y))}catch{}const r=window.location.hostname;if(Array.isArray(l)&&l.some(y=>r===y||r.endsWith(`.${y}`)))return;const d=a.inlineFocusMode==="true"||a.inlineFocusMode===!0;d&&Ky();let f=await Py(),h=!1;Dj(d);function p(){if(!f||h)return;h=!0,chrome.runtime.onMessage.addListener(T=>{if(T.action==="addNote"&&document.dispatchEvent(new CustomEvent("inline:addNote")),T.type==="INLINE_COMMAND"&&document.dispatchEvent(new CustomEvent("inline:command",{detail:{command:T.command}})),T.type==="INLINE_FEATURE"&&T.featureId==="clip-to-workspace"){const L=T.selectedText?.trim()??"";if(!L)return;try{chrome.storage.local.get(["inlineActiveWorkspaceId"],H=>{const J=typeof H.inlineActiveWorkspaceId=="string"?H.inlineActiveWorkspaceId:"";chrome.runtime.sendMessage({type:"CLIP_TO_WORKSPACE",payload:{pageUrl:window.location.href,pageTitle:document.title,selection:L,highlights:[],workspaceId:J}},()=>{chrome.runtime.lastError})})}catch{}}});let y=null;function g(T){y=T,Cj(T)}uy().then(g).catch(()=>{}),document.addEventListener("inline:layerToggle",(T=>{T.detail&&g(T.detail)})),document.addEventListener("inline:highlightsRestored",b),document.addEventListener("inline:highlightAdded",b);function b(){y&&$y(y.highlights)}let w=null,A=[],j=!1;function k(){return`st-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function D(T){if(document.querySelector(`[data-inline-stamp-id="${T.id}"]`))return;const L=document.createElement("div");L.setAttribute("data-inline-stamp","true"),L.setAttribute("data-inline-stamp-id",T.id),L.textContent=T.emoji,L.style.cssText=["position:absolute",`left:${T.x}px`,`top:${T.y}px`,"font-size:24px","line-height:1","pointer-events:none","z-index:2147483640","user-select:none","transform:translate(-50%,-50%)"].join(";"),document.body.appendChild(L)}function O(){chrome.runtime?.id&&chrome.runtime.sendMessage({type:"SAVE_ANNOTATIONS",payload:{pageUrl:window.location.href,featureKey:"stamps",data:A,pageTitle:document.title,domain:window.location.hostname,clearedAt:A.length===0?Date.now():null}},()=>{chrome.runtime.lastError})}chrome.runtime?.id?chrome.runtime.sendMessage({type:"LOAD_ANNOTATIONS",payload:{pageUrl:window.location.href}},T=>{if(j=!0,chrome.runtime.lastError||!T?.ok)return;const L=T.data?.elements?.stamps;if(Array.isArray(L)){A=L;for(const H of A)D(H)}}):j=!0,document.addEventListener("inline:stampPlace",(T=>{w=T.detail?.emoji??null,document.body.style.cursor="crosshair"}));let q=!1;chrome.storage.local.get(["inlineScreenReader"],T=>{q=T.inlineScreenReader==="true"||T.inlineScreenReader===!0}),document.addEventListener("inline:screenReader",(T=>{q=!!T.detail?.enabled,q||Cs()}));function W(){const T=window.getSelection()?.toString().trim();if(T)return T;const L=document.activeElement;if(L){if("value"in L&&typeof L.value=="string")return L.value.trim();const H=(L.innerText??L.textContent??"").trim();if(H)return H.slice(0,600)}return""}function E(){if(!q)return;const T=W();T&&lr(T)}document.addEventListener("keydown",T=>{q&&(T.altKey&&T.shiftKey&&(T.key==="S"||T.key==="s")&&(T.preventDefault(),E()),T.key==="Escape"&&Cs())}),document.addEventListener("inline:speakSelection",()=>{E()}),document.addEventListener("inline:stopSpeaking",()=>{Cs()}),document.addEventListener("click",T=>{if(!w||T.target?.closest?.("#inline-extension-root"))return;const H=T.pageX,J=T.pageY,$={id:k(),emoji:w,x:H,y:J,createdAt:Date.now()};A=[...A,$],D($),w=null,document.body.style.cursor="",j&&O(),document.dispatchEvent(new CustomEvent("inline:stampPlaced",{detail:$}))},!0)}document.addEventListener("inline:privacyAccepted",()=>{f=!0,p()}),f&&p(),document.addEventListener("inline:focusMode",(y=>{const g=document.getElementById("inline-extension-root");g&&(y.detail.enabled?(g.dataset.inlineFocus="true",Ky()):(delete g.dataset.inlineFocus,Ej()))})),document.addEventListener("inline:saveResult",(y=>{const g=document.getElementById("inline-extension-root")?.shadowRoot?.getElementById("inline-offline-badge");if(!g)return;const b=y.detail?.error??"";/offline|queued/i.test(b)&&(g.style.display="block")}))})()})(); diff --git a/inlineExtension/dist/index.html b/inlineExtension/dist/index.html index 123020d..cc4df9d 100644 --- a/inlineExtension/dist/index.html +++ b/inlineExtension/dist/index.html @@ -1,14 +1,14 @@ - - - - - - - Inline - - - - -
- - + + + + + + + Inline + + + + +
+ + diff --git a/inlineExtension/eslint.config.js b/inlineExtension/eslint.config.js index 99459c9..7398b73 100644 --- a/inlineExtension/eslint.config.js +++ b/inlineExtension/eslint.config.js @@ -20,6 +20,8 @@ export default defineConfig([ globals: globals.browser, }, rules: { + // Utility modules export helpers alongside components by design. + 'react-refresh/only-export-components': 'warn', // React Compiler strictness rules flag mount-time restore patterns // (loading saved annotations into state) that are intentional here. 'react-hooks/set-state-in-effect': 'warn', diff --git a/inlineExtension/package-lock.json b/inlineExtension/package-lock.json index dfb17ca..2796433 100644 --- a/inlineExtension/package-lock.json +++ b/inlineExtension/package-lock.json @@ -25,7 +25,7 @@ "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.4.24", "globals": "^16.5.0", - "typescript": "^6.0.2", + "typescript": "~5.9.3", "typescript-eslint": "^8.48.0", "vite": "^7.3.1" } @@ -2974,9 +2974,9 @@ } }, "node_modules/typescript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", - "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/inlineExtension/package.json b/inlineExtension/package.json index e69d27e..de51ede 100644 --- a/inlineExtension/package.json +++ b/inlineExtension/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "vite", "build": "tsc -b && vite build && vite build --config vite.content.config.ts && vite build --config vite.background.config.ts", - "build:dev": "tsc -b && vite build --mode development && vite build --mode development --config vite.content.config.ts && vite build --mode development --config vite.background.config.ts", + "build:dev": "tsc -b && vite build --mode development && vite build --mode development --config vite.content.config.ts && vite build --mode development --config vite.background.config.ts && node -e \"require('fs').copyFileSync('manifest.dev.json','dist/manifest.json')\"", "lint": "eslint .", "preview": "vite preview" }, @@ -28,7 +28,7 @@ "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.4.24", "globals": "^16.5.0", - "typescript": "^6.0.2", + "typescript": "~5.9.3", "typescript-eslint": "^8.48.0", "vite": "^7.3.1" } diff --git a/inlineExtension/src/background/background.ts b/inlineExtension/src/background/background.ts index 1c06def..a60d2fa 100644 --- a/inlineExtension/src/background/background.ts +++ b/inlineExtension/src/background/background.ts @@ -3,9 +3,8 @@ * script, and proxies backend API calls for content scripts. */ -import { enqueue, getQueue, persistQueue } from '../lib/syncQueue' +import { enqueue } from '../lib/syncQueue' import { DEFAULT_INLINE_VOICE_ID, normalizeInlineVoiceId } from '../lib/inlineVoicePresets' -import { decryptJson, encryptJson, isEncryptedJson } from '../lib/localCrypto' import { DEFAULT_BACKEND_URL, DEFAULT_WEB_URL } from '../lib/inlineUrls' import { assertSecureTransport, isSecureTransportUrl, normalizeSecureBase } from '../lib/secureTransport' @@ -59,9 +58,10 @@ function asLocalAnnotationDoc(value: unknown, pageUrl: string): LocalAnnotationD return { pageUrl, pageTitle: '', domain: '', elements: {}, updatedAt: 0 } } const doc = value as Partial - const elements = doc.elements && typeof doc.elements === 'object' && !Array.isArray(doc.elements) - ? doc.elements as Record - : {} + const elements = + doc.elements && typeof doc.elements === 'object' && !Array.isArray(doc.elements) + ? (doc.elements as Record) + : {} return { pageUrl: typeof doc.pageUrl === 'string' ? doc.pageUrl : pageUrl, pageTitle: typeof doc.pageTitle === 'string' ? doc.pageTitle : '', @@ -75,18 +75,7 @@ function asLocalAnnotationDoc(value: unknown, pageUrl: string): LocalAnnotationD async function loadLocalAnnotations(pageUrl: string): Promise { const key = localAnnotationsKey(pageUrl) const stored = await chrome.storage.local.get(key) - if (isEncryptedJson(stored[key])) { - try { - return asLocalAnnotationDoc(await decryptJson(stored[key]), pageUrl) - } catch { - return asLocalAnnotationDoc(null, pageUrl) - } - } - const legacy = asLocalAnnotationDoc(stored[key], pageUrl) - if (stored[key]) { - await chrome.storage.local.set({ [key]: await encryptJson(legacy) }) - } - return legacy + return asLocalAnnotationDoc(stored[key], pageUrl) } async function saveLocalAnnotation(input: { @@ -107,10 +96,14 @@ async function saveLocalAnnotation(input: { updatedAt: Date.now(), clearedAt: input.clearedAt ?? current.clearedAt ?? null, } - await chrome.storage.local.set({ [key]: await encryptJson(next) }) + await chrome.storage.local.set({ [key]: next }) return next } +function canSyncToWorkspace(accessToken: string, workspaceId: string): boolean { + return isUsableJwt(accessToken) && !!workspaceId +} + function safeBaseFromStored(value: unknown, fallback: string): string { const raw = typeof value === 'string' && value ? value : fallback const base = raw.replace(/\/$/, '') @@ -130,8 +123,6 @@ function arrayBufferToBase64(buffer: ArrayBuffer): string { // ─── Context Menus ────────────────────────────────────────────────────────── chrome.runtime.onInstalled.addListener(() => { - chrome.alarms.create('inline-sync-retry', { periodInMinutes: 2 }) - chrome.contextMenus.removeAll(() => { chrome.contextMenus.create({ id: 'inline-analyze-risk', @@ -481,19 +472,20 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { const headers: Record = { 'Content-Type': 'application/json' } if (isUsableJwt(accessToken)) headers.Authorization = `Bearer ${accessToken}` - if (!isUsableJwt(accessToken) || !workspaceId) { + const saveInput = { pageUrl, featureKey, data, pageTitle, domain, clearedAt } + + if (!canSyncToWorkspace(accessToken, workspaceId)) { try { - const localDoc = await saveLocalAnnotation({ pageUrl, featureKey, data, pageTitle, domain, clearedAt }) + const localDoc = await saveLocalAnnotation(saveInput) sendResponse({ ok: true, data: localDoc, storageMode: 'local' }) - return + } catch { + sendResponse({ ok: false, storageMode: 'local', error: 'Browser storage is full.' }) } - catch { /* storage full - best-effort */ } - sendResponse({ ok: false, storageMode: 'local', error: 'Browser storage is full.' }) return } try { - await saveLocalAnnotation({ pageUrl, featureKey, data, pageTitle, domain, clearedAt }) + const localDoc = await saveLocalAnnotation(saveInput) const url = `${base}/api/annotations` assertSecureTransport(url) const res = await fetch(url, { @@ -512,8 +504,10 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { let json: unknown try { json = JSON.parse(text) as unknown } catch { sendResponse({ - ok: false, - error: 'Server did not return JSON (check API URL / is the app running?).', + ok: true, + data: localDoc, + storageMode: 'local', + warning: 'Server did not return JSON (saved in browser).', }) return } @@ -521,17 +515,33 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { const err = typeof json === 'object' && json !== null && 'error' in json ? String((json as { error?: string }).error) : `HTTP ${res.status}` - sendResponse({ ok: false, error: err }) + await enqueue({ pageUrl, featureKey, data, timestamp: Date.now() }).catch(() => {}) + sendResponse({ + ok: true, + data: localDoc, + storageMode: 'local', + warning: err, + }) return } sendResponse({ ok: true, data: json, storageMode: 'workspace' }) - } catch { + } catch (err) { try { - await saveLocalAnnotation({ pageUrl, featureKey, data, pageTitle, domain, clearedAt }) - await enqueue({ pageUrl, featureKey, data, timestamp: Date.now() }) + const localDoc = await saveLocalAnnotation(saveInput) + await enqueue({ pageUrl, featureKey, data, timestamp: Date.now() }).catch(() => {}) + sendResponse({ + ok: true, + data: localDoc, + storageMode: 'local', + warning: err instanceof Error ? err.message : 'Backend unreachable', + }) + } catch { + sendResponse({ + ok: false, + storageMode: 'local', + error: 'Browser storage is full.', + }) } - catch { /* storage full – best-effort */ } - sendResponse({ ok: false, queued: true, storageMode: 'local', error: 'Queued for retry (backend unreachable)' }) } }, ) @@ -542,13 +552,16 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'LOAD_ANNOTATIONS') { const { pageUrl } = message.payload; - void chrome.storage.local.get(['inlineBackendBase', 'inlineAccessToken'], async (r) => { + void chrome.storage.local.get( + ['inlineBackendBase', 'inlineAccessToken', 'inlineActiveWorkspaceId'], + async (r) => { const base = safeBaseFromStored(r.inlineBackendBase, BACKEND_URL) const accessToken = typeof r.inlineAccessToken === 'string' ? r.inlineAccessToken : '' + const workspaceId = typeof r.inlineActiveWorkspaceId === 'string' ? r.inlineActiveWorkspaceId : '' const headers: Record = {} if (isUsableJwt(accessToken)) headers.Authorization = `Bearer ${accessToken}` - if (!isUsableJwt(accessToken)) { + if (!canSyncToWorkspace(accessToken, workspaceId)) { const localDoc = await loadLocalAnnotations(pageUrl) sendResponse({ ok: true, data: localDoc, storageMode: 'local' }) return @@ -563,20 +576,45 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { try { json = JSON.parse(text) as unknown } catch { const localDoc = await loadLocalAnnotations(pageUrl) - sendResponse({ ok: true, data: localDoc, storageMode: 'local', warning: 'Using browser copy.' }) + sendResponse({ + ok: true, + data: localDoc, + storageMode: 'local', + warning: 'Using browser copy.', + }) return } if (!res.ok) { const localDoc = await loadLocalAnnotations(pageUrl) - sendResponse({ ok: true, data: localDoc, storageMode: 'local', warning: 'Using browser copy.' }) + sendResponse({ + ok: true, + data: localDoc, + storageMode: 'local', + warning: 'Using browser copy.', + }) return } - sendResponse({ ok: true, data: json }) + const serverJson = json as { elements?: Record } + const serverElements = + serverJson.elements && typeof serverJson.elements === 'object' && !Array.isArray(serverJson.elements) + ? serverJson.elements + : {} + sendResponse({ + ok: true, + data: { elements: serverElements }, + storageMode: 'workspace', + }) } catch (err) { const localDoc = await loadLocalAnnotations(pageUrl) - sendResponse({ ok: true, data: localDoc, storageMode: 'local', warning: err instanceof Error ? err.message : 'Using browser copy.' }) + sendResponse({ + ok: true, + data: localDoc, + storageMode: 'local', + warning: err instanceof Error ? err.message : 'Using browser copy.', + }) } - }) + }, + ) return true } }); @@ -590,49 +628,3 @@ chrome.commands.onCommand.addListener((command) => { chrome.tabs.sendMessage(tabId, { type: 'INLINE_COMMAND', command }) }) }) - -// ─── Offline Sync Retry ───────────────────────────────────────────────────── - -chrome.alarms.onAlarm.addListener(async (alarm) => { - if (alarm.name !== 'inline-sync-retry') return - - const queue = await getQueue() - if (queue.length === 0) return - - const stored = await chrome.storage.local.get([ - 'inlineBackendBase', 'inlineAccessToken', 'inlineActiveWorkspaceId', - ]) - const base = safeBaseFromStored(stored.inlineBackendBase, BACKEND_URL) - const accessToken = typeof stored.inlineAccessToken === 'string' ? stored.inlineAccessToken : '' - const workspaceId = typeof stored.inlineActiveWorkspaceId === 'string' ? stored.inlineActiveWorkspaceId : '' - - const headers: Record = { 'Content-Type': 'application/json' } - if (isUsableJwt(accessToken)) headers.Authorization = `Bearer ${accessToken}` - - const remaining = [...queue] - - for (let i = 0; i < remaining.length; i++) { - const item = remaining[i] - try { - const url = `${base}/api/annotations` - assertSecureTransport(url) - const res = await fetch(url, { - method: 'POST', - headers, - body: JSON.stringify({ - pageUrl: item.pageUrl, - featureKey: item.featureKey, - data: item.data, - workspaceId, - }), - }) - if (!res.ok) throw new Error(`HTTP ${res.status}`) - remaining.splice(i, 1) - i-- - } catch { - break - } - } - - await persistQueue(remaining) -}) diff --git a/inlineExtension/src/components/CropOverlay.tsx b/inlineExtension/src/components/CropOverlay.tsx index 3919c33..6d6f9e0 100644 --- a/inlineExtension/src/components/CropOverlay.tsx +++ b/inlineExtension/src/components/CropOverlay.tsx @@ -3,6 +3,7 @@ import { PANEL as C, FONT } from '../lib/extensionTheme' import { loadSettings } from '../lib/extensionSettings' import { fetchViaBackground } from '../lib/backgroundFetch' import { GUEST_AI_LIMIT, reserveAiPrompt } from '../lib/aiAccess' +import FormattedAiText from './FormattedAiText' interface CropOverlayProps { screenshot: string @@ -214,11 +215,8 @@ export default function CropOverlay({ screenshot, onClose }: CropOverlayProps) { -
- {result} +
+
+ {segments.map((seg, i) => { + switch (seg.type) { + case 'bold': + return {seg.value} + case 'italic': + return {seg.value} + case 'underline': + return {seg.value} + case 'code': + return ( + + {seg.value} + + ) + default: + return {seg.value} + } + })} + + ) } interface FormattedAiTextProps { @@ -13,7 +44,7 @@ interface FormattedAiTextProps { style?: CSSProperties } -/** Renders AI output with real list bullets instead of literal * characters. */ +/** Renders AI output with bullets, bold, italic, underline — no literal asterisks. */ export default function FormattedAiText({ text, style }: FormattedAiTextProps) { const base: CSSProperties = { fontSize: 14, @@ -22,69 +53,70 @@ export default function FormattedAiText({ text, style }: FormattedAiTextProps) { ...style, } - if (!text.trim()) return null - - const blocks = text.split(/\n\n+/) + const blocks = parseAiTextBlocks(text) + if (blocks.length === 0) return null return (
{blocks.map((block, blockIdx) => { - const trimmed = block.trim() - if (!trimmed) return null - - const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean) - const bulletLines = lines.filter(l => BULLET_RE.test(l)) - const numberedLines = lines.filter(l => NUMBER_RE.test(l)) - const proseLines = lines.filter(l => !BULLET_RE.test(l) && !NUMBER_RE.test(l)) const blockGap = blockIdx < blocks.length - 1 ? 12 : 0 + let node: ReactNode - if (bulletLines.length > 0) { - return ( -
- {proseLines.length > 0 && ( -

{proseLines.join(' ')}

- )} + switch (block.type) { + case 'bullet-list': + node = (
    - {bulletLines.map((line, j) => ( + {block.items.map((item, j) => (
  • - {stripMarker(line)} +
  • ))}
-
- ) - } - - if (numberedLines.length > 0) { - return ( -
- {proseLines.length > 0 && ( -

{proseLines.join(' ')}

- )} + ) + break + case 'numbered-list': + node = (
    - {numberedLines.map((line, j) => ( + {block.items.map((item, j) => (
  1. - {stripMarker(line)} +
  2. ))}
-
- ) + ) + break + case 'blockquote': + node = ( +
+ +
+ ) + break + default: + node = ( +

+ +

+ ) } return ( -

- {trimmed} -

+
+ {node} +
) })}
diff --git a/inlineExtension/src/components/Search.tsx b/inlineExtension/src/components/Search.tsx index 7990262..e2523ea 100644 --- a/inlineExtension/src/components/Search.tsx +++ b/inlineExtension/src/components/Search.tsx @@ -1,5 +1,6 @@ import { useState, useCallback, useRef, useEffect } from 'react' import { PANEL as C, FONT } from '../lib/extensionTheme' +import { stripMarkdownToPlainText } from '../lib/aiTextFormat' import { loadSettings } from '../lib/extensionSettings' import { fetchViaBackground } from '../lib/backgroundFetch' import { PanelShell, PanelLoading, PanelEmpty, Segmented } from './panelKit' @@ -109,13 +110,14 @@ export default function Search({ onClose }: SearchProps) { }, [query, runSearch]) const snippet = (text: string) => { + const plain = stripMarkdownToPlainText(text) const max = 120 - if (text.length <= max) return text - const lower = text.toLowerCase() + if (plain.length <= max) return plain + const lower = plain.toLowerCase() const idx = lower.indexOf(query.toLowerCase()) - if (idx < 0) return text.slice(0, max) + '...' + if (idx < 0) return plain.slice(0, max) + '...' const start = Math.max(0, idx - 40) - return (start > 0 ? '...' : '') + text.slice(start, start + max) + '...' + return (start > 0 ? '...' : '') + plain.slice(start, start + max) + '...' } return ( diff --git a/inlineExtension/src/components/panelKit.tsx b/inlineExtension/src/components/panelKit.tsx index a12da63..b7d5ef4 100644 --- a/inlineExtension/src/components/panelKit.tsx +++ b/inlineExtension/src/components/panelKit.tsx @@ -1,5 +1,6 @@ import { useEffect, useState, type ReactNode, type CSSProperties, type MouseEvent } from 'react' import { InlineChatBadge } from './InlineChatIcon' +import FormattedAiText from './FormattedAiText' import { ToolHeaderIcon, type ToolId } from './toolIcons' import { PANEL as C, CHAT, FONT, BRAND_GRADIENT, PANEL_HEADER_ICON, DOCK_CLEARANCE, Z } from '../lib/extensionTheme' @@ -287,21 +288,21 @@ export const DIFF = { export function DiffRemovedBlock({ children }: { children: ReactNode }) { return ( -

{children}

+ }}>{children}
) } export function DiffAddedBlock({ children }: { children: ReactNode }) { return ( -

{children}

+ }}>{children}
) } @@ -310,12 +311,20 @@ export function BlockDiffView({ original, updated }: { original: string; updated const oldText = original.trim() const newText = updated.trim() if (!oldText) { - return {newText} + return ( + + + + ) } return (
- {oldText} - {newText} + + + + + +
) } diff --git a/inlineExtension/src/content/ContentShell.tsx b/inlineExtension/src/content/ContentShell.tsx index c9de717..fd4df33 100644 --- a/inlineExtension/src/content/ContentShell.tsx +++ b/inlineExtension/src/content/ContentShell.tsx @@ -4,6 +4,7 @@ import PanelHost from './PanelHost' import SmartOverlay from './SmartOverlay' import StickyNotesManager from './StickyNotesManager' import { restoreAIReplacements } from './aiReplacements' +import { restoreManualRewrites } from './manualRewrites' import { restoreDrawings } from './drawingsRestore' import { restoreHandwriting } from './handwritingRestore' import { restoreHighlights } from './highlightWrap' @@ -36,6 +37,7 @@ export default function ContentShell() { restoreDrawings() restoreHandwriting() restoreAIReplacements() + restoreManualRewrites() }, 800) return () => window.clearTimeout(timer) }, [accepted]) diff --git a/inlineExtension/src/content/SmartOverlay.tsx b/inlineExtension/src/content/SmartOverlay.tsx index a2b5a51..0e09f99 100644 --- a/inlineExtension/src/content/SmartOverlay.tsx +++ b/inlineExtension/src/content/SmartOverlay.tsx @@ -11,8 +11,9 @@ import { wrapSelectionWithHighlight } from './highlightWrap' import { loadSettings } from '../lib/extensionSettings' import { speakWithElevenLabs } from '../lib/elevenLabsTts' import { fetchViaBackground } from '../lib/backgroundFetch' -import { buildAIInsertMark } from '../lib/insertBadge' +import { buildAIInsertMark, buildManualInsertMark } from '../lib/insertBadge' import { saveAIReplacement } from './aiReplacements' +import { saveManualRewrite } from './manualRewrites' import { TOOLBAR as TB, HIGHLIGHT_SWATCHES, FONT, PANEL as C } from '../lib/extensionTheme' import { FloatingPanelShell, @@ -581,6 +582,42 @@ export default function SmartOverlay() { void runAiTask(task, instruction) } + /** Replace the pill's saved selection with user-typed text (no AI). */ + function runManualRewriteFromPill() { + const newText = subInput.trim() + if (!newText) return + + const saved = savedRangeRef.current + if (!saved) return + + let range: Range + try { + range = saved.cloneRange() + } catch { + return + } + + const originalText = range.toString() + if (!originalText.trim()) return + + // Best-effort: re-highlight for the user, but the clone above is what we mutate. + restoreSavedSelection() + + try { + range.deleteContents() + const wrapper = buildManualInsertMark(newText) + range.insertNode(wrapper) + saveManualRewrite(wrapper, originalText, newText) + + setSubPanel(null) + setToolbar(null) + setSubInput('') + savedRangeRef.current = null + selRef.current = '' + window.getSelection()?.removeAllRanges() + } catch { /* range detached */ } + } + function aiTaskLabel(task: 'summarize' | 'rephrase' | 'rewrite' | 'shorten'): string { if (task === 'summarize') return 'Summary' if (task === 'rephrase') return 'Rephrased' @@ -815,7 +852,7 @@ export default function SmartOverlay() { runPillAiTask('summarize')} title="Summarize">Summarize runPillAiTask('rephrase')} title="Rephrase">Rephrase runPillAiTask('shorten')} title="Shorten">Shorten - toggleSub('rewrite')} title="Custom rewrite"> + toggleSub('rewrite')} title="Manual rewrite"> @@ -920,11 +957,11 @@ export default function SmartOverlay() { onChange={e => setSubInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && subInput.trim()) { - runPillAiTask('rewrite', subInput.trim()) + runManualRewriteFromPill() } if (e.key === 'Escape') setSubPanel(null) }} - placeholder="How should I rewrite this?" + placeholder="Replace selection with…" style={{ flex: 1, padding: '8px 10px', border: 'none', @@ -937,7 +974,7 @@ export default function SmartOverlay() { disabled={!subInput.trim()} onClick={() => { if (!subInput.trim()) return - runPillAiTask('rewrite', subInput.trim()) + runManualRewriteFromPill() }} style={{ padding: '7px 16px', borderRadius: 9999, border: 'none', @@ -1132,7 +1169,7 @@ export default function SmartOverlay() { Analysing… ) : ( -
{riskText}
+ )} diff --git a/inlineExtension/src/content/aiReplacements.ts b/inlineExtension/src/content/aiReplacements.ts index 2b4198c..5da4bec 100644 --- a/inlineExtension/src/content/aiReplacements.ts +++ b/inlineExtension/src/content/aiReplacements.ts @@ -1,80 +1,88 @@ /** - * AI Insert persistence — saves the (original → AI) text replacements - * performed from the Rewrite panel so they survive a page reload. - * - * Flow on save (Rewrite.tsx → handleInsert): - * 1. `buildAIInsertMark` creates the styled element. - * 2. The original text in the selection range is replaced with that mark. - * 3. We then call `saveAIReplacement(...)` to persist - * { id, originalText, aiText, task, instruction, timestamp } - * under the `aiReplacements` feature key for this page URL. - * - * Flow on restore (content.tsx → restoreAIReplacements): - * 1. Load the list from the backend (via the service worker). - * 2. Walk the DOM looking for `originalText` as a contiguous substring. - * 3. Replace it with a freshly-built mark and wire up click-to-remove. - * - * Remove (user discards an AI edit): - * Hovering a persisted mark shows a small "×" badge. Clicking it - * restores the original text in the DOM AND removes the entry from - * encrypted browser/workspace storage, so the edit doesn't come back on - * the next reload. + * AI text replacement persistence → `aiReplacements` feature key. + * Manual pill rewrites live in manualRewrites.ts. */ -import { buildAIInsertMark } from '../lib/insertBadge' +import { buildAIInsertMark } from "../lib/insertBadge"; +import { emitSaveToast } from "../lib/saveToast"; export interface AIReplacement { - id: string - originalText: string - aiText: string - task: string - instruction?: string - timestamp: number + id: string; + originalText: string; + aiText: string; + task: string; + instruction?: string; + timestamp: number; } -let sessionReplacements: AIReplacement[] = [] +const PAGE_URL = window.location.href; +const RESTORE_RETRY_MS = 2500; -function replacementId(): string { - return `air-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}` -} +let sessionAiReplacements: AIReplacement[] = []; -function readLocal(): AIReplacement[] { - return sessionReplacements +function replacementId(): string { + return `air-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; } -function writeLocal(list: AIReplacement[]): void { - sessionReplacements = list +function mergeById(...lists: AIReplacement[][]): AIReplacement[] { + const byId = new Map(); + for (const list of lists) { + for (const item of list) { + if (item?.id) byId.set(item.id, item); + } + } + return [...byId.values()]; } -function pushToBackend(list: AIReplacement[]): void { +function pushAnnotations(list: AIReplacement[]): void { + sessionAiReplacements = list; try { - if (!chrome.runtime?.id) return + if (!chrome.runtime?.id) return; chrome.runtime.sendMessage( { - type: 'SAVE_ANNOTATIONS', + type: "SAVE_ANNOTATIONS", payload: { - pageUrl: window.location.href, - featureKey: 'aiReplacements', + pageUrl: PAGE_URL, + featureKey: "aiReplacements", data: list, pageTitle: document.title, domain: window.location.hostname, clearedAt: list.length === 0 ? Date.now() : null, }, }, - () => { if (chrome.runtime.lastError) { /* ignore */ } }, - ) - } catch { /* extension context unavailable */ } + (response) => { + emitSaveToast(response); + if (chrome.runtime.lastError) { + console.error("[Inline] Save failed:", chrome.runtime.lastError.message); + } else if (!response?.ok) { + console.error("[Inline] Backend sync failed:", response?.error); + } + }, + ); + } catch { + /* extension context unavailable */ + } +} + +function loadAndApplyAi(): void { + try { + if (!chrome.runtime?.id) return; + chrome.runtime.sendMessage( + { type: "LOAD_ANNOTATIONS", payload: { pageUrl: PAGE_URL } }, + (response) => { + if (chrome.runtime.lastError || !response?.ok) return; + const raw = response.data?.elements?.aiReplacements; + if (!Array.isArray(raw) || raw.length === 0) return; + const aiRemote = (raw as AIReplacement[]).filter((r) => r.task !== "manual"); + sessionAiReplacements = mergeById(sessionAiReplacements, aiRemote); + applyAiReplacements(sessionAiReplacements); + }, + ); + } catch { + /* extension context unavailable */ + } } -/** - * Persist a newly-inserted AI replacement. The caller is expected to - * have already mutated the DOM; this function only records what happened - * so we can replay it on the next page load. - * - * The returned ID is written to the live element as - * `data-inline-ai-id` so the click-to-remove handler can delete the - * matching entry later. - */ export function saveAIReplacement( mark: HTMLElement, originalText: string, @@ -82,8 +90,8 @@ export function saveAIReplacement( task: string, instruction?: string, ): string { - const id = replacementId() - mark.setAttribute('data-inline-ai-id', id) + const id = replacementId(); + mark.setAttribute("data-inline-ai-id", id); const entry: AIReplacement = { id, @@ -92,150 +100,122 @@ export function saveAIReplacement( task, instruction, timestamp: Date.now(), - } + }; - const next = [...readLocal(), entry] - writeLocal(next) - pushToBackend(next) - - attachRemoveHandler(mark, id) - return id + const next = mergeById(sessionAiReplacements, [entry]); + pushAnnotations(next); + attachRemoveHandler(mark, id); + return id; } -function removeReplacementById(id: string): void { - const next = readLocal().filter(r => r.id !== id) - writeLocal(next) - pushToBackend(next) +function removeAiReplacementById(id: string): void { + const next = sessionAiReplacements.filter((r) => r.id !== id); + pushAnnotations(next); } -/** - * Wire a small "×" badge to a persisted mark. Clicking the × unwraps - * the mark (restoring the original text) AND deletes its storage entry. - */ function attachRemoveHandler(mark: HTMLElement, id: string): void { - // The original text is what the mark displays (we set mark.textContent in - // buildAIInsertMark), but Rewrite.tsx also appends a
+ citation span, - // so strip them when unwrapping so the user just sees their original text - // back. We read the original from storage on click to be safe. - mark.style.cursor = 'pointer' + mark.style.cursor = "pointer"; const onClick = (e: MouseEvent) => { - // Only act on the × badge child, or on Alt/Option+click as a fallback. - const target = e.target as HTMLElement | null - const isBadge = target?.classList.contains('inline-ai-remove-badge') - if (!isBadge && !e.altKey) return - e.preventDefault() - e.stopPropagation() - - const stored = readLocal().find(r => r.id === id) - removeReplacementById(id) - - const parent = mark.parentNode - if (!parent) return - const text = document.createTextNode(stored?.originalText ?? mark.textContent ?? '') - parent.replaceChild(text, mark) - } - - mark.addEventListener('click', onClick) - - // Hover badge — positioned absolutely inside the mark. - const badge = document.createElement('span') - badge.className = 'inline-ai-remove-badge' - badge.textContent = '×' - badge.setAttribute('aria-label', 'Remove this AI edit') - badge.title = 'Remove this AI edit' + const target = e.target as HTMLElement | null; + const isBadge = target?.classList.contains("inline-ai-remove-badge"); + if (!isBadge && !e.altKey) return; + e.preventDefault(); + e.stopPropagation(); + + const stored = sessionAiReplacements.find((r) => r.id === id); + removeAiReplacementById(id); + + const parent = mark.parentNode; + if (!parent) return; + const text = document.createTextNode( + stored?.originalText ?? mark.textContent ?? "", + ); + parent.replaceChild(text, mark); + }; + + mark.addEventListener("click", onClick); + + const badge = document.createElement("span"); + badge.className = "inline-ai-remove-badge"; + badge.textContent = "×"; + badge.setAttribute("aria-label", "Remove this edit"); + badge.title = "Remove this edit"; badge.style.cssText = [ - 'display:none', 'position:absolute', 'top:-10px', 'right:-8px', - 'width:18px', 'height:18px', 'border-radius:9999px', - 'background:#1C1E26', 'color:#fff', 'font:600 11px/18px system-ui,sans-serif', - 'text-align:center', 'cursor:pointer', 'user-select:none', - 'box-shadow:none', 'z-index:2147483646', - ].join(';') - - // Ensure the mark can host absolutely-positioned children. - if (!mark.style.position) mark.style.position = 'relative' - mark.appendChild(badge) - mark.addEventListener('mouseenter', () => { badge.style.display = 'inline-block' }) - mark.addEventListener('mouseleave', () => { badge.style.display = 'none' }) + "display:none", + "position:absolute", + "top:-10px", + "right:-8px", + "width:18px", + "height:18px", + "border-radius:9999px", + "background:#1C1E26", + "color:#fff", + "font:600 11px/18px system-ui,sans-serif", + "text-align:center", + "cursor:pointer", + "user-select:none", + "box-shadow:none", + "z-index:2147483646", + ].join(";"); + + if (!mark.style.position) mark.style.position = "relative"; + mark.appendChild(badge); + mark.addEventListener("mouseenter", () => { + badge.style.display = "inline-block"; + }); + mark.addEventListener("mouseleave", () => { + badge.style.display = "none"; + }); } -/** - * Replay saved AI replacements on page load. - * - * We walk every text node and, for each saved replacement, look for the - * first contiguous occurrence of `originalText`. If found, replace that - * range with a freshly-built mark. If the page's content shifted so the - * text can't be located, we leave that entry untouched in storage — it - * may match on a future load. - */ export function restoreAIReplacements(): void { - // Local cache first so the page paints immediately; then merge backend. - const local = readLocal() - if (local.length > 0) applyReplacements(local) - - try { - if (!chrome.runtime?.id) return - chrome.runtime.sendMessage( - { type: 'LOAD_ANNOTATIONS', payload: { pageUrl: window.location.href } }, - (response) => { - if (chrome.runtime.lastError || !response?.ok) return - const remote = response.data?.elements?.aiReplacements as AIReplacement[] | undefined - if (!Array.isArray(remote) || remote.length === 0) return - - const localIds = new Set(readLocal().map(r => r.id)) - const fresh = remote.filter(r => !localIds.has(r.id)) - if (fresh.length === 0) return - - const merged = [...readLocal(), ...fresh] - writeLocal(merged) - applyReplacements(fresh) - }, - ) - } catch { /* extension context unavailable */ } + loadAndApplyAi(); + window.setTimeout(loadAndApplyAi, RESTORE_RETRY_MS); } -function applyReplacements(list: AIReplacement[]): void { - const body = document.body - if (!body) return +function applyAiReplacements(list: AIReplacement[]): void { + const body = document.body; + if (!body) return; for (const r of list) { - if (!r.originalText || r.originalText.length < 3) continue - // Already rendered? Skip. - if (document.querySelector(`[data-inline-ai-id="${CSS.escape(r.id)}"]`)) continue + if (!r.originalText?.trim() || r.task === "manual") continue; + if (r.originalText.length < 3) continue; + if (document.querySelector(`[data-inline-ai-id="${CSS.escape(r.id)}"]`)) continue; const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT, { acceptNode(node) { - const parent = node.parentElement - if (!parent) return NodeFilter.FILTER_REJECT - // Skip text that's already inside an inline-ai mark, our shadow - // root host, or a script/style container. - if (parent.closest('[data-inline-ai-id]')) return NodeFilter.FILTER_REJECT - if (parent.closest('#inline-extension-root')) return NodeFilter.FILTER_REJECT - const tag = parent.tagName - if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') return NodeFilter.FILTER_REJECT - return NodeFilter.FILTER_ACCEPT + const parent = node.parentElement; + if (!parent) return NodeFilter.FILTER_REJECT; + if (parent.closest("[data-inline-ai-id]")) return NodeFilter.FILTER_REJECT; + if (parent.closest("[data-inline-manual-id]")) return NodeFilter.FILTER_REJECT; + if (parent.closest("#inline-extension-root")) return NodeFilter.FILTER_REJECT; + const tag = parent.tagName; + if (tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT") { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; }, - }) + }); - let node: Text | null + let node: Text | null; while ((node = walker.nextNode() as Text | null)) { - const idx = node.textContent?.indexOf(r.originalText) ?? -1 - if (idx === -1) continue + const idx = node.textContent?.indexOf(r.originalText) ?? -1; + if (idx === -1) continue; try { - const range = document.createRange() - range.setStart(node, idx) - range.setEnd(node, idx + r.originalText.length) - - const mark = buildAIInsertMark(r.aiText, r.task, r.instruction) - mark.setAttribute('data-inline-ai-id', r.id) - range.deleteContents() - range.insertNode(mark) - - attachRemoveHandler(mark, r.id) - } catch { /* range invalid — skip, try next match */ } - - break + const range = document.createRange(); + range.setStart(node, idx); + range.setEnd(node, idx + r.originalText.length); + const mark = buildAIInsertMark(r.aiText, r.task, r.instruction); + mark.setAttribute("data-inline-ai-id", r.id); + range.deleteContents(); + range.insertNode(mark); + attachRemoveHandler(mark, r.id); + } catch { + /* range invalid */ + } + break; } } } diff --git a/inlineExtension/src/content/content.tsx b/inlineExtension/src/content/content.tsx index 351446e..3f73e61 100644 --- a/inlineExtension/src/content/content.tsx +++ b/inlineExtension/src/content/content.tsx @@ -4,7 +4,7 @@ * Creates an isolated Shadow DOM container, injects scoped CSS, * and mounts ContentShell (privacy gate + capture UI) inside it. */ -import { createRoot } from 'react-dom/client' +import { createRoot, type Root } from 'react-dom/client' import ContentShell from './ContentShell' import { enableReaderMode, disableReaderMode } from '../lib/readerMode' import { loadLayers, type LayerVisibility } from '../lib/layerState' @@ -14,36 +14,49 @@ import { readPrivacyAccepted } from '../lib/privacyConsent' import cssText from './content.css?inline' import { FONT_FACE_CSS } from '../lib/extensionFonts' -;(async () => { - const stored = await new Promise>(resolve => - chrome.storage.local.get(['inlineBlockedDomains', 'inlineFocusMode'], r => resolve(r)), - ) +const HOST_ID = 'inline-extension-root' +let uiRoot: Root | null = null - let blockedDomains: string[] = [] - try { - const raw = stored.inlineBlockedDomains - if (typeof raw === 'string') blockedDomains = JSON.parse(raw) - } catch { /* keep default */ } - - const hostname = window.location.hostname - if (Array.isArray(blockedDomains) && blockedDomains.some(d => hostname === d || hostname.endsWith(`.${d}`))) { - return +function waitForBody(): Promise { + if (document.body) return Promise.resolve(document.body) + return new Promise(resolve => { + const done = () => { + if (document.body) { + observer.disconnect() + resolve(document.body) + } + } + const observer = new MutationObserver(done) + observer.observe(document.documentElement, { childList: true, subtree: true }) + done() + }) +} + +function ensureMountPoint(shadow: ShadowRoot): HTMLDivElement { + const existing = shadow.getElementById('inline-mount') + const mountPoint = document.createElement('div') + mountPoint.id = 'inline-mount' + mountPoint.style.cssText = + 'position:fixed; top:0; left:0; width:100vw; height:100vh; pointer-events:none;' + if (existing) existing.replaceWith(mountPoint) + else shadow.appendChild(mountPoint) + return mountPoint +} + +function mountContentShell(focusMode: boolean): void { + let host = document.getElementById(HOST_ID) as HTMLDivElement | null + + if (host && !host.shadowRoot) { + host.remove() + host = null } - const focusMode = stored.inlineFocusMode === 'true' || stored.inlineFocusMode === true - if (focusMode) enableReaderMode() - - let privacyAccepted = await readPrivacyAccepted() - let postConsentInitialized = false - - const HOST_ID = 'inline-extension-root' - if (!document.getElementById(HOST_ID)) { - const host = document.createElement('div') + if (!host) { + host = document.createElement('div') host.id = HOST_ID host.style.cssText = 'position:fixed; top:0; left:0; width:0; height:0; z-index:2147483647; pointer-events:none;' if (focusMode) host.dataset.inlineFocus = 'true' - document.body.appendChild(host) const shadow = host.attachShadow({ mode: 'open' }) @@ -51,12 +64,6 @@ import { FONT_FACE_CSS } from '../lib/extensionFonts' style.textContent = FONT_FACE_CSS + '\n' + cssText shadow.appendChild(style) - const mountPoint = document.createElement('div') - mountPoint.id = 'inline-mount' - mountPoint.style.cssText = - 'position:fixed; top:0; left:0; width:100vw; height:100vh; pointer-events:none;' - shadow.appendChild(mountPoint) - const extraStyle = document.createElement('style') extraStyle.textContent = ` .sticky-note, .add-note-button, @@ -92,10 +99,44 @@ import { FONT_FACE_CSS } from '../lib/extensionFonts' window.addEventListener('online', hideBadge) if (!navigator.onLine) showBadge() - const root = createRoot(mountPoint) - root.render() + document.body.appendChild(host) } + const mountPoint = ensureMountPoint(host.shadowRoot!) + try { uiRoot?.unmount() } catch { /* stale after extension reload */ } + uiRoot = createRoot(mountPoint) + uiRoot.render() +} + +;(async () => { + if (!chrome.runtime?.id) return + + const body = await waitForBody().catch(() => null) + if (!body) return + + const stored = await new Promise>(resolve => + chrome.storage.local.get(['inlineBlockedDomains', 'inlineFocusMode'], r => resolve(r)), + ) + + let blockedDomains: string[] = [] + try { + const raw = stored.inlineBlockedDomains + if (typeof raw === 'string') blockedDomains = JSON.parse(raw) + } catch { /* keep default */ } + + const hostname = window.location.hostname + if (Array.isArray(blockedDomains) && blockedDomains.some(d => hostname === d || hostname.endsWith(`.${d}`))) { + return + } + + const focusMode = stored.inlineFocusMode === 'true' || stored.inlineFocusMode === true + if (focusMode) enableReaderMode() + + let privacyAccepted = await readPrivacyAccepted() + let postConsentInitialized = false + + mountContentShell(focusMode) + function initAfterPrivacyConsent(): void { if (!privacyAccepted || postConsentInitialized) return postConsentInitialized = true diff --git a/inlineExtension/src/content/manualRewrites.ts b/inlineExtension/src/content/manualRewrites.ts new file mode 100644 index 0000000..0d05857 --- /dev/null +++ b/inlineExtension/src/content/manualRewrites.ts @@ -0,0 +1,425 @@ +/** + * Manual pill rewrite persistence — same SAVE_ANNOTATIONS / LOAD_ANNOTATIONS + * pipeline as highlights and sticky notes. + * + * Saves under `manualRewrites` (browser storage when unsigned in, Supabase when synced). + */ + +import { buildManualInsertMark } from "../lib/insertBadge"; +import { emitSaveToast } from "../lib/saveToast"; + +/** Stored in annotations.elements.manualRewrites */ +export interface ManualRewrite { + id: string; + originalText: string; + /** User-typed text shown in the DOM */ + text: string; + /** Legacy field kept for backend mirror + older readers */ + aiText: string; + task: "manual"; + timestamp: number; +} + +const RESTORE_RETRY_MS = 2500; + +function pageUrl(): string { + return window.location.href; +} + +function generateId(): string { + return `mwr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +let sessionManualRewrites: ManualRewrite[] = []; +let restoreWatchInstalled = false; +/** Ids pushed but not yet confirmed by a load/save response — never strip these from the DOM. */ +const pendingSaveIds = new Set(); + +function mergeById(...lists: ManualRewrite[][]): ManualRewrite[] { + const byId = new Map(); + for (const list of lists) { + for (const item of list) { + if (item?.id) byId.set(item.id, item); + } + } + return [...byId.values()]; +} + +function normalizeStoredRewrite(raw: unknown): ManualRewrite | null { + if (!raw || typeof raw !== "object") return null; + const r = raw as Record; + const id = typeof r.id === "string" && r.id ? r.id : null; + if (!id) return null; + const text = + typeof r.text === "string" + ? r.text + : typeof r.aiText === "string" + ? r.aiText + : ""; + if (!text.trim()) return null; + const originalText = typeof r.originalText === "string" ? r.originalText : ""; + const timestamp = + typeof r.timestamp === "number" && Number.isFinite(r.timestamp) + ? r.timestamp + : Date.now(); + return { + id, + originalText, + text, + aiText: text, + task: "manual", + timestamp, + }; +} + +function pushToBackend(list: ManualRewrite[]): void { + sessionManualRewrites = list; + for (const item of list) pendingSaveIds.add(item.id); + try { + if (!chrome.runtime?.id) return; + chrome.runtime.sendMessage( + { + type: "SAVE_ANNOTATIONS", + payload: { + pageUrl: pageUrl(), + featureKey: "manualRewrites", + data: list, + pageTitle: document.title, + domain: window.location.hostname, + clearedAt: list.length === 0 ? Date.now() : null, + }, + }, + (response) => { + if (chrome.runtime.lastError) { + console.error("[Inline] Manual rewrite save failed:", chrome.runtime.lastError.message); + return; + } + if (response?.ok) { + for (const item of list) pendingSaveIds.delete(item.id); + } + emitSaveToast(response); + if (!response?.ok) { + console.error("[Inline] Manual rewrite backend sync failed:", response?.error); + } + }, + ); + } catch { + /* extension context unavailable */ + } +} + +function textFromManualWrapper(wrapper: HTMLElement): string { + const mark = wrapper.querySelector(".inline-manual-text"); + return mark?.textContent ?? ""; +} + +function restoreOriginalInDom(wrapper: HTMLElement, originalText: string): void { + const parent = wrapper.parentNode; + if (!parent) return; + parent.replaceChild(document.createTextNode(originalText), wrapper); +} + +function removeManualRewriteById(id: string, knownWrapper?: HTMLElement): void { + const stored = sessionManualRewrites.find((r) => r.id === id); + const wrapper = + knownWrapper ?? + (document.querySelector( + `[data-inline-manual-id="${CSS.escape(id)}"]`, + ) as HTMLElement | null); + + if (wrapper) { + restoreOriginalInDom( + wrapper, + stored?.originalText ?? textFromManualWrapper(wrapper), + ); + } + + pendingSaveIds.delete(id); + pushToBackend(sessionManualRewrites.filter((r) => r.id !== id)); +} + +function attachRemoveHandler(wrapper: HTMLElement, id: string): void { + if (wrapper.getAttribute("data-inline-manual-remove") === "true") return; + wrapper.setAttribute("data-inline-manual-remove", "true"); + + const mark = wrapper.querySelector(".inline-manual-text"); + if (!(mark instanceof HTMLElement)) return; + + mark.style.cursor = "pointer"; + mark.title = "Double-click to restore original text"; + + mark.addEventListener("dblclick", (e) => { + e.preventDefault(); + e.stopPropagation(); + removeManualRewriteById(id, wrapper); + }); +} + +/** + * Record a manual rewrite after the DOM has been updated. + * Call from SmartOverlay after inserting `buildManualInsertMark(...)). + */ +export function saveManualRewrite( + wrapper: HTMLElement, + originalText: string, + insertedText: string, +): string { + const id = generateId(); + wrapper.setAttribute("data-inline-manual-id", id); + + const entry: ManualRewrite = { + id, + originalText, + text: insertedText, + aiText: insertedText, + task: "manual", + timestamp: Date.now(), + }; + + const next = mergeById(sessionManualRewrites, [entry]); + pushToBackend(next); + attachRemoveHandler(wrapper, id); + return id; +} + +function acceptTextNode(node: Node): number { + const parent = node.parentElement; + if (!parent) return NodeFilter.FILTER_REJECT; + if (parent.closest("[data-inline-manual-id]")) return NodeFilter.FILTER_REJECT; + if (parent.closest("[data-inline-ai-id]")) return NodeFilter.FILTER_REJECT; + if (parent.closest("#inline-extension-root")) return NodeFilter.FILTER_REJECT; + const tag = parent.tagName; + if (tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT") { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; +} + +interface TextSegment { + node: Text; + start: number; + end: number; +} + +function collectTextSegments(): { full: string; segments: TextSegment[] } { + const body = document.body; + const segments: TextSegment[] = []; + if (!body) return { full: "", segments }; + + const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT, { + acceptNode: acceptTextNode, + }); + + let full = ""; + let node: Text | null; + while ((node = walker.nextNode() as Text | null)) { + const text = node.textContent ?? ""; + const start = full.length; + full += text; + segments.push({ node, start, end: full.length }); + } + + return { full, segments }; +} + +function pointAtOffset( + segments: TextSegment[], + offset: number, + side: "start" | "end", +): { node: Text; offset: number } | null { + if (segments.length === 0) return null; + + for (let i = 0; i < segments.length; i++) { + const seg = segments[i]!; + if (offset > seg.start && offset < seg.end) { + return { node: seg.node, offset: offset - seg.start }; + } + if (offset === seg.start && side === "start") { + return { node: seg.node, offset: 0 }; + } + if (offset === seg.end && side === "end") { + return { node: seg.node, offset: seg.node.length }; + } + if (offset === seg.end && side === "start" && i + 1 < segments.length) { + return { node: segments[i + 1]!.node, offset: 0 }; + } + } + + const last = segments[segments.length - 1]!; + if (offset === last.end) { + return { node: last.node, offset: last.node.length }; + } + return null; +} + +/** Find needle even when it spans multiple text nodes (common for multi-element selections). */ +function findTextRange(needle: string): Range | null { + if (!needle.trim()) return null; + const { full, segments } = collectTextSegments(); + if (!full) return null; + + const idx = full.indexOf(needle); + if (idx === -1) return null; + + const start = pointAtOffset(segments, idx, "start"); + const end = pointAtOffset(segments, idx + needle.length, "end"); + if (!start || !end) return null; + + try { + const range = document.createRange(); + range.setStart(start.node, start.offset); + range.setEnd(end.node, end.offset); + return range; + } catch { + return null; + } +} + +function applyManualRewriteToDom(r: ManualRewrite): boolean { + const existing = document.querySelector( + `[data-inline-manual-id="${CSS.escape(r.id)}"]`, + ) as HTMLElement | null; + if (existing) { + attachRemoveHandler(existing, r.id); + return true; + } + + const needles = [r.originalText, r.text].filter((s) => s.trim().length > 0); + for (const needle of needles) { + const range = findTextRange(needle); + if (!range) continue; + + try { + const wrapper = buildManualInsertMark(r.text, r.id, r.timestamp); + range.deleteContents(); + range.insertNode(wrapper); + attachRemoveHandler(wrapper, r.id); + return true; + } catch { + /* range invalid — try next needle */ + } + } + return false; +} + +function applyManualRewrites(saved: ManualRewrite[]): void { + if (!document.body) return; + for (const r of saved) { + applyManualRewriteToDom(r); + } +} + +/** Remove DOM marks absent from the merged session (skip in-flight saves). */ +function removeStaleManualMarks(allowedIds: Set): void { + document.querySelectorAll("[data-inline-manual-id]").forEach((el) => { + if (!(el instanceof HTMLElement)) return; + const id = el.getAttribute("data-inline-manual-id"); + if (!id || allowedIds.has(id) || pendingSaveIds.has(id)) return; + + const stored = sessionManualRewrites.find((r) => r.id === id); + restoreOriginalInDom( + el, + stored?.originalText ?? textFromManualWrapper(el), + ); + }); +} + +function parseRemoteList(raw: unknown): ManualRewrite[] { + if (!Array.isArray(raw)) return []; + return raw.map(normalizeStoredRewrite).filter((x): x is ManualRewrite => x !== null); +} + +/** Older builds stored manual pill edits under aiReplacements with task === "manual". */ +function parseLegacyManualFromAi(raw: unknown): ManualRewrite[] { + if (!Array.isArray(raw)) return []; + return raw + .filter((item) => { + if (!item || typeof item !== "object") return false; + return (item as Record).task === "manual"; + }) + .map(normalizeStoredRewrite) + .filter((x): x is ManualRewrite => x !== null); +} + +function syncFromServer(remote: ManualRewrite[]): void { + for (const r of remote) pendingSaveIds.delete(r.id); + sessionManualRewrites = mergeById(sessionManualRewrites, remote); + + const allowedIds = new Set(sessionManualRewrites.map((r) => r.id)); + for (const id of pendingSaveIds) allowedIds.add(id); + removeStaleManualMarks(allowedIds); + + applyManualRewrites(sessionManualRewrites); +} + +function loadAndApply(): void { + try { + if (!chrome.runtime?.id) return; + chrome.runtime.sendMessage( + { type: "LOAD_ANNOTATIONS", payload: { pageUrl: pageUrl() } }, + (response) => { + if (chrome.runtime.lastError || !response?.ok) { + console.error( + "[Inline] Manual rewrite load failed:", + chrome.runtime.lastError?.message ?? response?.error, + ); + return; + } + + const elements = response.data?.elements ?? {}; + const fromManual = parseRemoteList(elements.manualRewrites); + const fromLegacy = parseLegacyManualFromAi(elements.aiReplacements); + const remote = mergeById(fromManual, fromLegacy); + + syncFromServer(remote); + + // Migrate legacy rows into the dedicated manualRewrites feature key once. + if (fromLegacy.length > 0 && fromManual.length === 0) { + pushToBackend(sessionManualRewrites); + } + + document.dispatchEvent(new CustomEvent("inline:manualRewritesRestored")); + }, + ); + } catch { + /* extension context unavailable */ + } +} + +function installRestoreWatch(): void { + if (restoreWatchInstalled) return; + restoreWatchInstalled = true; + + let lastUrl = pageUrl(); + const onUrlChange = () => { + const next = pageUrl(); + if (next === lastUrl) return; + lastUrl = next; + sessionManualRewrites = []; + pendingSaveIds.clear(); + restoreManualRewrites(); + }; + + window.addEventListener("popstate", onUrlChange); + window.addEventListener("hashchange", onUrlChange); + + const wrapHistory = (original: T): T => + ((...args: Parameters) => { + original.apply(history, args); + onUrlChange(); + }) as T; + + try { + history.pushState = wrapHistory(history.pushState); + history.replaceState = wrapHistory(history.replaceState); + } catch { + /* read-only history in some embed contexts */ + } +} + +/** Replay saved manual rewrites when the user returns to this URL. */ +export function restoreManualRewrites(): void { + installRestoreWatch(); + loadAndApply(); + window.setTimeout(loadAndApply, RESTORE_RETRY_MS); +} diff --git a/inlineExtension/src/lib/aiTextFormat.ts b/inlineExtension/src/lib/aiTextFormat.ts new file mode 100644 index 0000000..4bc47f0 --- /dev/null +++ b/inlineExtension/src/lib/aiTextFormat.ts @@ -0,0 +1,149 @@ +/** + * Parse and normalize AI-produced text for display. + * Markdown-like markers render as styled UI — never as literal asterisks. + */ + +export const AI_KIND_LABELS: Record = { + 'ai-rephrase': 'Rephrase', + 'ai-shorten': 'Shorten', + 'ai-summarize': 'Summarize', + 'ai-rewrite': 'Rewrite', + 'ai-custom': 'Custom', + rephrase: 'Rephrase', + shorten: 'Shorten', + summary: 'Summary', + summarize: 'Summary', + rewrite: 'Rewrite', + custom: 'Custom', + ai: 'AI', +} + +export function formatAiKindLabel(kind: string): string { + const lower = kind.toLowerCase() + if (AI_KIND_LABELS[lower]) return AI_KIND_LABELS[lower]! + const stripped = lower.replace(/^ai-/, '') + if (AI_KIND_LABELS[stripped]) return AI_KIND_LABELS[stripped]! + return stripped.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) +} + +export function stripMarkdownToPlainText(text: string): string { + return text + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/__(.+?)__/g, '$1') + .replace(/(?\s*/gm, '') + .replace(/\s+/g, ' ') + .trim() +} + +export type InlineSegment = + | { type: 'text'; value: string } + | { type: 'bold'; value: string } + | { type: 'italic'; value: string } + | { type: 'underline'; value: string } + | { type: 'code'; value: string } + +const INLINE_TOKEN_RE = /(\*\*[^*]+\*\*|__[^_]+__|\*[^*]+\*|_[^_]+_|`[^`]+`)/g + +export function parseInlineFormatting(text: string): InlineSegment[] { + if (!text) return [] + const parts = text.split(INLINE_TOKEN_RE) + const segments: InlineSegment[] = [] + + for (const part of parts) { + if (!part) continue + const bold = /^\*\*([^*]+)\*\*$/.exec(part) + if (bold) { + segments.push({ type: 'bold', value: bold[1]! }) + continue + } + const underline = /^__([^_]+)__$/.exec(part) + if (underline) { + segments.push({ type: 'underline', value: underline[1]! }) + continue + } + const italicStar = /^\*([^*]+)\*$/.exec(part) + if (italicStar) { + segments.push({ type: 'italic', value: italicStar[1]! }) + continue + } + const italicUnderscore = /^_([^_]+)_$/.exec(part) + if (italicUnderscore) { + segments.push({ type: 'italic', value: italicUnderscore[1]! }) + continue + } + const code = /^`([^`]+)`$/.exec(part) + if (code) { + segments.push({ type: 'code', value: code[1]! }) + continue + } + segments.push({ type: 'text', value: part }) + } + + return segments +} + +export type AiTextBlock = + | { type: 'paragraph'; inline: InlineSegment[] } + | { type: 'bullet-list'; items: InlineSegment[][] } + | { type: 'numbered-list'; items: InlineSegment[][] } + | { type: 'blockquote'; inline: InlineSegment[] } + +const BULLET_LINE = /^[-*•]\s+/ +const NUMBER_LINE = /^\d+[.)]\s+/ + +export function parseAiTextBlocks(text: string): AiTextBlock[] { + const normalized = text.replace(/\r\n/g, '\n').trim() + if (!normalized) return [] + + const blocks = normalized.split(/\n\n+/) + const result: AiTextBlock[] = [] + + for (const block of blocks) { + const trimmed = block.trim() + if (!trimmed) continue + + const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean) + const bulletLines = lines.filter(l => BULLET_LINE.test(l)) + const numberedLines = lines.filter(l => NUMBER_LINE.test(l)) + const proseLines = lines.filter(l => !BULLET_LINE.test(l) && !NUMBER_LINE.test(l)) + + if (bulletLines.length > 0) { + if (proseLines.length > 0) { + result.push({ type: 'paragraph', inline: parseInlineFormatting(proseLines.join(' ')) }) + } + result.push({ + type: 'bullet-list', + items: bulletLines.map(l => parseInlineFormatting(l.replace(BULLET_LINE, ''))), + }) + continue + } + + if (numberedLines.length > 0 && proseLines.length === 0) { + result.push({ + type: 'numbered-list', + items: numberedLines.map(l => parseInlineFormatting(l.replace(NUMBER_LINE, ''))), + }) + continue + } + + if (lines.every(l => l.startsWith('>'))) { + result.push({ + type: 'blockquote', + inline: parseInlineFormatting(lines.map(l => l.replace(/^>\s?/, '')).join(' ')), + }) + continue + } + + result.push({ + type: 'paragraph', + inline: parseInlineFormatting(trimmed.replace(/\n/g, ' ')), + }) + } + + return result +} diff --git a/inlineExtension/src/lib/extensionFonts.ts b/inlineExtension/src/lib/extensionFonts.ts index 4e6765e..d006b27 100644 --- a/inlineExtension/src/lib/extensionFonts.ts +++ b/inlineExtension/src/lib/extensionFonts.ts @@ -48,7 +48,11 @@ export function injectExtensionFonts(root: Document | ShadowRoot | null) { const style = document.createElement('style') style.setAttribute('data-inline-fonts', 'geist') style.textContent = FONT_FACE_CSS - ;(root as ShadowRoot).appendChild?.(style) ?? (root as Document).head?.appendChild(style) + if (root instanceof ShadowRoot) { + root.appendChild(style) + } else { + root.head?.appendChild(style) + } fontsInjected = true } catch { /* ignore */ diff --git a/inlineExtension/src/lib/historyApi.ts b/inlineExtension/src/lib/historyApi.ts index 478d4ee..248451d 100644 --- a/inlineExtension/src/lib/historyApi.ts +++ b/inlineExtension/src/lib/historyApi.ts @@ -6,69 +6,84 @@ * user (Bearer JWT) or userId fallback. */ -import { loadSettings } from './extensionSettings' -import { fetchViaBackground } from './backgroundFetch' -import { looksLikeJwt } from './aiAccess' +import { loadSettings } from "./extensionSettings"; +import { fetchViaBackground } from "./backgroundFetch"; +import { looksLikeJwt } from "./aiAccess"; type HistoryEntryKind = - | 'ai-rephrase' - | 'ai-shorten' - | 'ai-summarize' - | 'ai-rewrite' - | 'ai-custom' - | 'clip' + | "ai-rephrase" + | "ai-shorten" + | "ai-summarize" + | "ai-rewrite" + | "ai-custom" + | "manual-rewrite" + | "clip"; export interface HistoryEntry { - kind: HistoryEntryKind - selection?: string - result: string - pageUrl?: string - pageTitle?: string - workspaceId?: string + kind: HistoryEntryKind; + selection?: string; + result: string; + pageUrl?: string; + pageTitle?: string; + workspaceId?: string; } function guessPage(): { pageUrl: string; pageTitle: string } { - if (typeof window === 'undefined') return { pageUrl: '', pageTitle: '' } - return { pageUrl: window.location?.href ?? '', pageTitle: document?.title ?? '' } + if (typeof window === "undefined") return { pageUrl: "", pageTitle: "" }; + return { + pageUrl: window.location?.href ?? "", + pageTitle: document?.title ?? "", + }; } -export async function saveAIResultToHistory(entry: HistoryEntry): Promise { +export async function saveAIResultToHistory( + entry: HistoryEntry, +): Promise { try { - const { pageUrl, pageTitle } = guessPage() - const { apiBaseUrl, accessToken } = await loadSettings() + const { pageUrl, pageTitle } = guessPage(); + const { apiBaseUrl, accessToken } = await loadSettings(); - const storage = await new Promise<{ inlineActiveWorkspaceId?: string; inlineUserId?: string }>( - (resolve) => { - chrome.storage.local.get(['inlineActiveWorkspaceId', 'inlineUserId'], (r) => { - resolve(r as { inlineActiveWorkspaceId?: string; inlineUserId?: string }) - }) - }, - ) + const storage = await new Promise<{ + inlineActiveWorkspaceId?: string; + inlineUserId?: string; + }>((resolve) => { + chrome.storage.local.get( + ["inlineActiveWorkspaceId", "inlineUserId"], + (r) => { + resolve( + r as { inlineActiveWorkspaceId?: string; inlineUserId?: string }, + ); + }, + ); + }); - const workspaceId = entry.workspaceId ?? storage.inlineActiveWorkspaceId ?? '' - const userId = storage.inlineUserId ?? '' - if (!looksLikeJwt(accessToken) || !workspaceId) return + const workspaceId = + entry.workspaceId ?? storage.inlineActiveWorkspaceId ?? ""; + const userId = storage.inlineUserId ?? ""; + if (!looksLikeJwt(accessToken) || !workspaceId) return; // The notes.type column has a CHECK constraint, so every AI action is // written as 'ai-summary' and differentiated via tags. UI filters and // counts should read tags for fine-grained distinctions. const tagMap: Record = { - 'ai-rephrase': ['ai', 'rephrase'], - 'ai-shorten': ['ai', 'shorten'], - 'ai-summarize': ['ai', 'summary'], - 'ai-rewrite': ['ai', 'rewrite'], - 'ai-custom': ['ai', 'custom'], - 'clip': ['clip'], - } + "ai-rephrase": ["ai", "rephrase"], + "ai-shorten": ["ai", "shorten"], + "ai-summarize": ["ai", "summary"], + "ai-rewrite": ["ai", "rewrite"], + "ai-custom": ["ai", "custom"], + "manual-rewrite": ["manual", "rewrite"], + clip: ["clip"], + }; const typeMap: Record = { - 'ai-rephrase': 'ai-summary', - 'ai-shorten': 'ai-summary', - 'ai-summarize': 'ai-summary', - 'ai-rewrite': 'ai-summary', - 'ai-custom': 'ai-summary', - 'clip': 'clip', - } + "ai-rephrase": "ai-summary", + "ai-shorten": "ai-summary", + "ai-summarize": "ai-summary", + "ai-rewrite": "ai-summary", + "ai-custom": "ai-summary", + "manual-rewrite": "text", + clip: "clip", + }; const body = { pageUrl: entry.pageUrl ?? pageUrl, @@ -78,19 +93,32 @@ export async function saveAIResultToHistory(entry: HistoryEntry): Promise type: typeMap[entry.kind], tags: tagMap[entry.kind], content: entry.selection - ? `**${entry.kind}**\n\n> ${entry.selection}\n\n${entry.result}` + ? `> ${entry.selection}\n\n${entry.result}` : entry.result, - } + }; - const headers: Record = { 'Content-Type': 'application/json' } - headers.Authorization = `Bearer ${accessToken}` + const headers: Record = { + "Content-Type": "application/json", + }; + headers.Authorization = `Bearer ${accessToken}`; await fetchViaBackground(`${apiBaseUrl}/api/clip`, { - method: 'POST', + method: "POST", headers, body: JSON.stringify(body), - }) + }); } catch { /* best-effort: a failed history write should never block the UI */ } } + +export async function saveManualEditToHistory( + originalText: string, + manualText: string, +): Promise { + await saveAIResultToHistory({ + kind: "manual-rewrite", + selection: originalText, + result: manualText, + }); +} diff --git a/inlineExtension/src/lib/inlineUrls.ts b/inlineExtension/src/lib/inlineUrls.ts index a905e34..4a35c91 100644 --- a/inlineExtension/src/lib/inlineUrls.ts +++ b/inlineExtension/src/lib/inlineUrls.ts @@ -1,8 +1,13 @@ /** Hosted production origin — Chrome Web Store builds use this by default. */ export const INLINE_PRODUCTION_ORIGIN = 'https://useinline.vercel.app' +/** True for `vite dev` and `vite build --mode development` (extension local builds). */ +function isLocalDevBuild(): boolean { + return import.meta.env.MODE === 'development' +} + /** Next.js app — /api/clip, /api/ai/*, /api/tts, etc. */ -export const DEFAULT_WEB_URL = import.meta.env.DEV +export const DEFAULT_WEB_URL = isLocalDevBuild() ? 'http://localhost:3000' : INLINE_PRODUCTION_ORIGIN @@ -10,6 +15,6 @@ export const DEFAULT_WEB_URL = import.meta.env.DEV * Annotation API origin. In production the extension targets the web app, which * rewrites `/api/annotations` to the Express backend via ANNOTATION_API_ORIGIN. */ -export const DEFAULT_BACKEND_URL = import.meta.env.DEV +export const DEFAULT_BACKEND_URL = isLocalDevBuild() ? 'http://localhost:3030' : INLINE_PRODUCTION_ORIGIN diff --git a/inlineExtension/src/lib/insertBadge.ts b/inlineExtension/src/lib/insertBadge.ts index e08523c..616c6b0 100644 --- a/inlineExtension/src/lib/insertBadge.ts +++ b/inlineExtension/src/lib/insertBadge.ts @@ -10,47 +10,214 @@ */ const ACTION_COLORS: Record = { - rephrase: { bg: 'rgba(167, 139, 250, 0.25)', border: 'rgba(139, 92, 246, 0.5)' }, - shorten: { bg: 'rgba(251, 191, 36, 0.3)', border: 'rgba(217, 119, 6, 0.5)' }, - summarize: { bg: 'rgba(110, 231, 183, 0.3)', border: 'rgba(5, 150, 105, 0.5)' }, - rewrite: { bg: 'rgba(147, 197, 253, 0.3)', border: 'rgba(37, 99, 235, 0.55)' }, - custom: { bg: 'rgba(248, 180, 217, 0.35)', border: 'rgba(236, 72, 153, 0.55)' }, - default: { bg: 'rgba(244, 231, 211, 0.4)', border: 'rgba(161, 98, 7, 0.4)' }, -} + rephrase: { + bg: "rgba(167, 139, 250, 0.25)", + border: "rgba(139, 92, 246, 0.5)", + }, + shorten: { bg: "rgba(251, 191, 36, 0.3)", border: "rgba(217, 119, 6, 0.5)" }, + summarize: { + bg: "rgba(110, 231, 183, 0.3)", + border: "rgba(5, 150, 105, 0.5)", + }, + rewrite: { + bg: "rgba(147, 197, 253, 0.3)", + border: "rgba(37, 99, 235, 0.55)", + }, + custom: { + bg: "rgba(248, 180, 217, 0.35)", + border: "rgba(236, 72, 153, 0.55)", + }, + default: { bg: "rgba(244, 231, 211, 0.4)", border: "rgba(161, 98, 7, 0.4)" }, +}; const ACTION_LABEL: Record = { - rephrase: 'Rephrased by Inline AI', - shorten: 'Shortened by Inline AI', - summarize: 'Summarized by Inline AI', - rewrite: 'Rewritten by Inline AI', - custom: 'Custom AI prompt applied', -} - -export function buildAIInsertMark(text: string, task: string, instruction?: string): HTMLElement { - const key = ACTION_COLORS[task] ? task : 'default' - const palette = ACTION_COLORS[key] - const label = ACTION_LABEL[task] ?? 'Inline AI edit' - const tipExtra = instruction ? ` — ${instruction.slice(0, 120)}` : '' - - const mark = document.createElement('mark') - mark.setAttribute('data-inline-ai', task || 'edit') - mark.setAttribute('title', `${label}${tipExtra}`) - mark.setAttribute('aria-label', label) - mark.style.background = palette.bg - mark.style.borderBottom = `1.5px solid ${palette.border}` - mark.style.borderRadius = '3px' - mark.style.padding = '0 2px' - mark.style.color = 'inherit' - mark.style.transition = 'background 120ms ease' - mark.textContent = text + rephrase: "Rephrased by Inline AI", + shorten: "Shortened by Inline AI", + summarize: "Summarized by Inline AI", + rewrite: "Rewritten by Inline AI", + custom: "Custom AI prompt applied", +}; + +export function buildAIInsertMark( + text: string, + task: string, + instruction?: string, +): HTMLElement { + const key = ACTION_COLORS[task] ? task : "default"; + const palette = ACTION_COLORS[key]; + const label = ACTION_LABEL[task] ?? "Inline AI edit"; + const tipExtra = instruction ? ` — ${instruction.slice(0, 120)}` : ""; + + const mark = document.createElement("mark"); + mark.setAttribute("data-inline-ai", task || "edit"); + mark.setAttribute("title", `${label}${tipExtra}`); + mark.setAttribute("aria-label", label); + mark.style.background = palette.bg; + mark.style.borderBottom = `1.5px solid ${palette.border}`; + mark.style.borderRadius = "3px"; + mark.style.padding = "0 2px"; + mark.style.color = "inherit"; + mark.style.transition = "background 120ms ease"; + mark.textContent = text; // Subtle glow on hover to reinforce that the span is meaningful. - mark.addEventListener('mouseenter', () => { - mark.style.boxShadow = `0 0 0 2px ${palette.border}` - }) - mark.addEventListener('mouseleave', () => { - mark.style.boxShadow = 'none' - }) - - return mark + mark.addEventListener("mouseenter", () => { + mark.style.boxShadow = `0 0 0 2px ${palette.border}`; + }); + mark.addEventListener("mouseleave", () => { + mark.style.boxShadow = "none"; + }); + + return mark; +} + +const MANUAL_STYLE_ID = "inline-manual-insert-styles"; + +const MANUAL_INSERT_CSS = ` +.inline-manual-wrap { + display: inline; + position: relative; + vertical-align: baseline; +} +.inline-manual-wrap .inline-manual-text { + background: rgba(147, 197, 253, 0.3); + border-bottom: 1.5px solid rgba(37, 99, 235, 0.55); + border-radius: 3px; + padding: 0 2px; + color: inherit; + transition: box-shadow 180ms ease, background 180ms ease; +} +.inline-manual-wrap:hover .inline-manual-text, +.inline-manual-wrap:focus-within .inline-manual-text { + background: rgba(147, 197, 253, 0.42); + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.28); +} +.inline-manual-popover { + position: absolute; + top: calc(100% + 5px); + left: 0; + z-index: 2147483640; + pointer-events: none; + min-width: 148px; + max-width: 220px; + padding: 6px 10px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.98); + border: 1px solid rgba(37, 99, 235, 0.22); + box-shadow: 0 4px 16px rgba(28, 30, 38, 0.14); + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + opacity: 0; + visibility: hidden; + transform: translateY(-5px) scale(0.97); + transform-origin: top left; + transition: + opacity 200ms ease, + transform 220ms cubic-bezier(0.22, 1, 0.36, 1), + visibility 0s linear 220ms; +} +.inline-manual-popover--above { + top: auto; + bottom: calc(100% + 5px); + transform-origin: bottom left; + transform: translateY(5px) scale(0.97); +} +.inline-manual-wrap:hover .inline-manual-popover, +.inline-manual-wrap:focus-within .inline-manual-popover { + opacity: 1; + visibility: visible; + transform: translateY(0) scale(1); + transition: + opacity 200ms ease, + transform 220ms cubic-bezier(0.22, 1, 0.36, 1), + visibility 0s linear 0s; +} +.inline-manual-wrap:hover .inline-manual-popover--above, +.inline-manual-wrap:focus-within .inline-manual-popover--above { + transform: translateY(0) scale(1); +} +.inline-manual-popover-label { + display: block; + font-size: 10px; + font-weight: 600; + color: #2563eb; + line-height: 1.3; + letter-spacing: 0.01em; +} +.inline-manual-popover-time { + display: block; + font-size: 10px; + color: #78716c; + font-style: italic; + line-height: 1.35; + margin-top: 2px; +} +`; + +function ensureManualInsertStyles(): void { + let style = document.getElementById(MANUAL_STYLE_ID) as HTMLStyleElement | null; + if (!style) { + style = document.createElement("style"); + style.id = MANUAL_STYLE_ID; + document.head.appendChild(style); + } + style.textContent = MANUAL_INSERT_CSS; +} + +function formatManualEditTime(timestamp: number): string { + return new Date(timestamp).toLocaleString(); +} + +function positionManualPopover(wrapper: HTMLElement, popover: HTMLElement): void { + popover.classList.remove("inline-manual-popover--above"); + const wrapRect = wrapper.getBoundingClientRect(); + const estimatedH = 44; + if (wrapRect.bottom + estimatedH + 8 > window.innerHeight && wrapRect.top > estimatedH + 8) { + popover.classList.add("inline-manual-popover--above"); + } +} + +/** Manual pill rewrite — highlighted text in flow; meta popover on hover. */ +export function buildManualInsertMark( + text: string, + id?: string, + timestamp?: number, +): HTMLElement { + ensureManualInsertStyles(); + + const ts = timestamp ?? Date.now(); + const timeLabel = formatManualEditTime(ts); + const wrapper = document.createElement("span"); + wrapper.className = "inline-manual-wrap"; + wrapper.setAttribute("data-inline-manual", "true"); + if (id) wrapper.setAttribute("data-inline-manual-id", id); + wrapper.setAttribute("tabindex", "0"); + wrapper.setAttribute("aria-label", `Manual edit via Inline, ${timeLabel}`); + + const mark = document.createElement("mark"); + mark.className = "inline-manual-text"; + mark.textContent = text; + + const popover = document.createElement("span"); + popover.className = "inline-manual-popover"; + popover.setAttribute("role", "tooltip"); + + const label = document.createElement("span"); + label.className = "inline-manual-popover-label"; + label.textContent = "Manual edit via Inline"; + + const time = document.createElement("span"); + time.className = "inline-manual-popover-time"; + time.textContent = timeLabel; + + popover.appendChild(label); + popover.appendChild(time); + + wrapper.appendChild(mark); + wrapper.appendChild(popover); + + const onShow = () => positionManualPopover(wrapper, popover); + wrapper.addEventListener("mouseenter", onShow); + wrapper.addEventListener("focusin", onShow); + + return wrapper; } diff --git a/inlineExtension/src/lib/saveToast.ts b/inlineExtension/src/lib/saveToast.ts index b4bd3ec..44a4eae 100644 --- a/inlineExtension/src/lib/saveToast.ts +++ b/inlineExtension/src/lib/saveToast.ts @@ -1,15 +1,13 @@ export type SaveToastResponse = { ok?: boolean - queued?: boolean storageMode?: 'local' | 'workspace' + error?: string } export function emitSaveToast(response: SaveToastResponse | undefined): void { - if (!response?.ok && !response?.queued) return - const synced = response.storageMode === 'workspace' + if (!response?.ok) return + if (response.storageMode !== 'workspace') return document.dispatchEvent(new CustomEvent('inline:toast', { - detail: synced - ? { message: 'Saved to Workspace', tone: 'success', action: 'dashboard' } - : { message: 'Saved to browser.', tone: 'local' }, + detail: { message: 'Saved to Workspace', tone: 'success', action: 'dashboard' }, })) } diff --git a/inlineExtension/vite.background.config.ts b/inlineExtension/vite.background.config.ts index 5d64e39..f3c206e 100644 --- a/inlineExtension/vite.background.config.ts +++ b/inlineExtension/vite.background.config.ts @@ -1,10 +1,12 @@ import { defineConfig } from "vite"; import { resolve } from "path"; +import { copyExtensionAssets } from "./vite.extensionCopy"; // Background service worker build: produces a single IIFE at dist/background.js -export default defineConfig({ +export default defineConfig(({ mode }) => ({ + plugins: [copyExtensionAssets(mode)], define: { - "process.env.NODE_ENV": '"production"', + 'process.env.NODE_ENV': JSON.stringify(mode === 'production' ? 'production' : 'development'), }, build: { lib: { @@ -21,4 +23,4 @@ export default defineConfig({ }, }, }, -}); +})); diff --git a/inlineExtension/vite.config.ts b/inlineExtension/vite.config.ts index 5446328..f27c235 100644 --- a/inlineExtension/vite.config.ts +++ b/inlineExtension/vite.config.ts @@ -5,10 +5,11 @@ import { copyExtensionAssets } from "./vite.extensionCopy"; // Popup build: bundles index.html + React popup UI into dist/ export default defineConfig(({ mode }) => ({ + base: './', + plugins: [react(), copyExtensionAssets(mode)], define: { - "process.env.NODE_ENV": '"production"', + 'process.env.NODE_ENV': JSON.stringify(mode === 'production' ? 'production' : 'development'), }, - plugins: [react(), copyExtensionAssets(mode)], build: { outDir: "dist", emptyOutDir: true, diff --git a/inlineExtension/vite.content.config.ts b/inlineExtension/vite.content.config.ts index 6fc1003..02b5d26 100644 --- a/inlineExtension/vite.content.config.ts +++ b/inlineExtension/vite.content.config.ts @@ -1,13 +1,14 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { resolve } from "path"; +import { copyExtensionAssets } from "./vite.extensionCopy"; // Content script build: produces a single self-contained IIFE at dist/content.js -export default defineConfig({ +export default defineConfig(({ mode }) => ({ + plugins: [react(), copyExtensionAssets(mode)], define: { - "process.env.NODE_ENV": '"production"', + 'process.env.NODE_ENV': JSON.stringify(mode === 'production' ? 'production' : 'development'), }, - plugins: [react()], build: { lib: { entry: resolve(__dirname, "src/content/content.tsx"), @@ -24,4 +25,4 @@ export default defineConfig({ }, }, }, -}); +})); diff --git a/inlineExtension/vite.extensionCopy.ts b/inlineExtension/vite.extensionCopy.ts index 3ca7c34..847251d 100644 --- a/inlineExtension/vite.extensionCopy.ts +++ b/inlineExtension/vite.extensionCopy.ts @@ -6,7 +6,9 @@ import type { Plugin } from 'vite' export function copyExtensionAssets(mode: string): Plugin { return { name: 'copy-extension-files', - closeBundle() { + enforce: 'post', + // Run after Vite copies `public/` so dev manifest is not overwritten. + buildEnd() { const outDir = resolve(__dirname, 'dist') mkdirSync(outDir, { recursive: true }) diff --git a/supabase/migrations/2026_06_25_ai_feedback.sql b/supabase/migrations/2026_06_25_ai_feedback.sql new file mode 100644 index 0000000..3c81080 --- /dev/null +++ b/supabase/migrations/2026_06_25_ai_feedback.sql @@ -0,0 +1,21 @@ +-- AI output feedback for prompt iteration (thumbs up/down on chat, insights, etc.) + +create table if not exists public.ai_feedback ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references auth.users(id) on delete cascade, + workspace_id text not null default '', + surface text not null, + target_id text not null default '', + rating smallint not null check (rating in (-1, 1)), + comment text, + created_at timestamptz not null default now() +); + +create index if not exists ai_feedback_user_workspace_idx + on public.ai_feedback (user_id, workspace_id, created_at desc); + +alter table public.ai_feedback enable row level security; + +drop policy if exists "ai feedback is owner-only" on public.ai_feedback; +create policy "ai feedback is owner-only" on public.ai_feedback + for all using (auth.uid() = user_id) with check (auth.uid() = user_id); diff --git a/web/app/(marketing)/page.tsx b/web/app/(marketing)/page.tsx index 9070281..a0fac68 100644 --- a/web/app/(marketing)/page.tsx +++ b/web/app/(marketing)/page.tsx @@ -12,9 +12,9 @@ import FaqSection from '@/components/marketing/sections/FaqSection' import ClosingCta from '@/components/marketing/sections/ClosingCta' export const metadata: Metadata = { - title: 'Inline — Your memory layer for the web', + title: 'Inline — Turn tab hoarding into something you can use', description: - 'Capture context directly on the web. Turn highlights, notes, drawings, rewrites, and page recaps into a searchable AI workspace.', + 'More tabs feels like progress — until you close them and realize nothing compounded. Inline turns your highlights and notes into source-backed briefs you can search, ask about, and actually remember.', } export default function HomePage() { diff --git a/web/app/(workspace)/app/[workspaceId]/analytics/page.tsx b/web/app/(workspace)/app/[workspaceId]/analytics/page.tsx index 0316be0..74cb7b1 100644 --- a/web/app/(workspace)/app/[workspaceId]/analytics/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/analytics/page.tsx @@ -5,6 +5,7 @@ import { getWorkspaceName } from '@/lib/workspaces' import { resolveWorkspaceId, workspacePath } from '@/lib/workspace-routes' import { fetchDashboardStats, fetchCaptureTimeSeries } from '@/lib/data' import AnalyticsCharts from '@/components/analytics/AnalyticsCharts' +import AnalyticsPageClient from '@/components/analytics/AnalyticsPageClient' import { Skeleton } from '@/components/ui/skeleton' export const metadata: Metadata = { title: 'Analytics' } @@ -36,14 +37,14 @@ export default async function AnalyticsPage({ const workspaceName = getWorkspaceName(workspaceId) return ( -
+
-
+
@@ -56,7 +57,10 @@ export default async function AnalyticsPage({
}> - + } + />
diff --git a/web/app/(workspace)/app/[workspaceId]/dashboard/page.tsx b/web/app/(workspace)/app/[workspaceId]/dashboard/page.tsx index 044f689..53639c2 100644 --- a/web/app/(workspace)/app/[workspaceId]/dashboard/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/dashboard/page.tsx @@ -12,6 +12,7 @@ import TopDomainsChart from '@/components/dashboard/TopDomainsChart' import ActivityHeatmap from '@/components/dashboard/ActivityHeatmap' import PinnedCapturesRow from '@/components/dashboard/PinnedCapturesRow' import LibraryDocumentsSection from '@/components/dashboard/LibraryDocumentsSection' +import DashboardOnboarding from '@/components/dashboard/DashboardOnboarding' import { KpiSkeleton, ChartSkeleton, HeatmapSkeleton } from '@/components/dashboard/DashboardSkeleton' import { fetchDashboardStats, fetchNotes } from '@/lib/data' import { getWorkspaceName } from '@/lib/workspaces' @@ -57,7 +58,13 @@ async function StatsSection({ workspaceId }: { workspaceId: string }) { async function CapturesSection({ workspaceId }: { workspaceId: string }) { const notes = await fetchNotes(workspaceId) - return + return ( + <> + +

Web Captures

+ + + ) } export default async function WorkspaceDashboardPage({ @@ -96,7 +103,6 @@ export default async function WorkspaceDashboardPage({ {/* ── Web Captures ── */}
-

Web Captures

{[...Array(4)].map((_, i) => ( diff --git a/web/app/(workspace)/app/[workspaceId]/doc/[docId]/page.tsx b/web/app/(workspace)/app/[workspaceId]/doc/[docId]/page.tsx index c81fc59..359f12d 100644 --- a/web/app/(workspace)/app/[workspaceId]/doc/[docId]/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/doc/[docId]/page.tsx @@ -1,10 +1,9 @@ 'use client' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import Link from 'next/link' import { useParams, usePathname, useRouter } from 'next/navigation' import { - Loader2, ExternalLink, Trash2, Copy, ArrowLeft, + Loader2, ExternalLink, Trash2, Copy, } from 'lucide-react' import { getDocumentById, upsertFolderDocument, deleteFolderDocument, type FolderDocument } from '@/lib/workspace-library' import { loadWorkspaceFolders } from '@/lib/workspace-folders' @@ -14,9 +13,12 @@ import { buildRecapHeaderTags } from '@/lib/recap-meta' import { useRecapNotes } from '@/lib/use-recap-notes' import FolderDocumentEditor from '@/components/documents/FolderDocumentEditor' import DocumentViewHeader from '@/components/documents/DocumentViewHeader' +import DocumentTopBar from '@/components/documents/DocumentTopBar' import DocumentHeaderActions from '@/components/documents/DocumentHeaderActions' import RecapContextPanel from '@/components/documents/RecapContextPanel' -import RecapFooterActions from '@/components/documents/RecapFooterActions' +import RecapChatDock from '@/components/documents/RecapChatDock' +import RecapDocEnhancements from '@/components/documents/RecapDocEnhancements' +import SynthesisRoiIndicator from '@/components/documents/SynthesisRoiIndicator' import { resolveWorkspaceIdFromBrowserPath, workspacePath } from '@/lib/workspace-routes' export default function DocPage() { @@ -161,21 +163,9 @@ export default function DocPage() { return (
- - - All documents in {folderName} - -
-
- 0 ? ( + + ) : undefined + } actions={(
+
+ + - {isAutoRecap && ( - 0 && ( + )} +
+ {isAutoRecap && ( + + )} + {isAutoRecap && ( + +
+ )} + > + + + ) +} diff --git a/web/app/(workspace)/app/[workspaceId]/folder/[folderId]/doc/[documentId]/page.tsx b/web/app/(workspace)/app/[workspaceId]/folder/[folderId]/doc/[documentId]/page.tsx index db294cc..1b6608c 100644 --- a/web/app/(workspace)/app/[workspaceId]/folder/[folderId]/doc/[documentId]/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/folder/[folderId]/doc/[documentId]/page.tsx @@ -15,12 +15,15 @@ import { findFolder, loadWorkspaceFolders } from '@/lib/workspace-folders' import { isPinnedDocument, togglePinnedDocument } from '@/lib/dashboard-favorites' import FolderDocumentEditor from '@/components/documents/FolderDocumentEditor' import DocumentViewHeader from '@/components/documents/DocumentViewHeader' +import DocumentTopBar from '@/components/documents/DocumentTopBar' import DocumentHeaderActions from '@/components/documents/DocumentHeaderActions' import { normalizeRecapContent, regenerateRecapFromNotes, regenerateRecapFromNotesAsync } from '@/lib/auto-recap' import { buildRecapHeaderTags } from '@/lib/recap-meta' import { useRecapNotes } from '@/lib/use-recap-notes' import RecapContextPanel from '@/components/documents/RecapContextPanel' -import RecapFooterActions from '@/components/documents/RecapFooterActions' +import RecapChatDock from '@/components/documents/RecapChatDock' +import RecapDocEnhancements from '@/components/documents/RecapDocEnhancements' +import SynthesisRoiIndicator from '@/components/documents/SynthesisRoiIndicator' import { useConfirm, useToast } from '@/components/ui/notifications' import { DropdownMenu, @@ -330,36 +333,53 @@ export default function FolderDocumentEditorPage() { {/* ── Main area ── */}
-
+ {isAutoRecap && ( + 0 ? ( + + ) : undefined + } + actions={( + setRecapMenuOpen(v => !v)} + onMenuClose={() => setRecapMenuOpen(false)} + menuItems={[ + { icon: Link2, label: linkCopied ? 'Copied!' : 'Copy link', action: copyDocLink }, + { icon: Trash2, label: 'Delete', action: handleDeleteDocument, danger: true }, + ]} + /> + )} + /> + )} + +
{isAutoRecap ? ( persist(title, doc.content)} - actions={( - setRecapMenuOpen(v => !v)} - onMenuClose={() => setRecapMenuOpen(false)} - menuItems={[ - { icon: Link2, label: linkCopied ? 'Copied!' : 'Copy link', action: copyDocLink }, - { icon: Trash2, label: 'Delete', action: handleDeleteDocument, danger: true }, - ]} - /> - )} /> ) : ( <> @@ -396,17 +416,27 @@ export default function FolderDocumentEditorPage() { recapMode={isAutoRecap} /> - {isAutoRecap && ( - 0 && ( + )} +
+ {isAutoRecap && ( + + )} + {isAutoRecap && ( + +
+ )} + > + + + ) +} diff --git a/web/app/(workspace)/app/[workspaceId]/history/[noteId]/page.tsx b/web/app/(workspace)/app/[workspaceId]/history/[noteId]/page.tsx index 14b5645..7f183f8 100644 --- a/web/app/(workspace)/app/[workspaceId]/history/[noteId]/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/history/[noteId]/page.tsx @@ -2,7 +2,8 @@ import Link from 'next/link' import { fetchNoteById, fetchExtractionsForNote } from '@/lib/data' import { ArrowLeft, Globe, Calendar, Tag, MapPin, FileText } from 'lucide-react' import CreateDocFromNoteCTA from './CreateDocFromNoteCTA' -import { prettyNotePreview } from '@/lib/note-preview' +import { FormattedAiOutput, FormattedNoteContent } from '@/components/history/FormattedNoteContent' +import { stripMarkdownToPlainText } from '@/lib/ai-text-format' import { formatDisplayTitle, truncateDisplayUrl } from '@/lib/utils' import { resolveWorkspaceId, workspacePath } from '@/lib/workspace-routes' @@ -94,9 +95,7 @@ export default async function NoteDetailPage({ Original Text
-

- {prettyNotePreview(note) || '(no content)'} -

+
@@ -162,7 +161,7 @@ function humanizeKey(key: string) { function formatValue(value: unknown): string { if (value == null) return 'Not provided' - if (typeof value === 'string') return value + if (typeof value === 'string') return stripMarkdownToPlainText(value) if (typeof value === 'number' || typeof value === 'boolean') return String(value) if (Array.isArray(value)) return value.map(formatValue).join(', ') if (typeof value === 'object') { @@ -175,7 +174,7 @@ function formatValue(value: unknown): string { function ReadableExtraction({ data }: { data: unknown }) { if (typeof data === 'string') { - return

{data}

+ return } if (Array.isArray(data)) { diff --git a/web/app/(workspace)/app/[workspaceId]/library/[docId]/page.tsx b/web/app/(workspace)/app/[workspaceId]/library/[docId]/page.tsx index dd279f1..0d5efa2 100644 --- a/web/app/(workspace)/app/[workspaceId]/library/[docId]/page.tsx +++ b/web/app/(workspace)/app/[workspaceId]/library/[docId]/page.tsx @@ -1,15 +1,20 @@ 'use client' -import { useEffect, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { useParams, usePathname, useRouter } from 'next/navigation' import { Loader2, ChevronRight, ArrowLeft, ExternalLink, Sparkles, Share2, } from 'lucide-react' import FolderDocumentEditor from '@/components/documents/FolderDocumentEditor' +import RecapContextPanel from '@/components/documents/RecapContextPanel' +import RecapDocEnhancements from '@/components/documents/RecapDocEnhancements' +import SynthesisRoiIndicator from '@/components/documents/SynthesisRoiIndicator' import { getWorkspaceName } from '@/lib/workspaces' import { loadServerDocument, saveServerDocument, type ServerDocument } from '@/lib/library-api' import { resolveWorkspaceIdFromBrowserPath, workspacePath } from '@/lib/workspace-routes' +import { useRecapNotes } from '@/lib/use-recap-notes' +import type { FolderDocument } from '@/lib/workspace-library' /** * Server-backed library document viewer/editor. @@ -29,8 +34,30 @@ export default function LibraryDocPage() { const [title, setTitle] = useState('') const [loading, setLoading] = useState(true) const [saved, setSaved] = useState(false) + const [panelCollapsed, setPanelCollapsed] = useState(false) const skipNextContentRef = useRef(false) + const { notes: pageNotes, loading: notesLoading } = useRecapNotes( + workspaceId, + doc?.pageUrl ?? undefined, + ) + + const recapDoc = useMemo((): FolderDocument | null => { + if (!doc) return null + return { + id: doc.id, + workspaceId: doc.workspaceId, + folderId: doc.folderId, + title: doc.title, + content: doc.content, + createdAt: doc.createdAt, + updatedAt: doc.updatedAt, + autoGenerated: doc.autoGenerated, + pageUrl: doc.pageUrl ?? undefined, + recapStale: doc.recapStale, + } + }, [doc]) + useEffect(() => { let cancelled = false async function load() { @@ -91,7 +118,7 @@ export default function LibraryDocPage() { const displayTitle = title.trim() || 'Untitled' return ( -
+
{doc.autoGenerated && (
-
-
+
+
+
+ {doc.autoGenerated && ( +
+ + {!notesLoading && pageNotes.length > 0 && ( + + )} +
+ )} +
{workspaceName} @@ -151,6 +200,7 @@ export default function LibraryDocPage() { )} + {!doc.autoGenerated && ( + )} + + {doc.autoGenerated && !notesLoading && pageNotes.length > 0 && ( + + )} +
+ + {doc.autoGenerated && recapDoc && ( + { /* server-backed; auto-regenerates */ }} + collapsed={panelCollapsed} + onCollapsedChange={setPanelCollapsed} + /> + )}
) diff --git a/web/app/(workspace)/app/[workspaceId]/library/[docId]/study/page.tsx b/web/app/(workspace)/app/[workspaceId]/library/[docId]/study/page.tsx new file mode 100644 index 0000000..84f7d48 --- /dev/null +++ b/web/app/(workspace)/app/[workspaceId]/library/[docId]/study/page.tsx @@ -0,0 +1,17 @@ +import { Suspense } from 'react' +import { Loader2 } from 'lucide-react' +import LibraryStudyPlanPage from '@/components/documents/LibraryStudyPlanPage' + +export default function LibraryStudyPlanRoute() { + return ( + + +
+ )} + > + + + ) +} diff --git a/web/app/api/ai/knowledge-cards/route.ts b/web/app/api/ai/knowledge-cards/route.ts new file mode 100644 index 0000000..eb8c7d5 --- /dev/null +++ b/web/app/api/ai/knowledge-cards/route.ts @@ -0,0 +1,99 @@ +import { NextResponse } from 'next/server' +import { generateText } from 'ai' +import { createGoogleGenerativeAI } from '@ai-sdk/google' +import { getAIApiKey, getSupabaseAndUserFromRequest } from '@/lib/ai-key' +import { INLINE_SHORT_PERSONA } from '@/lib/inline-persona' + +const TOPICS = new Set(['interview', 'concepts', 'connections', 'gaps']) + +const TOPIC_PROMPTS: Record = { + interview: 'Generate tough PM-style interview questions from the material. Front = question, back = concise model answer grounded in the captures.', + concepts: 'Extract key terms and definitions. Front = term, back = clear definition from the material.', + connections: 'Show how ideas across captures relate. Front = relationship prompt, back = explanation tying sources together.', + gaps: 'Surface what the notes do not cover yet. Front = gap or open question, back = what is missing or under-explored (lightweight, not exhaustive).', +} + +export async function POST(request: Request) { + const { user, supabase } = await getSupabaseAndUserFromRequest(request) + if (!user || !supabase) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + let recapText = '' + let notesText = '' + let topic = 'interview' + + try { + const body = await request.json() + recapText = typeof body.recapText === 'string' ? body.recapText : '' + notesText = typeof body.notes === 'string' ? body.notes : '' + topic = typeof body.topic === 'string' ? body.topic : 'interview' + } catch { + return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) + } + + if (!TOPICS.has(topic)) { + return NextResponse.json({ error: 'Invalid topic' }, { status: 400 }) + } + + const combined = `${recapText}\n\n${notesText}`.trim() + if (!combined) { + return NextResponse.json({ error: 'recapText or notes required' }, { status: 400 }) + } + + const apiKey = await getAIApiKey() + if (!apiKey) { + return NextResponse.json({ error: 'No AI API key configured.' }, { status: 403 }) + } + + const google = createGoogleGenerativeAI({ apiKey }) + const instruction = TOPIC_PROMPTS[topic] ?? TOPIC_PROMPTS.interview! + + try { + const { text } = await generateText({ + model: google('gemini-2.5-flash'), + system: INLINE_SHORT_PERSONA, + prompt: [ + instruction, + '', + 'Return ONLY valid JSON:', + '{"cards":[{"front":"string","back":"string","topic":"' + topic + '"}]}', + '', + 'Rules:', + '- Exactly 3 cards.', + '- Use only facts from the material below.', + '- Keep fronts short; backs scannable (2-4 sentences max).', + '', + 'Material:', + combined.slice(0, 14000), + ].join('\n'), + }) + + const jsonMatch = text.trim().match(/\{[\s\S]*\}/) + if (!jsonMatch) { + return NextResponse.json({ error: 'Failed to parse cards' }, { status: 500 }) + } + + const parsed = JSON.parse(jsonMatch[0]) as { + cards?: { front?: string; back?: string; topic?: string }[] + } + + const cards = (parsed.cards ?? []) + .filter(c => typeof c.front === 'string' && typeof c.back === 'string') + .slice(0, 3) + .map(c => ({ + front: c.front!.trim(), + back: c.back!.trim(), + topic, + })) + + if (cards.length === 0) { + return NextResponse.json({ error: 'No cards generated' }, { status: 500 }) + } + + return NextResponse.json({ cards }) + } catch (err) { + console.error('[knowledge-cards] Error:', err) + return NextResponse.json({ error: 'AI request failed.' }, { status: 500 }) + } +} diff --git a/web/app/api/ai/page-recap/route.ts b/web/app/api/ai/page-recap/route.ts index 6bf50ee..6730e56 100644 --- a/web/app/api/ai/page-recap/route.ts +++ b/web/app/api/ai/page-recap/route.ts @@ -148,7 +148,7 @@ export async function POST(request: Request) { const body = (n.content ?? '').trim() const stamp = new Date(n.updated_at ?? n.created_at).toLocaleString() const bullet = body ? body.replace(/\n+/g, ' ').slice(0, 500) : '_empty_' - return `- **${stamp}** — ${bullet}` + return `- ${stamp} — ${bullet}` }).join('\n') return `## ${heading}\n\n${rows}` }) diff --git a/web/app/api/feedback/route.ts b/web/app/api/feedback/route.ts new file mode 100644 index 0000000..b45789f --- /dev/null +++ b/web/app/api/feedback/route.ts @@ -0,0 +1,57 @@ +import { NextResponse } from 'next/server' +import { getSupabaseAndUserFromRequest } from '@/lib/ai-key' + +const ALLOWED_SURFACES = new Set([ + 'chat', + 'insights', + 'roi', + 'knowledge-cards', +]) + +export async function POST(request: Request) { + const { user, supabase } = await getSupabaseAndUserFromRequest(request) + if (!user || !supabase) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + let workspaceId = '' + let surface = '' + let targetId = '' + let rating = 0 + let comment: string | null = null + + try { + const body = await request.json() + workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : '' + surface = typeof body.surface === 'string' ? body.surface : '' + targetId = typeof body.targetId === 'string' ? body.targetId : '' + rating = body.rating === 1 || body.rating === -1 ? body.rating : 0 + comment = typeof body.comment === 'string' && body.comment.trim() + ? body.comment.trim().slice(0, 500) + : null + } catch { + return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) + } + + if (!workspaceId || !ALLOWED_SURFACES.has(surface) || rating === 0) { + return NextResponse.json({ error: 'workspaceId, surface, and rating required' }, { status: 400 }) + } + + /* eslint-disable @typescript-eslint/no-explicit-any */ + const { error } = await (supabase as any).from('ai_feedback').insert({ + user_id: user.id, + workspace_id: workspaceId, + surface, + target_id: targetId, + rating, + comment, + }) + /* eslint-enable @typescript-eslint/no-explicit-any */ + + if (error) { + console.error('[feedback] insert error:', error) + return NextResponse.json({ error: 'Failed to save feedback' }, { status: 500 }) + } + + return NextResponse.json({ ok: true }) +} diff --git a/web/app/api/workspace/[workspaceId]/activity/route.ts b/web/app/api/workspace/[workspaceId]/activity/route.ts index cd34535..f5d25ac 100644 --- a/web/app/api/workspace/[workspaceId]/activity/route.ts +++ b/web/app/api/workspace/[workspaceId]/activity/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from 'next/server' import { getSupabaseAndUserFromRequest } from '@/lib/ai-key' +import { stripMarkdownToPlainText } from '@/lib/ai-text-format' export async function GET( request: Request, @@ -44,7 +45,9 @@ export async function GET( label: n.page_title || n.domain || 'Untitled', sub: n.domain, type: n.type, - snippet: typeof n.content === 'string' ? n.content.slice(0, 120) : '', + snippet: typeof n.content === 'string' + ? stripMarkdownToPlainText(n.content).slice(0, 120) + : '', time: n.created_at, })), ...exs.map(e => ({ diff --git a/web/components/ai/AiFeedbackBar.tsx b/web/components/ai/AiFeedbackBar.tsx new file mode 100644 index 0000000..0bbe5c7 --- /dev/null +++ b/web/components/ai/AiFeedbackBar.tsx @@ -0,0 +1,148 @@ +'use client' + +import { useState } from 'react' +import { ThumbsDown, ThumbsUp } from 'lucide-react' +import { cn } from '@/lib/utils' + +const DOWN_OPTIONS = [ + 'Too long', + 'Hallucinated', + 'Missed the point', +] as const + +export type FeedbackSurface = 'chat' | 'insights' | 'roi' | 'knowledge-cards' + +interface Props { + workspaceId: string + surface: FeedbackSurface + targetId: string + className?: string +} + +export default function AiFeedbackBar({ workspaceId, surface, targetId, className }: Props) { + const [rating, setRating] = useState<-1 | 1 | null>(null) + const [showDown, setShowDown] = useState(false) + const [comment, setComment] = useState('') + const [sending, setSending] = useState(false) + const [done, setDone] = useState(false) + + async function submit(nextRating: -1 | 1, nextComment?: string) { + if (sending || done) return + setSending(true) + try { + const res = await fetch('/api/feedback', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + workspaceId, + surface, + targetId, + rating: nextRating, + comment: nextComment, + }), + }) + if (res.ok) { + setRating(nextRating) + setDone(true) + setShowDown(false) + } + } catch { /* ignore */ } + finally { setSending(false) } + } + + function handleUp() { + void submit(1) + } + + function handleDown() { + if (done) return + setShowDown(v => !v) + } + + function handleDownOption(option: string) { + setComment(option) + void submit(-1, option) + } + + if (done) { + return ( +

+ Thanks for the feedback. +

+ ) + } + + return ( +
+
+ Helpful? + + +
+ + {showDown && !done && ( +
+
+ {DOWN_OPTIONS.map(opt => ( + + ))} +
+