File size: 17,799 Bytes
2dfd598
 
 
 
 
 
 
 
502e615
 
 
 
 
 
 
 
 
 
 
 
 
 
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
502e615
2dfd598
 
 
 
 
502e615
2dfd598
 
 
 
502e615
2dfd598
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
502e615
 
 
2dfd598
502e615
 
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
502e615
2dfd598
 
502e615
2dfd598
 
 
 
 
 
 
502e615
2dfd598
502e615
2dfd598
 
 
 
 
 
 
502e615
2dfd598
 
502e615
2dfd598
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502e615
2dfd598
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import React, { useState } from 'react';
import { runPipelineForSegment } from '../utils/pipeline';
import { 
  Globe, Play, Search, Save, Settings, 
  CheckCircle2, XCircle, Loader2, Info, Download
} from 'lucide-react';

const LANGUAGES = [
  { code: 'FR', locale: 'fr-FR', name: 'French' },
  { code: 'NL', locale: 'nl-NL', name: 'Dutch' },
  { code: 'DE', locale: 'de-DE', name: 'German' },
  { code: 'ES', locale: 'es-ES', name: 'Spanish' },
  { code: 'PT', locale: 'pt-PT', name: 'Portuguese (Portugal)' },
  { code: 'BR', locale: 'pt-BR', name: 'Portuguese (Brazil)' },
  { code: 'HU', locale: 'hu-HU', name: 'Hungarian' },
  { code: 'CS', locale: 'cs-CZ', name: 'Czech' },
  { code: 'PL', locale: 'pl-PL', name: 'Polish' },
  { code: 'IT', locale: 'it-IT', name: 'Italian' },
  { code: 'EL', locale: 'el-GR', name: 'Greek' },
  { code: 'AZ', locale: 'az-AZ', name: 'Azerbaijani' },
  { code: 'TR', locale: 'tr-TR', name: 'Turkish' },
  { code: 'RU', locale: 'ru-RU', name: 'Russian' }
];

export default function FormbricksTranslator() {
  const [surveyId, setSurveyId] = useState('');
  const [surveyData, setSurveyData] = useState(null);
  const [isFetching, setIsFetching] = useState(false);
  const [error, setError] = useState(null);

  const [selectedLocales, setSelectedLocales] = useState([]);
  
  const [translationStatus, setTranslationStatus] = useState('idle'); // idle, translating, complete
  const [progress, setProgress] = useState({ current: 0, total: 0, details: '' });
  
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncStatus, setSyncStatus] = useState(null);

  const extractDefaultTexts = (obj, paths = [], currentPath = '') => {
    let results = [];
    if (!obj || typeof obj !== 'object') return results;

    if (obj.hasOwnProperty('default') && typeof obj.default === 'string') {
      results.push({
        path: currentPath,
        text: obj.default,
        parentRef: obj
      });
    }

    for (const key in obj) {
      if (typeof obj[key] === 'object') {
        const nextPath = currentPath ? `${currentPath}.${key}` : key;
        results = results.concat(extractDefaultTexts(obj[key], paths, nextPath));
      }
    }
    return results;
  };

  const fetchSurvey = async () => {
    if (!surveyId.trim()) return;
    
    // Extract ID if URL is pasted
    let finalId = surveyId.trim();
    if (finalId.includes('surveys/')) {
      const parts = finalId.split('surveys/');
      finalId = parts[1].split('/')[0];
    }
    
    setIsFetching(true);
    setError(null);
    setSurveyData(null);
    
    try {
      const res = await fetch(`/api/formbricks/survey/${finalId}`);
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.error || 'Failed to fetch survey');
      }
      
      const fetchedData = data.data || data;
      
      // Check if we have a locally cached translated version
      const cached = localStorage.getItem(`fb_cached_survey_${finalId}`);
      if (cached) {
        try {
          const parsedCache = JSON.parse(cached);
          setSurveyData(parsedCache);
          setTranslationStatus('complete');
          setSyncStatus(null);
        } catch (e) {
          setSurveyData(fetchedData);
        }
      } else {
        setSurveyData(fetchedData);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setIsFetching(false);
    }
  };

  const startTranslation = async () => {
    if (!surveyData || selectedLocales.length === 0) return;
    
    setTranslationStatus('translating');
    setError(null);
    setSyncStatus(null);
    
    const cloneData = JSON.parse(JSON.stringify(surveyData));
    const defaultTexts = extractDefaultTexts(cloneData);
    
    const totalSteps = defaultTexts.length * selectedLocales.length;
    let completedSteps = 0;
    
    setProgress({ current: 0, total: totalSteps, details: 'Starting translation pipeline...' });
    
    try {
      for (const locale of selectedLocales) {
        const langObj = LANGUAGES.find(l => l.locale === locale) || { name: locale };
        
        for (const item of defaultTexts) {
          setProgress({ 
            current: completedSteps + 1, 
            total: totalSteps, 
            details: `[${locale}] Translating: ${item.text.substring(0, 30)}...` 
          });
          
          if (!item.text.trim()) {
            completedSteps++;
            continue;
          }
          
          const targetCode = langObj.code || locale.split('-')[0].toUpperCase();
          const result = await runPipelineForSegment(
            { original: item.text }, 
            targetCode, 
            {}, 
            false, 
            "This is a Formbricks survey element.",
            "MARKDOWN"
          );
          
          let currentRef = cloneData;
          const pathParts = item.path.split('.');
          for (const part of pathParts) {
            currentRef = currentRef[part];
          }
          
          currentRef[locale] = result.claude?.final_translation || result.deepl || item.text;
          completedSteps++;

          await new Promise(r => setTimeout(r, 250));
        }
        
        if (cloneData.languages) {
           const hasLang = cloneData.languages.find(l => l.language?.code === locale || l.code === locale);
           if (!hasLang) {
             console.warn(`Language ${locale} should be activated in Formbricks dashboard.`);
           }
        }
      }
      
      if (cloneData.id) {
        localStorage.setItem(`fb_cached_survey_${cloneData.id}`, JSON.stringify(cloneData));
      }
      
      setSurveyData(cloneData);
      setTranslationStatus('complete');
      setProgress({ current: totalSteps, total: totalSteps, details: 'Translation complete! (Saved to local cache)' });
      
    } catch (err) {
      console.error(err);
      setError(`Translation Error: ${err.message}`);
      setTranslationStatus('idle');
    }
  };

  const syncSurvey = async () => {
    if (!surveyData) return;
    
    setIsSyncing(true);
    setSyncStatus(null);
    
    try {
      const res = await fetch(`/api/formbricks/survey/${surveyData.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(surveyData)
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        const detailMsg = data.details ? (typeof data.details === 'string' ? data.details : JSON.stringify(data.details)) : '';
        throw new Error(`${data.error || 'Update failed'} ${detailMsg ? ': ' + detailMsg : ''}`);
      }
      
      setSyncStatus('success');
    } catch (err) {
      setSyncStatus('error');
      setError(`Sync Error: ${err.message}`);
    } finally {
      setIsSyncing(false);
    }
  };

  const downloadJson = () => {
    if (!surveyData) return;
    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(surveyData, null, 2));
    const downloadAnchor = document.createElement('a');
    downloadAnchor.setAttribute("href", dataStr);
    downloadAnchor.setAttribute("download", `formbricks_survey_${surveyData.id}_translated.json`);
    document.body.appendChild(downloadAnchor);
    downloadAnchor.click();
    downloadAnchor.remove();
  };

  const clearLocalCache = () => {
    if (!surveyData?.id) return;
    if (window.confirm("Do you want to clear the locally cached translations for this survey and reset?")) {
      localStorage.removeItem(`fb_cached_survey_${surveyData.id}`);
      fetchSurvey();
    }
  };

  const toggleLocale = (locale) => {
    if (selectedLocales.includes(locale)) {
      setSelectedLocales(selectedLocales.filter(l => l !== locale));
    } else {
      setSelectedLocales([...selectedLocales, locale]);
    }
  };

  return (
    <div className="glass-panel" style={{ padding: '2rem', minHeight: '80vh', margin: '2rem' }}>
      <div style={{ marginBottom: '2rem' }}>
        <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.5rem' }}>
          <Globe size={24} style={{ color: 'var(--accent-blue)' }} />
          Formbricks Survey Localizer
        </h2>
        <p style={{ color: 'var(--text-secondary)' }}>
          Seamlessly localize Formbricks surveys across multiple languages using multi-agent consensus.
        </p>
      </div>

      <div style={{ display: 'grid', gap: '2rem', gridTemplateColumns: '1fr 350px' }}>
        
        {/* Left Panel: Input & Progress */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
          
          <div className="editor-card" style={{ padding: '1.5rem' }}>
            <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <Search size={18} /> Survey ID or URL
            </h3>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <input 
                type="text" 
                className="input" 
                placeholder="https://app.formbricks.com/surveys/... or survey ID" 
                value={surveyId}
                onChange={(e) => setSurveyId(e.target.value)}
                style={{ flex: 1 }}
              />
              <button 
                className="btn btn-primary" 
                onClick={fetchSurvey}
                disabled={isFetching || !surveyId.trim()}
              >
                {isFetching ? <Loader2 size={18} className="spin" /> : 'Fetch'}
              </button>
            </div>
            
            {error && (
              <div style={{ marginTop: '1rem', padding: '1rem', background: 'rgba(239, 68, 68, 0.1)', color: '#ef4444', borderRadius: '8px', fontSize: '0.875rem' }}>
                Error: {error}
              </div>
            )}
          </div>

          {surveyData && (
            <div className="editor-card" style={{ padding: '1.5rem' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                <h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  <Info size={18} /> Survey Details
                </h3>
                <span style={{ fontSize: '0.75rem', background: 'rgba(255,255,255,0.1)', padding: '0.2rem 0.5rem', borderRadius: '4px' }}>
                  ID: {surveyData.id}
                </span>
              </div>
              
              <div style={{ background: 'rgba(0,0,0,0.2)', padding: '1rem', borderRadius: '8px', marginBottom: '1.5rem' }}>
                <strong>Title:</strong> {surveyData?.name || 'Untitled Survey'} <br/>
                <strong>Question Count:</strong> {surveyData?.questions?.length || surveyData?.blocks?.length || 0} <br/>
                <strong>Extracted Translatable Blocks:</strong> {extractDefaultTexts(surveyData).length} <br/>
                <div style={{ marginTop: '0.75rem', padding: '0.75rem', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)', borderRadius: '6px', fontSize: '0.8rem', color: '#93c5fd' }}>
                  💡 <strong>Configured Survey Languages:</strong> {surveyData?.languages?.map(l => l.language?.code || l.code).join(', ') || 'No secondary languages configured'} <br/>
                  <span style={{ opacity: 0.8 }}>Ensure target languages are enabled in your Formbricks survey dashboard before syncing back.</span>
                </div>
              </div>

              {translationStatus === 'translating' && (
                <div style={{ marginBottom: '1.5rem' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                    <span>{progress.details}</span>
                    <span>{progress.current} / {progress.total}</span>
                  </div>
                  <div style={{ width: '100%', height: '8px', background: 'rgba(255,255,255,0.1)', borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${(progress.current / Math.max(1, progress.total)) * 100}%`, height: '100%', background: 'var(--accent-emerald)', transition: 'width 0.3s' }}></div>
                  </div>
                </div>
              )}

              <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
                <button 
                  className="btn btn-primary"
                  onClick={startTranslation}
                  disabled={translationStatus === 'translating' || selectedLocales.length === 0}
                  style={{ flex: 1, display: 'flex', justifyContent: 'center', gap: '0.5rem', minWidth: '160px' }}
                >
                  {translationStatus === 'translating' ? <Loader2 size={18} className="spin" /> : <Play size={18} />}
                  Start Localization
                </button>
                
                <button 
                  className="btn btn-secondary"
                  onClick={syncSurvey}
                  disabled={translationStatus !== 'complete' || isSyncing}
                  style={{ flex: 1, display: 'flex', justifyContent: 'center', gap: '0.5rem', minWidth: '160px', background: translationStatus === 'complete' ? 'rgba(16, 185, 129, 0.15)' : '', color: translationStatus === 'complete' ? '#10b981' : '' }}
                >
                  {isSyncing ? <Loader2 size={18} className="spin" /> : <Save size={18} />}
                  {syncStatus === 'success' ? 'Synced to Formbricks!' : 'Sync to Formbricks'}
                </button>

                <button 
                  className="btn btn-secondary"
                  onClick={downloadJson}
                  disabled={!surveyData}
                  style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'rgba(59, 130, 246, 0.15)', color: '#60a5fa', borderColor: 'rgba(59, 130, 246, 0.4)' }}
                  title="Download translated JSON file"
                >
                  <Download size={18} />
                  <span>Download JSON</span>
                </button>

                {surveyData?.id && localStorage.getItem(`fb_cached_survey_${surveyData.id}`) && (
                  <button 
                    className="btn btn-secondary"
                    onClick={clearLocalCache}
                    style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', fontSize: '0.75rem', opacity: 0.7 }}
                    title="Reset cached translations and reload from server"
                  >
                    <span>Reset Cache</span>
                  </button>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Right Panel: Languages */}
        <div className="editor-card" style={{ padding: '1.5rem', height: 'fit-content' }}>
          <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            <Settings size={18} /> Target Locales
          </h3>
          <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '1rem' }}>
            Select target languages to translate:
          </p>
          
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', maxHeight: '400px', overflowY: 'auto', paddingRight: '0.5rem' }}>
            {LANGUAGES.map(lang => {
              const activeLangs = surveyData?.languages?.map(l => (l.language?.code || l.code || '').toLowerCase()) || [];
              const isConfiguredInFormbricks = !surveyData || activeLangs.some(code => 
                code === lang.locale.toLowerCase() || 
                code === lang.code.toLowerCase() || 
                code.startsWith(lang.code.toLowerCase()) ||
                lang.locale.toLowerCase().startsWith(code)
              );
              
              return (
                <label 
                  key={lang.locale} 
                  style={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'space-between',
                    padding: '0.75rem', 
                    background: selectedLocales.includes(lang.locale) ? 'rgba(59, 130, 246, 0.1)' : 'rgba(255, 255, 255, 0.05)',
                    border: `1px solid ${selectedLocales.includes(lang.locale) ? 'rgba(59, 130, 246, 0.5)' : 'transparent'}`,
                    borderRadius: '8px',
                    cursor: 'pointer',
                    opacity: isConfiguredInFormbricks ? 1 : 0.65,
                    transition: 'all 0.2s'
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                    <input 
                      type="checkbox" 
                      checked={selectedLocales.includes(lang.locale)}
                      onChange={() => toggleLocale(lang.locale)}
                      style={{ width: '16px', height: '16px' }}
                    />
                    <span style={{ fontSize: '0.875rem' }}>{lang.name} <strong>({lang.locale})</strong></span>
                  </div>
                  {surveyData && (
                    <span style={{ 
                      fontSize: '0.7rem', 
                      padding: '0.15rem 0.4rem', 
                      borderRadius: '4px',
                      background: isConfiguredInFormbricks ? 'rgba(16, 185, 129, 0.15)' : 'rgba(245, 158, 11, 0.15)',
                      color: isConfiguredInFormbricks ? '#10b981' : '#f59e0b'
                    }}>
                      {isConfiguredInFormbricks ? 'Configured' : 'Not in FB'}
                    </span>
                  )}
                </label>
              );
            })}
          </div>
        </div>

      </div>
    </div>
  );
}