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
 
 
 
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import {
  Bold, Italic, List, ListOrdered, Quote, Code,
  Type, Palette, Layout, Settings, X, Check, Copy,
  AlignLeft, AlignCenter, AlignRight, Maximize2, Minimize2
} from 'lucide-react';
import {
  DEFAULT_STYLE_CONFIG,
  subscribeToStyleConfig,
  saveStyleConfigToCloud,
  type StyleConfig,
  type CodeStyleConfig,
  type QuoteStyleConfig
} from '../services/codeStyleService';
import { StyleSettingsPanel } from './StyleSettingsPanel';

interface TextFormatToolbarProps {
  textareaRef: React.RefObject<HTMLTextAreaElement>;
  onApplyFormat: (start: number, end: number, formatted: string) => void;
}

export interface TextFormatToolbarRef {
  openSettings: (tab: 'code' | 'quote') => void;
  syncStylesFromSelection: () => void;
}

type FormatType = 'bold' | 'italic' | 'code' | 'quote' | 'uppercase' | 'lowercase' | 'plain';
type SettingsTab = 'code' | 'quote' | 'general' | 'link';

export const TextFormatToolbar = forwardRef<TextFormatToolbarRef, TextFormatToolbarProps>(({ textareaRef, onApplyFormat }, ref) => {
  const [selectedText, setSelectedText] = useState('');
  const [selectedRange, setSelectedRange] = useState<{ start: number; end: number } | null>(null);
  const [activeFormats, setActiveFormats] = useState<Set<FormatType>>(new Set());
  const [showSettings, setShowSettings] = useState(false);
  const [settingsTab, setSettingsTab] = useState<SettingsTab>('code');

  const [localStyleConfig, setLocalStyleConfig] = useState<StyleConfig>(DEFAULT_STYLE_CONFIG);
  // Estado temporal para la configuraci贸n (borrador)
  const [tempStyleConfig, setTempStyleConfig] = useState<StyleConfig | null>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);

  // Expose methods via ref
  useImperativeHandle(ref, () => ({
    openSettings: (tab) => {
      setShowSettings(true);
      setSettingsTab(tab);
      // Inicializar el borrador con la configuraci贸n actual
      setTempStyleConfig(localStyleConfig);
    },
    syncStylesFromSelection: () => {
      checkSelectionFormat();
    }
  }));

  useEffect(() => {
    const unsubscribe = subscribeToStyleConfig((config) => {
      setLocalStyleConfig(config);
    });
    return () => unsubscribe();
  }, []);

  // Usar tempStyleConfig si existe (modo edici贸n), sino localStyleConfig
  const styleConfig = tempStyleConfig || localStyleConfig;

  // Helper to update style config (Draft logic)
  const handleConfigUpdate = (newConfig: StyleConfig) => {
    // Solo actualizamos el estado temporal, no aplicamos cambios al texto ni a la nube todav铆a
    setTempStyleConfig(newConfig);
  };

  const handleConfirmSettings = () => {
    if (!tempStyleConfig) return;

    // Aplicar cambios permanentemente
    setLocalStyleConfig(tempStyleConfig);

    // Guardar en la nube y aplicar al texto seleccionado
    const newConfig = tempStyleConfig;

    const textarea = textareaRef.current;
    if (!textarea) {
      saveStyleConfigToCloud(newConfig);
      setShowSettings(false);
      setTempStyleConfig(null);
      return;
    }

    const cursor = textarea.selectionStart;
    const text = textarea.value;

    let isInBlock = false;

    // Check for Blockquote
    const quoteRegex = /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/g;
    let match;
    while ((match = quoteRegex.exec(text)) !== null) {
      if (cursor >= match.index && cursor <= match.index + match[0].length) {
        isInBlock = true;
        const newStyle = getQuoteStyleString(newConfig.quote);
        const openTagRegex = /<blockquote[^>]*>/;
        const openTagMatch = openTagRegex.exec(match[0]);

        if (openTagMatch) {
          const newOpenTag = `<blockquote style="${newStyle}" data-show-copy="${newConfig.quote.showCopyButton}">`;
          const newFullBlock = match[0].replace(openTagMatch[0], newOpenTag);
          setTimeout(() => {
            onApplyFormat(match.index, match.index + match[0].length, newFullBlock);
          }, 0);
        }
        break;
      }
    }

    // Check for Code if not in quote
    if (!isInBlock) {
      const codeRegex = /<code[^>]*>([\s\S]*?)<\/code>/g;
      while ((match = codeRegex.exec(text)) !== null) {
        if (cursor >= match.index && cursor <= match.index + match[0].length) {
          isInBlock = true;
          const newStyle = getCodeStyleString(newConfig.code);
          const openTagRegex = /<code[^>]*>/;
          const openTagMatch = openTagRegex.exec(match[0]);

          if (openTagMatch) {
            const newOpenTag = `<code style="${newStyle}">`;
            const newFullBlock = match[0].replace(openTagMatch[0], newOpenTag);
            setTimeout(() => {
              onApplyFormat(match.index, match.index + match[0].length, newFullBlock);
            }, 0);
          }
          break;
        }
      }
    }

    // If NOT in a block, update global config
    if (!isInBlock) {
      saveStyleConfigToCloud(newConfig);
    }

    setShowSettings(false);
    setTempStyleConfig(null);
  };

  const handleCancelSettings = () => {
    // Descartar cambios
    setTempStyleConfig(null);
    setShowSettings(false);
  };

  const checkSelectionFormat = () => {
    // Placeholder for now, can be implemented to read styles from selection
    // For now, double click just opens the settings
  };

  const updateSelectionState = () => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value.substring(start, end);

    setSelectedText(text);
    setSelectedRange({ start, end });
  };

  useEffect(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    textarea.addEventListener('mouseup', updateSelectionState);
    textarea.addEventListener('keyup', updateSelectionState);
    textarea.addEventListener('click', updateSelectionState);
    textarea.addEventListener('select', updateSelectionState);
    textarea.addEventListener('focus', updateSelectionState);

    return () => {
      textarea.removeEventListener('mouseup', updateSelectionState);
      textarea.removeEventListener('keyup', updateSelectionState);
      textarea.removeEventListener('click', updateSelectionState);
      textarea.removeEventListener('select', updateSelectionState);
      textarea.removeEventListener('focus', updateSelectionState);
    };
  }, [textareaRef]);


  useEffect(() => {
    const style = document.createElement('style');
    style.id = 'dynamic-style-config';

    const codeStyle = styleConfig.code;
    const quoteStyle = styleConfig.quote;

    const rgbaMatch = codeStyle.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
    let bgColorWithOpacity = codeStyle.bgColor;

    if (rgbaMatch) {
      const [_, r, g, b] = rgbaMatch;
      bgColorWithOpacity = `rgba(${r}, ${g}, ${b}, ${codeStyle.opacity / 100})`;
    }

    const widthValue = codeStyle.width === 'auto' ? 0 : parseFloat(codeStyle.width) || 0;
    const heightValue = codeStyle.height === 'auto' ? 0 : parseFloat(codeStyle.height) || 0;

    style.innerHTML = `

      :not(pre) > code {

        background-color: ${bgColorWithOpacity} !important;

        color: ${codeStyle.textColor} !important;

        font-size: ${codeStyle.fontSize} !important;

        border-radius: ${codeStyle.borderRadius} !important;



        padding: 0px 2px !important;



        ${codeStyle.width !== 'auto' && widthValue > 0 ? `min-width: ${codeStyle.width} !important;` : ''}

        ${codeStyle.height !== 'auto' && heightValue > 0 ? `min-height: ${codeStyle.height} !important;` : ''}



        display: inline-flex !important;

        align-items: center !important;

        justify-content: center !important;



        vertical-align: middle !important;

        border: 1px solid rgba(255,255,255,0.05) !important;

        font-family: 'Consolas', 'Monaco', monospace !important;

        line-height: 1 !important;

        margin: 0 1px !important;

      }



      blockquote {

        background-color: ${quoteStyle.bgColor} !important;

        color: ${quoteStyle.textColor} !important;

        border-left: ${quoteStyle.borderWidth} solid ${quoteStyle.borderColor} !important;

        padding: ${quoteStyle.padding} !important;

        font-size: ${quoteStyle.fontSize} !important;

        border-radius: ${quoteStyle.borderRadius} !important;

        font-style: ${quoteStyle.italic ? 'italic' : 'normal'} !important;

        

        ${quoteStyle.width !== 'auto' ? `width: ${quoteStyle.width} !important;` : ''}

        ${quoteStyle.height !== 'auto' ? `min-height: ${quoteStyle.height} !important;` : ''}

        

        overflow: visible !important;

        position: relative !important;

        margin-bottom: 1rem !important;

        display: flex !important;

        flex-direction: column !important;

        justify-content: center !important;

        word-break: break-word !important;

      }



      button code, a code, .btn code {

        background: transparent !important;

        padding: 0 !important;

        color: inherit !important;

        border: none !important;

        margin: 0 !important;

      }

    `;

    const existingStyle = document.getElementById('dynamic-style-config');
    if (existingStyle) {
      existingStyle.remove();
    }

    document.head.appendChild(style);

    return () => {
      style.remove();
    };
  }, [styleConfig]);

  const applyFormat = (format: FormatType) => {
    let currentStart = selectedRange?.start || 0;
    let currentEnd = selectedRange?.end || 0;
    let currentText = selectedText;

    if (!selectedRange && textareaRef.current) {
      currentStart = textareaRef.current.selectionStart;
      currentEnd = textareaRef.current.selectionEnd;
      currentText = textareaRef.current.value.substring(currentStart, currentEnd);
    }

    if (textareaRef.current) {
      currentStart = textareaRef.current.selectionStart;
      currentEnd = textareaRef.current.selectionEnd;
      currentText = textareaRef.current.value.substring(currentStart, currentEnd);
    }

    let formatted = currentText;

    switch (format) {
      case 'bold':
        formatted = `**${currentText}**`;
        break;
      case 'italic':
        formatted = `*${currentText}*`;
        break;
      case 'code':
        formatted = `\`${currentText}\``;
        break;
      case 'quote':
        const lines = currentText.split('\n');
        const quotedLines = lines.map(line => `> ${line}`);
        formatted = quotedLines.join('\n') + '\n\n';
        break;
      case 'uppercase':
        formatted = currentText.toUpperCase();
        break;
      case 'lowercase':
        formatted = currentText.toLowerCase();
        break;
      case 'plain':
        formatted = currentText
          .replace(/\*\*/g, '')
          .replace(/\*/g, '')
          .replace(/`/g, '')
          .replace(/<[^>]+>/g, ''); // Remove HTML tags
        break;
    }

    onApplyFormat(currentStart, currentEnd, formatted);
    setSelectedText(formatted);

    const newActiveFormats = new Set(activeFormats);

    // Code format is transient/stateless for this toolbar
    if (format === 'code') {
      // Do nothing to activeFormats, or remove if it was there (though it shouldn't be)
      if (newActiveFormats.has('code')) {
        newActiveFormats.delete('code');
      }
    } else {
      if (newActiveFormats.has(format)) {
        newActiveFormats.delete(format);
      } else {
        if (['uppercase', 'lowercase', 'plain'].includes(format)) {
          newActiveFormats.clear();
        }
        newActiveFormats.add(format);
      }
    }
    setActiveFormats(newActiveFormats);
  };

  const getCodeStyleString = (config: CodeStyleConfig) => {
    const rgbaMatch = config.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
    let bgColor = config.bgColor;
    if (rgbaMatch) {
      const [_, r, g, b] = rgbaMatch;
      bgColor = `rgba(${r}, ${g}, ${b}, ${config.opacity / 100})`;
    }

    return [
      `background-color: ${bgColor}`,
      `color: ${config.textColor}`,
      `font-size: ${config.fontSize}`,
      `border-radius: ${config.borderRadius}`,
      `padding: 0px 2px`,
      config.width !== 'auto' ? `min-width: ${config.width}` : '',
      config.height !== 'auto' ? `min-height: ${config.height}` : '',
      'display: inline-flex',
      'align-items: center',
      'justify-content: center',
      'vertical-align: middle',
      'border: 1px solid rgba(255,255,255,0.05)',
      "font-family: 'Consolas', 'Monaco', monospace",
      'line-height: 1',
      'margin: 0 1px'
    ].filter(Boolean).join('; ');
  };

  const getQuoteStyleString = (config: QuoteStyleConfig) => {
    return [
      `background-color: ${config.bgColor}`,
      `color: ${config.textColor}`,
      `border-left: ${config.borderWidth} solid ${config.borderColor}`,
      `padding: ${config.padding}`,
      `font-size: ${config.fontSize}`,
      `border-radius: ${config.borderRadius}`,
      config.italic ? 'font-style: italic' : 'font-style: normal',
      config.width !== 'auto' ? `width: ${config.width}` : '',
      config.height !== 'auto' ? `height: ${config.height}` : '',
      'overflow: visible',
      'position: relative',
      'margin-bottom: 1rem',
      'display: flex',
      'flex-direction: column',
      'justify-content: center'
    ].filter(Boolean).join('; ');
  };

  return (
    <>

      <div

        ref={toolbarRef}

        className="fixed bottom-8 left-1/2 -translate-x-1/2 flex items-center gap-1 bg-surface/95 backdrop-blur-sm border border-white/10 rounded-xl p-1.5 shadow-[0_4px_20px_rgba(0,0,0,0.4)] z-50 pointer-events-auto animate-fade-in transition-all duration-300"

        style={{ position: 'fixed', bottom: '3rem', left: '50%', transform: 'translateX(-50%)' }}

      >

        <button

          type="button"

          onClick={() => applyFormat('bold')}

          className={`p-2 rounded-lg transition-all ${activeFormats.has('bold')

            ? 'bg-primary text-background shadow-md'

            : 'hover:bg-white/10 text-gray-400 hover:text-white'

            }`}

          title="Negrita"

        >

          <Bold size={18} strokeWidth={2.5} />

        </button>



        <button

          type="button"

          onClick={() => applyFormat('italic')}

          className={`p-2 rounded-lg transition-all ${activeFormats.has('italic')

            ? 'bg-primary text-background shadow-md'

            : 'hover:bg-white/10 text-gray-400 hover:text-white'

            }`}

          title="Cursiva"

        >

          <Italic size={18} strokeWidth={2.5} />

        </button>



        <button

          type="button"

          onClick={() => applyFormat('code')}

          className={`p-2 rounded-lg transition-all ${activeFormats.has('code')

            ? 'bg-primary text-background shadow-md'

            : 'hover:bg-white/10 text-gray-400 hover:text-white'

            }`}

          title="C贸digo Inline"

        >

          <Code size={18} strokeWidth={2.5} />

        </button>



        <button

          type="button"

          onClick={() => applyFormat('quote')}

          className={`p-2 rounded-lg transition-all ${activeFormats.has('quote')

            ? 'bg-primary text-background shadow-md'

            : 'hover:bg-white/10 text-gray-400 hover:text-white'

            }`}

          title="Citar"

        >

          <Quote size={18} strokeWidth={2.5} />

        </button>



        <div className="w-px h-6 bg-white/10 mx-1"></div>



        <button

          type="button"

          onClick={() => applyFormat('uppercase')}

          className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-all text-xs font-bold"

          title="MAY脷SCULAS"

        >

          AA

        </button>



        <button

          type="button"

          onClick={() => applyFormat('lowercase')}

          className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-all text-xs font-bold"

          title="min煤sculas"

        >

          aa

        </button>



        <button

          type="button"

          onClick={() => applyFormat('plain')}

          className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-red-400 transition-all"

          title="Limpiar Formato"

        >

          <X size={18} />

        </button>



        <div className="w-px h-6 bg-white/10 mx-1"></div>



        <button

          type="button"

          onClick={() => setShowSettings(!showSettings)}

          className={`p-2 rounded-lg transition-all ${showSettings

            ? 'bg-primary text-background shadow-md'

            : 'hover:bg-white/10 text-gray-400 hover:text-white'

            }`}

          title="Configuraci贸n"

        >

          <Settings size={18} strokeWidth={2.5} />

        </button>

      </div>



      {showSettings && (

        <div

          className="fixed bottom-24 left-1/2 -translate-x-1/2 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-[0_0_40px_rgba(0,0,0,0.6)] z-50 w-[380px] flex flex-col max-h-[75vh] animate-fade-in overflow-hidden"

          style={{ position: 'fixed', bottom: '7rem', left: '50%', transform: 'translateX(-50%)' }}

        >

          <StyleSettingsPanel

            styleConfig={styleConfig}

            onUpdateConfig={handleConfigUpdate}

            activeTab={settingsTab}

            onTabChange={setSettingsTab}

            onClose={handleCancelSettings}

            onConfirm={handleConfirmSettings}

          />

        </div>

      )}

    </>
  );
});