import { ChatView } from './views/chat/chat-view.js?v=13';
import { db } from './db/database.js';
import { Clipboard } from '@capacitor/clipboard';
import { authService } from './services/auth-service.js';
import { syncManager } from './services/sync-service.js';
import { ttsService } from './services/tts-service.js';
import { appShortcutsService } from './services/app-shortcuts-service.js';
import { showVocabularyModal } from './views/vocabulary-modal.js';
import { TextToSpeech } from '@capacitor-community/text-to-speech';
// Handle PWA Service Worker
if ('serviceWorker' in navigator) {
if (window.Capacitor) {
// IMPORTANT: If we are in the native Capacitor app, we MUST NOT use a Service Worker.
// A Service Worker here would aggressively cache local files and prevent app updates!
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for(let registration of registrations) {
registration.unregister();
console.log('Successfully unregistered old PWA Service Worker in Capacitor');
}
});
} else {
// We are in a normal browser (e.g. HuggingFace). Register the PWA Service Worker.
import('virtual:pwa-register').then(({ registerSW }) => {
registerSW({ immediate: true });
}).catch(err => console.warn('PWA Registration failed', err));
}
}
// Handle App Shortcuts and Intents globally
window.addEventListener('appShortcutAction', (e) => {
if (e.detail && e.detail.shortcutId === 'add_vocabulary') {
showVocabularyModal();
}
});
window.ttsService = ttsService;
window.TextToSpeech = TextToSpeech;
window.appPrompt = function(message) {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'custom-modal-overlay';
overlay.innerHTML = `
`;
document.body.appendChild(overlay);
const cancelBtn = overlay.querySelector('.cancel');
const confirmBtn = overlay.querySelector('.confirm');
const close = (val) => {
overlay.classList.add('fade-out');
setTimeout(() => { overlay.remove(); resolve(val); }, 300);
};
cancelBtn.onclick = () => close(false);
confirmBtn.onclick = () => close(true);
});
};
window.copyToClipboard = async (text, btnElement) => {
const showCheckmark = () => {
if (!btnElement) return;
const svg = btnElement.querySelector('svg');
if (!svg) return;
const oldHtml = svg.outerHTML;
svg.outerHTML = '';
setTimeout(() => {
btnElement.innerHTML = oldHtml;
}, 2000);
};
const formatForNotes = (raw) => {
if (!raw) return raw;
// 1. Strip inline formatting and block markers
let text = raw
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/__(.*?)__/g, '$1')
.replace(/\*(.*?)\*/g, '$1')
.replace(/_(.*?)_/g, '$1')
.replace(/~~(.*?)~~/g, '$1')
.replace(/`(.*?)`/g, '$1')
.replace(/\[(.*?)\]\(.*?\)/g, '$1')
.replace(/^```[a-z]*\n/gm, '')
.replace(/^```\s*$/gm, '')
.replace(/^>\s+/gm, '');
const lines = text.split('\n');
const processedLines = [];
let previousRealLineWasList = false;
let emptyLinesSeen = 0;
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
if (line === '') {
emptyLinesSeen++;
continue;
}
const headerMatch = line.match(/^#+\s+(.*)$/);
const listMatch = line.match(/^([\*\-]|\d+\.)\s+(.*)$/);
if (headerMatch) {
// Empty line before header
if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') {
processedLines.push('');
}
processedLines.push(headerMatch[1]);
// Empty line after header
processedLines.push('');
previousRealLineWasList = false;
emptyLinesSeen = 0;
} else if (listMatch) {
if (!previousRealLineWasList) {
// Empty line before first list item
if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') {
processedLines.push('');
}
}
const bullet = (listMatch[1] === '*' || listMatch[1] === '-') ? '• ' : `${listMatch[1]} `;
processedLines.push(`${bullet}${listMatch[2]}`);
previousRealLineWasList = true;
emptyLinesSeen = 0;
} else {
// Normal text
if (previousRealLineWasList) {
// Ensure empty line after list
if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') {
processedLines.push('');
}
} else if (emptyLinesSeen > 0 && processedLines.length > 0) {
// Maintain paragraph breaks for text
if (processedLines[processedLines.length - 1] !== '') {
processedLines.push('');
}
}
processedLines.push(line);
previousRealLineWasList = false;
emptyLinesSeen = 0;
}
}
return processedLines.join('\n').trim();
};
const formattedText = formatForNotes(text);
try {
await Clipboard.write({ string: formattedText });
showCheckmark();
} catch (e) {
console.log('Capacitor Clipboard fallback:', e);
// Legacy fallback for non-secure HTTP contexts
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(formattedText);
} else {
const textArea = document.createElement("textarea");
textArea.value = formattedText;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
textArea.remove();
}
showCheckmark();
} catch (err) {
console.error('Copy failed:', err);
}
}
};
const initApp = async () => {
// FAST PATH: Check for overlay mode IMMEDIATELY, before any heavy initialization.
// This cuts ~1-2 seconds off overlay startup by skipping auth, sync, etc.
const isNative = window.Capacitor && typeof window.Capacitor.isNativePlatform === 'function' && window.Capacitor.isNativePlatform();
if (isNative) {
const { QuickSettings } = window.Capacitor.Plugins;
if (QuickSettings) {
const intentResult = await QuickSettings.getPendingIntentAction();
if (intentResult && intentResult.overlay_mode === true) {
// Force transparent on EVERY layer via cssText (highest inline priority)
document.documentElement.style.cssText = 'background: transparent !important; background-color: transparent !important;';
document.body.style.cssText = 'background: transparent !important; background-color: transparent !important; margin: 0; padding: 0; visibility: visible !important;';
// Hide ALL non-modal elements
const hideSelectors = ['#app', '.aurora-background', '#ambient-light', '#live-version-badge', 'svg[style*="pointer-events: none"]'];
hideSelectors.forEach(sel => {
const el = document.querySelector(sel);
if (el) el.style.display = 'none';
});
window.isOverlayMode = true;
await db.initPromise;
showVocabularyModal();
// Signal native side to fade in the window (prevents black flash)
QuickSettings.overlayReady();
return; // Early return — skip ALL heavy initialization
}
}
}
// NORMAL APP PATH: Full initialization
await db.initPromise;
await authService.initialize();
await syncManager.initialize();
await appShortcutsService.initialize();
// Load background style
const bgStyle = db.getSetting('background_style') || 'standard';
document.body.setAttribute('data-bg-style', bgStyle);
// Make body visible for normal app
document.body.style.visibility = 'visible';
// Process any pending vocabulary from the Quick Settings native overlay
const processOfflineVocabularyQueue = async () => {
if (!isNative) return;
try {
const { QuickSettings } = window.Capacitor.Plugins;
if (QuickSettings) {
const { queue } = await QuickSettings.getPendingVocab();
if (queue && queue !== '[]') {
const words = JSON.parse(queue);
if (words.length > 0) {
console.log("Processing offline vocabulary queue:", words);
// Start background translation process
setTimeout(async () => {
const { aiRouter } = await import('./ai/router.js');
let addedCount = 0;
for (const word of words) {
try {
const prompt = `Übersetze das folgende Wort oder den Satz. Wenn es Deutsch ist, übersetze es ins Englische. Wenn es Englisch ist, übersetze es ins Deutsche.
Falls das Wort extrem falsch geschrieben ist (z.B. phonetisch nach Gehör geschrieben), erkenne das korrekte Wort automatisch und übersetze es.
Das korrekte Wort soll in "front" stehen und die Übersetzung in "back".
Zusätzlich generiere:
- "explanation": 1-2 kurze Sätze in der Sprache der Übersetzung ('back'), die genau dieses Wort erklären. WICHTIG: Markiere das Lernwort (und seine Abwandlungen) IMMER fett mit HTML-Tags (z.B. Wort).
- "example": Ein prägnanter Beispielsatz mit der Übersetzung ('back'). Das Lernwort MUSS auch hier mit ... fett markiert sein.
- "imageQuery": Ein präziser englischer Suchbegriff für die Bing-Bildersuche. Das Bild muss EINDEUTIG zur Übersetzung passen. Füge IMMER 'single photo, clear focus, high quality' am Ende hinzu. Keine abstrakten Cartoons.
Antworte AUSSCHLIESSLICH mit einem validen JSON-Objekt. Keine Markdown-Formatierung.
Beispiel für "abanden":
{"front": "abandon", "back": "verlassen", "explanation": "Jemanden oder etwas verlassen oder aufgeben.", "example": "Er musste das alte Auto verlassen.", "imageQuery": "abandoned old car single photo clear focus"}
Zu übersetzen: "${word}"`;
const response = await aiRouter.sendMessage(prompt, {
model: db.getSetting('model') || 'gemini-1.5-flash'
});
let jsonStr = response.trim();
if (jsonStr.startsWith('```json')) jsonStr = jsonStr.replace(/```json/g, '').replace(/```/g, '').trim();
else if (jsonStr.startsWith('```')) jsonStr = jsonStr.replace(/```/g, '').trim();
let parsed = null;
try {
parsed = JSON.parse(jsonStr);
} catch (e) {
console.warn("JSON parse failed, trying fallback...", jsonStr);
parsed = { front: word, back: response.replace(/\{|\}/g, '').replace(/"/g, '').replace(/back:|front:|\\n/gi, '').trim(), explanation: "", example: "", imageQuery: encodeURIComponent(word) };
}
if (parsed && parsed.back) {
let decks = db.getDecks();
let schnelldeck = decks.find(d => d.title === 'Schnelleingabe' || d.title === 'Inbox');
if (!schnelldeck) schnelldeck = db.createDeck('Schnelleingabe', 'Automatisch gespeicherte Vokabeln aus der Schnelleingabe', '#8a53e6', 'Englisch', 'Deutsch');
let finalBack = parsed.back;
if (parsed.explanation && parsed.example) {
finalBack = `${parsed.back}\n\n**Erklärung:** ${parsed.explanation}\n\n**Beispiel:** ${parsed.example}`;
}
const searchTerms = encodeURIComponent(parsed.imageQuery || parsed.front);
const imageUrl = `https://tse1.mm.bing.net/th?q=${searchTerms}&w=800&h=1000&c=7&rs=1`;
db.addFlashcard(schnelldeck.id, parsed.front, finalBack, imageUrl);
addedCount++;
}
} catch (e) {
console.error("Failed to translate offline word:", word, e);
}
}
await QuickSettings.clearPendingVocab();
if (addedCount > 0) {
// Dispatch event so UI can refresh if user is on flashcards page
window.dispatchEvent(new CustomEvent('flashcards-updated'));
// Show a small toast notification
const toast = document.createElement('div');
toast.style = "position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: rgba(52, 199, 89, 0.95); color: white; padding: 12px 24px; border-radius: 30px; font-weight: 600; font-size: 15px; z-index: 99999; box-shadow: 0 8px 24px rgba(0,0,0,0.3); animation: slide-down 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);";
toast.innerHTML = `✨ ${addedCount} Vokabel(n) hinzugefügt!`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.4s';
setTimeout(() => toast.remove(), 400);
}, 4000);
}
}, 1000); // Wait 1s instead of 2s
}
}
}
} catch (e) {
console.warn("Error reading pending vocab queue:", e);
}
};
const processEnrichmentQueue = async () => {
// Only run if we're not in the tiny transparent overlay mode
if (window.isOverlayMode) return;
let pendingCards = db.getPendingCards();
if (!pendingCards || pendingCards.length === 0) return;
if (!window.isEnriching) {
window.isEnriching = true;
try {
const { aiRouter } = await import('./ai/router.js');
// Process sequentially
for (const card of pendingCards) {
const word = card.front;
const pureTranslation = card.back.replace('', '').replace('', '').trim();
const prompt = `Erstelle eine kurze Erklärung und ein passendes Beispiel für diese Vokabelkarte, sowie einen Suchbegriff für ein Bild.
Wort: "${word}"
Übersetzung: "${pureTranslation}"
WICHTIG: Prüfe, ob das "Wort" offensichtlich falsch geschrieben ist (z.B. phonetisch nach Gehör geschrieben).
Falls es einen Tippfehler enthält, gib das richtig geschriebene Wort im Feld "correctedWord" zurück. Wenn es korrekt geschrieben ist, lass das Feld weg oder setze es auf null.
Generiere:
- "explanation": 1-2 kurze Sätze in der Sprache der Übersetzung, die genau dieses Wort erklären. WICHTIG: Markiere das Lernwort (und seine Abwandlungen) IMMER fett mit HTML-Tags (z.B. Wort).
- "example": Ein prägnanter Beispielsatz mit der Übersetzung. Das Lernwort MUSS auch hier mit ... fett markiert sein.
- "imageQuery": Ein präziser englischer Suchbegriff für die Bing-Bildersuche. Das Bild muss EINDEUTIG zur Übersetzung passen. Füge IMMER 'single photo, clear focus, high quality' am Ende hinzu. Keine abstrakten Cartoons.
Antworte AUSSCHLIESSLICH mit einem validen JSON-Objekt. Keine Markdown-Formatierung.
Beispiel für Tippfehler bei "abanden":
{"correctedWord": "abandon", "explanation": "Jemanden oder etwas verlassen oder aufgeben.", "example": "Er musste das alte Auto verlassen.", "imageQuery": "abandoned old car single photo clear focus"}`;
const response = await aiRouter.sendMessage(prompt, {
model: db.getSetting('model') || 'gemini-1.5-flash', // Use standard model to ensure it doesn't fail
disableTools: true // VERY IMPORTANT: Prevent AI from calling create_flashcards and duplicating the deck
});
let jsonStr = response.trim();
if (jsonStr.startsWith('```json')) jsonStr = jsonStr.replace(/```json/g, '').replace(/```/g, '').trim();
else if (jsonStr.startsWith('```')) jsonStr = jsonStr.replace(/```/g, '').trim();
try {
const parsed = JSON.parse(jsonStr);
if (parsed.explanation && parsed.example) {
const finalBack = `${pureTranslation}\n\n**Erklärung:** ${parsed.explanation}\n\n**Beispiel:** ${parsed.example}`;
const searchTerms = encodeURIComponent(parsed.imageQuery || word);
const imageUrl = `https://tse1.mm.bing.net/th?q=${searchTerms}&w=800&h=1000&c=7&rs=1`;
// If the AI corrected a typo, use it. Otherwise use the original front.
const finalFront = parsed.correctedWord ? parsed.correctedWord : card.front;
db.editFlashcard(card.id, finalFront, finalBack, imageUrl);
console.log(`Enriched card: ${word}`);
}
} catch (e) {
console.warn("JSON parse failed for enrichment", jsonStr);
}
// Small pause between requests to avoid rate limits
await new Promise(r => setTimeout(r, 500));
}
// Dispatch event ONCE after all retroactive enrichment is done, to prevent UI scrolling spam
window.dispatchEvent(new CustomEvent('flashcards-updated'));
if (document.visibilityState === 'visible') {
const toast = document.createElement('div');
toast.style = "position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: rgba(52, 199, 89, 0.95); color: white; padding: 12px 24px; border-radius: 30px; font-weight: 600; font-size: 15px; z-index: 99999; box-shadow: 0 8px 24px rgba(0,0,0,0.3); animation: slide-down 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);";
toast.innerHTML = `✨ Vokabel im Hintergrund geprüft und vervollständigt!`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.4s ease';
setTimeout(() => toast.remove(), 400);
}, 3000);
}
} catch (e) {
console.error("Enrichment queue failed", e);
} finally {
window.isEnriching = false;
}
}
};
// Run on startup
processOfflineVocabularyQueue();
processEnrichmentQueue();
// Check if we were launched with a native Intent (non-overlay)
if (isNative) {
const { QuickSettings } = window.Capacitor.Plugins;
if (QuickSettings) {
const intentResult = await QuickSettings.getPendingIntentAction();
if (intentResult && intentResult.action === 'add_vocabulary') {
showVocabularyModal();
}
}
}
// Run whenever the app resumes (comes to foreground)
document.addEventListener("visibilitychange", async () => {
if (document.visibilityState === 'visible') {
processOfflineVocabularyQueue();
processEnrichmentQueue();
if (isNative) {
const { QuickSettings } = window.Capacitor.Plugins;
if (QuickSettings) {
const intentResult = await QuickSettings.getPendingIntentAction();
if (intentResult && intentResult.overlay_mode === true) {
document.body.style.background = 'transparent';
document.body.style.backgroundColor = 'transparent';
const appElement = document.getElementById('app');
if (appElement) appElement.style.display = 'none';
window.isOverlayMode = true;
showVocabularyModal();
} else if (intentResult && intentResult.action === 'add_vocabulary') {
showVocabularyModal();
}
}
}
}
});
// Scale up UI on web (HuggingFace) to match Capacitor native scale
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (!isNative && isMobile) {
document.documentElement.style.zoom = '1.15';
}
console.log('SchoolMind AI initialized');
const appContainer = document.getElementById('app');
// Basic skeleton for the layout
appContainer.innerHTML = `
Verlauf
KI Dateizugriff
Gemini möchte Datei X lesen.
Aktionen
Features
✨ Vertiefte Recherche
🕵️ Detective Board
Dauer (Tiefe):
🧠 Erweitertes Denken
Lokales Wissen
Vault durchsuchen
Stimme & Stil
✍️ Persönlicher Style
`;
// View Instances
const chatView = new ChatView('router-view');
try {
await chatView.init();
} catch (err) {
console.error('Failed to initialize ChatView:', err);
// Continue execution so tabs still work even if chat fails
}
window.chatView = chatView; // Export globally for IServ View to trigger PDF modal
window.openPdfModal = chatView.openPdfModal ? chatView.openPdfModal.bind(chatView) : null;
window.openArticleModal = chatView.openArticleModal ? chatView.openArticleModal.bind(chatView) : null;
// We lazily import or instantiate SettingsView when needed, or just import it at top
// To keep it simple, we'll instantiate it directly here but handle rendering in tab clicks.
// --- TAB NAVIGATION LOGIC ---
const tabItems = document.querySelectorAll('.tab-item');
const inputCapsule = document.querySelector('.input-capsule-container');
const routerView = document.getElementById('router-view');
let activeView = null; // Track the currently active view to destroy it when switching
tabItems.forEach(tab => {
tab.addEventListener('click', async () => {
const tabName = tab.getAttribute('data-tab');
// Remove active class from all
tabItems.forEach(t => t.classList.remove('active'));
// Add active class to clicked
tab.classList.add('active');
await window.openView(tabName);
});
});
const handleImportError = (e) => {
if (e.message && e.message.includes('Failed to fetch dynamically imported module')) {
// The app was updated and the old chunks are gone from the server.
// Force a reload to fetch the new index.html and its new chunk map.
routerView.innerHTML = `