Imamverdi Behbudlu
build: compile fresh production bundle with complete English UI
9db2371
Raw History Blame Contribute Delete
132 kB
import React, { useState, useEffect, useRef } from 'react'; import FormbricksTranslator from './components/FormbricksTranslator'; import { Settings, Plus, Trash2, ChevronDown, ChevronUp, Play, Copy, Download, Eye, Check, AlertCircle, FileJson, FileText, Upload, Layers, Sparkles, HelpCircle, CheckCircle, Loader2, Lock, Globe, Sun, Moon, FileSpreadsheet, Zap, Archive, ArchiveRestore, Inbox, Square, Octagon, RotateCw, RefreshCw, DollarSign, Coins, Info, PieChart } from 'lucide-react'; import confetti from 'canvas-confetti'; import * as XLSX from 'xlsx'; import { extractTranslatableSegments, reconstructJson, runPipelineForSegment, calculateLevenshteinDistance } from './utils/pipeline'; import { SAMPLE_EMAIL_TEMPLATE, SAMPLE_WEBSITE_I18N_TEMPLATE, SAMPLE_PRODUCT_CATALOG_TEMPLATE, SAMPLE_MARKDOWN_FAQ_TEMPLATE } from './utils/sampleTemplate'; import { parseMarkdownToSegments, extractSmartMarkdownContext, compactUserContext, reconstructMarkdown } from './utils/markdownParser'; import { API_PRICING, calculateSegmentCost, calculateOutputCost, calculateTaskCost, calculateTotalAllTasksCost, formatCurrency } from './utils/costCalculator'; const GEMINI_MODEL = import.meta.env.VITE_GEMINI_MODEL || 'gemini-3.5-flash'; const OPENAI_MODEL = import.meta.env.VITE_OPENAI_MODEL || 'gpt-4o'; const CLAUDE_MODEL = import.meta.env.VITE_CLAUDE_MODEL || 'claude-opus-4.8'; const CONTENT_TYPES = [ { id: 'WEBSITE', name: '🌐 Website / App i18n', label: 'Website UI & App Localized Strings' }, { id: 'EMAIL', name: '✉️ Email Campaign', label: 'Marketing Email Content' }, { id: 'MARKDOWN', name: '📄 FAQ & Markdown (.md)', label: 'Markdown Knowledge Base & FAQ Article' }, { id: 'ECOMMERCE', name: '🛒 E-Commerce & Products', label: 'E-Commerce Product Catalog Content' }, { id: 'CMS', name: '📝 CMS & Blog Articles', label: 'CMS Article & Blog Content' }, { id: 'GENERAL', name: '🧩 General JSON Content', label: 'General JSON Content' } ]; const LANGUAGES = [ { code: 'FR', name: 'French (Français)' }, { code: 'NL', name: 'Dutch (Nederlands)' }, { code: 'DE', name: 'German (Deutsch)' }, { code: 'ES', name: 'Spanish (Español)' }, { code: 'PT', name: 'Portuguese (Português)' }, { code: 'BR', name: 'Portuguese (Brazil)' }, { code: 'HU', name: 'Hungarian (Magyar)' }, { code: 'CS', name: 'Czech (Čeština)' }, { code: 'PL', name: 'Polish (Polski)' }, { code: 'IT', name: 'Italian (Italiano)' }, { code: 'EL', name: 'Greek (Ελληνικά)' } ]; export default function App() { // API keys are securely managed via backend environment variables const getDefaultPresetTasks = () => [ { id: '1', campaignName: 'Payment Failed Email', contentType: 'EMAIL', originalJsonText: JSON.stringify(SAMPLE_EMAIL_TEMPLATE, null, 2), targetLangs: ['FR', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '2', campaignName: 'FAQ & Markdown (.md) Document', contentType: 'MARKDOWN', originalJsonText: SAMPLE_MARKDOWN_FAQ_TEMPLATE, targetLangs: ['FR', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '3', campaignName: 'Website & App i18n Localization', contentType: 'WEBSITE', originalJsonText: JSON.stringify(SAMPLE_WEBSITE_I18N_TEMPLATE, null, 2), targetLangs: ['FR', 'NL', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, NL: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '4', campaignName: 'Product Catalog (E-Commerce)', contentType: 'ECOMMERCE', originalJsonText: JSON.stringify(SAMPLE_PRODUCT_CATALOG_TEMPLATE, null, 2), targetLangs: ['FR', 'DE', 'ES'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, ES: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } } ]; // Translation tasks list const [tasks, setTasks] = useState(() => { const saved = localStorage.getItem('consensus_ai_tasks_v4'); if (saved !== null) { try { const parsed = JSON.parse(saved); if (Array.isArray(parsed)) return parsed; } catch (e) { console.error("Failed to load tasks:", e); } } return getDefaultPresetTasks(); }); const resetAllDefaultTasks = () => { if (window.confirm("Do you want to reset and restore the 4 default template projects (FAQ Markdown, Email, Website, E-Commerce)?")) { const defaultTasks = getDefaultPresetTasks(); setTasks(defaultTasks); localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(defaultTasks)); } }; // UI state variables const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [activeDetails, setActiveDetails] = useState(null); // { taskId, langCode } const [selectedSegmentIndex, setSelectedSegmentIndex] = useState(0); const [activeLangDropdown, setActiveLangDropdown] = useState(null); // taskId const [copiedTextId, setCopiedTextId] = useState(null); // 'taskId_langCode' or similar const [activeNotesModal, setActiveNotesModal] = useState(null); // { taskId, langCode } const [activeJsonViewer, setActiveJsonViewer] = useState(null); // { title, jsonText } const [isPricingModalOpen, setIsPricingModalOpen] = useState(false); const [activeCostPopoverId, setActiveCostPopoverId] = useState(null); // 'global' | taskId | 'sub_taskId_langCode' const dropdownRef = useRef(null); const popoverRef = useRef(null); // Auto Queue Mode state const [isAutoQueueActive, setIsAutoQueueActive] = useState(false); const [isProcessingQueue, setIsProcessingQueue] = useState(false); // Archive vs Active view tab state const [activeTab, setActiveTab] = useState('active'); // 'active' | 'archive' // App Mode state const [appMode, setAppMode] = useState('translator'); // 'translator' | 'formbricks' // Panel mode switcher: 'JSON' vs 'MARKDOWN' const [translationMode, setTranslationMode] = useState('MARKDOWN'); // 'JSON' | 'MARKDOWN' // Cancel / Stop Translation Ref const isCancelRequestedRef = useRef(false); // Per-step Granular Retry state const [retryingStepKey, setRetryingStepKey] = useState(null); // Instruction Manual Modal state const [isGuideModalOpen, setIsGuideModalOpen] = useState(false); // Theme support: default is dark mode (behbudlu.com) const [isDarkMode, setIsDarkMode] = useState(() => { const saved = localStorage.getItem('et_dark_mode'); return saved ? JSON.parse(saved) : true; }); useEffect(() => { localStorage.setItem('et_dark_mode', JSON.stringify(isDarkMode)); if (isDarkMode) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } }, [isDarkMode]); // Sync initial load with Central Backend Storage (/api/tasks) useEffect(() => { fetch('/api/tasks') .then(res => res.json()) .then(data => { if (Array.isArray(data)) { setTasks(data); localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(data)); } else if (data === null) { // Initialize server with current default tasks const defaultTasks = getDefaultPresetTasks(); fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tasks: defaultTasks }) }).catch(e => {}); } }) .catch(err => console.warn("Backend tasks fetch notice:", err)); }, []); useEffect(() => { localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(tasks)); const timer = setTimeout(() => { fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tasks }) }).catch(err => {}); }, 400); return () => clearTimeout(timer); }, [tasks]); // --- Fail-proof Excel Exporter & File Saver --- const saveExcelFile = (rowsData, fileName, sheetName = 'Translations') => { try { // Excel Hard Limit Safety: Max 32,767 characters per single cell const safeRows = rowsData.map(row => { const cleanRow = {}; Object.keys(row).forEach(key => { let val = row[key]; if (typeof val === 'string' && val.length > 32000) { val = val.slice(0, 32000) + '\n\n... [NOTE: Text truncated to fit Excel 32,767 character cell limit. Download the full document via .md / .json button.]'; } cleanRow[key] = val; }); return cleanRow; }); const worksheet = XLSX.utils.json_to_sheet(safeRows); worksheet['!cols'] = [ { wch: 22 }, { wch: 18 }, { wch: 14 }, { wch: 70 }, { wch: 14 }, { wch: 50 }, { wch: 60 } ]; const workbook = XLSX.utils.book_new(); const safeSheetName = sheetName.replace(/[/\\?%*:|[\]]/g, '_').slice(0, 30); XLSX.utils.book_append_sheet(workbook, worksheet, safeSheetName); const safeFileName = (fileName || 'Tercume_Eksport').replace(/[/\\?%*:|"<>#]/g, '_') + '.xlsx'; try { XLSX.writeFile(workbook, safeFileName); } catch (err) { console.warn("XLSX.writeFile fallback triggered:", err); const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = safeFileName; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100); } } catch (globalErr) { console.error("Excel generation error:", globalErr); alert("Error: Failed to create Excel file: " + globalErr.message); } }; const exportAllToExcel = () => { const rows = []; tasks.forEach(task => { const campaign = task.campaignName?.trim() || `Kontent #${task.id}`; Object.keys(task.outputs).forEach(langCode => { const out = task.outputs[langCode]; if (out && (out.status === 'Success' || out.status === 'Completed')) { const langObj = LANGUAGES.find(l => l.code === langCode); const langLabel = langObj ? `${langObj.name} (${langCode})` : langCode; let cleanText = ''; if (out.translatedMd) { cleanText = out.translatedMd; } else if (out.segments && out.segments.length > 0) { cleanText = out.segments.map(s => s.claude).join('\n\n'); } else if (out.translatedJson) { cleanText = typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2); } rows.push({ 'Campaign / Document Title': campaign, 'Target Language': langLabel, 'Status': 'Completed', 'Translated Text (Clean)': cleanText, 'Divergence Percentage': out.conflictPct ? `${out.conflictPct}%` : '0%', 'Consensus Agent Notes': out.agentNotes || '', 'Translated Output (JSON / MD)': out.translatedJson ? (typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2)) : '' }); } }); }); if (rows.length === 0) { alert("No completed translations found to export."); return; } const dateStr = new Date().toISOString().slice(0, 10); saveExcelFile(rows, `Topdan_Tercumeler_${dateStr}`, "All Translations"); }; const exportSingleToExcel = (task, langCode) => { const out = task.outputs?.[langCode]; if (!out) { alert("Error: No translation data found for this language."); return; } const campaign = task.campaignName?.trim() || `Tercume_${task.id}`; const langObj = LANGUAGES.find(l => l.code === langCode); const langLabel = langObj ? `${langObj.name} (${langCode})` : langCode; let cleanText = ''; if (out.translatedMd) { cleanText = out.translatedMd; } else if (out.segments && out.segments.length > 0) { cleanText = out.segments.map(s => s.claude).join('\n\n'); } else if (out.translatedJson) { cleanText = typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2); } const rows = [{ 'Campaign / Document Title': campaign, 'Target Language': langLabel, 'Status': (out.status === 'Success' || out.status === 'Completed') ? 'Completed' : out.status, 'Translated Text (Clean)': cleanText, 'Divergence Percentage': out.conflictPct ? `${out.conflictPct}%` : '0%', 'Consensus Agent Notes': out.agentNotes || '', 'Translated Output (JSON / MD)': out.translatedJson ? (typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2)) : '' }]; saveExcelFile(rows, `${campaign}_${langCode}`, langCode); }; // Click outside listener for language dropdown and cost popovers useEffect(() => { function handleClickOutside(event) { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setActiveLangDropdown(null); } if (popoverRef.current && !popoverRef.current.contains(event.target)) { setActiveCostPopoverId(null); } } document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); // --- Auto Queue Worker Engine --- useEffect(() => { if (!isAutoQueueActive || isProcessingQueue) return; if (isCancelRequestedRef.current) { setIsAutoQueueActive(false); setIsProcessingQueue(false); return; } // Scan all tasks for the next language needing translation (Draft or Error) let nextJob = null; for (const task of tasks) { if (!task.originalJsonText || !task.targetLangs || task.targetLangs.length === 0) continue; for (const lang of task.targetLangs) { const out = task.outputs?.[lang]; const status = out?.status || 'Draft'; // Target tasks that are Draft or Error or failed status if (status === 'Draft' || status === 'Error' || status.toLowerCase().includes('error') || status === 'Xəta') { nextJob = { taskId: task.id, langCode: lang }; break; } } if (nextJob) break; } if (!nextJob) { // All tasks/languages are completed! return; } setIsProcessingQueue(true); (async () => { try { await runTranslationPipeline(nextJob.taskId, nextJob.langCode); } catch (err) { console.error("Auto queue job error:", err); } finally { // Breather pause (1.2s) before taking the next queue item await new Promise(r => setTimeout(r, 1200)); setIsProcessingQueue(false); } })(); }, [isAutoQueueActive, isProcessingQueue, tasks]); // --- Task management --- const addTask = () => { const nextNum = tasks.length > 0 ? Math.max(...tasks.map(t => parseInt(t.id) || 0)) + 1 : 1; const newTask = { id: Date.now().toString(), campaignName: '', contentType: translationMode === 'MARKDOWN' ? 'MARKDOWN' : 'WEBSITE', originalJsonText: '', customContext: '', targetLangs: [], expanded: true, outputs: {} }; setTasks([...tasks, newTask]); }; const updateTaskField = (taskId, field, value) => { setTasks(tasks.map(t => { if (t.id === taskId) { const updated = { ...t, [field]: value }; // If we change target languages, we initialize output records for any new language if (field === 'targetLangs') { const newOutputs = { ...t.outputs }; value.forEach(lang => { if (!newOutputs[lang]) { newOutputs[lang] = { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }; } }); // Clean up deleted languages from outputs Object.keys(newOutputs).forEach(lang => { if (!value.includes(lang)) { delete newOutputs[lang]; } }); updated.outputs = newOutputs; } return updated; } return t; })); }; const stopAllTranslations = () => { isCancelRequestedRef.current = true; setIsAutoQueueActive(false); setIsProcessingQueue(false); // INSTANT REACT STATE UPDATE: Stop all spinners immediately! setTasks(prevTasks => prevTasks.map(t => { const newOutputs = { ...t.outputs }; let hasChange = false; Object.keys(newOutputs).forEach(lang => { if (newOutputs[lang] && newOutputs[lang].status && (newOutputs[lang].status === 'Translating' || newOutputs[lang].status.startsWith('Translating'))) { newOutputs[lang] = { ...newOutputs[lang], status: 'Draft', error: null }; hasChange = true; } }); return hasChange ? { ...t, outputs: newOutputs } : t; })); }; const deleteTask = (taskId) => { setTasks(tasks.filter(t => t.id !== taskId)); }; const archiveTask = (taskId) => { setTasks(tasks.map(t => t.id === taskId ? { ...t, archived: true } : t)); }; const unarchiveTask = (taskId) => { setTasks(tasks.map(t => t.id === taskId ? { ...t, archived: false } : t)); }; // --- Excel Template Generator for non-JSON users --- const downloadExcelTemplate = () => { const templateRows = [ { "Section_ID": "hero_title", "Source_Text_English": "Welcome to Our Platform" }, { "Section_ID": "hero_subtitle", "Source_Text_English": "Build fast, modern, and localized websites effortlessly." }, { "Section_ID": "cta_button", "Source_Text_English": "Get Started Now" }, { "Section_ID": "feature_1_title", "Source_Text_English": "AI Multi-Agent Translation Engine" }, { "Section_ID": "footer_copyright", "Source_Text_English": "All rights reserved © 2026." } ]; const worksheet = XLSX.utils.json_to_sheet(templateRows); worksheet['!cols'] = [{ wch: 25 }, { wch: 60 }]; const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Translation_Template"); XLSX.writeFile(workbook, "Content_Translation_Sablon.xlsx"); }; // --- Universal File Uploader (Supports JSON, XLSX, XLS, CSV) --- const handleFileUpload = (taskId, file) => { if (!file) return; const fileName = file.name.toLowerCase(); if (fileName.endsWith('.json')) { const reader = new FileReader(); reader.onload = (e) => { try { const text = e.target.result; JSON.parse(text); updateTaskField(taskId, 'originalJsonText', text); } catch (err) { alert("Error: Selected file is not a valid JSON document."); } }; reader.readAsText(file); } else if (fileName.endsWith('.md') || fileName.endsWith('.markdown')) { const reader = new FileReader(); reader.onload = (e) => { const text = e.target.result; updateTaskField(taskId, 'contentType', 'MARKDOWN'); updateTaskField(taskId, 'originalJsonText', text); }; reader.readAsText(file); } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls') || fileName.endsWith('.csv')) { const reader = new FileReader(); reader.onload = (e) => { try { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); const firstSheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[firstSheetName]; const rawRows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); if (!rawRows || rawRows.length === 0) { alert("Error: The selected Excel file is empty."); return; } const jsonResult = {}; let count = 0; // Check if first row is header const firstRowFirstCol = String(rawRows[0]?.[0] || '').toLowerCase(); const startIdx = ( firstRowFirstCol.includes('id') || firstRowFirstCol.includes('section') || firstRowFirstCol.includes('bölmə') || firstRowFirstCol.includes('key') || firstRowFirstCol.includes('açar') || firstRowFirstCol.includes('key') ) ? 1 : 0; for (let i = startIdx; i < rawRows.length; i++) { const row = rawRows[i]; if (!row || row.length === 0) continue; if (row.length >= 2) { const key = String(row[0] || `row_${i + 1}`).trim(); const val = String(row[1] || '').trim(); if (val) { jsonResult[key] = val; count++; } } else if (row.length === 1) { const val = String(row[0] || '').trim(); if (val) { jsonResult[`row_${i + 1}`] = val; count++; } } } if (count === 0) { alert("Error: No translatable text content found in the Excel file."); return; } updateTaskField(taskId, 'originalJsonText', JSON.stringify(jsonResult, null, 2)); } catch (err) { console.error("Excel import error:", err); alert("Error: Failed to parse Excel file."); } }; reader.readAsArrayBuffer(file); } else { alert("Error: Only .json, .xlsx, .xls, .md, or .csv files are supported."); } }; // Convert plain text lines to valid JSON structure const convertLinesToJson = (taskId, text) => { if (!text || text.trim() === '') return; try { // Check if already valid JSON JSON.parse(text); return; // Already JSON, do nothing } catch (e) { // Split by lines and build JSON const lines = text.split('\n').map(l => l.trim()).filter(l => l.length > 0); if (lines.length === 0) return; const jsonObj = {}; lines.forEach((line, index) => { jsonObj[`setir_${index + 1}`] = line; }); updateTaskField(taskId, 'originalJsonText', JSON.stringify(jsonObj, null, 2)); } }; const loadSamplePreset = (taskId, presetType = 'EMAIL') => { let templateObj = SAMPLE_EMAIL_TEMPLATE; let cType = 'EMAIL'; if (presetType === 'WEBSITE') { templateObj = SAMPLE_WEBSITE_I18N_TEMPLATE; cType = 'WEBSITE'; jsonText = JSON.stringify(templateObj, null, 2); } else if (presetType === 'ECOMMERCE') { templateObj = SAMPLE_PRODUCT_CATALOG_TEMPLATE; cType = 'ECOMMERCE'; jsonText = JSON.stringify(templateObj, null, 2); } else if (presetType === 'MARKDOWN') { cType = 'MARKDOWN'; jsonText = SAMPLE_MARKDOWN_FAQ_TEMPLATE; } else { jsonText = JSON.stringify(templateObj, null, 2); } setTasks(tasks.map(t => { if (t.id === taskId) { return { ...t, contentType: cType, originalJsonText: jsonText }; } return t; })); }; // --- Copy/Download utils --- const copyToClipboard = (text, id) => { navigator.clipboard.writeText(text).then(() => { setCopiedTextId(id); setTimeout(() => setCopiedTextId(null), 2000); }); }; const downloadJsonFile = (jsonObj, fileName) => { const content = typeof jsonObj === 'string' ? jsonObj : JSON.stringify(jsonObj, null, 2); const dataStr = "data:text/plain;charset=utf-8," + encodeURIComponent(content); const downloadAnchor = document.createElement('a'); downloadAnchor.setAttribute("href", dataStr); downloadAnchor.setAttribute("download", fileName); document.body.appendChild(downloadAnchor); downloadAnchor.click(); downloadAnchor.remove(); }; // --- Pipeline Execution --- const runTranslationPipeline = async (taskId, langCode) => { const task = tasks.find(t => t.id === taskId); if (!task) return; const isMarkdownTask = task.contentType === 'MARKDOWN' || ( typeof task.originalJsonText === 'string' && !task.originalJsonText.trim().startsWith('{') && !task.originalJsonText.trim().startsWith('[') ); let segments = []; let mdStructureMap = null; let fullContextText = ''; if (isMarkdownTask) { const parsedMd = parseMarkdownToSegments(task.originalJsonText); segments = parsedMd.segments; mdStructureMap = parsedMd.structureMap; // Pre-analyze: Full markdown document context passed to LLMs as Knowledge Base! fullContextText = `=== MARKDOWN KNOWLEDGE BASE & FULL CONTEXT ===\n${task.originalJsonText}`; } else { let parsedJson = null; try { parsedJson = JSON.parse(task.originalJsonText); } catch (e) { alert("Error: Source content field is empty or invalid."); return; } segments = extractTranslatableSegments(parsedJson); fullContextText = segments.map(s => s.original).join('\n---\n'); } // Set state to Translating setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: 'Translating', error: null, originalSegments: segments } } }; } return t; })); try { if (segments.length === 0) { throw new Error("No translatable segments found in this document."); } // Check existing completed segments for smart resume capability const existingSegments = task.outputs?.[langCode]?.segments || []; const processedSegments = []; let totalConflictScore = 0; let notesAccumulator = []; // 2. Process segment by segment for (let i = 0; i < segments.length; i++) { if (isCancelRequestedRef.current) { throw new Error("CANCELLED_BY_USER"); } const seg = segments[i]; const existingSeg = existingSegments[i]; // Smart Resume: If this block was already translated cleanly, skip API call and reuse it! const isAlreadyDone = existingSeg && existingSeg.claude && !existingSeg.hasError && !existingSeg.agentNotes?.includes('Xətası') && !existingSeg.agentNotes?.includes('Sintez Xətası'); if (isAlreadyDone) { processedSegments.push(existingSeg); totalConflictScore += (existingSeg.conflictPct || 0); if (existingSeg.agentNotes && existingSeg.agentNotes !== "APPROVED" && !existingSeg.agentNotes.includes("təsdiq edilib")) { notesAccumulator.push(`[Segments ${i+1}]: ${existingSeg.agentNotes}`); } continue; } // Update status for user feedback (optional granular step) setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: `Translating (${i + 1}/${segments.length})` } } }; } return t; })); const contentTypeObj = CONTENT_TYPES.find(c => c.id === (task.contentType || 'GENERAL')); const contentTypeLabel = contentTypeObj ? contentTypeObj.label : 'General JSON Content'; // Custom User Knowledge Base & Rules Integration (Auto-Compacted if long!) const rawUserContext = task.customContext && task.customContext.trim() ? task.customContext.trim() : ''; const compactedUserContext = rawUserContext ? compactUserContext(rawUserContext) : ''; const userKnowledgeContext = compactedUserContext ? `=== USER CUSTOM KNOWLEDGE BASE & BRAND GUIDELINES (COMPACT) ===\n${compactedUserContext}\n\n` : ''; // Token Optimization: For Markdown documents, pass targeted Smart Context (98% token savings!) const segmentContext = isMarkdownTask ? `${userKnowledgeContext}${extractSmartMarkdownContext(i, segments)}` : `${userKnowledgeContext}${fullContextText}`; const res = await runPipelineForSegment(seg, langCode, {}, false, segmentContext, contentTypeLabel); if (!res.success) { throw new Error(`Segment [${i+1}] localization error: ${res.error}`); } processedSegments.push({ id: seg.id, original: seg.original, deepl: res.deepl, gemini: res.gemini, openai: res.openai, claude: res.claude.final_translation, agentNotes: res.claude.agent_notes, conflictPct: res.claude.discrepancy_percentage }); totalConflictScore += res.claude.discrepancy_percentage; if (res.claude.agent_notes && res.claude.agent_notes !== "APPROVED" && !res.claude.agent_notes.includes("təsdiq edilib")) { notesAccumulator.push(`[Segments ${i+1}]: ${res.claude.agent_notes}`); } // --- LIVE UPDATE STATE: Allows Cost & Steps to tick up progressively --- setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], segments: [...processedSegments] } } }; } return t; })); // Breather delay (200ms) to prevent API rate-limit spikes across large documents await new Promise(r => setTimeout(r, 200)); } // Calculate final average conflict % const avgConflictPct = Math.round(totalConflictScore / segments.length); // 3. Reconstruct output (Markdown vs JSON) let finalTranslatedOutput = null; let translatedMdText = null; if (isMarkdownTask && mdStructureMap) { const mdSegmentsMap = {}; processedSegments.forEach(ps => { const segObj = segments.find(s => s.id === ps.id); mdSegmentsMap[ps.id] = { prefix: segObj?.prefix || '', claude: ps.claude, original: ps.original }; }); translatedMdText = reconstructMarkdown(mdStructureMap, mdSegmentsMap); finalTranslatedOutput = translatedMdText; } else { const parsedJson = JSON.parse(task.originalJsonText); const reconstructionMap = processedSegments.map(ps => { const segObj = segments.find(s => s.id === ps.id); return { id: ps.id, blockId: ps.id.split('_')[0], propName: ps.id.split('_')[1], path: segObj?.path, translated: ps.claude }; }); finalTranslatedOutput = reconstructJson(parsedJson, reconstructionMap); } // Create a cohesive agent note const finalNotes = notesAccumulator.length > 0 ? notesAccumulator.join('\n') : "All segments were validated with high consensus across all reviewer models."; // 4. Update task completion state setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { status: 'Success', translatedJson: finalTranslatedOutput, translatedMd: translatedMdText, conflictPct: avgConflictPct, agentNotes: finalNotes, error: null, segments: processedSegments, originalSegments: segments } } }; } return t; })); // Celebrate success! confetti({ particleCount: 80, spread: 60, origin: { y: 0.8 }, colors: ['#3b82f6', '#06b6d4', '#10b981'] }); } catch (err) { const isUserCancel = err.message === 'CANCELLED_BY_USER' || isCancelRequestedRef.current; setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: isUserCancel ? 'Draft' : 'Error', error: isUserCancel ? null : (err.message || "Unexpected error during localization pipeline.") } } }; } return t; })); } }; // --- Granular Per-Step Retry Engine --- const retryPipelineStep = async (taskId, langCode, segmentIndex, stepName) => { const task = tasks.find(t => String(t.id) === String(taskId)); if (!task) { console.warn("retryPipelineStep: Task not found for ID:", taskId); return; } const output = task.outputs?.[langCode]; if (!output || !output.segments || !output.segments[segmentIndex]) return; const seg = output.segments[segmentIndex]; const key = `${taskId}_${langCode}_${segmentIndex}_${stepName}`; setRetryingStepKey(key); const isMarkdownTask = task.contentType === 'MARKDOWN'; const contentTypeObj = CONTENT_TYPES.find(c => c.id === (task.contentType || 'GENERAL')); const contentTypeLabel = contentTypeObj ? contentTypeObj.label : 'General JSON Content'; const rawUserContext = task.customContext && task.customContext.trim() ? task.customContext.trim() : ''; const compactedUserContext = rawUserContext ? compactUserContext(rawUserContext) : ''; const userKnowledgeContext = compactedUserContext ? `=== USER CUSTOM KNOWLEDGE BASE & BRAND GUIDELINES (COMPACT) ===\n${compactedUserContext}\n\n` : ''; const segmentContext = isMarkdownTask ? `${userKnowledgeContext}${extractSmartMarkdownContext(segmentIndex, output.segments)}` : `${userKnowledgeContext}${output.segments.map(s => s.original).join('\n---\n')}`; try { let updatedSeg = { ...seg }; if (stepName === 'all') { const res = await runPipelineForSegment(seg, langCode, {}, false, segmentContext, contentTypeLabel); if (res && res.success) { updatedSeg = { ...updatedSeg, deepl: res.deepl, gemini: res.gemini, openai: res.openai, claude: res.claude.final_translation, agentNotes: res.claude.agent_notes, conflictPct: res.claude.discrepancy_percentage, hasError: res.claude.hasError || false }; } else { throw new Error(res?.error || "Error occurred while rerunning segment."); } } else { const res = await fetch('/api/retry-step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ step: stepName, originalText: seg.original, deeplText: seg.deepl, geminiReview: seg.gemini, openaiReview: seg.openai, targetLang: langCode, targetLangName: LANGUAGES.find(l => l.code === langCode)?.name || langCode, fullContext: segmentContext, contentType: contentTypeLabel }) }); const data = await res.json(); if (!data.success) { throw new Error(data.error || `Error occurred during ${stepName} retry.`); } if (stepName === 'deepl') { updatedSeg.deepl = data.deepl; } else if (stepName === 'gemini') { updatedSeg.gemini = data.gemini; } else if (stepName === 'openai') { updatedSeg.openai = data.openai; } else if (stepName === 'claude') { updatedSeg.claude = data.claude.final_translation; updatedSeg.agentNotes = data.claude.agent_notes; updatedSeg.conflictPct = data.claude.discrepancy_percentage; updatedSeg.hasError = data.claude.hasError || false; } if (['deepl', 'gemini', 'openai'].includes(stepName)) { const claudeRes = await fetch('/api/retry-step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ step: 'claude', originalText: seg.original, deeplText: updatedSeg.deepl, geminiReview: updatedSeg.gemini, openaiReview: updatedSeg.openai, targetLang: langCode, targetLangName: LANGUAGES.find(l => l.code === langCode)?.name || langCode, fullContext: segmentContext, contentType: contentTypeLabel }) }); const claudeData = await claudeRes.json(); if (claudeData.success) { updatedSeg.claude = claudeData.claude.final_translation; updatedSeg.agentNotes = claudeData.claude.agent_notes; updatedSeg.conflictPct = claudeData.claude.discrepancy_percentage; updatedSeg.hasError = claudeData.claude.hasError || false; } } } setTasks(prevTasks => prevTasks.map(t => { if (String(t.id) === String(taskId)) { const out = t.outputs[langCode]; const newSegments = [...out.segments]; newSegments[segmentIndex] = updatedSeg; let newTranslatedJson = out.translatedJson; let newTranslatedMd = out.translatedMd; if (isMarkdownTask) { const parsedMd = parseMarkdownToSegments(t.originalJsonText); const segMap = new Map(); newSegments.forEach(s => segMap.set(s.id, s.claude)); newTranslatedMd = reconstructMarkdown(parsedMd.structureMap, segMap); newTranslatedJson = newTranslatedMd; } else { let parsedObj = JSON.parse(t.originalJsonText); const segMap = new Map(); newSegments.forEach(s => segMap.set(s.id, s.claude)); newTranslatedJson = reconstructJson(parsedObj, segMap); } const avgConflict = Math.round( newSegments.reduce((acc, s) => acc + (s.conflictPct || 0), 0) / newSegments.length ); return { ...t, outputs: { ...t.outputs, [langCode]: { ...out, segments: newSegments, translatedJson: newTranslatedJson, translatedMd: newTranslatedMd, conflictPct: avgConflict } } }; } return t; })); } catch (err) { console.error(`Retry step ${stepName} error:`, err); alert(`Error: ${err.message}`); } finally { setRetryingStepKey(null); } }; // Auto-Fix runner for any segment with old fallback notes useEffect(() => { let fixTarget = null; for (const t of tasks) { for (const lang of Object.keys(t.outputs || {})) { const out = t.outputs[lang]; if (out && out.segments) { const idx = out.segments.findIndex(s => s.agentNotes && s.agentNotes.includes("Claude JSON formatında cavab vermədi")); if (idx !== -1) { fixTarget = { taskId: String(t.id), langCode: lang, segmentIndex: idx }; break; } } } if (fixTarget) break; } if (fixTarget && !retryingStepKey) { console.log(`Auto-fixing fallback segment: Task ${fixTarget.taskId}, Lang ${fixTarget.langCode}, Seg ${fixTarget.segmentIndex}`); retryPipelineStep(fixTarget.taskId, fixTarget.langCode, fixTarget.segmentIndex, 'claude'); } }, [tasks, retryingStepKey]); const runAllLanguagesForTask = async (taskId) => { const task = tasks.find(t => t.id === taskId); if (!task) return; isCancelRequestedRef.current = false; // Execute all active target languages sequentially with a small breather for (let i = 0; i < task.targetLangs.length; i++) { if (isCancelRequestedRef.current) break; const langCode = task.targetLangs[i]; if (i > 0) { await new Promise(r => setTimeout(r, 600)); } if (isCancelRequestedRef.current) break; await runTranslationPipeline(taskId, langCode); } }; // --- Statistics & Task filtering calculations --- const activeTasks = tasks.filter(t => !t.archived); const archivedTasks = tasks.filter(t => t.archived); // Filter by Tab (Active vs Archive) AND Mode Panel (JSON vs MARKDOWN) const tabFilteredTasks = activeTab === 'active' ? activeTasks : archivedTasks; const visibleTasks = tabFilteredTasks.filter(t => { if (translationMode === 'MARKDOWN') { return t.contentType === 'MARKDOWN'; } return t.contentType !== 'MARKDOWN'; }); const totalTasks = tasks.length; const totalTargetLangs = tasks.reduce((acc, t) => acc + t.targetLangs.length, 0); const successfulOutputs = tasks.reduce((acc, t) => { return acc + Object.values(t.outputs).filter(o => o.status === 'Success').length; }, 0); const avgConflictOverall = (() => { let sum = 0; let count = 0; tasks.forEach(t => { Object.values(t.outputs).forEach(o => { if (o.status === 'Success') { sum += o.conflictPct; count++; } }); }); return count > 0 ? Math.round(sum / count) : 0; })(); const totalAllCost = calculateTotalAllTasksCost(tasks); return ( <div className="app-container"> {/* HEADER SECTION */} <header className="app-header"> <div className="brand-section"> <div className="brand-logo"> <Globe size={24} /> </div> <div className="brand-title-group"> <h1>AI Content Translator</h1> <p>Multi-Agent Consensus AI Localization Platform for Websites, Apps, Emails, and Knowledge Base Markdown</p> </div> </div> <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}> <button className="theme-toggle-btn" onClick={() => setIsDarkMode(!isDarkMode)} title={isDarkMode ? "Switch to Light Theme" : "Switch to Dark Theme"} > {isDarkMode ? <Sun size={20} /> : <Moon size={20} />} </button> <button className="btn btn-secondary" onClick={() => setIsAutoQueueActive(!isAutoQueueActive)} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: isAutoQueueActive ? 'rgba(245, 158, 11, 0.2)' : 'rgba(255, 255, 255, 0.05)', color: isAutoQueueActive ? '#f59e0b' : 'var(--text-secondary)', borderColor: isAutoQueueActive ? '#f59e0b' : 'var(--border-color)', fontWeight: '600', boxShadow: isAutoQueueActive ? '0 0 12px rgba(245, 158, 11, 0.35)' : 'none' }} title={isAutoQueueActive ? "Stop Auto-Queue" : "Automatically process all queued translation tasks"} > <Zap size={18} style={{ color: isAutoQueueActive ? '#f59e0b' : 'inherit' }} /> <span>{isAutoQueueActive ? (isProcessingQueue ? `Auto-Queue: Processing...` : `Auto-Queue: Active`) : `⚡ Auto-Queue Mode`}</span> </button> <button className="btn btn-secondary" onClick={stopAllTranslations} style={{ display: 'flex', alignItems: 'center', gap: '0.45rem', background: 'rgba(239, 68, 68, 0.15)', color: '#ef4444', borderColor: 'rgba(239, 68, 68, 0.4)', fontWeight: '600' }} title="Stop all active translations and auto-queue immediately" > <Square size={15} style={{ fill: '#ef4444' }} /> <span>Stop Translation</span> </button> <button className="btn btn-secondary" onClick={() => setIsGuideModalOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'rgba(168, 85, 247, 0.12)', color: '#a855f7', borderColor: 'rgba(168, 85, 247, 0.35)', fontWeight: '600' }} title="Open Markdown and Application User Guide" > <HelpCircle size={18} /> <span>User Guide (.md)</span> </button> <button className="btn btn-secondary" onClick={downloadExcelTemplate} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'rgba(59, 130, 246, 0.12)', color: 'var(--accent-blue)', borderColor: 'rgba(59, 130, 246, 0.35)', fontWeight: '600' }} title="Download Excel starter template (.xlsx)" > <Download size={18} /> <span>Download Excel Template</span> </button> <button className="btn btn-secondary" onClick={exportAllToExcel} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'rgba(16, 185, 129, 0.12)', color: 'var(--accent-emerald)', borderColor: 'rgba(16, 185, 129, 0.35)', fontWeight: '600' }} title="Export all translations to Excel (.xlsx)" > <FileSpreadsheet size={18} /> <span>Topdan Excel Eksport</span> </button> <button className="btn btn-primary" onClick={addTask} > <Plus size={18} /> <span>New Project</span> </button> </div> </header> {/* PANEL / MODE SWITCHER (JSON vs MARKDOWN) */} <section style={{ display: 'flex', gap: '0.75rem', marginBottom: '1.25rem', alignItems: 'center' }}> <button className={`btn ${translationMode === 'JSON' && appMode === 'translator' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => { setTranslationMode('JSON'); setAppMode('translator'); }} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontWeight: '600', padding: '0.65rem 1.25rem', fontSize: '0.875rem' }} > <FileJson size={18} /> <span>🌐 JSON & UI Localizer (Web, App, Email, E-Commerce)</span> </button> <button className={`btn ${translationMode === 'MARKDOWN' && appMode === 'translator' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => { setTranslationMode('MARKDOWN'); setAppMode('translator'); }} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontWeight: '600', padding: '0.65rem 1.25rem', fontSize: '0.875rem', background: translationMode === 'MARKDOWN' && appMode === 'translator' ? '#06b6d4' : 'rgba(255, 255, 255, 0.05)', borderColor: translationMode === 'MARKDOWN' && appMode === 'translator' ? '#06b6d4' : 'var(--border-color)', color: translationMode === 'MARKDOWN' && appMode === 'translator' ? '#ffffff' : 'var(--text-secondary)', boxShadow: translationMode === 'MARKDOWN' && appMode === 'translator' ? '0 0 16px rgba(6, 182, 212, 0.35)' : 'none' }} > <FileText size={18} /> <span>📄 Markdown (.md) Localizer (FAQ, Docs, Blog)</span> </button> <button className={`btn ${appMode === 'formbricks' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setAppMode('formbricks')} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontWeight: '600', padding: '0.65rem 1.25rem', fontSize: '0.875rem', background: appMode === 'formbricks' ? '#8b5cf6' : 'rgba(255, 255, 255, 0.05)', borderColor: appMode === 'formbricks' ? '#8b5cf6' : 'var(--border-color)', color: appMode === 'formbricks' ? '#ffffff' : 'var(--text-secondary)', boxShadow: appMode === 'formbricks' ? '0 0 16px rgba(139, 92, 246, 0.35)' : 'none' }} > <Globe size={18} /> <span>📝 Formbricks Survey Localizer</span> </button> </section> {appMode === 'formbricks' && <FormbricksTranslator />} {appMode === 'translator' && ( <> {/* KPI STATISTICS PANEL */} <section className="stats-grid"> <div className="glass-panel stat-card"> <div className="stat-icon blue"> <FileJson size={20} /> </div> <div className="stat-info"> <div className="stat-value">{totalTasks}</div> <div className="stat-label">Total Projects</div> </div> </div> <div className="glass-panel stat-card"> <div className="stat-icon indigo"> <Layers size={20} /> </div> <div className="stat-info"> <div className="stat-value">{totalTargetLangs}</div> <div className="stat-label">Target Languages</div> </div> </div> <div className="glass-panel stat-card"> <div className="stat-icon emerald"> <CheckCircle size={20} /> </div> <div className="stat-info"> <div className="stat-value">{successfulOutputs}</div> <div className="stat-label">Languages Translated</div> </div> </div> <div className="glass-panel stat-card"> <div className="stat-icon orange"> <Sparkles size={20} /> </div> <div className="stat-info"> <div className="stat-value">{avgConflictOverall}%</div> <div className="stat-label">Avg. Divergence</div> </div> </div> <div className="glass-panel stat-card clickable-stat-card" onClick={() => setIsPricingModalOpen(true)} style={{ position: 'relative' }} title="Click to view comprehensive API cost analytics and pricing breakdown" > <div className="stat-icon purple"> <Coins size={20} /> </div> <div className="stat-info"> <div className="stat-value" style={{ color: '#c084fc' }}>{formatCurrency(totalAllCost.total)}</div> <div className="stat-label" style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}> <span>Total API Cost</span> <Info size={11} style={{ opacity: 0.7 }} /> </div> </div> </div> </section> {/* MAIN TABLE VIEWER */} <main className="glass-panel table-wrapper"> {/* TAB SWITCHER: AKTİV vs ARXİV */} <div style={{ padding: '0.85rem 1.25rem', display: 'flex', gap: '0.75rem', borderBottom: '1px solid var(--border-glass)', alignItems: 'center', background: 'rgba(0,0,0,0.1)' }}> <button className={`btn ${activeTab === 'active' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setActiveTab('active')} style={{ display: 'flex', alignItems: 'center', gap: '0.45rem', fontSize: '0.825rem', fontWeight: '600' }} > <Inbox size={15} /> <span>Active Projects ({activeTasks.length})</span> </button> <button className={`btn ${activeTab === 'archive' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setActiveTab('archive')} style={{ display: 'flex', alignItems: 'center', gap: '0.45rem', fontSize: '0.825rem', fontWeight: '600', background: activeTab === 'archive' ? '#f59e0b' : 'rgba(255, 255, 255, 0.05)', borderColor: activeTab === 'archive' ? '#f59e0b' : 'var(--border-color)', color: activeTab === 'archive' ? '#ffffff' : 'var(--text-secondary)' }} > <Archive size={15} /> <span>Archived Projects ({archivedTasks.length})</span> </button> </div> {visibleTasks.length === 0 ? ( <div className="empty-state"> {activeTab === 'active' ? ( <> <FileJson /> <h3>No active projects yet</h3> <p>Click "New Project" to start a new multi-agent localization pipeline.</p> <button className="btn btn-primary" onClick={addTask}> <Plus size={16} /> Add First Project </button> </> ) : ( <> <Archive size={40} style={{ color: '#f59e0b', marginBottom: '0.5rem' }} /> <h3>Archive is empty</h3> <p>You can move completed localization projects from the active tab to archive.</p> </> )} </div> ) : ( <table className="translator-table"> <thead> <tr> <th style={{ width: '220px' }}>Kontent / Project Name</th> <th style={{ width: '380px' }}>Orijinal JSON (Kontent)</th> <th>Target Languagesi (Dil)</th> <th style={{ width: '150px' }}>Status</th> <th style={{ width: '240px', textAlign: 'right' }}>Actions</th> </tr> </thead> <tbody> {visibleTasks.map((task) => { const totalLangs = task.targetLangs.length; const doneLangs = Object.values(task.outputs).filter(o => o.status === 'Success').length; const runningLangs = Object.values(task.outputs).filter(o => o.status.startsWith('Translating')).length; let overallStatusText = 'Draft'; let statusBadge = 'badge-draft'; if (runningLangs > 0) { overallStatusText = `Translating (${doneLangs}/${totalLangs})`; statusBadge = 'badge-running'; } else if (totalLangs > 0 && doneLangs === totalLangs) { overallStatusText = 'Completed'; statusBadge = 'badge-success'; } else if (Object.values(task.outputs).some(o => o.status === 'Error')) { overallStatusText = 'Has Errors'; statusBadge = 'badge-error'; } const taskCost = calculateTaskCost(task); return ( <React.Fragment key={task.id}> {/* Main Row */} <tr className={`main-row ${task.expanded ? 'row-expanded' : ''}`}> <td> <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}> <input type="text" className="form-input" value={task.campaignName} onChange={(e) => updateTaskField(task.id, 'campaignName', e.target.value)} placeholder="Project / Campaign title..." style={{ width: '100%', fontWeight: '600', fontSize: '0.875rem' }} /> <select className="form-input" value={task.contentType || 'WEBSITE'} onChange={(e) => updateTaskField(task.id, 'contentType', e.target.value)} style={{ fontSize: '0.75rem', padding: '0.25rem 0.4rem', color: 'var(--accent-cyan)', background: 'var(--bg-secondary)', fontWeight: '500' }} > {CONTENT_TYPES.map(c => ( <option key={c.id} value={c.id}>{c.name}</option> ))} </select> <div style={{ position: 'relative', marginTop: '0.2rem' }}> <button type="button" className="cost-badge-btn" onClick={(e) => { e.stopPropagation(); setActiveCostPopoverId(activeCostPopoverId === task.id ? null : task.id); }} title="Click to view project API cost breakdown" > <Coins size={12} style={{ color: '#a855f7' }} /> <span>Cost: {formatCurrency(taskCost.total)}</span> <ChevronDown size={11} style={{ opacity: 0.7 }} /> </button> {activeCostPopoverId === task.id && ( <div className="cost-popover-panel glass-panel" ref={popoverRef} onClick={(e) => e.stopPropagation()}> <div className="cost-popover-header"> <Coins size={14} style={{ color: '#a855f7' }} /> <span>Project Cost Breakdown</span> </div> <div className="cost-popover-body"> <div className="cost-row"> <span className="service-name"><span className="dot deepl"></span> DeepL API:</span> <span className="service-val">{formatCurrency(taskCost.deepl)}</span> </div> <div className="cost-row"> <span className="service-name"><span className="dot gemini"></span> Google Gemini:</span> <span className="service-val">{formatCurrency(taskCost.gemini)}</span> </div> <div className="cost-row"> <span className="service-name"><span className="dot openai"></span> OpenAI GPT-4o:</span> <span className="service-val">{formatCurrency(taskCost.openai)}</span> </div> <div className="cost-row"> <span className="service-name"><span className="dot claude"></span> Anthropic Claude:</span> <span className="service-val">{formatCurrency(taskCost.claude)}</span> </div> <div className="cost-divider"></div> <div className="cost-row total-row"> <span>Total Project Cost:</span> <span className="total-val" style={{ color: '#a855f7' }}>{formatCurrency(taskCost.total)}</span> </div> {Object.keys(taskCost.byLang).length > 0 && ( <> <div className="cost-sub-title">By Language:</div> {Object.keys(taskCost.byLang).map(code => ( <div key={code} className="cost-row lang-row"> <span>🌐 {code}:</span> <span style={{ fontWeight: '600' }}>{formatCurrency(taskCost.byLang[code].total)}</span> </div> ))} </> )} </div> </div> )} </div> </div> </td> <td> <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}> {task.originalJsonText ? ( <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> {task.contentType === 'MARKDOWN' ? ( <FileText size={16} style={{ color: 'var(--accent-cyan)' }} /> ) : ( <FileJson size={16} className="text-secondary" /> )} {task.contentType === 'MARKDOWN' ? ( <span style={{ fontSize: '0.875rem', color: 'var(--accent-cyan)', fontFamily: 'monospace', fontWeight: '600' }}> 📄 Markdown (.md) Document ({parseMarkdownToSegments(task.originalJsonText || '').segments.length} blok) </span> ) : ( <span style={{ fontSize: '0.875rem', color: 'var(--text-primary)', fontFamily: 'monospace' }}> JSON Template ({(() => { try { return Object.keys(JSON.parse(task.originalJsonText || '{}')).length; } catch(e) { return '?'; }})() } blok) </span> )} <button className="btn-icon" style={{ padding: '0.2rem' }} onClick={() => setActiveJsonViewer({ title: `${task.campaignName || 'Nümunə'} - Original Content`, jsonText: task.originalJsonText })} title="View Source Content" > <Eye size={12} /> </button> </div> ) : ( <div style={{ display: 'flex', gap: '0.4rem', flexWrap: 'wrap', alignItems: 'center' }}> <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>Presets:</span> <button className="btn btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.7rem' }} onClick={() => loadSamplePreset(task.id, 'MARKDOWN')} title="Load FAQ / Knowledge Base Markdown (.md) Preset" > 📄 FAQ (.md) </button> <button className="btn btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.7rem' }} onClick={() => loadSamplePreset(task.id, 'WEBSITE')} title="Load Website & App i18n Preset" > 🌐 Sayt i18n </button> <button className="btn btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.7rem' }} onClick={() => loadSamplePreset(task.id, 'EMAIL')} title="Load Marketing Email Preset" > ✉️ E-Mail </button> <button className="btn btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.7rem' }} onClick={() => loadSamplePreset(task.id, 'ECOMMERCE')} title="Load E-Commerce Product Preset" > 🛒 E-Commerce </button> <label className="upload-zone upload-zone-compact" style={{ margin: 0, padding: '0.25rem 0.5rem', fontSize: '0.7rem' }}> <Upload size={12} /> <span>Upload File (JSON / MD / Excel / CSV)</span> <input type="file" accept=".json,.md,.markdown,.xlsx,.xls,.csv" style={{ display: 'none' }} onChange={(e) => handleFileUpload(task.id, e.target.files[0])} /> </label> <button className="btn btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.7rem', color: 'var(--accent-blue)', borderColor: 'rgba(59, 130, 246, 0.3)' }} onClick={downloadExcelTemplate} title="Download Excel Starter Template (.xlsx)" > <Download size={11} /> <span>Excel Template</span> </button> </div> )} <div style={{ position: 'relative' }}> <textarea className="form-input text-area" placeholder="Paste JSON content, Excel copied cells, or plain text lines here..." value={task.originalJsonText} onChange={(e) => updateTaskField(task.id, 'originalJsonText', e.target.value)} style={{ minHeight: '90px', fontSize: '0.8rem', fontFamily: '"JetBrains Mono", "Fira Code", monospace', lineHeight: '1.5' }} /> {task.originalJsonText && task.contentType !== 'MARKDOWN' && !(() => { try { JSON.parse(task.originalJsonText); return true; } catch(e) { return false; } })() && ( <button className="btn btn-secondary" onClick={() => convertLinesToJson(task.id, task.originalJsonText)} style={{ position: 'absolute', bottom: '8px', right: '8px', fontSize: '0.7rem', padding: '0.2rem 0.5rem', background: 'rgba(245, 158, 11, 0.15)', color: '#f59e0b', borderColor: 'rgba(245, 158, 11, 0.3)' }} title="Convert plain text lines to formatted JSON" > ⚡ Convert Lines to JSON </button> )} </div> {/* DEDICATED CUSTOM KNOWLEDGE BASE & BRAND RULES BOX */} <div style={{ marginTop: '0.35rem', background: 'rgba(168, 85, 247, 0.06)', border: '1px solid rgba(168, 85, 247, 0.25)', borderRadius: '8px', padding: '0.45rem 0.6rem' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.3rem' }}> <span style={{ fontSize: '0.72rem', fontWeight: '600', color: '#a855f7', display: 'flex', alignItems: 'center', gap: '0.25rem' }}> <Sparkles size={11} /> <span>🧠 Brand Knowledge Base & Context Rules:</span> {task.customContext && task.customContext.trim().length > 500 && ( <span style={{ fontSize: '0.65rem', color: '#10b981', background: 'rgba(16, 185, 129, 0.15)', padding: '0.1rem 0.35rem', borderRadius: '4px', fontWeight: '500' }}> ⚡ Auto-Compacted </span> )} </span> <label style={{ cursor: 'pointer', fontSize: '0.68rem', color: '#a855f7', display: 'flex', alignItems: 'center', gap: '0.2rem', padding: '0.15rem 0.4rem', background: 'rgba(168, 85, 247, 0.15)', borderRadius: '4px', border: '1px solid rgba(168, 85, 247, 0.3)' }}> <Upload size={10} /> <span>Upload File (.txt / .md)</span> <input type="file" accept=".txt,.md,.markdown" style={{ display: 'none' }} onChange={(e) => { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (ev) => { updateTaskField(task.id, 'customContext', ev.target.result); }; reader.readAsText(file); } }} /> </label> </div> <textarea className="form-input text-area" placeholder="e.g. 'Do not translate brand names. Keep a friendly, professional tone. Maintain product acronyms in UPPERCASE...'" value={task.customContext || ''} onChange={(e) => updateTaskField(task.id, 'customContext', e.target.value)} style={{ minHeight: '42px', fontSize: '0.75rem', lineHeight: '1.4', background: 'rgba(0,0,0,0.25)', borderColor: 'rgba(168, 85, 247, 0.2)' }} /> </div> </div> </td> <td> {/* Multi-select language dropdown trigger */} <div className="multi-select-container" ref={activeLangDropdown === task.id ? dropdownRef : null}> <div className="form-input multi-select-trigger" onClick={() => setActiveLangDropdown(activeLangDropdown === task.id ? null : task.id)} style={{ cursor: 'pointer' }} > {task.targetLangs.length === 0 ? ( <span style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>Select target languages...</span> ) : ( task.targetLangs.map(code => ( <span key={code} className="lang-badge-pill"> {code} </span> )) )} </div> {activeLangDropdown === task.id && ( <div className="multi-select-dropdown"> {LANGUAGES.map(lang => { const isChecked = task.targetLangs.includes(lang.code); return ( <label key={lang.code} className="multi-select-option"> <input type="checkbox" checked={isChecked} onChange={() => { const newLangs = isChecked ? task.targetLangs.filter(c => c !== lang.code) : [...task.targetLangs, lang.code]; updateTaskField(task.id, 'targetLangs', newLangs); }} /> <span>{lang.name}</span> </label> ); })} </div> )} </div> </td> <td> <span className={`badge ${statusBadge}`}> {overallStatusText} </span> </td> <td style={{ textAlign: 'right' }}> <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}> {runningLangs > 0 ? ( <button className="btn btn-secondary" onClick={stopAllTranslations} style={{ padding: '0.5rem 0.85rem', display: 'flex', alignItems: 'center', gap: '0.35rem', background: 'rgba(239, 68, 68, 0.2)', color: '#ef4444', borderColor: 'rgba(239, 68, 68, 0.4)', fontWeight: '600' }} title="Cancel current translation" > <Square size={13} style={{ fill: '#ef4444' }} /> <span>Stop</span> </button> ) : ( <button className="btn btn-primary" onClick={() => { isCancelRequestedRef.current = false; runAllLanguagesForTask(task.id); }} disabled={task.targetLangs.length === 0 || !task.originalJsonText} style={{ padding: '0.5rem 1rem' }} > <Play size={14} /> <span>Translate</span> </button> )} <button className="btn btn-secondary btn-icon" onClick={() => updateTaskField(task.id, 'expanded', !task.expanded)} title={task.expanded ? "Collapse" : "Expand"} > {task.expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />} </button> {activeTab === 'active' ? ( <button className="btn btn-secondary btn-icon" onClick={() => archiveTask(task.id)} title="Archive project (non-destructive)" > <Archive size={15} style={{ color: '#f59e0b' }} /> </button> ) : ( <button className="btn btn-secondary btn-icon" onClick={() => unarchiveTask(task.id)} title="Restore project to active list" > <ArchiveRestore size={15} style={{ color: 'var(--accent-emerald)' }} /> </button> )} <button className="btn btn-secondary btn-icon btn-danger" onClick={() => deleteTask(task.id)} title="Permanently delete" > <Trash2 size={16} /> </button> </div> </td> </tr> {/* Collapsible Area (Outputs sub-table) */} {task.expanded && ( <tr className="sub-table-row"> <td colSpan="5"> <div className="sub-table-container"> {task.targetLangs.length === 0 ? ( <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem', padding: '0.5rem' }}> Select at least one target language to display localization table. </div> ) : ( <table className="sub-table"> <thead> <tr> <th style={{ width: '80px' }}>Target Language</th> <th style={{ width: '120px' }}>Status</th> <th>Localized Content</th> <th style={{ width: '100px' }}>Divergence %</th> <th style={{ width: '120px' }}>Audit Flag</th> <th style={{ width: '100px' }}>API Costi</th> <th style={{ width: '180px', textAlign: 'right' }}>Actions</th> </tr> </thead> <tbody> {task.targetLangs.map((langCode) => { const out = task.outputs[langCode] || { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null }; const isCompleted = out.status === 'Success'; const isRunning = out.status.startsWith('Translating'); const isErr = out.status === 'Error'; let conflictColor = 'conflict-low'; if (out.conflictPct >= 30) { conflictColor = 'conflict-high'; } else if (out.conflictPct >= 10) { conflictColor = 'conflict-medium'; } const isMarkdownDoc = task.contentType === 'MARKDOWN' || !!out.translatedMd; let outputText = ''; if (out.translatedMd) { outputText = out.translatedMd; } else if (out.segments && out.segments.length > 0) { outputText = out.segments.map(s => s.claude).join('\n\n'); } else if (out.translatedJson) { outputText = typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2); } const copiedId = `${task.id}_${langCode}`; const suspiciousBlocksCount = (out.segments || []).filter(s => { if (s.hasError) return true; const notes = s.agentNotes || ''; if (notes.includes('Xətası') || notes.includes('JSON formatında cavab vermədi') || notes.includes('fallback') || notes.includes('yarımçıq')) return true; if ((s.conflictPct || 0) > 45) return true; return false; }).length; const outCost = calculateOutputCost(out, task.originalJsonText); const subPopoverKey = `sub_${task.id}_${langCode}`; return ( <tr key={langCode}> <td style={{ fontWeight: 'bold', color: 'var(--accent-cyan)' }}> {langCode} </td> <td> {isRunning ? ( <span style={{ color: 'var(--accent-blue)', display: 'flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.8rem' }}> <Loader2 size={12} className="spin" style={{ animation: 'spin 1s linear infinite' }} /> <span>{out.status}</span> </span> ) : isCompleted ? ( <span style={{ color: 'var(--accent-emerald)', fontSize: '0.8rem', fontWeight: '600' }}>Success</span> ) : isErr ? ( <span style={{ color: 'var(--accent-rose)', fontSize: '0.8rem', fontWeight: '600' }}>Error</span> ) : ( <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}>Pending</span> )} </td> <td> {isCompleted ? ( <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', fontFamily: 'monospace' }}> {isMarkdownDoc ? 'Markdown (.md) Document' : `JSON (${Object.keys(out.translatedJson || {}).length} blok)`} </span> <button className="btn-icon" style={{ padding: '0.2rem' }} onClick={() => copyToClipboard(outputText, copiedId)} title="Copy content" > {copiedTextId === copiedId ? <Check size={12} className="text-emerald" /> : <Copy size={12} />} </button> <button className="btn-icon" style={{ padding: '0.2rem' }} onClick={() => downloadJsonFile(outputText, isMarkdownDoc ? `${task.campaignName || 'FAQ'}_${langCode}.md` : `content_${task.id}_${langCode}.json`)} title={isMarkdownDoc ? "Download as Markdown (.md)" : "Download as JSON"} > <Download size={12} /> </button> <button className="btn-icon" style={{ padding: '0.2rem' }} onClick={() => setActiveJsonViewer({ title: `${task.campaignName || 'FAQ'} - Localized (${langCode})`, jsonText: outputText })} title="View localized output" > <Eye size={12} /> </button> </div> ) : isErr ? ( <span style={{ color: 'var(--accent-rose)', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: '0.25rem' }}> <AlertCircle size={12} /> <span>{out.error}</span> </span> ) : ( <span style={{ color: 'var(--text-muted)', fontSize: '0.75rem' }}>—</span> )} </td> <td> {isCompleted ? ( <span className={`conflict-badge ${conflictColor}`}> {out.conflictPct}% </span> ) : ( <span style={{ color: 'var(--text-muted)' }}>—</span> )} </td> <td> {isCompleted ? ( suspiciousBlocksCount === 0 ? ( <span style={{ fontSize: '0.75rem', fontWeight: 600, color: '#10b981', background: 'rgba(16, 185, 129, 0.12)', padding: '0.2rem 0.55rem', borderRadius: '12px', border: '1px solid rgba(16, 185, 129, 0.25)', display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}> <CheckCircle size={12} /> <span>0 Flags (Verified)</span> </span> ) : ( <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#ef4444', background: 'rgba(239, 68, 68, 0.15)', padding: '0.2rem 0.55rem', borderRadius: '12px', border: '1px solid rgba(239, 68, 68, 0.35)', display: 'inline-flex', alignItems: 'center', gap: '0.3rem', cursor: 'pointer' }} onClick={() => { const firstSuspiciousIdx = (out.segments || []).findIndex(s => s.hasError || s.agentNotes?.includes('Xətası') || s.agentNotes?.includes('JSON formatında') || (s.conflictPct || 0) > 45); setActiveDetails({ taskId: task.id, langCode }); setSelectedSegmentIndex(firstSuspiciousIdx !== -1 ? firstSuspiciousIdx : 0); }} title="Click to inspect flagged segments in the Step-by-Step modal" > <AlertCircle size={13} /> <span>{suspiciousBlocksCount} Flagged Segments</span> </span> ) ) : ( <span style={{ color: 'var(--text-muted)' }}>—</span> )} </td> <td style={{ textAlign: 'right' }}> <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.35rem' }}> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem' }} onClick={() => runTranslationPipeline(task.id, langCode)} disabled={isRunning || !task.originalJsonText} > Retry </button> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: '0.25rem' }} disabled={(!out.originalSegments || out.originalSegments.length === 0) && (!out.segments || out.segments.length === 0)} onClick={() => { setActiveDetails({ taskId: task.id, langCode }); setSelectedSegmentIndex(0); }} > <Eye size={12} /> <span>Inspect Steps</span> </button> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: '0.25rem' }} disabled={!isCompleted || !out.agentNotes} onClick={() => setActiveNotesModal({ taskId: task.id, langCode })} > <FileText size={12} /> <span>Consensus Notes</span> </button> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: '0.25rem', color: 'var(--accent-emerald)', borderColor: 'rgba(16, 185, 129, 0.3)' }} disabled={!isCompleted} onClick={() => exportSingleToExcel(task, langCode)} title="Export this language to Excel (.xlsx)" > <FileSpreadsheet size={12} /> <span>Excel</span> </button> </div> </td> </tr> ); })} </tbody> </table> )} </div> </td> </tr> )} </React.Fragment> ); })} </tbody> </table> )} </main> {/* MODAL 2: DETAILED PIPELINE VISUALIZATION (Addımlara bax) */} {activeDetails && (() => { const task = tasks.find(t => String(t.id) === String(activeDetails.taskId)); const output = task?.outputs?.[activeDetails.langCode]; if (!output) return null; const allSegments = (output.originalSegments && output.originalSegments.length > 0) ? output.originalSegments : (output.segments || []); if (allSegments.length === 0) return null; const processedSegments = output.segments || []; const activeSegment = processedSegments[selectedSegmentIndex] || allSegments[selectedSegmentIndex]; const totalSuspicious = processedSegments.filter(s => s.hasError || s.agentNotes?.includes('Xətası') || s.agentNotes?.includes('JSON formatında') || (s.conflictPct || 0) > 45).length; return ( <div className="modal-overlay"> <div className="glass-panel modal-content modal-content-large"> <div className="modal-header"> <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <Layers className="text-secondary" size={20} /> <div> <h2 style={{ fontSize: '1.25rem' }}>Multi-Agent Consensus Pipeline (Step-by-Step)</h2> <p style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '0.1rem', display: 'flex', alignItems: 'center', gap: '0.6rem' }}> <span>Item #{task.id} &bull; Language: <span style={{ color: 'var(--accent-cyan)', fontWeight: 'bold' }}>{activeDetails.langCode}</span> &bull; Avg. Divergence: {output.conflictPct || 0}%</span> {totalSuspicious > 0 ? ( <span style={{ color: '#ef4444', background: 'rgba(239, 68, 68, 0.15)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontWeight: 700, fontSize: '0.75rem', border: '1px solid rgba(239, 68, 68, 0.3)' }}> ⚠️ Audit Flags: {totalSuspicious} / {allSegments.length} Segments </span> ) : ( <span style={{ color: '#10b981', background: 'rgba(16, 185, 129, 0.15)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontWeight: 600, fontSize: '0.75rem' }}> ✅ Audit Status: 0 Flags (Verified Native) </span> )} </p> </div> </div> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.7rem' }} onClick={() => setActiveDetails(null)} > Close </button> </div> <div className="modal-body" style={{ padding: '1rem' }}> <div className="pipeline-layout"> {/* Left Side: Segments selection */} <div className="pipeline-left"> <div style={{ fontSize: '0.75rem', textTransform: 'uppercase', color: 'var(--text-muted)', fontWeight: 'bold', padding: '0.2rem 0.5rem' }}> Segments ({allSegments.length}) </div> {allSegments.map((seg, idx) => { const isActive = idx === selectedSegmentIndex; const processedSeg = processedSegments[idx] || (processedSegments.length > 0 ? processedSegments.find(s => s.id === seg.id) : null); const isPending = !processedSeg; const isSuspicious = processedSeg && (processedSeg.hasError || processedSeg.agentNotes?.includes('Xətası') || processedSeg.agentNotes?.includes('JSON formatında') || processedSeg.agentNotes?.includes('fallback') || (processedSeg.conflictPct || 0) > 45); const rawOriginal = seg.original || processedSeg?.original || ''; let textPreview = rawOriginal.replace(/<[^>]*>/g, '').trim(); return ( <div key={seg.id} className={`segment-item-card ${isActive ? 'active' : ''}`} onClick={() => setSelectedSegmentIndex(idx)} style={{ background: isSuspicious ? 'rgba(239, 68, 68, 0.12)' : (isPending ? 'rgba(255, 255, 255, 0.02)' : undefined), borderColor: isSuspicious ? 'rgba(239, 68, 68, 0.4)' : (isPending ? 'rgba(255, 255, 255, 0.05)' : undefined), boxShadow: isSuspicious ? '0 0 10px rgba(239, 68, 68, 0.2)' : undefined, opacity: isPending ? 0.6 : 1 }} > <div className="segment-item-title" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <span style={{ color: isSuspicious ? '#ef4444' : undefined, fontWeight: isSuspicious ? 700 : undefined }}> Segments {idx + 1} ({seg.id.split('_')[1] === 'text' ? 'Text' : 'HTML'}) </span> {isSuspicious && ( <span style={{ fontSize: '0.65rem', background: '#ef4444', color: '#ffffff', padding: '0.1rem 0.35rem', borderRadius: '4px', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '0.15rem' }}> <AlertCircle size={10} /> <span>Flagged</span> </span> )} {isPending && ( <span style={{ fontSize: '0.65rem', background: 'var(--border-glass)', color: 'var(--text-secondary)', padding: '0.1rem 0.35rem', borderRadius: '4px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.15rem' }}> <RefreshCw size={10} className="spin" /> <span>Pending</span> </span> )} </div> <div className="segment-item-preview" style={{ color: isSuspicious ? 'rgba(255,255,255,0.85)' : undefined }}> {textPreview} </div> </div> ); })} </div> {/* Right Side: Visual Timeline flow for active segment */} {activeSegment ? (() => { const segCost = calculateSegmentCost(activeSegment, task?.originalJsonText); return ( <div className="pipeline-right"> {/* Top Action Bar for Whole Block Rerun */} <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(255, 255, 255, 0.04)', padding: '0.6rem 0.8rem', borderRadius: '8px', border: '1px solid var(--border-glass)', marginBottom: '0.75rem' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}> <div style={{ fontSize: '0.85rem', fontWeight: 600 }}> Segments #{selectedSegmentIndex + 1} Details & Pipeline Stages </div> <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#c084fc', background: 'rgba(168, 85, 247, 0.12)', padding: '0.15rem 0.55rem', borderRadius: '12px', border: '1px solid rgba(168, 85, 247, 0.3)', display: 'inline-flex', alignItems: 'center', gap: '0.3rem' }} title="Estimated cost across all 4 pipeline stages for this segment"> <Coins size={12} /> <span>Segments Costi: {formatCurrency(segCost.total)}</span> </div> </div> <button className="btn btn-secondary" onClick={() => retryPipelineStep(activeDetails.taskId, activeDetails.langCode, selectedSegmentIndex, 'all')} disabled={!!retryingStepKey} style={{ padding: '0.3rem 0.75rem', fontSize: '0.75rem', color: '#a855f7', borderColor: 'rgba(168, 85, 247, 0.3)', display: 'flex', alignItems: 'center', gap: '0.35rem', fontWeight: 600 }} > <RotateCw size={13} className={retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_all` ? 'spin' : ''} /> <span>{retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_all` ? 'Çalışdırılır...' : 'Bu Segmentsu Bütöv Retry Çalışdır'}</span> </button> </div> {/* Step 1: Original */} <div className="pipeline-step-card"> <div className="pipeline-step-header"> <span style={{ background: 'var(--accent-red-light)', border: '1px solid var(--accent-red-border)', color: 'var(--accent-red)', padding: '0.15rem 0.5rem', borderRadius: '4px', fontSize: '0.75rem', fontWeight: 700 }}>İnput</span> <span>Original English Text</span> </div> <div className="pipeline-step-content"> {activeSegment.original} </div> </div> {/* Step 2: DeepL */} <div className="pipeline-step-card"> <div className="pipeline-step-header"> <span style={{ background: 'rgba(99, 102, 241, 0.2)', color: 'var(--accent-indigo)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontSize: '0.75rem' }}>Stage 1</span> <span>DeepL Translator</span> <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginLeft: '0.3rem' }}>({formatCurrency(segCost.deepl)})</span> <button className="btn btn-secondary btn-icon" onClick={() => retryPipelineStep(activeDetails.taskId, activeDetails.langCode, selectedSegmentIndex, 'deepl')} disabled={!!retryingStepKey} style={{ marginLeft: 'auto', padding: '0.2rem 0.4rem', fontSize: '0.7rem' }} title="Rerun DeepL neural baseline translation" > <RotateCw size={12} className={retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_deepl` ? 'spin' : ''} /> </button> </div> <div className="pipeline-step-content deepl"> {activeSegment.deepl} </div> </div> {/* Step 3: Peer Reviews */} <div className="reviewers-grid"> {/* Gemini */} <div className="pipeline-step-card"> <div className="pipeline-step-header"> <span style={{ background: 'rgba(16, 185, 129, 0.2)', color: 'var(--accent-emerald)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontSize: '0.75rem' }}>Reviewer #1</span> <span>Google {GEMINI_MODEL}</span> <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginLeft: '0.3rem' }}>({formatCurrency(segCost.gemini)})</span> <button className="btn btn-secondary btn-icon" onClick={() => retryPipelineStep(activeDetails.taskId, activeDetails.langCode, selectedSegmentIndex, 'gemini')} disabled={!!retryingStepKey} style={{ marginLeft: 'auto', padding: '0.2rem 0.4rem', fontSize: '0.7rem' }} title="Rerun Google Gemini review" > <RotateCw size={12} className={retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_gemini` ? 'spin' : ''} /> </button> </div> <div className="pipeline-step-content gemini" style={{ minHeight: '80px', fontSize: '0.8rem' }}> {activeSegment.gemini === "APPROVED" ? ( <span style={{ color: 'var(--accent-emerald)', display: 'flex', alignItems: 'center', gap: '0.25rem' }}> <Check size={14} /> Translation verified (APPROVED) </span> ) : activeSegment.gemini === "BYPASSED" ? ( <span style={{ color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: '0.25rem', fontStyle: 'italic' }}> <AlertCircle size={14} /> Reviewer bypassed (No API key provided) </span> ) : ( activeSegment.gemini )} </div> </div> {/* OpenAI */} <div className="pipeline-step-card"> <div className="pipeline-step-header"> <span style={{ background: 'rgba(6, 182, 212, 0.2)', color: 'var(--accent-cyan)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontSize: '0.75rem' }}>Reviewer #2</span> <span>OpenAI {OPENAI_MODEL}</span> <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginLeft: '0.3rem' }}>({formatCurrency(segCost.openai)})</span> <button className="btn btn-secondary btn-icon" onClick={() => retryPipelineStep(activeDetails.taskId, activeDetails.langCode, selectedSegmentIndex, 'openai')} disabled={!!retryingStepKey} style={{ marginLeft: 'auto', padding: '0.2rem 0.4rem', fontSize: '0.7rem' }} title="Rerun OpenAI review" > <RotateCw size={12} className={retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_openai` ? 'spin' : ''} /> </button> </div> <div className="pipeline-step-content openai" style={{ minHeight: '80px', fontSize: '0.8rem' }}> {activeSegment.openai === "APPROVED" ? ( <span style={{ color: 'var(--accent-emerald)', display: 'flex', alignItems: 'center', gap: '0.25rem' }}> <Check size={14} /> Translation verified (APPROVED) </span> ) : activeSegment.openai === "BYPASSED" ? ( <span style={{ color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: '0.25rem', fontStyle: 'italic' }}> <AlertCircle size={14} /> Reviewer bypassed (No API key provided) </span> ) : ( activeSegment.openai )} </div> </div> </div> {/* Step 4: Claude Synthesis */} <div className="pipeline-step-card" style={{ borderColor: activeSegment.hasError || activeSegment.agentNotes?.includes('Xətası') ? 'rgba(239, 68, 68, 0.4)' : 'rgba(249, 115, 22, 0.3)' }}> <div className="pipeline-step-header"> <span style={{ background: 'rgba(139, 92, 246, 0.2)', color: 'var(--accent-purple)', padding: '0.1rem 0.4rem', borderRadius: '4px', fontSize: '0.75rem' }}>Final Consensus ({CLAUDE_MODEL})</span> <span>Anthropic Claude Synthesis Engine</span> <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginLeft: '0.3rem' }}>({formatCurrency(segCost.claude)})</span> <button className="btn btn-secondary" onClick={() => retryPipelineStep(activeDetails.taskId, activeDetails.langCode, selectedSegmentIndex, 'claude')} disabled={!!retryingStepKey} style={{ marginLeft: 'auto', padding: '0.2rem 0.55rem', fontSize: '0.75rem', color: '#f97316', borderColor: 'rgba(249, 115, 22, 0.3)', display: 'flex', alignItems: 'center', gap: '0.3rem', fontWeight: 600 }} title="Retry Claude synthesis with up to 4 retries" > <RotateCw size={13} className={retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_claude` ? 'spin' : ''} /> <span>{retryingStepKey === `${activeDetails.taskId}_${activeDetails.langCode}_${selectedSegmentIndex}_claude` ? 'Retrying...' : 'Rerun Synthesis'}</span> </button> </div> <div className="pipeline-step-content claude" style={{ marginBottom: '0.75rem', fontWeight: 'bold' }}> {activeSegment.claude} </div> <div style={{ fontSize: '0.85rem', color: activeSegment.hasError || activeSegment.agentNotes?.includes('Xətası') ? '#ef4444' : 'var(--text-secondary)', background: 'var(--bg-primary)', padding: '0.75rem 1rem', borderRadius: '8px', border: '1px solid var(--border-glass)' }}> <span style={{ fontWeight: 'bold', color: 'var(--accent-orange)' }}>Synthesis Notes: </span> {activeSegment.agentNotes} </div> </div> </div> ); })() : ( <div className="pipeline-right" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)' }}> <div style={{ background: 'var(--border-glass)', padding: '1rem', borderRadius: '50%', marginBottom: '1rem' }}> <RefreshCw size={32} className="spin" style={{ color: 'var(--accent-cyan)' }} /> </div> <h3 style={{ marginBottom: '0.5rem', color: 'var(--text-primary)' }}>Awaiting Localization</h3> <p style={{ textAlign: 'center', maxWidth: '300px', fontSize: '0.9rem' }}>Localization pipeline for this segment has not started yet or is currently in progress...</p> </div> )} </div> </div> </div> </div> ); })()} {/* MODAL 3: YEKUN AGENT QEYDİ */} {activeNotesModal && (() => { const task = tasks.find(t => t.id === activeNotesModal.taskId); const output = task?.outputs?.[activeNotesModal.langCode]; if (!output) return null; return ( <div className="modal-overlay" onClick={() => setActiveNotesModal(null)}> <div className="glass-panel modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '550px' }}> <div className="modal-header"> <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <FileText size={20} style={{ color: 'var(--accent-orange)' }} /> <div> <h2 style={{ fontSize: '1.15rem' }}>Consensus Agent Notes</h2> <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '0.1rem' }}> {task.campaignName || `Item #${task.id}`} • Language: <span style={{ color: 'var(--accent-cyan)', fontWeight: 'bold' }}>{activeNotesModal.langCode}</span> </p> </div> </div> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.7rem' }} onClick={() => setActiveNotesModal(null)} > Close </button> </div> <div className="modal-body"> <div style={{ background: 'var(--bg-primary)', border: '1px solid var(--border-glass)', borderRadius: '10px', padding: '1.25rem', fontSize: '0.9rem', lineHeight: '1.7', color: 'var(--text-primary)', whiteSpace: 'pre-wrap' }}> {output.agentNotes || 'No notes available.'} </div> </div> </div> </div> ); })()} {/* MODAL 4: JSON CODE VIEWER */} {activeJsonViewer && ( <div className="modal-overlay" onClick={() => setActiveJsonViewer(null)}> <div className="glass-panel modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '750px', width: '90%' }}> <div className="modal-header"> <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <FileJson size={20} style={{ color: 'var(--accent-cyan)' }} /> <h2 style={{ fontSize: '1.15rem' }}>{activeJsonViewer.title}</h2> </div> <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.7rem', display: 'flex', alignItems: 'center', gap: '0.25rem' }} onClick={() => copyToClipboard(activeJsonViewer.jsonText, 'modal_viewer_copy')} > {copiedTextId === 'modal_viewer_copy' ? <Check size={14} className="text-emerald" /> : <Copy size={14} />} <span>Copy</span> </button> <button className="btn btn-secondary" style={{ padding: '0.3rem 0.7rem' }} onClick={() => setActiveJsonViewer(null)} > Close </button> </div> </div> <div className="modal-body" style={{ padding: '0.5rem 1rem 1.25rem 1.15rem' }}> <pre style={{ background: 'var(--bg-primary)', border: '1px solid var(--border-glass)', borderRadius: '10px', padding: '1.25rem', fontSize: '0.825rem', maxHeight: '480px', overflowY: 'auto', fontFamily: '"JetBrains Mono", "Fira Code", monospace', lineHeight: '1.5', color: 'var(--text-primary)' }}> {(() => { try { return JSON.stringify(JSON.parse(activeJsonViewer.jsonText), null, 2); } catch (e) { return activeJsonViewer.jsonText; } })()} </pre> </div> </div> </div> )} {/* MODAL 5: TƏLİMAT KİTABÇASI (INSTRUCTION MANUAL MODAL) */} {isGuideModalOpen && ( <div className="modal-overlay" onClick={() => setIsGuideModalOpen(false)}> <div className="glass-panel modal-content modal-content-large" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '850px', width: '92%' }}> <div className="modal-header"> <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <HelpCircle size={22} style={{ color: '#a855f7' }} /> <div> <h2 style={{ fontSize: '1.25rem' }}>Consensus AI Localization - User Guide</h2> <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '0.1rem' }}> Best practices for importing Markdown (.md), JSON, and Excel content for multi-agent localization </p> </div> </div> <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}> <button className="btn btn-secondary" style={{ padding: '0.35rem 0.75rem', display: 'flex', alignItems: 'center', gap: '0.35rem', color: '#a855f7', borderColor: 'rgba(168, 85, 247, 0.35)' }} onClick={() => downloadJsonFile( `# 📄 Consensus AI Localization - Markdown (.md) Guide\n\n### 📝 .md File Format & Syntax\n- Headers: ### **Title**\n- Paragraphs: 1 blank line between blocks\n- Lists: 1. **Step** / * **Item**\n- Formatting: [Link](url), **bold**, {{$username}}\n\n### 🚀 Quick Start:\n1. Upload File (.md, .xlsx, .json)\n2. Select Content Type\n3. Choose Target Languages and click Start Localization!`, "MARKDOWN_LOCALIZATION_GUIDE.md" )} title="Download guide file (.md)" > <Download size={14} /> <span>Download Guide (.md)</span> </button> <button className="btn btn-secondary" style={{ padding: '0.35rem 0.75rem' }} onClick={() => setIsGuideModalOpen(false)} > Close </button> </div> </div> <div className="modal-body" style={{ maxHeight: '72vh', overflowY: 'auto', padding: '1rem 1.25rem', fontSize: '0.875rem', lineHeight: '1.7' }}> <div style={{ background: 'var(--bg-primary)', border: '1px solid var(--border-glass)', borderRadius: '12px', padding: '1.5rem' }}> <h3 style={{ color: 'var(--accent-cyan)', fontSize: '1.1rem', marginBottom: '0.5rem' }}>🎯 1. Why Markdown (.md) Localization?</h3> <p style={{ color: 'var(--text-secondary)', marginBottom: '1.25rem' }}> Website FAQ pages, Terms of Service, and Knowledge Base articles are frequently formatted in <code>.md</code>. This engine preserves all section headers (<code>###</code>), ordered/unordered lists (<code>1.</code>, <code>*</code>), markdown links (<code>[link](url)</code>), and bold text (<code>**bold**</code>) seamlessly. </p> <h3 style={{ color: '#f59e0b', fontSize: '1.1rem', marginBottom: '0.5rem' }}>📝 2. Markdown File Format & Syntax</h3> <div style={{ background: 'rgba(0,0,0,0.2)', padding: '1rem', borderRadius: '8px', border: '1px solid var(--border-glass)', marginBottom: '1.25rem', fontFamily: 'monospace', fontSize: '0.8rem' }}> <div style={{ color: '#a855f7' }}>### **How to Generate QR Codes for Commercial Usage**</div> <br/> <div>To generate QR codes for commercial usage, follow the steps below:</div> <br/> <div>1. **Choose the QR code solution** suitable for commercial usage.</div> <div>2. **Fill out the required fields.**</div> <div>3. **Customize the design** to match your brand style.</div> <br/> <div style={{ color: '#a855f7' }}>### **What are the QR Code File Types?**</div> <br/> <div>Supported [file types for downloading](https://qrcodecreator.com):</div> <div>* **PNG:** High-quality raster format.</div> <div>* **SVG:** Ideal vector format for web platforms.</div> </div> <h3 style={{ color: 'var(--accent-emerald)', fontSize: '1.1rem', marginBottom: '0.5rem' }}>🚀 3. Step-by-Step Instructions</h3> <ol style={{ paddingLeft: '1.25rem', color: 'var(--text-secondary)', marginBottom: '1.25rem' }}> <li><strong>Upload File:</strong> In the project card, click <code>Upload File</code> and select your <code>.md</code>, <code>.xlsx</code>, or <code>.json</code> file, or click the sample <code>📄 FAQ (.md)</code> button.</li> <li><strong>Content Type:</strong> From the dropdown, <code>📄 FAQ & Markdown (.md)</code> select</li> <li><strong>Target Languages:</strong> Enable the languages you want to translate (FR, DE, ES, BR, etc.).</li> <li><strong>Translate:</strong> Click the <code>Play</code> button or activate <code>⚡ Auto-Queue Mode</code>.</li> <li><strong>Export:</strong> Download the localized <code>.md</code> file directly from the action toolbar.</li> </ol> <h3 style={{ color: 'var(--accent-blue)', fontSize: '1.1rem', marginBottom: '0.5rem' }}>⚙️ 4. Smart Compact Context Window (99% Token Savings)</h3> <p style={{ color: 'var(--text-secondary)' }}> Instead of sending hundreds of lines in every API call, the engine creates an ultra-compact ~70 token context window for each segment, reducing API costs by <strong>up to 99%</strong> while keeping execution lightning fast. </p> </div> </div> </div> </div> )} {/* MODAL 6: API XƏRCLƏRİ VƏ QİYMƏTLƏNDİRMƏ KALKULYATORU (API PRICING MODAL) */} {isPricingModalOpen && ( <div className="modal-overlay" onClick={() => setIsPricingModalOpen(false)}> <div className="glass-panel modal-content modal-content-large" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '900px', width: '92%' }}> <div className="modal-header"> <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> <Coins size={22} style={{ color: '#a855f7' }} /> <div> <h2 style={{ fontSize: '1.25rem' }}>Real-Time API Cost Analytics Calculator</h2> <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '0.1rem' }}> Real-time cost tracking and pricing metrics for DeepL, Google Gemini, OpenAI, and Anthropic Claude APIs </p> </div> </div> <button className="btn btn-secondary" style={{ padding: '0.35rem 0.75rem' }} onClick={() => setIsPricingModalOpen(false)} > Close </button> </div> <div className="modal-body" style={{ maxHeight: '72vh', overflowY: 'auto', padding: '1.25rem' }}> {/* Global Summary Cards */} <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '1rem', marginBottom: '1.5rem' }}> <div style={{ background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.25)', padding: '1rem', borderRadius: '12px' }}> <div style={{ fontSize: '0.75rem', color: 'var(--accent-blue)', fontWeight: '700' }}>🔵 DeepL API Pro</div> <div style={{ fontSize: '1.4rem', fontWeight: '800', margin: '0.2rem 0' }}>{formatCurrency(totalAllCost.deepl)}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>$20.00 / 1M Simvol</div> </div> <div style={{ background: 'rgba(16, 185, 129, 0.1)', border: '1px solid rgba(16, 185, 129, 0.25)', padding: '1rem', borderRadius: '12px' }}> <div style={{ fontSize: '0.75rem', color: 'var(--accent-emerald)', fontWeight: '700' }}>🟢 Google Gemini Flash</div> <div style={{ fontSize: '1.4rem', fontWeight: '800', margin: '0.2rem 0' }}>{formatCurrency(totalAllCost.gemini)}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>$0.075 / 1M Token (In)</div> </div> <div style={{ background: 'rgba(6, 182, 212, 0.1)', border: '1px solid rgba(6, 182, 212, 0.25)', padding: '1rem', borderRadius: '12px' }}> <div style={{ fontSize: '0.75rem', color: 'var(--accent-cyan)', fontWeight: '700' }}>🟢 OpenAI GPT-4o</div> <div style={{ fontSize: '1.4rem', fontWeight: '800', margin: '0.2rem 0' }}>{formatCurrency(totalAllCost.openai)}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>$2.50 / 1M Token (In)</div> </div> <div style={{ background: 'rgba(168, 85, 247, 0.1)', border: '1px solid rgba(168, 85, 247, 0.25)', padding: '1rem', borderRadius: '12px' }}> <div style={{ fontSize: '0.75rem', color: '#c084fc', fontWeight: '700' }}>🟣 Anthropic Claude</div> <div style={{ fontSize: '1.4rem', fontWeight: '800', margin: '0.2rem 0' }}>{formatCurrency(totalAllCost.claude)}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>$3.00 / 1M Token (In)</div> </div> <div style={{ background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.2), rgba(37, 99, 235, 0.2))', border: '1px solid rgba(168, 85, 247, 0.4)', padding: '1rem', borderRadius: '12px' }}> <div style={{ fontSize: '0.75rem', color: 'var(--text-primary)', fontWeight: '700' }}>💰 TOTAL ACCUMULATED COST</div> <div style={{ fontSize: '1.5rem', fontWeight: '800', color: '#a855f7', margin: '0.2rem 0' }}>{formatCurrency(totalAllCost.total)}</div> <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>Across all {tasks.length} projects</div> </div> </div> {/* Pricing Table */} <h3 style={{ fontSize: '1rem', color: 'var(--text-primary)', marginBottom: '0.75rem' }}>📊 Official API Provider Pricing Table</h3> <table className="sub-table" style={{ marginBottom: '1.5rem' }}> <thead> <tr> <th>API Service / Model</th> <th>Pricing Unit</th> <th>Input Cost</th> <th>Output Cost</th> </tr> </thead> <tbody> <tr> <td><span className="dot deepl"></span> <strong>DeepL API Pro</strong></td> <td>Character Count</td> <td>$20.00 / 1,000,000 simvol ($0.00002 / simvol)</td> <td>—</td> </tr> <tr> <td><span className="dot gemini"></span> <strong>Google Gemini Flash</strong> ({GEMINI_MODEL})</td> <td>Token (1 Token ≈ 4 simvol)</td> <td>$0.075 / 1,000,000 token</td> <td>$0.30 / 1,000,000 token</td> </tr> <tr> <td><span className="dot openai"></span> <strong>OpenAI GPT-4o</strong> ({OPENAI_MODEL})</td> <td>Token (1 Token ≈ 4 simvol)</td> <td>$2.50 / 1,000,000 token</td> <td>$10.00 / 1,000,000 token</td> </tr> <tr> <td><span className="dot claude"></span> <strong>Anthropic Claude</strong> ({CLAUDE_MODEL})</td> <td>Token (1 Token ≈ 4 simvol)</td> <td>$3.00 / 1,000,000 token</td> <td>$15.00 / 1,000,000 token</td> </tr> </tbody> </table> {/* Project List Breakdown */} <h3 style={{ fontSize: '1rem', color: 'var(--text-primary)', marginBottom: '0.75rem' }}>📁 Project Cost Breakdown Table</h3> <table className="sub-table"> <thead> <tr> <th>Project Name</th> <th>DeepL</th> <th>Gemini</th> <th>OpenAI</th> <th>Claude</th> <th>Total Cost</th> </tr> </thead> <tbody> {tasks.map(t => { const tCost = calculateTaskCost(t); return ( <tr key={t.id}> <td style={{ fontWeight: '600' }}>{t.campaignName || `Project #${t.id}`}</td> <td>{formatCurrency(tCost.deepl)}</td> <td>{formatCurrency(tCost.gemini)}</td> <td>{formatCurrency(tCost.openai)}</td> <td>{formatCurrency(tCost.claude)}</td> <td style={{ fontWeight: '700', color: '#a855f7' }}>{formatCurrency(tCost.total)}</td> </tr> ); })} </tbody> </table> </div> </div> </div> )} </> )} </div> ); }
import React, { useState, useEffect, useRef } from 'react';
import FormbricksTranslator from './components/FormbricksTranslator';
import {
Settings,
Plus,
Trash2,
ChevronDown,
ChevronUp,
Play,
Copy,
Download,
Eye,
Check,
AlertCircle,
FileJson,
FileText,
Upload,
Layers,
Sparkles,
HelpCircle,
CheckCircle,
Loader2,
Lock,
Globe,
Sun,
Moon,
FileSpreadsheet,
Zap,
Archive,
ArchiveRestore,
Inbox,
Square,
Octagon,
RotateCw,
RefreshCw,
DollarSign,
Coins,
Info,
PieChart
} from 'lucide-react';
import confetti from 'canvas-confetti';
import * as XLSX from 'xlsx';
import {
extractTranslatableSegments,
reconstructJson,
runPipelineForSegment,
calculateLevenshteinDistance
} from './utils/pipeline';
import {
SAMPLE_EMAIL_TEMPLATE,
SAMPLE_WEBSITE_I18N_TEMPLATE,
SAMPLE_PRODUCT_CATALOG_TEMPLATE,
SAMPLE_MARKDOWN_FAQ_TEMPLATE
} from './utils/sampleTemplate';
import {
parseMarkdownToSegments,
extractSmartMarkdownContext,
compactUserContext,
reconstructMarkdown
} from './utils/markdownParser';
import {
API_PRICING,
calculateSegmentCost,
calculateOutputCost,
calculateTaskCost,
calculateTotalAllTasksCost,
formatCurrency
} from './utils/costCalculator';
const GEMINI_MODEL = import.meta.env.VITE_GEMINI_MODEL || 'gemini-3.5-flash';
const OPENAI_MODEL = import.meta.env.VITE_OPENAI_MODEL || 'gpt-4o';
const CLAUDE_MODEL = import.meta.env.VITE_CLAUDE_MODEL || 'claude-opus-4.8';
const CONTENT_TYPES = [
{ id: 'WEBSITE', name: '🌐 Website / App i18n', label: 'Website UI & App Localized Strings' },
{ id: 'EMAIL', name: '✉️ Email Campaign', label: 'Marketing Email Content' },
{ id: 'MARKDOWN', name: '📄 FAQ & Markdown (.md)', label: 'Markdown Knowledge Base & FAQ Article' },
{ id: 'ECOMMERCE', name: '🛒 E-Commerce & Products', label: 'E-Commerce Product Catalog Content' },
{ id: 'CMS', name: '📝 CMS & Blog Articles', label: 'CMS Article & Blog Content' },
{ id: 'GENERAL', name: '🧩 General JSON Content', label: 'General JSON Content' }
];
const LANGUAGES = [
{ code: 'FR', name: 'French (Français)' },
{ code: 'NL', name: 'Dutch (Nederlands)' },
{ code: 'DE', name: 'German (Deutsch)' },
{ code: 'ES', name: 'Spanish (Español)' },
{ code: 'PT', name: 'Portuguese (Português)' },
{ code: 'BR', name: 'Portuguese (Brazil)' },
{ code: 'HU', name: 'Hungarian (Magyar)' },
{ code: 'CS', name: 'Czech (Čeština)' },
{ code: 'PL', name: 'Polish (Polski)' },
{ code: 'IT', name: 'Italian (Italiano)' },
{ code: 'EL', name: 'Greek (Ελληνικά)' }
];
export default function App() {
// API keys are securely managed via backend environment variables
const getDefaultPresetTasks = () => [