// ============================================================================
// PRESENTATIONAL & CONTAINER COMPONENT: Modals.jsx (SHADCN/UI STYLE + TAGS)
// ============================================================================

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ============================================================================
// COMPONENTE REUTILIZÁVEL: ServiceCombobox (Pesquisa Inteligente + Cadastro Rápido)
// ============================================================================
function ServiceCombobox({
  value,
  onChange,
  label = "Vincular a Servicio (Opcional)",
  placeholder = "Escriba para buscar servicio o registrar en el momento...",
  allowNone = true,
  noneLabel = "Ninguno (Movimiento manual / cuota académica)",
  onAutoFill = null,
  helperText = null
}) {
  const { services = [], triggerRefresh, showToast } = window.useFinance ? window.useFinance() : { services: [] };
  const [searchQuery, setSearchQuery] = useState('');
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showQuickCreate, setShowQuickCreate] = useState(false);
  
  // Estado del registro rápido inline
  const [quickName, setQuickName] = useState('');
  const [quickAmount, setQuickAmount] = useState('');
  const [quickCategory, setQuickCategory] = useState('Prestación de Servicios');
  const [quickUnit, setQuickUnit] = useState('unidad');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const containerRef = useRef(null);
  const inputRef = useRef(null);

  // Cierra dropdown al hacer clic fuera
  useEffect(() => {
    function handleClickOutside(e) {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setDropdownOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const selectedService = services.find(s => String(s.id) === String(value));

  const normalize = (t) => {
    return (t || '')
      .toString()
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .trim();
  };

  // Filtrado insensible a acentos e inteligente (anun -> anúncios, video -> vídeo, trafego -> tráfego)
  const filteredServices = services.filter(s => {
    if (!searchQuery.trim()) return true;
    const qTokens = normalize(searchQuery).split(/\s+/).filter(Boolean);
    const searchable = [
      s.name,
      s.description,
      s.category,
      s.unit,
      `#srv-${String(s.id).padStart(3, '0')}`,
      String(s.id)
    ].map(normalize).join(' ');
    return qTokens.every(tok => searchable.includes(tok));
  });

  const handleOpenQuickCreate = (initialName = '') => {
    setQuickName(initialName || searchQuery.trim() || '');
    setQuickAmount('');
    setQuickCategory('Prestación de Servicios');
    setQuickUnit('unidad');
    setShowQuickCreate(true);
    setDropdownOpen(false);
  };

  const handleSaveQuickService = async (e) => {
    if (e) e.preventDefault();
    const cleanName = quickName.trim();
    if (!cleanName) {
      if (showToast) showToast('Ingrese el nombre del servicio.');
      return;
    }

    setIsSubmitting(true);
    try {
      const created = await window.Api.createService({
        name: cleanName,
        default_amount: window.unmaskCurrencyPYG(quickAmount),
        category: quickCategory.trim() || 'Prestação de Serviço',
        unit: quickUnit.trim() || 'unidad',
        description: 'Registrado rápidamente por vinculación'
      });

      if (showToast) showToast(`¡Servicio "${created.name}" registrado y vinculado!`);
      if (triggerRefresh) triggerRefresh();

      onChange(created.id, created);
      if (onAutoFill) onAutoFill(created);

      setShowQuickCreate(false);
      setSearchQuery('');
      setDropdownOpen(false);
    } catch (err) {
      if (showToast) showToast('Error al registrar servicio rápido.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="form-group" ref={containerRef} style={{ position: 'relative' }}>
      {/* ENCABEZADO DEL CAMPO CON BOTÓN DE REGISTRO RÁPIDO */}
      <div className="flex items-center justify-between mb-1.5">
        <label className="form-label font-semibold text-xs text-zinc-700 m-0">
          {label}
        </label>
        {!showQuickCreate && (
          <button
            type="button"
            className="text-[11px] font-semibold text-zinc-600 hover:text-zinc-950 hover:bg-zinc-100 px-2 py-0.5 rounded cursor-pointer transition-colors flex items-center gap-1 border border-zinc-200"
            onClick={() => handleOpenQuickCreate('')}
          >
            <span>+ Nuevo Servicio Rápido</span>
          </button>
        )}
      </div>

      {/* CUANDO EL FORMULARIO DE REGISTRO RÁPIDO ESTÁ ABIERTO */}
      {showQuickCreate ? (
        <div className="p-3.5 rounded-lg border-2 border-zinc-900 bg-zinc-50/90 space-y-3 shadow-md animate-in fade-in">
          <div className="flex items-center justify-between border-b border-zinc-200 pb-2">
            <div className="flex items-center gap-2">
              <span className="w-5 h-5 rounded-full bg-zinc-950 text-white flex items-center justify-center text-[10px] font-bold">⚡</span>
              <span className="font-bold text-xs text-zinc-950">Registro Rápido de Servicio en el Catálogo</span>
            </div>
            <button
              type="button"
              className="text-zinc-400 hover:text-zinc-950 text-xs font-bold px-1 cursor-pointer"
              onClick={() => setShowQuickCreate(false)}
            >
              ✕
            </button>
          </div>

          <div className="space-y-2.5 text-xs">
            <div>
              <label className="form-label text-[11px] font-semibold text-zinc-700">Nombre del Servicio *</label>
              <input
                type="text"
                className="input-control w-full text-xs font-medium"
                value={quickName}
                onChange={(e) => setQuickName(e.target.value)}
                placeholder="Ej: Grabación de Clases, Soporte TI, Redes Sociales..."
                required
                autoFocus
              />
            </div>

            <div className="grid grid-cols-2 gap-2.5">
              <div>
                <label className="form-label text-[11px] font-semibold text-zinc-700">Monto Estándar (G$)</label>
                <input
                  type="text"
                  inputMode="numeric"
                  className="input-control w-full font-mono font-bold text-xs"
                  value={quickAmount}
                  onChange={(e) => setQuickAmount(window.maskCurrencyPYG(e.target.value))}
                  placeholder="Ej: 1.500.000"
                />
              </div>
              <div>
                <label className="form-label text-[11px] font-semibold text-zinc-700">Categoría</label>
                <select
                  className="select-control w-full text-xs"
                  value={quickCategory}
                  onChange={(e) => setQuickCategory(e.target.value)}
                >
                  <option value="Prestação de Serviço">Prestación de Servicios</option>
                  <option value="Audiovisual / Gravação">Audiovisual / Grabación</option>
                  <option value="Tecnologia & TI">Tecnología & TI</option>
                  <option value="Educação / Ensino">Educación / Docencia</option>
                  <option value="Design & Marketing">Diseño & Marketing</option>
                  <option value="Administrativo / Gestão">Administrativo / Gestión</option>
                  <option value="Geral">General</option>
                </select>
              </div>
            </div>

            <div className="flex items-center justify-end gap-2 pt-1 border-t border-zinc-200">
              <button
                type="button"
                className="btn btn-secondary text-xs h-7 px-3 rounded text-zinc-700 cursor-pointer"
                onClick={() => setShowQuickCreate(false)}
                disabled={isSubmitting}
              >
                Cancelar
              </button>
              <button
                type="button"
                className="btn btn-primary text-xs h-7 px-3 rounded bg-zinc-950 text-white font-semibold flex items-center gap-1 cursor-pointer"
                onClick={handleSaveQuickService}
                disabled={isSubmitting || !quickName.trim()}
              >
                {isSubmitting ? 'Guardando...' : '✓ Guardar y Vincular'}
              </button>
            </div>
          </div>
        </div>
      ) : selectedService ? (
        /* SERVICIO ACTUALMENTE SELECCIONADO */
        <div className="flex items-center justify-between p-2.5 rounded-md border border-zinc-300 bg-zinc-50 shadow-2xs">
          <div className="flex items-center gap-2 overflow-hidden">
            <span className="font-mono text-[10px] font-bold bg-zinc-900 text-white px-2 py-0.5 rounded shrink-0">
              #SRV-{String(selectedService.id).padStart(3, '0')}
            </span>
            <div className="truncate">
              <div className="font-bold text-xs text-zinc-950 truncate">{selectedService.name}</div>
              <div className="text-[10px] text-zinc-500 font-medium">
                {selectedService.category || 'General'} • {selectedService.unit || 'unidad'}
              </div>
            </div>
            <span className="font-mono font-bold text-xs text-zinc-900 bg-zinc-200/80 px-2 py-0.5 rounded ml-1 shrink-0">
              {window.formatCurrencyPYG(selectedService.default_amount)}
            </span>
          </div>

          <div className="flex items-center gap-1.5 shrink-0">
            <button
              type="button"
              className="text-xs text-zinc-600 hover:text-zinc-950 hover:bg-zinc-200 px-2 py-1 rounded font-medium cursor-pointer transition-colors"
              onClick={() => {
                setDropdownOpen(true);
                setSearchQuery('');
                setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
              }}
            >
              Cambiar
            </button>
            {allowNone && (
              <button
                type="button"
                className="text-xs text-red-600 hover:text-red-800 hover:bg-red-50 px-2 py-1 rounded font-semibold cursor-pointer transition-colors"
                title="Desvincular servicio"
                onClick={() => {
                  onChange('', null);
                  setDropdownOpen(false);
                }}
              >
                ✕ Desvincular
              </button>
            )}
          </div>
        </div>
      ) : (
        /* CAMPO DE BÚSQUEDA CON DROPDOWN INTELIGENTE */
        <div>
          <div className="relative">
            <input
              ref={inputRef}
              type="text"
              className="input-control w-full pl-8 pr-24 text-xs font-medium"
              placeholder={placeholder}
              value={searchQuery}
              onFocus={() => setDropdownOpen(true)}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setDropdownOpen(true);
              }}
            />
            <div className="absolute left-2.5 top-2.5 text-zinc-400 pointer-events-none text-xs">🔍</div>
            <button
              type="button"
              className="absolute right-1.5 top-1.5 h-6 px-2 text-[11px] font-semibold bg-zinc-100 hover:bg-zinc-200 text-zinc-900 rounded border border-zinc-200 cursor-pointer flex items-center gap-1 transition-colors"
              onClick={() => handleOpenQuickCreate(searchQuery)}
            >
              <span>+ Crear Rápido</span>
            </button>
          </div>

          {dropdownOpen && (
            <div 
              className="absolute left-0 right-0 z-50 bg-white border border-zinc-300 rounded-md shadow-xl mt-1 overflow-hidden"
              style={{ maxHeight: '260px', overflowY: 'auto' }}
            >
              {/* ENCABEZADO DE CONTEO Y ESTADO */}
              <div className="px-3 py-1.5 bg-zinc-100 border-b border-zinc-200 text-[10px] font-bold text-zinc-500 uppercase tracking-wider flex items-center justify-between">
                <span>
                  {searchQuery.trim() 
                    ? `Resultados (${filteredServices.length})` 
                    : `Catálogo de Servicios (${services.length})`}
                </span>
                {searchQuery.trim() && (
                  <button
                    type="button"
                    className="text-zinc-600 hover:text-zinc-950 underline font-semibold normal-case cursor-pointer text-[10px]"
                    onClick={() => setSearchQuery('')}
                  >
                    Ver todos ({services.length})
                  </button>
                )}
              </div>

              {allowNone && (
                <div
                  className="p-2.5 text-xs text-zinc-600 hover:bg-zinc-100 hover:text-zinc-950 cursor-pointer border-b border-zinc-100 flex items-center justify-between font-medium"
                  onClick={() => {
                    onChange('', null);
                    setDropdownOpen(false);
                    setSearchQuery('');
                  }}
                >
                  <span className="italic">{noneLabel}</span>
                  <span className="text-[10px] text-zinc-400 font-mono">Sin Vínculo</span>
                </div>
              )}

              {filteredServices.length > 0 ? (
                filteredServices.map(s => (
                  <div
                    key={s.id}
                    className="p-2.5 hover:bg-zinc-50 cursor-pointer border-b border-zinc-100 last:border-b-0 flex items-center justify-between transition-colors"
                    onClick={() => {
                      onChange(s.id, s);
                      if (onAutoFill) onAutoFill(s);
                      setDropdownOpen(false);
                      setSearchQuery('');
                    }}
                  >
                    <div className="flex items-start gap-2 overflow-hidden pr-2">
                      <span className="font-mono text-[10px] font-bold bg-zinc-100 text-zinc-700 px-1.5 py-0.5 rounded border border-zinc-200 shrink-0 mt-0.5">
                        #SRV-{String(s.id).padStart(3, '0')}
                      </span>
                      <div className="truncate">
                        <div className="font-semibold text-xs text-zinc-950 truncate">{s.name}</div>
                        <div className="text-[10px] text-zinc-500 flex items-center gap-1.5">
                          <span className="font-medium text-zinc-600">{s.category || 'General'}</span>
                          <span>•</span>
                          <span>{s.unit || 'unidad'}</span>
                        </div>
                        {s.description && (
                          <div className="text-[10px] text-zinc-400 truncate max-w-sm mt-0.5 font-normal">
                            {s.description}
                          </div>
                        )}
                      </div>
                    </div>
                    <div className="font-mono font-bold text-xs text-zinc-900 shrink-0 ml-2 text-right">
                      {window.formatCurrencyPYG(s.default_amount)}
                    </div>
                  </div>
                ))
              ) : (
                <div className="p-3 text-center text-xs text-zinc-500 space-y-1.5">
                  <div>Ningún servicio encontrado para "<strong>{searchQuery}</strong>".</div>
                  <button
                    type="button"
                    className="text-[11px] font-semibold text-zinc-700 hover:text-zinc-950 underline cursor-pointer"
                    onClick={() => setSearchQuery('')}
                  >
                    Ver los {services.length} servicios del catálogo
                  </button>
                </div>
              )}

              {/* OPCIÓN DE CREAR RÁPIDO LO QUE SE ESCRIBIÓ */}
              {searchQuery.trim() && !services.some(s => normalize(s.name) === normalize(searchQuery.trim())) && (
                <div
                  className="p-2.5 bg-zinc-950 text-white text-xs font-semibold hover:bg-zinc-800 cursor-pointer flex items-center justify-between border-t border-zinc-800 transition-colors"
                  onClick={() => handleOpenQuickCreate(searchQuery)}
                >
                  <span className="flex items-center gap-1.5 truncate pr-2">
                    <span>⚡</span>
                    <span className="truncate">Registrar "<strong>{searchQuery}</strong>" en el catálogo</span>
                  </span>
                  <span className="text-[10px] bg-zinc-800 text-zinc-200 px-2 py-0.5 rounded font-mono shrink-0">
                    Crear Rápido →
                  </span>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {helperText && (
        <div className="form-hint text-[11px] text-zinc-400 mt-1">
          {helperText}
        </div>
      )}
    </div>
  );
}

const getServiceIcon = (category = '', name = '') => {
  const c = ((category || '') + ' ' + (name || '')).toLowerCase();
  if (c.includes('vídeo') || c.includes('video') || c.includes('reels') || c.includes('audiovisual')) return '🎬';
  if (c.includes('arte') || c.includes('design') || c.includes('anúncio') || c.includes('anuncio')) return '🎨';
  if (c.includes('tráfego') || c.includes('trafego') || c.includes('pautaje')) return '📈';
  if (c.includes('foto') || c.includes('ensaio')) return '📸';
  if (c.includes('story') || c.includes('instagram')) return '📱';
  if (c.includes('web') || c.includes('página') || c.includes('landing')) return '🌐';
  if (c.includes('crm') || c.includes('sistema')) return '💻';
  if (c.includes('servidor') || c.includes('ti') || c.includes('hospedagem')) return '🖥️';
  return '📦';
};

window.getEmbedDeliverable = function(url) {
  if (!url) return null;
  const str = String(url).trim();
  if (!str) return null;

  // YouTube (normal, short, shorts, embed)
  const ytMatch = str.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|shorts)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i);
  if (ytMatch && ytMatch[1]) {
    return {
      type: 'youtube',
      label: 'Video en YouTube',
      icon: '🎬',
      embedUrl: `https://www.youtube-nocookie.com/embed/${ytMatch[1]}`,
      isEmbeddable: true
    };
  }

  // Vimeo
  const vimeoMatch = str.match(/vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|)(\d+)/i);
  if (vimeoMatch && vimeoMatch[2]) {
    return {
      type: 'vimeo',
      label: 'Video en Vimeo',
      icon: '🎬',
      embedUrl: `https://player.vimeo.com/video/${vimeoMatch[2]}`,
      isEmbeddable: true
    };
  }

  // Google Drive File (previewable)
  const driveFileMatch = str.match(/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)/i);
  if (driveFileMatch && driveFileMatch[1]) {
    return {
      type: 'gdrive_file',
      label: 'Archivo en Google Drive',
      icon: '📄',
      embedUrl: `https://drive.google.com/file/d/${driveFileMatch[1]}/preview`,
      isEmbeddable: true
    };
  }

  // Google Drive Folder
  const driveFolderMatch = str.match(/drive\.google\.com\/(?:drive\/folders|open\?id=)\/([a-zA-Z0-9_-]+)/i);
  if (driveFolderMatch && driveFolderMatch[1]) {
    return {
      type: 'gdrive_folder',
      label: 'Carpeta en Google Drive',
      icon: '📁',
      embedUrl: null,
      isEmbeddable: false
    };
  }

  return {
    type: 'generic',
    label: 'Enlace de Entrega',
    icon: '🔗',
    embedUrl: null,
    isEmbeddable: false
  };
};

window.ServiceCombobox = ServiceCombobox;

function TransactionModal() {
  const { 
    modalTxOpen, 
    setModalTxOpen, 
    editingTx, 
    setEditingTx, 
    services, 
    tags, 
    settings,
    triggerRefresh, 
    showToast 
  } = window.useFinance();

  const [step, setStep] = useState(1);

  const generateAutoRef = (type, date) => {
    const d = date ? new Date(date) : new Date();
    const ym = !isNaN(d.getTime()) 
      ? `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`
      : new Date().toISOString().slice(0, 7).replace('-', '');
    
    const prefix = type === 'CREDIT' 
      ? 'SRV' 
      : type === 'DEBIT' 
      ? 'CUOTA' 
      : type === 'PAYMENT_RECEIVED' 
      ? 'REC' 
      : 'PAG';

    const randomSuffix = Math.floor(100 + Math.random() * 900);
    return `${prefix}-${ym}-${randomSuffix}`;
  };

  const [formData, setFormData] = useState({
    type: 'CREDIT',
    service_id: '',
    title: '',
    amount: '',
    date: new Date().toISOString().substring(0, 10),
    document_ref: generateAutoRef('CREDIT', new Date()),
    description: '',
    deliverable_url: '',
    delivery_scope: '',
    custom_category: 'Avulso',
    custom_unit: 'serviço',
    custom_requester: ''
  });

  const [selectedTags, setSelectedTags] = useState([]);
  const [tagInput, setTagInput] = useState('');
  const [tagDropdownOpen, setTagDropdownOpen] = useState(false);

  const [serviceMode, setServiceMode] = useState('catalog'); // 'catalog' ou 'custom'
  const [selectedServiceName, setSelectedServiceName] = useState('');

  // Estado para múltiplos serviços / entregas no mesmo lançamento
  const [isMultiService, setIsMultiService] = useState(false);
  const [items, setItems] = useState([]);

  const tagInputRef = useRef(null);

  const calculateItemsSum = (currentItems) => {
    return currentItems.reduce((acc, it) => {
      const q = parseFloat(it.quantity) || 1;
      const u = window.unmaskCurrencyPYG(it.unit_price) || 0;
      return acc + (q * u);
    }, 0);
  };

  useEffect(() => {
    setStep(1);
    if (editingTx) {
      setFormData({
        type: editingTx.type,
        service_id: editingTx.service_id || '',
        title: editingTx.title,
        amount: window.maskCurrencyPYG(editingTx.amount),
        date: editingTx.date,
        document_ref: editingTx.document_ref || '',
        description: editingTx.description || '',
        deliverable_url: editingTx.deliverable_url || '',
        delivery_scope: editingTx.delivery_scope || '',
        custom_category: 'Avulso',
        custom_unit: 'serviço',
        custom_requester: ''
      });
      setServiceMode(editingTx.service_id ? 'catalog' : 'custom');
      setSelectedServiceName(editingTx.service_name || editingTx.title || '');
      const txTags = Array.isArray(editingTx.tags) 
        ? editingTx.tags.map(t => (typeof t === 'string' ? t : t.name)) 
        : [];
      setSelectedTags(txTags);

      if (Array.isArray(editingTx.items) && editingTx.items.length > 0) {
        setIsMultiService(true);
        setItems(editingTx.items.map(it => ({
          id: it.id || Math.random(),
          service_id: it.service_id ? String(it.service_id) : '',
          title: it.title || '',
          quantity: it.quantity || 1,
          unit_price: window.maskCurrencyPYG(it.unit_price || 0),
          deliverable_url: it.deliverable_url || ''
        })));
      } else {
        setIsMultiService(false);
        setItems([]);
      }
    } else {
      const today = new Date().toISOString().substring(0, 10);
      setFormData({
        type: 'CREDIT',
        service_id: '',
        title: '',
        amount: '',
        date: today,
        document_ref: generateAutoRef('CREDIT', today),
        description: '',
        deliverable_url: '',
        delivery_scope: '',
        custom_category: 'Avulso',
        custom_unit: 'serviço',
        custom_requester: ''
      });
      setServiceMode('catalog');
      setSelectedServiceName('');
      setSelectedTags([]);
      setIsMultiService(false);
      setItems([]);
    }
    setTagInput('');
    setTagDropdownOpen(false);
  }, [editingTx, modalTxOpen]);

  if (!modalTxOpen) return null;

  const handleToggleMultiService = (enable) => {
    setIsMultiService(enable);
    if (enable && items.length === 0) {
      const initialItem = {
        id: Date.now(),
        service_id: formData.service_id || '',
        title: formData.title || '',
        quantity: 1,
        unit_price: formData.amount || '',
        deliverable_url: formData.deliverable_url || ''
      };
      const newItems = [initialItem];
      setItems(newItems);
      const sum = calculateItemsSum(newItems);
      if (sum > 0) {
        setFormData(prev => ({ ...prev, amount: window.maskCurrencyPYG(sum) }));
      }
    }
  };

  const handleAddItem = () => {
    const newItem = {
      id: Date.now() + Math.random(),
      service_id: '',
      title: '',
      quantity: 1,
      unit_price: '',
      deliverable_url: ''
    };
    const updated = [...items, newItem];
    setItems(updated);
  };

  const handleRemoveItem = (index) => {
    const updated = items.filter((_, idx) => idx !== index);
    setItems(updated);
    const sum = calculateItemsSum(updated);
    setFormData(prev => ({
      ...prev,
      amount: window.maskCurrencyPYG(sum)
    }));
  };

  const handleItemChange = (index, field, value) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };

    if (field === 'service_id') {
      if (value) {
        const srv = services.find(s => String(s.id) === String(value));
        if (srv) {
          if (!updated[index].title || updated[index].title.startsWith('Item #')) {
            updated[index].title = srv.name;
          }
          if (srv.default_amount > 0 && !updated[index].unit_price) {
            updated[index].unit_price = window.maskCurrencyPYG(srv.default_amount);
          }
          if (srv.deliverable_url && !updated[index].deliverable_url) {
            updated[index].deliverable_url = srv.deliverable_url;
          }
        }
      }
    }

    setItems(updated);
    const sum = calculateItemsSum(updated);
    setFormData(prev => ({
      ...prev,
      amount: window.maskCurrencyPYG(sum),
      title: prev.title ? prev.title : (updated[0]?.title ? `Pacote: ${updated[0].title}` : '')
    }));
  };

  // --- LÓGICA DO CREATABLE TAG INPUT ---
  const handleAddTag = async (tagName) => {
    const clean = (tagName || '').trim();
    if (!clean) return;

    if (!selectedTags.includes(clean)) {
      setSelectedTags(prev => [...prev, clean]);
    }

    const exists = tags.some(t => t.name.toLowerCase() === clean.toLowerCase());
    if (!exists) {
      try {
        await window.Api.createTag({ name: clean });
        triggerRefresh();
      } catch (err) {
        console.error('Error al registrar nueva etiqueta:', err);
      }
    }

    setTagInput('');
    setTagDropdownOpen(false);
    if (tagInputRef.current) tagInputRef.current.focus();
  };

  const handleRemoveTag = (tagName) => {
    setSelectedTags(prev => prev.filter(t => t !== tagName));
  };

  const handleTagKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      if (tagInput.trim()) {
        handleAddTag(tagInput.trim());
      }
    } else if (e.key === 'Backspace' && !tagInput && selectedTags.length > 0) {
      handleRemoveTag(selectedTags[selectedTags.length - 1]);
    }
  };

  const matchingTags = tags.filter(t => 
    t.name.toLowerCase().includes(tagInput.toLowerCase().trim()) &&
    !selectedTags.includes(t.name)
  );

  const exactMatchExists = tags.some(t => t.name.toLowerCase() === tagInput.toLowerCase().trim());

  // Navegación con validación entre pasos
  const handleNextStep = () => {
    if (step === 1) {
      if (!formData.type) {
        showToast('Seleccione un tipo de movimiento.');
        return;
      }
      if (!formData.date) {
        showToast('Ingrese la fecha del movimiento.');
        return;
      }
      if (formData.type !== 'CREDIT' && !formData.title.trim()) {
        showToast('Ingrese el título o concepto del movimiento.');
        return;
      }
      setStep(2);
    } else if (step === 2) {
      if (formData.type === 'CREDIT' && isMultiService) {
        if (!items || items.length === 0) {
          showToast('Agregue al menos un servicio al paquete.');
          return;
        }
        const hasEmptyTitle = items.some(it => !it.title || !it.title.trim());
        if (hasEmptyTitle) {
          showToast('Complete el título de todos los servicios del paquete.');
          return;
        }
        const sum = calculateItemsSum(items);
        if (sum <= 0) {
          showToast('El monto total del paquete debe ser mayor a 0.');
          return;
        }
      } else {
        const amt = window.unmaskCurrencyPYG(formData.amount);
        if (!amt || amt <= 0) {
          showToast('Ingrese un monto válido mayor a 0.');
          return;
        }
        if (!formData.title || !formData.title.trim()) {
          showToast('Ingrese el título o actividad del movimiento.');
          return;
        }
      }
      setStep(3);
    } else if (step === 3) {
      setStep(4);
    }
  };

  const goToStep = (targetStep) => {
    if (targetStep === step) return;
    if (targetStep < step || editingTx) {
      setStep(targetStep);
      return;
    }
    if (step === 1 && targetStep > 1) {
      if (!formData.date) {
        showToast('Ingrese la fecha del movimiento.');
        return;
      }
      if (formData.type !== 'CREDIT' && !formData.title.trim()) {
        showToast('Ingrese el título del movimiento.');
        return;
      }
    }
    if ((step === 1 || step === 2) && targetStep > 2) {
      const amt = (formData.type === 'CREDIT' && isMultiService)
        ? calculateItemsSum(items)
        : window.unmaskCurrencyPYG(formData.amount);
      if (!amt || amt <= 0) {
        showToast('Defina los valores en el Paso 2.');
        return;
      }
      if (!formData.title.trim() && !(formData.type === 'CREDIT' && isMultiService && items[0]?.title)) {
        showToast('Complete el título del movimiento.');
        return;
      }
    }
    setStep(targetStep);
  };

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    try {
      let finalDescription = formData.description || '';
      if (!isMultiService && serviceMode === 'custom') {
        const extraDetails = [];
        if (formData.custom_category && formData.custom_category !== 'Avulso') {
          extraDetails.push(`Categoría: ${formData.custom_category}`);
        }
        if (formData.custom_unit && formData.custom_unit !== 'serviço') {
          extraDetails.push(`Alcance: ${formData.custom_unit}`);
        }
        if (formData.custom_requester) {
          extraDetails.push(`Solicitante: ${formData.custom_requester}`);
        }
        if (extraDetails.length > 0) {
          finalDescription = finalDescription 
            ? `${finalDescription} [${extraDetails.join(' | ')}]` 
            : `[${extraDetails.join(' | ')}]`;
        }
      }

      const finalItems = (formData.type === 'CREDIT' && isMultiService)
        ? items.filter(it => it.title && it.title.trim()).map(it => ({
            service_id: it.service_id ? parseInt(it.service_id) : null,
            title: it.title.trim(),
            quantity: parseFloat(it.quantity) || 1,
            unit_price: window.unmaskCurrencyPYG(it.unit_price) || 0,
            total_price: (parseFloat(it.quantity) || 1) * (window.unmaskCurrencyPYG(it.unit_price) || 0),
            deliverable_url: it.deliverable_url || ''
          }))
        : [];

      const calculatedTotal = (formData.type === 'CREDIT' && isMultiService && finalItems.length > 0)
        ? finalItems.reduce((acc, it) => acc + it.total_price, 0)
        : window.unmaskCurrencyPYG(formData.amount);

      const mainTitle = formData.title.trim() || 
        (finalItems.length > 0 ? `Paquete: ${finalItems[0].title}` : 'Movimiento de Servicios');

      const payload = {
        type: formData.type,
        service_id: (!isMultiService && serviceMode === 'catalog') ? (formData.service_id || null) : null,
        title: mainTitle,
        amount: calculatedTotal,
        date: formData.date,
        document_ref: formData.document_ref,
        description: finalDescription,
        deliverable_url: formData.deliverable_url || '',
        delivery_scope: formData.delivery_scope || '',
        tags: selectedTags,
        items: finalItems
      };

      if (editingTx) {
        await window.Api.updateTransaction(editingTx.id, payload);
        showToast('¡Movimiento actualizado!');
      } else {
        await window.Api.createTransaction(payload);
        showToast('¡Movimiento registrado con éxito!');
      }
      setModalTxOpen(false);
      setEditingTx(null);
      triggerRefresh();
    } catch (err) {
      showToast('Error al guardar movimiento.');
    }
  };

  // Configuración de tipos con títulos y descripciones personalizadas
  const creditTitle = settings?.movement_credit_title || 'Servicio Prestado';
  const creditDesc = settings?.movement_credit_desc !== undefined ? settings.movement_credit_desc : 'Crédito a mi favor / Cobro a la universidad';
  const debitTitle = settings?.movement_debit_title || 'Cuota Universitaria';
  const debitDesc = settings?.movement_debit_desc !== undefined ? settings.movement_debit_desc : 'Débito / Descuento de cuotas en cuenta';
  const payRecTitle = settings?.movement_payment_received_title || 'Pago Recibido';
  const payRecDesc = settings?.movement_payment_received_desc !== undefined ? settings.movement_payment_received_desc : 'Efectivo / Transferencia de Tesorería';
  const payMadeTitle = settings?.movement_payment_made_title || 'Pago Efectuado';
  const payMadeDesc = settings?.movement_payment_made_desc !== undefined ? settings.movement_payment_made_desc : 'Pago realizado a la universidad';

  const movementTypes = [
    {
      type: 'CREDIT',
      title: creditTitle,
      badge: 'Crédito (+)',
      desc: creditDesc,
      icon: '🎬',
      colorClass: 'border-emerald-600 bg-emerald-50/40 text-emerald-950',
      tagColor: 'bg-emerald-600 text-white'
    },
    {
      type: 'DEBIT',
      title: debitTitle,
      badge: 'Débito (-)',
      desc: debitDesc,
      icon: '🎓',
      colorClass: 'border-rose-600 bg-rose-50/40 text-rose-950',
      tagColor: 'bg-rose-600 text-white'
    },
    {
      type: 'PAYMENT_RECEIVED',
      title: payRecTitle,
      badge: 'Cobro en Mano',
      desc: payRecDesc,
      icon: '💵',
      colorClass: 'border-blue-600 bg-blue-50/40 text-blue-950',
      tagColor: 'bg-blue-600 text-white'
    },
    {
      type: 'PAYMENT_MADE',
      title: payMadeTitle,
      badge: 'Pago Hecho',
      desc: payMadeDesc,
      icon: '📤',
      colorClass: 'border-amber-600 bg-amber-50/40 text-amber-950',
      tagColor: 'bg-amber-600 text-white'
    }
  ];

  const currentTypeConfig = movementTypes.find(t => t.type === formData.type) || movementTypes[0];

  const stepsList = [
    { num: 1, label: 'Tipo & Actividad', icon: '🏷️' },
    { num: 2, label: 'Valor & Servicios', icon: '💰' },
    { num: 3, label: 'Entregables & Control', icon: '🔗' },
    { num: 4, label: 'Resumen & Confirmar', icon: '📋' }
  ];

  return (
    <div className="modal-backdrop open">
      <div className="modal" style={{ maxWidth: '680px' }}>
        {/* ENCABEZADO DEL MODAL */}
        <div className="modal-header pb-2 border-b border-zinc-200">
          <div>
            <div className="flex items-center gap-2">
              <span className="text-base font-bold text-zinc-950">
                {editingTx ? 'Editar Movimiento' : 'Nuevo Movimiento'}
              </span>
              <span className="px-2 py-0.5 rounded-full text-[10px] font-mono font-bold bg-zinc-100 text-zinc-700 border border-zinc-200">
                Paso {step} de 4
              </span>
            </div>
            <div className="text-xs text-zinc-500 mt-0.5">
              {step === 1 && 'Paso 1: Seleccione el tipo de movimiento y nombre de la actividad'}
              {step === 2 && 'Paso 2: Especifique el valor, formato de ejecución y etiquetas'}
              {step === 3 && 'Paso 3: Enlace de entregables y control técnico de auditoría'}
              {step === 4 && 'Paso 4: Revise el resumen ejecutivo antes de asentar en el libro contable'}
            </div>
          </div>
          <button 
            type="button" 
            className="modal-close" 
            onClick={() => { setModalTxOpen(false); setEditingTx(null); }}
          >
            ✕
          </button>
        </div>

        {/* BARRA DE NAVEGACIÓN DE PASOS (WIZARD PROGRESS) */}
        <div className="bg-zinc-50/80 border-b border-zinc-200 px-4 py-2.5">
          <div className="grid grid-cols-4 gap-1.5">
            {stepsList.map((s) => {
              const isCurrent = step === s.num;
              const isPast = step > s.num;
              return (
                <button
                  key={s.num}
                  type="button"
                  onClick={() => goToStep(s.num)}
                  className={`flex items-center gap-1.5 px-2 py-1.5 rounded-lg text-xs font-semibold transition-all text-left cursor-pointer border ${
                    isCurrent
                      ? 'bg-zinc-950 text-white border-zinc-950 shadow-xs'
                      : isPast
                      ? 'bg-emerald-50 text-emerald-800 border-emerald-200 hover:bg-emerald-100/70'
                      : 'bg-white text-zinc-500 border-zinc-200 hover:bg-zinc-100 hover:text-zinc-700'
                  }`}
                >
                  <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 ${
                    isCurrent 
                      ? 'bg-white text-zinc-950' 
                      : isPast 
                      ? 'bg-emerald-600 text-white' 
                      : 'bg-zinc-200 text-zinc-600'
                  }`}>
                    {isPast ? '✓' : s.num}
                  </span>
                  <span className="truncate hidden sm:inline">{s.label}</span>
                  <span className="truncate sm:hidden">{s.icon} P{s.num}</span>
                </button>
              );
            })}
          </div>
        </div>

        <form onSubmit={step === 4 ? handleSubmit : (e) => { e.preventDefault(); handleNextStep(); }}>
          <div className="modal-body space-y-4" style={{ maxHeight: '72vh', overflowY: 'auto' }}>
            
            {/* =========================================================================
                PASO 1: TIPO DE MOVIMIENTO & DATOS BÁSICOS (NOME E TIPO)
                ========================================================================= */}
            {step === 1 && (
              <div className="space-y-4 animate-fade-in">
                {/* SELECTOR VISUAL DE TIPO DE MOVIMIENTO */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="form-label font-bold text-xs text-zinc-900 m-0">
                      1. ¿Qué tipo de movimiento vas a registrar? *
                    </label>
                    <span className="text-[10px] text-zinc-400 font-mono">Seleccione una opción</span>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                    {movementTypes.map((t) => {
                      const isSelected = formData.type === t.type;
                      return (
                        <div
                          key={t.type}
                          onClick={() => {
                            setFormData(prev => {
                              const isAutoRef = !prev.document_ref || /^(SRV|CUOTA|REC|PAG)-\d{6}-\d{3}$/.test(prev.document_ref);
                              return {
                                ...prev,
                                type: t.type,
                                document_ref: (!editingTx && isAutoRef) ? generateAutoRef(t.type, prev.date) : prev.document_ref
                              };
                            });
                          }}
                          className={`p-3 rounded-xl border-2 transition-all cursor-pointer flex flex-col justify-between ${
                            isSelected
                              ? `${t.colorClass} shadow-xs ring-1 ring-zinc-950/10`
                              : 'border-zinc-200 bg-white hover:border-zinc-300 hover:bg-zinc-50/50'
                          }`}
                        >
                          <div className="flex items-start justify-between gap-2 mb-1.5">
                            <div className="flex items-center gap-2">
                              <span className="text-xl shrink-0">{t.icon}</span>
                              <div>
                                <div className="font-bold text-xs text-zinc-950">{t.title}</div>
                                <span className={`inline-block px-1.5 py-0.2 rounded text-[9px] font-mono font-bold ${
                                  isSelected ? t.tagColor : 'bg-zinc-100 text-zinc-600'
                                }`}>
                                  {t.badge}
                                </span>
                              </div>
                            </div>
                            <div className={`w-4 h-4 rounded-full border flex items-center justify-center shrink-0 ${
                              isSelected ? 'border-zinc-950 bg-zinc-950 text-white' : 'border-zinc-300 bg-white'
                            }`}>
                              {isSelected && <span className="text-[10px] font-bold">✓</span>}
                            </div>
                          </div>
                          <p className="text-[11px] text-zinc-500 leading-tight m-0">
                            {t.desc}
                          </p>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* SI ES SERVICIO PRESTADO: CATÁLOGO VISUAL DE SERVICIOS DIRECTO EN EL PASO 1 */}
                {formData.type === 'CREDIT' && (
                  <div className="p-3 bg-zinc-50/90 rounded-xl border border-zinc-200 space-y-2.5">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <span className="text-sm">✨</span>
                        <label className="form-label font-bold text-xs text-zinc-900 m-0">
                          Selecciona el Servicio del Catálogo
                        </label>
                      </div>
                      <span className="text-[10px] text-zinc-500 font-mono">
                        {services.length} servicios disponibles
                      </span>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-56 overflow-y-auto pr-1">
                      {services.map((srv) => {
                        const isSelected = String(formData.service_id) === String(srv.id);
                        return (
                          <div
                            key={srv.id}
                            onClick={() => {
                              if (isSelected) {
                                setFormData(prev => ({
                                  ...prev,
                                  service_id: '',
                                  title: '',
                                  amount: ''
                                }));
                                setSelectedServiceName('');
                              } else {
                                setFormData(prev => ({
                                  ...prev,
                                  service_id: srv.id,
                                  title: srv.name,
                                  amount: srv.default_amount > 0 ? window.maskCurrencyPYG(srv.default_amount) : prev.amount,
                                  delivery_scope: srv.delivery_scope || prev.delivery_scope,
                                  deliverable_url: srv.deliverable_url || prev.deliverable_url
                                }));
                                setSelectedServiceName(srv.name);
                              }
                            }}
                            className={`p-2.5 rounded-lg border transition-all cursor-pointer flex items-center justify-between gap-2 ${
                              isSelected
                                ? 'border-emerald-600 bg-emerald-50/70 text-emerald-950 font-semibold shadow-xs ring-1 ring-emerald-600'
                                : 'border-zinc-200 bg-white hover:border-zinc-300 hover:bg-zinc-50 text-zinc-800'
                            }`}
                          >
                            <div className="flex items-center gap-2 overflow-hidden">
                              <span className="text-base shrink-0">{getServiceIcon(srv.category, srv.name)}</span>
                              <div className="truncate">
                                <div className="text-xs font-bold truncate leading-tight">{srv.name}</div>
                                <div className="text-[10px] text-zinc-500 truncate">
                                  {srv.category} • {srv.unit}
                                </div>
                              </div>
                            </div>
                            <div className="text-right shrink-0">
                              <div className="font-mono font-bold text-xs text-emerald-700">
                                {window.formatCurrencyPYG(srv.default_amount)}
                              </div>
                              {isSelected && (
                                <span className="text-[10px] text-emerald-700 font-bold">✓ Elegido</span>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* FECHA DE REALIZACIÓN / ENTREGA */}
                <div className="form-group">
                  <label className="form-label font-bold text-xs text-zinc-800">
                    2. Fecha de Realización / Entrega *
                  </label>
                  <input 
                    type="date" 
                    className="input-control w-full font-medium" 
                    value={formData.date}
                    onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                    required
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    Fecha en que el servicio, cuota o pago fue formalizado.
                  </div>
                </div>

                {/* TÍTULO / ACTIVIDAD PRINCIPAL */}
                <div className="form-group">
                  <label className="form-label font-bold text-xs text-zinc-800 flex items-center justify-between">
                    <span>3. Título o Concepto de la Actividad {formData.type === 'CREDIT' ? '(Opcional aquí)' : '*'}</span>
                    {formData.type === 'CREDIT' && (
                      <span className="text-[10px] text-emerald-600 font-semibold font-mono">
                        Se puede autocompletar en el Paso 2
                      </span>
                    )}
                  </label>
                  <input 
                    type="text" 
                    className="input-control w-full" 
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    placeholder={
                      formData.type === 'CREDIT' 
                        ? 'Ej: Grabación de Videos Institucionales, Cobertura de Evento...'
                        : formData.type === 'DEBIT'
                        ? 'Ej: Cuota 04 - Semestre 2026/1'
                        : 'Ej: Cobro en Efectivo Caja Tesorería Central'
                    }
                    required={formData.type !== 'CREDIT'}
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    {formData.type === 'CREDIT'
                      ? '💡 Si vas a seleccionar un servicio del catálogo en el siguiente paso, se completará automáticamente si lo dejas en blanco.'
                      : 'Concepto identificador del movimiento contable.'}
                  </div>
                </div>
              </div>
            )}

            {/* =========================================================================
                PASO 2: VALOR & FORMATO DE EJECUCIÓN (SERVICIOS, PRECIO, TAGS)
                ========================================================================= */}
            {step === 2 && (
              <div className="space-y-4 animate-fade-in">
                {/* CUANDO ES SERVICIO PRESTADO (CRÉDITO): FORMATO DE EJECUCIÓN */}
                {formData.type === 'CREDIT' && (
                  <div className="p-3 bg-zinc-50/90 rounded-xl border border-zinc-200 space-y-3">
                    <div className="flex items-center justify-between">
                      <label className="form-label font-bold text-xs text-zinc-900 m-0">
                        Formato de Ejecución del Servicio
                      </label>
                      <span className="text-[10px] text-zinc-500 font-mono">
                        {isMultiService ? '🎬 Paquete de varios ítems' : '📦 1 servicio del catálogo o suelto'}
                      </span>
                    </div>

                    <div className="segmented-control">
                      <button 
                        type="button" 
                        className={`segmented-btn ${!isMultiService ? 'active' : ''}`}
                        onClick={() => handleToggleMultiService(false)}
                      >
                        <span>📦 Ítem Único (Catálogo o Suelto)</span>
                      </button>
                      <button 
                        type="button" 
                        className={`segmented-btn ${isMultiService ? 'active' : ''}`}
                        onClick={() => handleToggleMultiService(true)}
                      >
                        <span className="flex items-center gap-1.5 justify-center">
                          <span>🎬 Múltiples Servicios / Paquete</span>
                          {items.length > 0 && (
                            <span className="px-1.5 py-0.2 rounded-full bg-zinc-900 text-white text-[10px] font-mono">
                              {items.length}
                            </span>
                          )}
                        </span>
                      </button>
                    </div>

                    {/* MODO ÍTEM ÚNICO: CATÁLOGO O SUELTO */}
                    {!isMultiService && (
                      <div className="space-y-3 pt-1">
                        <div className="segmented-control">
                          <button 
                            type="button" 
                            className={`segmented-btn ${serviceMode === 'catalog' ? 'active' : ''}`}
                            onClick={() => setServiceMode('catalog')}
                          >
                            📦 Del Catálogo (Búsqueda)
                          </button>
                          <button 
                            type="button" 
                            className={`segmented-btn ${serviceMode === 'custom' ? 'active' : ''}`}
                            onClick={() => {
                              setServiceMode('custom');
                              setFormData(prev => ({ ...prev, service_id: '' }));
                            }}
                          >
                            ⚡ Servicio Suelto Especial
                          </button>
                        </div>

                        {serviceMode === 'catalog' && (
                          <ServiceCombobox
                            value={formData.service_id}
                            onChange={(newId, srvObj) => {
                              setFormData(prev => {
                                const updated = { ...prev, service_id: newId };
                                if (srvObj) {
                                  updated.title = srvObj.name;
                                  if (srvObj.default_amount > 0) {
                                    updated.amount = window.maskCurrencyPYG(srvObj.default_amount);
                                  }
                                  if (srvObj.delivery_scope && !prev.delivery_scope) {
                                    updated.delivery_scope = srvObj.delivery_scope;
                                  }
                                  if (srvObj.deliverable_url && !prev.deliverable_url) {
                                    updated.deliverable_url = srvObj.deliverable_url;
                                  }
                                }
                                return updated;
                              });
                              setSelectedServiceName(srvObj ? srvObj.name : '');
                            }}
                            label="Seleccionar Servicio del Catálogo"
                            placeholder="Escriba para buscar servicio o registrar en el momento..."
                            allowNone={false}
                            onAutoFill={(srvObj) => {
                              setFormData(prev => ({
                                ...prev,
                                title: srvObj.name,
                                amount: srvObj.default_amount > 0 ? window.maskCurrencyPYG(srvObj.default_amount) : prev.amount
                              }));
                            }}
                          />
                        )}

                        {serviceMode === 'custom' && (
                          <div className="p-3 rounded-lg border border-zinc-200 bg-white space-y-3 shadow-2xs">
                            <div className="text-xs font-bold text-zinc-900 flex items-center gap-1.5">
                              <span>⚡ Servicio Suelto Especial</span>
                              <span className="text-[10px] font-normal text-zinc-500">(No requiere registro previo en catálogo)</span>
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                              <div>
                                <label className="form-label text-[11px] font-semibold text-zinc-700">Categoría del Servicio</label>
                                <input 
                                  type="text" 
                                  className="input-control w-full text-xs"
                                  value={formData.custom_category}
                                  onChange={(e) => setFormData({ ...formData, custom_category: e.target.value })}
                                  placeholder="Ej: Audiovisual, Evento, TI"
                                />
                              </div>
                              <div>
                                <label className="form-label text-[11px] font-semibold text-zinc-700">Solicitante / Departamento</label>
                                <input 
                                  type="text" 
                                  className="input-control w-full text-xs"
                                  value={formData.custom_requester}
                                  onChange={(e) => setFormData({ ...formData, custom_requester: e.target.value })}
                                  placeholder="Ej: Coordinación de Medicina"
                                />
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    {/* MODO MÚLTIPLES SERVICIOS: LISTA DESGLOSADA */}
                    {isMultiService && (
                      <div className="space-y-3 pt-1">
                        <div className="flex items-center justify-between border-b border-zinc-200/80 pb-2">
                          <div className="flex items-center gap-2">
                            <span className="w-5 h-5 rounded-full bg-zinc-950 text-white flex items-center justify-center text-xs">🎬</span>
                            <div>
                              <div className="font-bold text-xs text-zinc-950">Servicios & Videos del Paquete ({items.length})</div>
                              <div className="text-[10px] text-zinc-500">Desglosados en el movimiento y en la hoja impresa</div>
                            </div>
                          </div>

                          <button
                            type="button"
                            className="text-xs font-bold text-zinc-950 bg-white hover:bg-zinc-100 border border-zinc-300 px-2.5 py-1 rounded shadow-2xs cursor-pointer flex items-center gap-1 transition-colors"
                            onClick={handleAddItem}
                          >
                            <span className="text-emerald-600 font-black">+</span>
                            <span>Agregar Servicio</span>
                          </button>
                        </div>

                        <div className="space-y-3 max-h-60 overflow-y-auto pr-1">
                          {items.map((it, idx) => {
                            const q = parseFloat(it.quantity) || 1;
                            const u = window.unmaskCurrencyPYG(it.unit_price) || 0;
                            const itemSubtotal = q * u;

                            return (
                              <div 
                                key={it.id || idx} 
                                className="p-3 bg-white rounded-lg border border-zinc-200 shadow-2xs space-y-2.5 relative hover:border-zinc-300 transition-colors"
                              >
                                <div className="flex items-center justify-between border-b border-zinc-100 pb-1.5">
                                  <div className="flex items-center gap-2">
                                    <span className="w-5 h-5 rounded-full bg-zinc-950 text-white text-[11px] font-bold font-mono flex items-center justify-center">
                                      {idx + 1}
                                    </span>
                                    <span className="font-bold text-xs text-zinc-800">
                                      Servicio #{idx + 1} {it.title ? `— ${it.title}` : ''}
                                    </span>
                                  </div>
                                  {items.length > 1 && (
                                    <button
                                      type="button"
                                      className="text-zinc-400 hover:text-red-600 text-xs px-2 py-0.5 rounded hover:bg-red-50 cursor-pointer font-medium flex items-center gap-1 transition-colors"
                                      onClick={() => handleRemoveItem(idx)}
                                      title="Eliminar este servicio"
                                    >
                                      <span>🗑️ Eliminar</span>
                                    </button>
                                  )}
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
                                  <div>
                                    <label className="text-[11px] font-semibold text-zinc-600 block mb-1">
                                      Base del Catálogo (Opcional)
                                    </label>
                                    <select
                                      className="select-control w-full text-xs font-medium"
                                      value={it.service_id || ''}
                                      onChange={(e) => handleItemChange(idx, 'service_id', e.target.value)}
                                    >
                                      <option value="">(Personalizado / Escribir Título)</option>
                                      {services.map(s => (
                                        <option key={s.id} value={s.id}>
                                          {s.name} ({window.formatCurrencyPYG(s.default_amount)})
                                        </option>
                                      ))}
                                    </select>
                                  </div>

                                  <div>
                                    <label className="text-[11px] font-semibold text-zinc-600 block mb-1">
                                      Título de la Entrega / Video *
                                    </label>
                                    <input
                                      type="text"
                                      className="input-control w-full text-xs font-medium"
                                      placeholder="Ej: Creativo 01 - Reels Estudiantes, Video 02..."
                                      value={it.title}
                                      onChange={(e) => handleItemChange(idx, 'title', e.target.value)}
                                      required
                                    />
                                  </div>
                                </div>

                                <div className="grid grid-cols-3 gap-2 items-end pt-1">
                                  <div>
                                    <label className="text-[11px] font-semibold text-zinc-600 block mb-1">
                                      Cant.
                                    </label>
                                    <input
                                      type="number"
                                      min="1"
                                      step="1"
                                      className="input-control w-full text-xs font-mono font-semibold"
                                      value={it.quantity}
                                      onChange={(e) => handleItemChange(idx, 'quantity', e.target.value)}
                                      required
                                    />
                                  </div>

                                  <div>
                                    <label className="text-[11px] font-semibold text-zinc-600 block mb-1">
                                      Precio Unitario (G$) *
                                    </label>
                                    <input
                                      type="text"
                                      inputMode="numeric"
                                      className="input-control w-full text-xs font-mono font-bold"
                                      placeholder="Ej: 500.000"
                                      value={it.unit_price}
                                      onChange={(e) => handleItemChange(idx, 'unit_price', window.maskCurrencyPYG(e.target.value))}
                                      required
                                    />
                                  </div>

                                  <div>
                                    <label className="text-[11px] font-semibold text-zinc-600 block mb-1">
                                      Subtotal
                                    </label>
                                    <div className="h-9 px-2.5 rounded-md border border-emerald-200 bg-emerald-50/70 flex items-center justify-end font-mono font-bold text-xs text-emerald-700">
                                      {window.formatCurrencyPYG(itemSubtotal)}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>

                        <div className="pt-2 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 border-t border-zinc-200/80">
                          <button
                            type="button"
                            className="btn btn-secondary text-xs h-8 px-3 rounded-md border border-zinc-300 bg-white hover:bg-zinc-100 text-zinc-900 font-semibold cursor-pointer flex items-center justify-center gap-1.5 shadow-2xs"
                            onClick={handleAddItem}
                          >
                            <span className="text-emerald-600 font-bold">➕</span>
                            <span>Agregar Otro Servicio al Paquete</span>
                          </button>

                          <div className="text-right">
                            <span className="text-[11px] text-zinc-500 mr-2 font-medium">Suma de los {items.length} Servicios:</span>
                            <span className="font-mono font-bold text-sm text-emerald-600">
                              {formData.amount ? `G$ ${formData.amount}` : 'G$ 0'}
                            </span>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* TÍTULO SI AÚN ESTÁ VACÍO (PARA MODO ÚNICO O DEBIT/PAYMENT) */}
                {(!isMultiService || !formData.title) && (
                  <div className="form-group">
                    <label className="form-label font-bold text-xs text-zinc-800">
                      Título Definitivo del Movimiento *
                    </label>
                    <input 
                      type="text" 
                      className="input-control w-full font-semibold" 
                      value={formData.title}
                      onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                      placeholder="Ej: Grabación Institucional Campaña 2026"
                      required
                    />
                  </div>
                )}

                {/* MONTO TOTAL EN GUARANÍES */}
                <div className="form-group">
                  <div className="flex items-center justify-between mb-1">
                    <label className="form-label font-bold text-xs text-zinc-900 m-0">
                      Monto Total del Movimiento (G$) *
                    </label>
                    {formData.type === 'CREDIT' && isMultiService && (
                      <span className="text-[10px] font-mono text-emerald-700 font-bold bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
                        Calculado de la suma de {items.length} {items.length === 1 ? 'servicio' : 'servicios'}
                      </span>
                    )}
                  </div>
                  <input 
                    type="text" 
                    inputMode="numeric"
                    className={`input-control w-full font-bold font-mono text-lg ${formData.type === 'CREDIT' && isMultiService ? 'bg-zinc-50 border-emerald-300 text-emerald-700' : ''}`} 
                    value={formData.amount}
                    onChange={(e) => {
                      if (!(formData.type === 'CREDIT' && isMultiService)) {
                        setFormData({ ...formData, amount: window.maskCurrencyPYG(e.target.value) });
                      }
                    }}
                    readOnly={formData.type === 'CREDIT' && isMultiService}
                    placeholder="Ej: 1.500.000"
                    required
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    {formData.type === 'CREDIT' && isMultiService 
                      ? 'El monto total se calcula sumando todos los servicios del paquete arriba.' 
                      : 'Moneda: Guaraníes (G$). Escriba solo los números; los puntos son automáticos.'}
                  </div>
                </div>

                {/* PROTOCOLO / DOCUMENTO DE REFERENCIA */}
                <div className="form-group">
                  <div className="flex items-center justify-between mb-1">
                    <label className="form-label font-bold text-xs text-zinc-800 m-0">
                      Nº de Protocolo, Recibo o Referencia
                    </label>
                    <button
                      type="button"
                      className="text-[11px] text-zinc-600 hover:text-zinc-950 font-semibold flex items-center gap-1 cursor-pointer bg-zinc-100 hover:bg-zinc-200 px-2 py-0.5 rounded border border-zinc-200 transition-colors shadow-2xs"
                      onClick={() => setFormData(prev => ({ ...prev, document_ref: generateAutoRef(prev.type, prev.date) }))}
                      title="Generar nuevo código automático"
                    >
                      <span>⚡ Generar Automático</span>
                    </button>
                  </div>
                  <input 
                    type="text" 
                    className="input-control w-full text-xs font-mono font-semibold" 
                    value={formData.document_ref}
                    onChange={(e) => setFormData({ ...formData, document_ref: e.target.value })}
                    placeholder="Ej: SRV-202610-101, OS-2026/982 o REC-102"
                  />
                  <div className="form-hint text-[11px] text-zinc-500 mt-1 leading-normal">
                    💡 <strong>¿Quién genera este código?</strong> Si la facultad te dio una Orden de Servicio (O.S.), recibo oficial o comprobante bancario, escríbelo aquí. Si <strong>no</strong> te dieron nada, dejamos este código automático generado por el sistema para tu control contable y hoja de rendición.
                  </div>
                </div>

                {/* ETIQUETAS / TAGS CREATABLE */}
                <div className="form-group">
                  <label className="form-label font-semibold text-xs text-zinc-700 flex items-center justify-between">
                    <span>Etiquetas / Tags del Movimiento</span>
                    <span className="text-[11px] font-normal text-zinc-400">Escriba y presione Enter</span>
                  </label>

                  <div 
                    className="min-h-[42px] p-2 rounded-md border border-zinc-200 bg-white flex flex-wrap items-center gap-1.5 focus-within:ring-1 focus-within:ring-zinc-950 focus-within:border-zinc-950"
                    onClick={() => { if (tagInputRef.current) tagInputRef.current.focus(); }}
                  >
                    {selectedTags.map(tagName => {
                      const tagObj = tags.find(t => t.name.toLowerCase() === tagName.toLowerCase());
                      const tagColor = tagObj?.color || '#18181b';
                      return (
                        <span 
                          key={tagName} 
                          className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-bold text-white shadow-2xs font-mono"
                          style={{ backgroundColor: tagColor }}
                        >
                          <span>#{tagName}</span>
                          <button 
                            type="button" 
                            onClick={(e) => { e.stopPropagation(); handleRemoveTag(tagName); }}
                            className="hover:opacity-75 ml-0.5 font-bold cursor-pointer text-xs leading-none"
                          >
                            ×
                          </button>
                        </span>
                      );
                    })}

                    <input 
                      ref={tagInputRef}
                      type="text" 
                      className="flex-1 min-w-[140px] text-xs outline-none bg-transparent placeholder-zinc-400 text-zinc-950 py-1"
                      placeholder={selectedTags.length === 0 ? "Escriba etiquetas (ej: Urgente, Medicina) y presione Enter..." : "Agregar otra..."}
                      value={tagInput}
                      onChange={(e) => {
                        setTagInput(e.target.value);
                        setTagDropdownOpen(true);
                      }}
                      onFocus={() => setTagDropdownOpen(true)}
                      onKeyDown={handleTagKeyDown}
                    />
                  </div>

                  {tagDropdownOpen && tagInput.trim() && (
                    <div className="mt-1 rounded-md border border-zinc-200 bg-white shadow-md overflow-hidden z-20 relative">
                      {matchingTags.length > 0 && (
                        <div className="p-1 divide-y divide-zinc-100 max-h-36 overflow-y-auto">
                          {matchingTags.map(t => (
                            <div 
                              key={t.id}
                              className="px-3 py-1.5 text-xs text-zinc-800 hover:bg-zinc-100 cursor-pointer flex items-center justify-between"
                              onClick={() => handleAddTag(t.name)}
                            >
                              <div className="flex items-center gap-2">
                                <span 
                                  className="w-2.5 h-2.5 rounded-full shrink-0" 
                                  style={{ backgroundColor: t.color || '#18181b' }} 
                                />
                                <span className="font-semibold">#{t.name}</span>
                              </div>
                              <span className="text-[10px] text-zinc-400 font-mono">{t.usage_count || 0} movimientos</span>
                            </div>
                          ))}
                        </div>
                      )}

                      {!exactMatchExists && (
                        <div 
                          className="px-3 py-2 bg-zinc-900 text-white text-xs font-semibold hover:bg-zinc-800 cursor-pointer flex items-center justify-between"
                          onClick={() => handleAddTag(tagInput.trim())}
                        >
                          <span>+ Crear nueva etiqueta <strong>"#{tagInput.trim()}"</strong></span>
                          <span className="text-[10px] bg-zinc-800 px-1.5 py-0.5 rounded">Enter ↵</span>
                        </div>
                      )}
                    </div>
                  )}

                  {tags.length > 0 && (
                    <div className="flex items-center gap-1.5 flex-wrap mt-2">
                      <span className="text-[11px] text-zinc-400">Sugerencias rápidas:</span>
                      {tags.slice(0, 8).map(t => {
                        const isSelected = selectedTags.includes(t.name);
                        return (
                          <button
                            key={t.id}
                            type="button"
                            onClick={() => isSelected ? handleRemoveTag(t.name) : handleAddTag(t.name)}
                            className="text-[11px] font-mono px-2 py-0.5 rounded-full border transition-all cursor-pointer font-bold shadow-2xs flex items-center gap-1"
                            style={isSelected ? {
                              backgroundColor: t.color || '#18181b',
                              color: '#ffffff',
                              borderColor: t.color || '#18181b'
                            } : {
                              backgroundColor: '#f4f4f5',
                              color: '#18181b',
                              borderColor: '#e4e4e7'
                            }}
                          >
                            <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: t.color || '#18181b' }} />
                            <span>{isSelected ? `✓ #${t.name}` : `+ #${t.name}`}</span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* =========================================================================
                PASO 3: ENTREGABLES & CONTROL TÉCNICO (AUDITORÍA & ENLACES)
                ========================================================================= */}
            {step === 3 && (
              <div className="space-y-4 animate-fade-in">
                <div className="p-3 bg-zinc-50 rounded-xl border border-zinc-200">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-base">🛡️</span>
                    <span className="font-bold text-xs text-zinc-950">Auditoría Técnica y Respaldo de Entrega</span>
                  </div>
                  <p className="text-[11px] text-zinc-500 m-0">
                    Estos datos quedarán impresos en la hoja de rendición y vinculados al código QR para verificación directa por las autoridades universitarias.
                  </p>
                </div>

                {/* ENLACE DE ARCHIVOS / ENTREGABLES */}
                <div className="form-group">
                  <label className="form-label font-bold text-xs text-zinc-800 flex items-center justify-between">
                    <span className="flex items-center gap-1.5">
                      <span>🔗 Enlace de Archivos / Entregables</span>
                      <span className="text-[10px] font-normal text-zinc-400">(Drive, YouTube, Dropbox, etc.)</span>
                    </span>
                    {formData.deliverable_url && (
                      <a 
                        href={formData.deliverable_url} 
                        target="_blank" 
                        rel="noreferrer" 
                        className="text-[11px] text-emerald-700 hover:text-emerald-900 font-bold underline inline-flex items-center gap-1"
                      >
                        <span>Probar enlace</span>
                        <span>↗</span>
                      </a>
                    )}
                  </label>
                  <input 
                    type="url" 
                    className="input-control w-full text-xs font-mono" 
                    value={formData.deliverable_url}
                    onChange={(e) => setFormData({ ...formData, deliverable_url: e.target.value })}
                    placeholder="https://drive.google.com/drive/folders/... o enlace de entrega"
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    Enlace de la nube con los archivos finales. Genera acceso directo en el PDF impreso.
                  </div>
                </div>

                {/* ESPECIFICACIONES TÉCNICAS (CONTROL INTERNO) */}
                <div className="form-group">
                  <label className="form-label font-bold text-xs text-zinc-800">
                    📋 Especificaciones Técnicas & Ítems Entregados (Control Interno)
                  </label>
                  <textarea 
                    className="input-control w-full text-xs" 
                    style={{ height: '75px', resize: 'vertical' }}
                    value={formData.delivery_scope}
                    onChange={(e) => setFormData({ ...formData, delivery_scope: e.target.value })}
                    placeholder="Ej: 4 videos grabados en Full HD 1080p (.mp4), 1 PDF de material, 2 spots en alta resolución, audio masterizado."
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    Cantidad de entregables, formatos de archivo y alcance técnico detallado para el informe.
                  </div>
                </div>

                {/* DETALLE DE LO QUE SE REALIZÓ */}
                <div className="form-group">
                  <label className="form-label font-bold text-xs text-zinc-800">
                    📝 Detalle de lo Realizado (Descripción del Trabajo y Justificación)
                  </label>
                  <textarea 
                    className="input-control w-full text-xs" 
                    style={{ height: '85px', resize: 'vertical', lineHeight: 1.4 }}
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    placeholder="Ej: Grabé y edité los videos institucionales solicitados. Entregué los archivos finales en MP4 por Google Drive a la coordinación de Medicina."
                  />
                  <div className="form-hint text-[11px] text-zinc-400 mt-1">
                    Texto detallado que figurará en la tabla principal y en el comprobante contable.
                  </div>
                </div>
              </div>
            )}

            {/* =========================================================================
                PASO 4: RESUMEN EJECUTIVO & CONFIRMACIÓN (REVISIÓN ANTES DE CREAR)
                ========================================================================= */}
            {step === 4 && (
              <div className="space-y-4 animate-fade-in">
                <div className="p-3 bg-zinc-950 text-white rounded-xl shadow-sm flex items-center justify-between">
                  <div>
                    <div className="text-[10px] font-mono text-zinc-400 uppercase tracking-wider">
                      Resumen Ejecutivo de Confirmación
                    </div>
                    <div className="text-sm font-bold">
                      {formData.title || 'Movimiento sin título'}
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="text-[10px] font-mono text-zinc-400">Total a Asentar</div>
                    <div className="text-lg font-bold font-mono text-emerald-400">
                      G$ {formData.amount || '0'}
                    </div>
                  </div>
                </div>

                {/* TARJETA DETALLADA DE REVISIÓN */}
                <div className="p-4 bg-zinc-50 rounded-xl border border-zinc-200 space-y-3 text-xs">
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 border-b border-zinc-200/80 pb-3">
                    <div>
                      <span className="text-[10px] text-zinc-400 font-mono block">Tipo de Movimiento</span>
                      <span className={`inline-flex items-center gap-1 font-bold ${
                        formData.type === 'CREDIT' ? 'text-emerald-700' :
                        formData.type === 'DEBIT' ? 'text-rose-700' :
                        formData.type === 'PAYMENT_RECEIVED' ? 'text-blue-700' : 'text-amber-700'
                      }`}>
                        <span>{currentTypeConfig.icon}</span>
                        <span>{currentTypeConfig.title}</span>
                      </span>
                    </div>

                    <div>
                      <span className="text-[10px] text-zinc-400 font-mono block">Fecha de Realización</span>
                      <span className="font-semibold text-zinc-900 font-mono">
                        {formData.date}
                      </span>
                    </div>

                    <div>
                      <span className="text-[10px] text-zinc-400 font-mono block">Protocolo / Ref.</span>
                      <span className="font-semibold text-zinc-900 font-mono">
                        {formData.document_ref || '(Sin referencia)'}
                      </span>
                    </div>
                  </div>

                  {/* DESGLOSE SI ES PAQUETE DE MÚLTIPLES SERVICIOS */}
                  {formData.type === 'CREDIT' && isMultiService && items.length > 0 && (
                    <div className="border-b border-zinc-200/80 pb-3 space-y-1.5">
                      <div className="font-bold text-[11px] text-zinc-700 flex items-center justify-between">
                        <span>🎬 Servicios Desglosados en este Paquete ({items.length}):</span>
                        <span className="text-emerald-700 font-mono font-bold">G$ {formData.amount}</span>
                      </div>
                      <div className="space-y-1 max-h-32 overflow-y-auto pr-1">
                        {items.map((it, idx) => (
                          <div key={idx} className="flex items-center justify-between p-1.5 rounded bg-white border border-zinc-200 text-[11px]">
                            <div className="truncate pr-2">
                              <span className="font-mono text-zinc-400 mr-1.5">#{idx + 1}</span>
                              <span className="font-medium text-zinc-900">{it.title}</span>
                              <span className="text-zinc-500 font-mono ml-1.5">({it.quantity} un × G$ {it.unit_price})</span>
                            </div>
                            <div className="font-bold font-mono text-emerald-600 shrink-0">
                              {window.formatCurrencyPYG((parseFloat(it.quantity) || 1) * (window.unmaskCurrencyPYG(it.unit_price) || 0))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* ETIQUETAS */}
                  <div className="border-b border-zinc-200/80 pb-3">
                    <span className="text-[10px] text-zinc-400 font-mono block mb-1">Etiquetas Asignadas</span>
                    {selectedTags.length > 0 ? (
                      <div className="flex flex-wrap gap-1">
                        {selectedTags.map(tagName => {
                          const tagObj = tags.find(t => t.name.toLowerCase() === tagName.toLowerCase());
                          return (
                            <span 
                              key={tagName} 
                              className="px-2 py-0.5 rounded-full text-[11px] font-bold text-white font-mono"
                              style={{ backgroundColor: tagObj?.color || '#18181b' }}
                            >
                              #{tagName}
                            </span>
                          );
                        })}
                      </div>
                    ) : (
                      <span className="text-zinc-400 italic">Sin etiquetas</span>
                    )}
                  </div>

                  {/* ENTREGABLES Y ESPECIFICACIONES */}
                  <div className="space-y-2">
                    <div>
                      <span className="text-[10px] text-zinc-400 font-mono block">Enlace de Entregable</span>
                      {formData.deliverable_url ? (
                        <a 
                          href={formData.deliverable_url} 
                          target="_blank" 
                          rel="noreferrer" 
                          className="text-emerald-700 hover:text-emerald-900 font-mono font-medium underline break-all flex items-center gap-1"
                        >
                          <span>🔗 {formData.deliverable_url}</span>
                          <span>↗</span>
                        </a>
                      ) : (
                        <span className="text-zinc-400 italic">Sin enlace de archivos</span>
                      )}
                    </div>

                    {formData.delivery_scope && (
                      <div>
                        <span className="text-[10px] text-zinc-400 font-mono block">Especificaciones Técnicas (Auditoría)</span>
                        <div className="p-2 rounded bg-white border border-zinc-200 text-zinc-800 font-mono text-[11px] whitespace-pre-wrap">
                          {formData.delivery_scope}
                        </div>
                      </div>
                    )}

                    {formData.description && (
                      <div>
                        <span className="text-[10px] text-zinc-400 font-mono block">Detalle de lo Realizado</span>
                        <div className="p-2 rounded bg-white border border-zinc-200 text-zinc-700 text-[11px] whitespace-pre-wrap">
                          {formData.description}
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                <div className="p-2.5 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center gap-2 text-emerald-800 text-xs">
                  <span className="text-base">✓</span>
                  <span>
                    Todo verificado. Haga clic en <strong>"Registrar Movimiento"</strong> para asentar los datos en el sistema.
                  </span>
                </div>
              </div>
            )}
          </div>

          {/* BOTONES DE NAVEGACIÓN EN EL FOOTER DEL WIZARD */}
          <div className="modal-footer flex items-center justify-between gap-2 border-t border-zinc-200 pt-3 px-4 pb-3">
            <div>
              {step > 1 ? (
                <button 
                  type="button" 
                  className="btn btn-secondary text-xs h-9 px-3.5 rounded-lg border border-zinc-300 bg-white hover:bg-zinc-100 text-zinc-800 font-semibold cursor-pointer flex items-center gap-1.5 shadow-2xs" 
                  onClick={() => setStep(prev => Math.max(1, prev - 1))}
                >
                  <span>◀ Anterior</span>
                </button>
              ) : (
                <button 
                  type="button" 
                  className="btn btn-secondary text-xs h-9 px-3 rounded-lg border border-zinc-200 text-zinc-600 hover:text-zinc-900" 
                  onClick={() => { setModalTxOpen(false); setEditingTx(null); }}
                >
                  Cancelar
                </button>
              )}
            </div>

            <div className="flex items-center gap-2">
              {step < 4 ? (
                <button 
                  type="button" 
                  className="btn btn-primary text-xs h-9 px-4 rounded-lg bg-zinc-950 hover:bg-zinc-800 text-white font-bold cursor-pointer flex items-center gap-1.5 shadow-sm"
                  onClick={handleNextStep}
                >
                  <span>
                    {step === 1 && 'Continuar: Valores y Servicios ➔'}
                    {step === 2 && 'Continuar: Entregables y Auditoría ➔'}
                    {step === 3 && 'Continuar: Revisar y Confirmar ➔'}
                  </span>
                </button>
              ) : (
                <button 
                  type="submit" 
                  className="btn btn-primary text-xs h-9 px-5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-bold cursor-pointer flex items-center gap-1.5 shadow-sm"
                >
                  <span>✓ {editingTx ? 'Actualizar Movimiento' : 'Registrar Movimiento'}</span>
                </button>
              )}
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

function ServiceModal() {
  const { modalServiceOpen, setModalServiceOpen, triggerRefresh, showToast } = window.useFinance();
  const [formData, setFormData] = useState({
    name: '',
    default_amount: '',
    unit: 'unidad',
    category: 'Prestación de Servicios',
    description: ''
  });

  if (!modalServiceOpen) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await window.Api.createService({
        name: formData.name,
        default_amount: window.unmaskCurrencyPYG(formData.default_amount),
        unit: formData.unit,
        category: formData.category,
        description: formData.description
      });
      showToast('¡Servicio registrado con éxito!');
      setModalServiceOpen(false);
      triggerRefresh();
    } catch (err) {
      showToast('Error al registrar servicio.');
    }
  };

  return (
    <div className="modal-backdrop open">
      <div className="modal" style={{ maxWidth: '500px' }}>
        <div className="modal-header">
          <h3 className="modal-title font-bold text-base text-zinc-950">Registrar Nuevo Servicio</h3>
          <button className="modal-close" onClick={() => setModalServiceOpen(false)}>✕</button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal-body space-y-3">
            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Nombre del Servicio</label>
              <input 
                type="text" 
                className="input-control w-full" 
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="Ej: Grabación de Clases, Edición de Video"
                required
              />
            </div>

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Precio Estándar (G$)</label>
              <input 
                type="text" 
                inputMode="numeric"
                className="input-control w-full font-mono font-bold" 
                value={formData.default_amount}
                onChange={(e) => setFormData({ ...formData, default_amount: window.maskCurrencyPYG(e.target.value) })}
                placeholder="Ej: 500.000"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div className="form-group">
                <label className="form-label font-semibold text-xs text-zinc-700">Unidad de Medida</label>
                <input 
                  type="text" 
                  className="input-control w-full" 
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  placeholder="hora, servicio, clase..."
                />
              </div>

              <div className="form-group">
                <label className="form-label font-semibold text-xs text-zinc-700">Categoría</label>
                <input 
                  type="text" 
                  className="input-control w-full" 
                  value={formData.category}
                  onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                  placeholder="Audiovisual, TI..."
                />
              </div>
            </div>

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Descripción / Alcance Estándar</label>
              <textarea 
                className="input-control w-full text-xs" 
                style={{ height: '60px' }}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Descripción de los entregables incluidos..."
              />
            </div>
          </div>
          <div className="modal-footer flex items-center justify-end gap-2 border-t border-zinc-200 pt-3">
            <button type="button" className="btn btn-secondary text-xs h-8 px-3 rounded-md border border-zinc-200" onClick={() => setModalServiceOpen(false)}>Cancelar</button>
            <button type="submit" className="btn btn-primary text-xs h-8 px-4 rounded-md bg-zinc-950 text-white font-medium">Guardar Servicio</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function RecurringModal() {
  const { modalRecurringOpen, setModalRecurringOpen, services, settings, triggerRefresh, showToast } = window.useFinance();
  const [formData, setFormData] = useState({
    title: 'Cuota Universitaria',
    type: 'DEBIT',
    amount: '',
    day_of_month: 10,
    service_id: '',
    duration_type: 'continuous', // 'continuous' | 'months' | 'until_date'
    total_installments: 12,
    end_date: '',
    start_date: new Date().toISOString().substring(0, 7),
    notes: 'Descuento automático de cuotas universitarias'
  });

  useEffect(() => {
    if (modalRecurringOpen) {
      setFormData({
        title: 'Cuota Universitaria',
        type: 'DEBIT',
        amount: '',
        day_of_month: 10,
        service_id: '',
        duration_type: 'continuous',
        total_installments: 12,
        end_date: '',
        start_date: new Date().toISOString().substring(0, 7),
        notes: 'Descuento automático de cuotas universitarias'
      });
    }
  }, [modalRecurringOpen]);

  if (!modalRecurringOpen) return null;

  const debitTitle = settings?.movement_debit_title || 'Cuota Universitaria';
  const debitDesc = settings?.movement_debit_desc !== undefined ? settings.movement_debit_desc : 'Débito mensual descontado de mis servicios';
  const creditTitle = settings?.movement_credit_title || 'Contrato Fijo Mensual';
  const creditDesc = settings?.movement_credit_desc !== undefined ? settings.movement_credit_desc : 'Crédito percibido mensualmente';

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await window.Api.createRecurringRule({
        title: formData.title,
        type: formData.type,
        amount: window.unmaskCurrencyPYG(formData.amount),
        day_of_month: formData.day_of_month,
        service_id: formData.service_id || null,
        duration_type: formData.duration_type,
        total_installments: formData.duration_type === 'months' ? parseInt(formData.total_installments, 10) : 0,
        end_date: formData.duration_type === 'until_date' ? formData.end_date : null,
        start_date: formData.start_date,
        notes: formData.notes
      });
      showToast('¡Regla recurrente guardada con éxito!');
      setModalRecurringOpen(false);
      triggerRefresh();
    } catch (err) {
      showToast('Error al guardar la regla recurrente.');
    }
  };

  return (
    <div className="modal-backdrop open">
      <div className="modal" style={{ maxWidth: '560px' }}>
        <div className="modal-header">
          <h3 className="modal-title font-bold text-base text-zinc-950">Nueva Regla Recurrente Automática</h3>
          <button className="modal-close" onClick={() => setModalRecurringOpen(false)}>✕</button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal-body space-y-3.5">
            {/* BANNER EXPLICATIVO */}
            <div className="p-3 bg-zinc-50 border border-zinc-200 rounded-lg text-xs text-zinc-700 leading-relaxed">
              <strong className="text-zinc-950 block mb-0.5">⚡ ¿Cómo funciona la automatización mensual?</strong>
              Registra tu cuota o contrato una sola vez. Al iniciar cada nuevo mes, el sistema genera el movimiento en el extracto automáticamente, sin necesidad de cargar todo nuevamente.
            </div>

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Tipo de Movimiento Recurrente</label>
              <select 
                className="select-control w-full font-medium"
                value={formData.type}
                onChange={(e) => setFormData({ ...formData, type: e.target.value })}
              >
                <option value="DEBIT">{debitTitle} {debitDesc ? `(${debitDesc})` : ''}</option>
                <option value="CREDIT">{creditTitle} {creditDesc ? `(${creditDesc})` : ''}</option>
              </select>
            </div>

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Título del Cobro / Descuento</label>
              <input 
                type="text" 
                className="input-control w-full" 
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="Ej: Cuota Universitaria o Contrato de Soporte Mensual"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div className="form-group">
                <label className="form-label font-semibold text-xs text-zinc-700">Importe Mensual (G$)</label>
                <input 
                  type="text" 
                  inputMode="numeric"
                  className="input-control w-full font-mono font-bold" 
                  value={formData.amount}
                  onChange={(e) => setFormData({ ...formData, amount: window.maskCurrencyPYG(e.target.value) })}
                  placeholder="Ej: 1.250.000"
                  required
                />
              </div>

              <div className="form-group">
                <label className="form-label font-semibold text-xs text-zinc-700">Día de Vencimiento Mensual</label>
                <input 
                  type="number" 
                  min="1" 
                  max="31" 
                  className="input-control w-full" 
                  value={formData.day_of_month}
                  onChange={(e) => setFormData({ ...formData, day_of_month: e.target.value })}
                  required
                />
              </div>
            </div>

            {/* DURAÇÃO E LIMITE DE REPETIÇÃO */}
            <div className="p-3 bg-zinc-50 border border-zinc-200 rounded-lg space-y-3">
              <div className="form-group">
                <label className="form-label font-semibold text-xs text-zinc-700">Período de Validez</label>
                <select 
                  className="select-control w-full font-medium"
                  value={formData.duration_type}
                  onChange={(e) => setFormData({ ...formData, duration_type: e.target.value })}
                >
                  <option value="continuous">Continuo (Repetir todos los meses indefinidamente)</option>
                  <option value="months">Fijo por número de meses (Ej: 6 meses, 12 meses)</option>
                  <option value="until_date">Fijo hasta un mes/año límite (Ej: hasta Diciembre/2026)</option>
                </select>
              </div>

              {/* SE FOR POR NÚMERO DE MESES */}
              {formData.duration_type === 'months' && (
                <div className="grid grid-cols-2 gap-3 pt-1">
                  <div>
                    <label className="form-label text-[11px] font-semibold text-zinc-700">Cantidad de Meses / Cuotas</label>
                    <input 
                      type="number"
                      min="1"
                      max="120"
                      className="input-control w-full font-semibold"
                      value={formData.total_installments}
                      onChange={(e) => setFormData({ ...formData, total_installments: e.target.value })}
                      placeholder="Ej: 12"
                      required
                    />
                  </div>
                  <div>
                    <label className="form-label text-[11px] font-semibold text-zinc-700">Mes de la 1ª Cuota</label>
                    <input 
                      type="month"
                      className="input-control w-full"
                      value={formData.start_date}
                      onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                    />
                  </div>
                </div>
              )}

              {/* SE FOR ATÉ UMA DATA LIMITE */}
              {formData.duration_type === 'until_date' && (
                <div className="grid grid-cols-2 gap-3 pt-1">
                  <div>
                    <label className="form-label text-[11px] font-semibold text-zinc-700">Mes de Inicio</label>
                    <input 
                      type="month"
                      className="input-control w-full"
                      value={formData.start_date}
                      onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                    />
                  </div>
                  <div>
                    <label className="form-label text-[11px] font-semibold text-zinc-700">Válido Hasta el Mes de</label>
                    <input 
                      type="month"
                      className="input-control w-full font-semibold"
                      value={formData.end_date}
                      onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
                      required
                    />
                  </div>
                </div>
              )}
            </div>

            {/* VINCULAR A SERVIÇO COM BUSCA E CADASTRO RÁPIDO */}
            <ServiceCombobox
              value={formData.service_id}
              onChange={(newId, srvObj) => {
                setFormData(prev => {
                  const updated = { ...prev, service_id: newId };
                  if (srvObj) {
                    if (!prev.title || prev.title === 'Cuota Universitaria' || prev.title === 'Mensalidade Curso Superior' || prev.title === 'Mensalidade Graduação') {
                      updated.title = srvObj.name;
                    }
                    if (!prev.amount && srvObj.default_amount > 0) {
                      updated.amount = window.maskCurrencyPYG(srvObj.default_amount);
                    }
                  }
                  return updated;
                });
              }}
              label="Vincular a Servicio (Opcional)"
              placeholder="Buscar servicio en el catálogo o registrar nuevo..."
              allowNone={true}
              noneLabel="Ninguno (Movimiento independiente / cuota académica)"
              onAutoFill={(srvObj) => {
                setFormData(prev => ({
                  ...prev,
                  title: (!prev.title || prev.title === 'Cuota Universitaria' || prev.title === 'Mensalidade Curso Superior' || prev.title === 'Mensalidade Graduação') ? srvObj.name : prev.title,
                  amount: prev.amount || (srvObj.default_amount > 0 ? window.maskCurrencyPYG(srvObj.default_amount) : '')
                }));
              }}
            />

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Observaciones / Detalles</label>
              <textarea 
                className="input-control w-full text-xs" 
                style={{ height: '45px' }}
                value={formData.notes}
                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                placeholder="Ej: Descuento automático directo sobre la planilla de servicios"
              />
            </div>
          </div>
          <div className="modal-footer flex items-center justify-end gap-2 border-t border-zinc-200 pt-3">
            <button type="button" className="btn btn-secondary text-xs h-8 px-3 rounded-md border border-zinc-200" onClick={() => setModalRecurringOpen(false)}>Cancelar</button>
            <button type="submit" className="btn btn-primary text-xs h-8 px-4 rounded-md bg-zinc-950 text-white font-medium">Guardar Regla</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// --- MODAL DE GERENCIAMENTO DE TAG INDIVIDUAL ---
function TagModal() {
  const { modalTagOpen, setModalTagOpen, editingTag, setEditingTag, triggerRefresh, showToast } = window.useFinance();
  const [name, setName] = useState('');
  const [color, setColor] = useState('#18181b');

  const colorPresets = [
    { label: 'Rojo Carmesí', val: '#dc2626' },
    { label: 'Coral / Rojo Vivo', val: '#ef4444' },
    { label: 'Amarillo Dorado', val: '#eab308' },
    { label: 'Ámbar / Mostaza', val: '#d97706' },
    { label: 'Verde Esmeralda', val: '#059669' },
    { label: 'Verde Menta / Suave', val: '#10b981' },
    { label: 'Verde Bosque', val: '#16a34a' },
    { label: 'Azul Real', val: '#2563eb' },
    { label: 'Azul Cielo', val: '#0284c7' },
    { label: 'Teal / Cian', val: '#0d9488' },
    { label: 'Púrpura Violeta', val: '#7c3aed' },
    { label: 'Rosa Pink', val: '#db2777' },
    { label: 'Naranja Cálido', val: '#ea580c' },
    { label: 'Negro Grafito', val: '#18181b' },
    { label: 'Gris Neutro', val: '#52525b' }
  ];

  useEffect(() => {
    if (editingTag) {
      setName(editingTag.name || '');
      setColor(editingTag.color || '#18181b');
    } else {
      setName('');
      setColor('#18181b');
    }
  }, [editingTag, modalTagOpen]);

  if (!modalTagOpen) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    const cleanName = name.trim();
    if (!cleanName) return;

    try {
      if (editingTag) {
        await window.Api.updateTag(editingTag.id, { name: cleanName, color });
        showToast('¡Etiqueta actualizada!');
      } else {
        await window.Api.createTag({ name: cleanName, color });
        showToast(`¡Etiqueta "${cleanName}" registrada!`);
      }
      setModalTagOpen(false);
      setEditingTag(null);
      triggerRefresh();
    } catch (err) {
      showToast('Error al guardar la etiqueta.');
    }
  };

  return (
    <div className="modal-backdrop open">
      <div className="modal" style={{ maxWidth: '420px' }}>
        <div className="modal-header">
          <h3 className="modal-title font-bold text-base text-zinc-950">
            {editingTag ? 'Editar Etiqueta' : 'Registrar Nueva Etiqueta'}
          </h3>
          <button className="modal-close" onClick={() => { setModalTagOpen(false); setEditingTag(null); }}>✕</button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal-body space-y-4">
            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Nombre de la Etiqueta</label>
              <input 
                type="text" 
                className="input-control w-full" 
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Ej: Grabación, Edición, Urgente..."
                required
              />
            </div>

            <div className="form-group">
              <label className="form-label font-semibold text-xs text-zinc-700">Color de la Etiqueta</label>
              <div className="flex items-center gap-2 mb-2">
                <input 
                  type="color" 
                  className="w-10 h-8 rounded border border-zinc-200 cursor-pointer p-0.5 bg-white" 
                  value={color}
                  onChange={(e) => setColor(e.target.value)}
                />
                <span className="text-xs font-mono text-zinc-600 bg-zinc-100 px-2 py-1 rounded border border-zinc-200">
                  {color}
                </span>
              </div>
              <div className="flex items-center gap-1.5 flex-wrap">
                {colorPresets.map(preset => (
                  <button
                    key={preset.val}
                    type="button"
                    title={preset.label}
                    onClick={() => setColor(preset.val)}
                    className="w-6 h-6 rounded-full border border-white shadow-xs cursor-pointer hover:scale-110 transition-transform"
                    style={{ backgroundColor: preset.val }}
                  />
                ))}
              </div>
            </div>

            {/* PREVIEW */}
            <div className="p-3 bg-zinc-50 rounded-lg border border-zinc-200 text-center">
              <span className="text-[11px] text-zinc-400 block mb-1">Vista previa:</span>
              <span 
                className="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-semibold text-white shadow-xs"
                style={{ backgroundColor: color }}
              >
                #{name.trim() || 'Ejemplo'}
              </span>
            </div>
          </div>

          <div className="modal-footer flex items-center justify-end gap-2 border-t border-zinc-200 pt-3">
            <button 
              type="button" 
              className="btn btn-secondary text-xs h-8 px-3 rounded-md border border-zinc-200" 
              onClick={() => { setModalTagOpen(false); setEditingTag(null); }}
            >
              Cancelar
            </button>
            <button 
              type="submit" 
              className="btn btn-primary text-xs h-8 px-4 rounded-md bg-zinc-950 text-white font-medium"
            >
              Guardar Etiqueta
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// --- SHADCN/UI STYLE CONFIRMATION & SPECIALIZED DELETE MODAL ---
function ConfirmModal() {
  const { confirmState, handleConfirmAction, handleCancelAction } = window.useFinance();
  const { Button, Lucide } = window.Shadcn || {};

  if (!confirmState || !confirmState.isOpen) return null;

  const isDestructive = confirmState.variant === 'destructive';
  const item = confirmState.itemDetails;

  return (
    <div className="modal-backdrop open flex items-center justify-center p-4 z-50">
      <div 
        className={`modal w-full bg-white rounded-xl shadow-2xl overflow-hidden transition-all duration-200 border ${
          isDestructive ? 'border-red-200' : 'border-zinc-200'
        }`}
        style={{ maxWidth: isDestructive ? '500px' : '420px' }}
      >
        {/* TOPO / HEADER */}
        {isDestructive ? (
          <div className="bg-red-500/10 border-b border-red-100 p-5 pb-4">
            <div className="flex items-center gap-2 mb-2">
              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-red-100 text-red-800 text-[11px] font-bold uppercase tracking-wider border border-red-200">
                {Lucide?.AlertTriangle ? <Lucide.AlertTriangle size={12} className="text-red-700" /> : <span>⚠️</span>}
                <span>Confirmación de Eliminación</span>
              </span>
            </div>
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-full bg-red-600 text-white flex items-center justify-center shrink-0 shadow-sm">
                {Lucide?.Trash ? <Lucide.Trash size={18} /> : <span>🗑️</span>}
              </div>
              <div>
                <h3 className="font-bold text-base sm:text-lg text-zinc-950 leading-tight">
                  {confirmState.title || '¿Realmente deseas eliminar este registro?'}
                </h3>
                <p className="text-xs text-zinc-600 mt-1 leading-relaxed">
                  {confirmState.description || 'Esta acción no se puede deshacer.'}
                </p>
              </div>
            </div>
          </div>
        ) : (
          <div className="p-5 pb-2">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-full bg-zinc-100 text-zinc-900 border border-zinc-200 flex items-center justify-center shrink-0">
                {Lucide?.Sparkles ? <Lucide.Sparkles size={18} /> : <span>✨</span>}
              </div>
              <div>
                <h3 className="font-bold text-base text-zinc-950 leading-tight">
                  {confirmState.title || 'Confirmar Operación'}
                </h3>
                <p className="text-xs text-zinc-600 mt-1.5 leading-relaxed">
                  {confirmState.description || '¿Deseas continuar con esta acción?'}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* CORPO DO MODAL */}
        <div className="p-5 space-y-4">
          {isDestructive && (
            <>
              {/* CARD DETALHADO DO QUE ESTÁ SENDO DELETADO */}
              {item && (
                <div className="rounded-lg border border-red-200/90 bg-red-50/40 p-4 space-y-2.5">
                  <div className="flex items-center justify-between gap-2 border-b border-red-100 pb-2">
                    <span className="text-[10px] font-mono font-bold uppercase tracking-wider text-red-800 bg-red-100/80 px-2 py-0.5 rounded">
                      Estás eliminando: {item.itemType || 'Registro'}
                    </span>
                    {item.typeLabel && (
                      <span className="text-[11px] font-bold text-zinc-700 font-mono">
                        {item.typeLabel}
                      </span>
                    )}
                  </div>

                  {/* TÍTULO / NOME DO ITEM */}
                  <div className="text-sm sm:text-base font-bold text-zinc-950 leading-snug flex items-center gap-2">
                    {item.color && (
                      <span className="w-3 h-3 rounded-full shrink-0 border border-black/10" style={{ backgroundColor: item.color }} />
                    )}
                    <span>{item.title}</span>
                  </div>

                  {/* VALOR SE HOUVER */}
                  {item.amount !== undefined && item.amount !== null && (
                    <div className="flex items-baseline gap-2 pt-0.5">
                      <span className="text-xs text-zinc-500 font-medium">Importe:</span>
                      <span className="font-mono font-bold text-base text-zinc-950">
                        {window.formatCurrencyPYG ? window.formatCurrencyPYG(item.amount) : `G$ ${item.amount}`}
                      </span>
                    </div>
                  )}

                  {/* METADADOS COMPLEMENTARES */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-zinc-600 pt-1 border-t border-red-100/80">
                    {item.date && (
                      <div className="flex items-center gap-1.5">
                        <span className="text-zinc-400">Fecha:</span>
                        <span className="font-mono font-semibold text-zinc-800">
                          {window.formatDateBR ? window.formatDateBR(item.date) : item.date}
                        </span>
                      </div>
                    )}
                    {item.document_ref && (
                      <div className="flex items-center gap-1.5">
                        <span className="text-zinc-400">Doc/Ref:</span>
                        <span className="font-mono font-semibold text-zinc-800">{item.document_ref}</span>
                      </div>
                    )}
                    {item.service_name && (
                      <div className="flex items-center gap-1.5 sm:col-span-2">
                        <span className="text-zinc-400">Servicio:</span>
                        <span className="font-medium text-zinc-800">{item.service_name}</span>
                      </div>
                    )}
                    {item.extra && (
                      <div className="flex items-center gap-1.5 sm:col-span-2">
                        <span className="text-zinc-400">Info:</span>
                        <span className="font-medium text-zinc-800">{item.extra}</span>
                      </div>
                    )}
                    {item.duration && (
                      <div className="flex items-center gap-1.5 sm:col-span-2">
                        <span className="text-zinc-400">Duración:</span>
                        <span className="font-semibold text-zinc-800">{item.duration}</span>
                      </div>
                    )}
                  </div>

                  {/* DESCRIÇÃO / OBSERVAÇÃO */}
                  {item.description && (
                    <div className="text-xs text-zinc-700 bg-white/80 border border-red-100 p-2 rounded leading-relaxed">
                      <span className="text-zinc-400 text-[10px] block font-mono uppercase mb-0.5">Descripción:</span>
                      {item.description}
                    </div>
                  )}

                  {/* TAGS VINCULADAS */}
                  {item.tags && item.tags.length > 0 && (
                    <div className="flex items-center gap-1 flex-wrap pt-1">
                      <span className="text-[10px] text-zinc-400 mr-1">Etiquetas:</span>
                      {item.tags.map(t => (
                        <span 
                          key={t.id || t.name}
                          className="inline-flex items-center text-[10px] font-mono px-1.5 py-0.5 rounded text-white font-medium"
                          style={{ backgroundColor: t.color || '#18181b' }}
                        >
                          #{t.name}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {/* AVISO DE SEGURANÇA */}
              <div className="flex items-start gap-2.5 p-3 rounded-lg bg-zinc-50 border border-zinc-200 text-xs text-zinc-600 leading-relaxed">
                <span className="text-red-600 font-bold text-sm shrink-0">⚠️</span>
                <span>
                  <strong>Atención:</strong> Este registro se eliminará permanentemente de la base de datos y los saldos e informes se recalcularán automáticamente.
                </span>
              </div>
            </>
          )}

          {/* BOTÕES DE AÇÃO */}
          <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-zinc-100">
            {Button ? (
              <>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleCancelAction}
                  className="cursor-pointer text-xs font-medium px-4 h-9 border-zinc-300 hover:bg-zinc-100 text-zinc-700"
                >
                  {confirmState.cancelText || 'Cancelar y Mantener'}
                </Button>
                <Button
                  variant={isDestructive ? 'destructive' : 'default'}
                  size="sm"
                  onClick={handleConfirmAction}
                  className={`cursor-pointer text-xs font-semibold px-4 h-9 flex items-center gap-1.5 shadow-sm ${
                    isDestructive ? 'bg-red-600 hover:bg-red-700 text-white border border-red-700' : 'bg-zinc-950 text-white'
                  }`}
                >
                  {isDestructive && Lucide?.Trash && <Lucide.Trash size={14} />}
                  <span>{confirmState.confirmText || 'Confirmar'}</span>
                </Button>
              </>
            ) : (
              <>
                <button 
                  type="button" 
                  className="btn btn-secondary text-xs h-9 px-4 rounded-md border border-zinc-200 text-zinc-700 hover:bg-zinc-100 font-medium" 
                  onClick={handleCancelAction}
                >
                  {confirmState.cancelText || 'Cancelar y Mantener'}
                </button>
                <button 
                  type="button" 
                  className={`text-xs h-9 px-4 rounded-md font-semibold text-white flex items-center gap-1.5 shadow-sm ${
                    isDestructive ? 'bg-red-600 hover:bg-red-700' : 'bg-zinc-950'
                  }`} 
                  onClick={handleConfirmAction}
                >
                  <span>{confirmState.confirmText || 'Confirmar'}</span>
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// --- FICHA TÉCNICA / DETALHES COMPLETOS DA ORDEM DE SERVIÇO (CONTROLE INTERNO) ---
function ServiceDetailModal() {
  const { detailTx, setDetailTx, setEditingTx, setModalTxOpen, setSinglePrintTx, settings, showToast } = window.useFinance();
  const { Button, Lucide } = window.Shadcn || {};

  if (!detailTx) return null;

  const isCredit = detailTx.type === 'CREDIT' || detailTx.type === 'PAYMENT_MADE';
  const typeLabel = detailTx.type === 'CREDIT' 
    ? (settings?.movement_credit_title || 'Servicio Prestado')
    : (detailTx.type === 'DEBIT' 
        ? (settings?.movement_debit_title || 'Cuota Universitaria')
        : (detailTx.type === 'PAYMENT_RECEIVED' 
            ? (settings?.movement_payment_received_title || 'Pago Recibido')
            : (settings?.movement_payment_made_title || 'Pago Efectuado')));

  const handleEdit = () => {
    const txToEdit = { ...detailTx };
    setDetailTx(null);
    setEditingTx(txToEdit);
    setModalTxOpen(true);
  };

  const handlePrintIndividual = () => {
    setSinglePrintTx(detailTx);
  };

  return (
    <div className="modal-backdrop open flex items-center justify-center p-4 z-50">
      <div 
        className="modal w-full bg-white rounded-xl border border-zinc-200 shadow-2xl overflow-hidden"
        style={{ maxWidth: '640px' }}
      >
        {/* CABEÇALHO DA FICHA */}
        <div className="p-5 border-b border-zinc-100 bg-zinc-50/70 flex items-start justify-between gap-4">
          <div className="space-y-1.5">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-md bg-zinc-950 text-white font-mono font-bold text-xs tracking-wider shadow-xs">
                <span>ORDEN Nº</span>
                <span>#OS-{String(detailTx.id).padStart(4, '0')}</span>
              </span>

              <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-mono font-bold border ${
                isCredit 
                  ? 'bg-emerald-50 text-emerald-700 border-emerald-300' 
                  : (detailTx.type === 'DEBIT' ? 'bg-rose-50 text-rose-700 border-rose-300' : 'bg-amber-50 text-amber-700 border-amber-300')
              }`}>
                {typeLabel}
              </span>

              <span className="text-xs text-zinc-500 font-mono">
                📅 {window.formatDateBR ? window.formatDateBR(detailTx.date) : detailTx.date}
              </span>
            </div>

            <h3 className="font-bold text-lg text-zinc-950 leading-tight pt-1">
              {detailTx.title}
            </h3>

            {detailTx.service_name && (
              <p className="text-xs text-zinc-500">
                Catálogo Vinculado: <strong className="text-zinc-700">{detailTx.service_name}</strong>
              </p>
            )}
          </div>

          <button 
            type="button" 
            className="w-8 h-8 rounded-md border border-zinc-200 bg-white hover:bg-zinc-100 text-zinc-500 hover:text-zinc-950 flex items-center justify-center shrink-0 cursor-pointer font-bold text-sm"
            onClick={() => setDetailTx(null)}
          >
            ✕
          </button>
        </div>

        {/* CORPO DO MODAL DE DETALHES */}
        <div className="p-5 space-y-4 text-xs" style={{ maxHeight: '72vh', overflowY: 'auto' }}>
          {/* CARDS COM MÉTRICAS */}
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <div className="p-3 rounded-lg border border-zinc-200 bg-white space-y-0.5">
              <span className="text-[10px] text-zinc-400 uppercase font-semibold">Importe del Movimiento</span>
              <div className={`font-mono font-bold text-lg ${
                isCredit 
                  ? 'text-emerald-600' 
                  : (detailTx.type === 'DEBIT' ? 'text-rose-600' : 'text-amber-600')
              }`}>
                {isCredit ? '+' : (detailTx.type === 'DEBIT' ? '-' : '')} {window.formatCurrencyPYG ? window.formatCurrencyPYG(detailTx.amount) : `G$ ${detailTx.amount}`}
              </div>
            </div>

            <div className="p-3 rounded-lg border border-zinc-200 bg-white space-y-0.5">
              <span className="text-[10px] text-zinc-400 uppercase font-semibold">Protocolo / Recibo</span>
              <div className="font-mono font-semibold text-zinc-800 truncate" title={detailTx.document_ref || '-'}>
                {detailTx.document_ref || '-'}
              </div>
            </div>

            <div className="p-3 rounded-lg border border-zinc-200 bg-white space-y-0.5 col-span-2 sm:col-span-1">
              <span className="text-[10px] text-zinc-400 uppercase font-semibold">Estado Contable</span>
              <div className="font-medium text-zinc-800 flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-emerald-600 shrink-0" />
                <span>Confirmado</span>
              </div>
            </div>
          </div>

          {/* SERVIÇOS & ENTREGAS INCLUSAS NO LANÇAMENTO (EM CASO DE MÚLTIPLOS SERVIÇOS) */}
          {detailTx.items && detailTx.items.length > 0 && (
            <div className="p-4 rounded-xl border border-zinc-200 bg-zinc-50/50 space-y-2">
              <div className="flex items-center justify-between">
                <h4 className="font-bold text-xs text-zinc-900 flex items-center gap-1.5">
                  <span>🎬</span>
                  <span>Servicios y Entregas Incluidos ({detailTx.items.length} ítems)</span>
                </h4>
                <span className="text-[10px] font-mono text-zinc-500 uppercase">
                  Detalle Individual
                </span>
              </div>
              
              <div className="overflow-hidden rounded-lg border border-zinc-200 bg-white">
                <table className="w-full text-xs text-left">
                  <thead>
                    <tr className="bg-zinc-100/80 border-b border-zinc-200 text-zinc-600 font-semibold">
                      <th className="py-2 px-3 w-10 text-center font-mono">#</th>
                      <th className="py-2 px-3">Servicio / Entregable</th>
                      <th className="py-2 px-3 w-16 text-center">Cant</th>
                      <th className="py-2 px-3 w-28 text-right">Unitario</th>
                      <th className="py-2 px-3 w-32 text-right">Subtotal</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-zinc-100 font-sans">
                    {detailTx.items.map((it, idx) => {
                      const qty = it.quantity || 1;
                      const unit = it.unit_price || 0;
                      const sub = it.total_price || (qty * unit);
                      return (
                        <tr key={it.id || idx} className="hover:bg-zinc-50/60">
                          <td className="py-2.5 px-3 text-center font-mono font-bold text-zinc-400">
                            {idx + 1}
                          </td>
                          <td className="py-2.5 px-3">
                            <div className="font-semibold text-zinc-950">{it.title}</div>
                            {it.service_name && (
                              <div className="text-[10px] text-zinc-400 font-normal">
                                Catálogo: {it.service_name}
                              </div>
                            )}
                            {it.deliverable_url && (
                              <a
                                href={it.deliverable_url}
                                target="_blank"
                                rel="noreferrer"
                                className="text-[10px] text-blue-600 hover:underline inline-flex items-center gap-0.5 mt-0.5 font-mono"
                              >
                                <span>Enlace de entrega</span> ↗
                              </a>
                            )}
                          </td>
                          <td className="py-2.5 px-3 text-center font-mono font-semibold text-zinc-700">
                            {qty}x
                          </td>
                          <td className="py-2.5 px-3 text-right font-mono text-zinc-600">
                            {window.formatCurrencyPYG ? window.formatCurrencyPYG(unit) : `G$ ${unit}`}
                          </td>
                          <td className="py-2.5 px-3 text-right font-mono font-bold text-emerald-700">
                            {window.formatCurrencyPYG ? window.formatCurrencyPYG(sub) : `G$ ${sub}`}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot>
                    <tr className="bg-zinc-50 font-bold border-t border-zinc-200">
                      <td colSpan="4" className="py-2.5 px-3 text-right text-zinc-700 text-xs">
                        Importe Total Sumado:
                      </td>
                      <td className="py-2.5 px-3 text-right font-mono text-emerald-700 text-sm">
                        {window.formatCurrencyPYG ? window.formatCurrencyPYG(detailTx.amount) : `G$ ${detailTx.amount}`}
                      </td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </div>
          )}

          {/* O QUE FOI REALIZADO */}
          <div className="p-4 rounded-xl border border-zinc-200 bg-zinc-50/50 space-y-1.5">
            <h4 className="font-bold text-xs text-zinc-900 flex items-center gap-1.5">
              <span>📋</span>
              <span>Detalle de lo Realizado y Entregado</span>
            </h4>
            <div className="bg-white p-3 rounded-lg border border-zinc-200/80 text-zinc-800 leading-relaxed text-xs">
              {detailTx.description ? (
                <p className="whitespace-pre-wrap">{detailTx.description}</p>
              ) : (
                <p className="text-zinc-400 italic">No se proporcionó una descripción detallada.</p>
              )}
            </div>
          </div>

          {/* ESCOPO TÉCNICO & ITENS ENTREGUES */}
          {detailTx.delivery_scope && (
            <div className="p-4 rounded-xl border border-zinc-200 bg-zinc-50/50 space-y-1.5">
              <h4 className="font-bold text-xs text-zinc-900 flex items-center gap-1.5">
                <span>📦</span>
                <span>Especificaciones Técnicas de los Entregables (Control Interno)</span>
              </h4>
              <div className="bg-white p-3 rounded-lg border border-zinc-200/80 text-zinc-800 leading-relaxed font-sans whitespace-pre-wrap">
                {detailTx.delivery_scope}
              </div>
            </div>
          )}

          {/* ARQUIVOS & LINKS DOS ENTREGÁVEIS (DRIVE, YOUTUBE, FIGMA, ETC.) */}
          {(() => {
            const embedInfo = window.getEmbedDeliverable ? window.getEmbedDeliverable(detailTx.deliverable_url) : null;
            
            const handleCopyDeliverableLink = (url) => {
              if (!url) return;
              if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(url);
              } else {
                const ta = document.createElement('textarea');
                ta.value = url;
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
              }
              if (showToast) showToast('¡Enlace de entrega copiado al portapapeles!');
            };

            return (
              <div className="p-4 rounded-xl border border-zinc-200 bg-zinc-50/50 space-y-3">
                <div className="flex items-center justify-between">
                  <h4 className="font-bold text-xs text-zinc-900 flex items-center gap-1.5 m-0">
                    <span>{embedInfo?.icon || '🔗'}</span>
                    <span>Archivos en la Nube y Comprobante de Entrega</span>
                  </h4>
                  {detailTx.deliverable_url && (
                    <span className="text-[10px] text-zinc-600 font-mono bg-zinc-200/80 px-2 py-0.5 rounded border border-zinc-300">
                      {embedInfo?.label || 'Enlace Activo'}
                    </span>
                  )}
                </div>

                {detailTx.deliverable_url ? (
                  <div className="space-y-3">
                    {/* REPRODUCTOR DE VIDEO O VISTA PREVIA DIRECTA INTERACTIVA */}
                    {embedInfo?.embedUrl && (
                      <div className="relative w-full rounded-xl overflow-hidden border border-zinc-300 bg-black aspect-video shadow-md">
                        <iframe
                          src={embedInfo.embedUrl}
                          className="absolute inset-0 w-full h-full"
                          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                          allowFullScreen
                          title="Vista previa del entregable"
                        />
                      </div>
                    )}

                    <div className="bg-white p-3.5 rounded-lg border border-zinc-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 shadow-2xs">
                      <div className="truncate flex-1">
                        <div className="flex items-center gap-1.5 mb-0.5">
                          <span className="text-sm">{embedInfo?.icon || '🔗'}</span>
                          <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-wider">
                            {embedInfo?.label || 'URL de Entrega'}
                          </span>
                        </div>
                        <a 
                          href={detailTx.deliverable_url} 
                          target="_blank" 
                          rel="noreferrer"
                          className="font-mono text-xs text-zinc-900 hover:text-blue-600 underline truncate block"
                          title={detailTx.deliverable_url}
                        >
                          {detailTx.deliverable_url}
                        </a>
                      </div>

                      <div className="flex items-center gap-2 shrink-0">
                        <button
                          type="button"
                          onClick={() => handleCopyDeliverableLink(detailTx.deliverable_url)}
                          className="inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md border border-zinc-300 bg-white hover:bg-zinc-100 text-zinc-800 font-semibold text-xs transition-colors shadow-2xs cursor-pointer"
                          title="Copiar enlace al portapapeles"
                        >
                          <span>📋 Copiar Enlace</span>
                        </button>
                        <a 
                          href={detailTx.deliverable_url} 
                          target="_blank" 
                          rel="noreferrer"
                          className="inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md bg-zinc-950 text-white font-semibold text-xs hover:bg-zinc-800 transition-colors shadow-xs"
                        >
                          <span>Abrir</span>
                          <span>↗</span>
                        </a>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="bg-white p-3 rounded-lg border border-dashed border-zinc-300 text-zinc-400 text-xs italic flex items-center justify-between">
                    <span>No hay enlace de Google Drive ni archivo externo adjunto.</span>
                    <button
                      type="button"
                      onClick={handleEdit}
                      className="text-xs text-zinc-800 underline font-medium cursor-pointer not-italic hover:text-zinc-950"
                    >
                      Agregar Enlace
                    </button>
                  </div>
                )}
              </div>
            );
          })()}

          {/* TAGS VINCULADAS */}
          {detailTx.tags && detailTx.tags.length > 0 && (
            <div className="flex items-center gap-2 flex-wrap pt-1">
              <span className="text-zinc-400 font-medium">Etiquetas:</span>
              {detailTx.tags.map(t => (
                <span 
                  key={t.id || t.name}
                  className="inline-flex items-center text-[11px] font-mono font-bold px-2.5 py-0.5 rounded-full text-white shadow-2xs"
                  style={{ backgroundColor: t.color || '#18181b' }}
                >
                  #{t.name}
                </span>
              ))}
            </div>
          )}

          {/* DADOS DE CONTROLE INTERNO */}
          <div className="pt-2 border-t border-zinc-200/80 text-[11px] text-zinc-500 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1.5">
            <div>
              Prestador: <strong className="text-zinc-700">{settings?.contractor_name || 'Prestador'}</strong> • {settings?.student_id || ''}
            </div>
            <div>
              Institución: <strong className="text-zinc-700">{settings?.institution_name || 'Universidad Columbia'}</strong>
            </div>
          </div>
        </div>

        {/* RODAPÉ DE AÇÕES */}
        <div className="p-4 border-t border-zinc-100 bg-zinc-50/70 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2.5">
          <Button
            variant="outline"
            size="sm"
            onClick={handleEdit}
            className="cursor-pointer text-xs flex items-center gap-1.5"
          >
            {Lucide?.Edit && <Lucide.Edit size={13} />}
            <span>Editar Información</span>
          </Button>

          <div className="flex items-center justify-end gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setDetailTx(null)}
              className="cursor-pointer text-xs"
            >
              Cerrar
            </Button>

            <Button
              variant="default"
              size="sm"
              onClick={handlePrintIndividual}
              className="cursor-pointer text-xs font-semibold flex items-center gap-1.5 bg-zinc-950 text-white shadow-xs"
            >
              {Lucide?.Printer && <Lucide.Printer size={14} />}
              <span>🖨️ Imprimir Orden de Servicio (A4)</span>
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ToastContainer() {
  const { toasts } = window.useFinance();
  return (
    <div className="toast-container">
      {toasts.map(t => (
        <div key={t.id} className="toast">{t.message}</div>
      ))}
    </div>
  );
}

window.TransactionModal = TransactionModal;
window.ServiceModal = ServiceModal;
window.RecurringModal = RecurringModal;
window.TagModal = TagModal;
window.ConfirmModal = ConfirmModal;
window.ServiceDetailModal = ServiceDetailModal;
window.ToastContainer = ToastContainer;
