import { useState, useEffect, useRef, useCallback } from 'react';
import api from '../services/api';
import { useDebounce } from '../hooks/useDebounce';
import { processCategories, type FlatCategory } from '../utils/categoryTreeUtils';
import {
  Printer, Save,
  AlignLeft, AlignCenter, AlignRight, AlignJustify,
  Type, Search, ChevronDown, Bold, Square as FrameIcon,
  ArrowUpRight,
  RefreshCw
} from 'lucide-react';
import clsx from 'clsx';
import PaymentModal, { type Payment } from '../components/PaymentModal';
import { motion, AnimatePresence } from 'framer-motion';
import { useToast } from '../context/use-toast';
import { useCashSession } from '../hooks/useCashSession';
import CashOpeningModal from '../components/CashOpeningModal';
import { useNavigate } from 'react-router-dom';

// Interfaces
interface Operation { id: number; name: string; }
interface Client { id: number; name: string; dniOrCuit: string; }
interface PricingResult {
  totalPrice: number; baseCost: number; extraCost: number;
  surcharges: number; discount: number; wordCount: number;
  specialCharCount: number; details: string; appliedPromotion: string;
}

const escapeHTML = (str: string) => {
  return str.replace(/[&<>"']/g, (m) => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  }[m] || m));
};

export default function FastEntryPage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const [flatCategories, setFlatCategories] = useState<FlatCategory[]>([]);
  const [operations, setOperations] = useState<Operation[]>([]);
  const { session, loading: sessionLoading, refreshSession } = useCashSession();

  const [categorySearch, setCategorySearch] = useState("");
  const [isCatDropdownOpen, setIsCatDropdownOpen] = useState(false);
  const catWrapperRef = useRef<HTMLDivElement>(null);

  const [formData, setFormData] = useState({
    categoryId: '', operationId: '', text: '', days: 3, clientName: '', clientDni: '',
  });

  const [options, setOptions] = useState({
    isBold: false, isFrame: false, fontSize: 'normal', alignment: 'left'
  });

  const [pricing, setPricing] = useState<PricingResult>({
    totalPrice: 0, baseCost: 0, extraCost: 0, surcharges: 0, discount: 0,
    wordCount: 0, specialCharCount: 0, details: '', appliedPromotion: ''
  });

  const [clientSuggestions, setClientSuggestions] = useState<Client[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const debouncedClientSearch = useDebounce(formData.clientName, 300);
  const clientWrapperRef = useRef<HTMLDivElement>(null);
  const textInputRef = useRef<HTMLTextAreaElement>(null);
  const debouncedText = useDebounce(formData.text, 500);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [errors, setErrors] = useState<Record<string, boolean>>({});

  const filteredCategories = flatCategories.filter(cat =>
    cat.path.toLowerCase().includes(categorySearch.toLowerCase()) ||
    cat.name.toLowerCase().includes(categorySearch.toLowerCase())
  );

  const selectedCategoryName = flatCategories.find(c => c.id === parseInt(formData.categoryId))?.name;

  const validate = useCallback(() => {
    const newErrors: Record<string, boolean> = {
      categoryId: !formData.categoryId,
      operationId: !formData.operationId,
      text: !formData.text || formData.text.trim().length === 0,
    };
    setErrors(newErrors);
    return !Object.values(newErrors).some(v => v);
  }, [formData]);

  const printCourtesyTicket = (data: typeof formData, priceInfo: PricingResult) => {
    const printWindow = window.open('', '_blank', 'width=300,height=600');
    if (!printWindow) return;

    const html = `
      <html>
        <body style="font-family: 'Courier New', monospace; width: 280px; padding: 10px; font-size: 12px;">
          <div style="text-align: center; border-bottom: 1px dashed #000; padding-bottom: 10px; margin-bottom: 10px;">
            <h2 style="margin: 0;">DIARIO EL DIA</h2>
            <p>Comprobante de Recepción</p>
            <p>${new Date().toLocaleString()}</p>
          </div>
          <div>
            <b>CLIENTE:</b> ${escapeHTML(data.clientName || 'Consumidor Final')}<br/>
            <b>RUBRO:</b> ${escapeHTML(selectedCategoryName || '')}<br/>
            <b>DÍAS:</b> ${data.days}<br/>
          </div>
          <div style="background: #f0f0f0; padding: 8px; margin: 10px 0; border: 1px solid #000;">
            ${escapeHTML(data.text).toUpperCase()}
          </div>
          <div style="text-align: right; border-top: 1px dashed #000; padding-top: 5px;">
            <b style="font-size: 16px;">TOTAL: $${priceInfo.totalPrice.toLocaleString()}</b>
          </div>
        </body>
      </html>
    `;
    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); printWindow.close(); }, 250);
  };

  const printPaymentReceipt = (data: typeof formData, priceInfo: PricingResult, payments: Payment[]) => {
    const printWindow = window.open('', '_blank', 'width=350,height=700');
    if (!printWindow) return;

    const username = localStorage.getItem('username') || 'Cajero';
    const now = new Date();
    const totalWithSurcharges = payments.reduce((sum, p) => sum + p.amount + p.surcharge, 0);

    const paymentRows = payments.map(p => {
      const paymentMethodMap: Record<string, string> = {
        'Cash': 'Efectivo',
        'Debit': 'Débito',
        'Credit': p.cardPlan || 'Crédito',
        'Transfer': 'Transferencia'
      };
      const methodName = paymentMethodMap[p.paymentMethod] || p.paymentMethod;

      return `
        <tr>
          <td style="padding: 5px 0; border-bottom: 1px solid #ddd;">${methodName}</td>
          <td style="padding: 5px 0; text-align: right; border-bottom: 1px solid #ddd;">$${p.amount.toLocaleString()}</td>
          ${p.surcharge > 0 ? `<td style="padding: 5px 0; text-align: right; border-bottom: 1px solid #ddd; color: #f59e0b;">+$${p.surcharge.toLocaleString()}</td>` : '<td></td>'}
        </tr>
      `;
    }).join('');

    const html = `
      <html>
        <head><style>@media print { body { margin: 0; } }</style></head>
        <body style="font-family: 'Courier New', monospace; width: 320px; padding: 15px; font-size: 11px; background: white;">
          <div style="text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 10px;">
            <h1 style="margin: 0; font-size: 20px; font-weight: bold;">DIARIO EL DÍA</h1>
            <p style="margin: 2px 0; font-size: 10px;">Comprobante de Pago</p>
            <p style="margin: 2px 0; font-size: 10px; font-weight: bold;">N° ${Math.floor(Math.random() * 100000).toString().padStart(8, '0')}</p>
            <p style="margin: 5px 0; font-size: 9px;">${now.toLocaleDateString('es-AR')} - ${now.toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' })}</p>
          </div>
          <div style="margin-bottom: 10px;">
            <p style="margin: 3px 0;"><b>CLIENTE:</b> ${escapeHTML(data.clientName || 'Consumidor Final')}</p>
            ${data.clientDni ? `<p style="margin: 3px 0;"><b>DNI/CUIT:</b> ${escapeHTML(data.clientDni)}</p>` : ''}
            <p style="margin: 3px 0;"><b>ATENDIDO POR:</b> ${escapeHTML(username)}</p>
          </div>
          <div style="border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 8px 0; margin-bottom: 10px;">
            <p style="margin: 3px 0; font-weight: bold;">DETALLE DEL SERVICIO:</p>
            <p style="margin: 3px 0;">Rubro: ${escapeHTML(selectedCategoryName || '')}</p>
            <p style="margin: 3px 0;">Duración: ${data.days} día${data.days > 1 ? 's' : ''}</p>
          </div>
          <div style="margin-bottom: 10px;">
            <table style="width: 100%; font-size: 10px;">
              <tr><td>Tarifa Base</td><td style="text-align: right;">$${priceInfo.baseCost.toLocaleString()}</td></tr>
              ${priceInfo.extraCost > 0 ? `<tr><td>Recargo texto</td><td style="text-align: right;">+$${priceInfo.extraCost.toLocaleString()}</td></tr>` : ''}
              <tr style="border-top: 2px solid #000; font-weight: bold; font-size: 12px;">
                <td style="padding: 8px 0;">SUBTOTAL</td><td style="text-align: right; padding: 8px 0;">$${priceInfo.totalPrice.toLocaleString()}</td>
              </tr>
            </table>
          </div>
          <div style="border-top: 2px solid #000; padding-top: 10px; margin-bottom: 10px;">
            <p style="margin: 5px 0; font-weight: bold; text-align: center;">MEDIOS DE PAGO</p>
            <table style="width: 100%; font-size: 10px;">${paymentRows}</table>
          </div>
          <div style="background: #000; color: #fff; padding: 12px; text-align: center; border-radius: 5px;">
            <p style="margin: 0; font-size: 10px;">TOTAL A PAGAR</p>
            <p style="margin: 5px 0; font-size: 24px; font-weight: bold;">$${totalWithSurcharges.toLocaleString('es-AR', { minimumFractionDigits: 2 })}</p>
          </div>
        </body>
      </html>
    `;
    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); printWindow.close(); }, 250);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [catRes, opRes] = await Promise.all([api.get('/categories'), api.get('/operations')]);
        setFlatCategories(processCategories(catRes.data));
        setOperations(opRes.data);
      } catch (error) { console.error(error); }
    };
    fetchData();
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!validate()) return;
    setShowPaymentModal(true);
  }, [validate]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'F10') { e.preventDefault(); handleSubmit(); }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handleSubmit]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (catWrapperRef.current && !catWrapperRef.current.contains(event.target as Node)) setIsCatDropdownOpen(false);
      if (clientWrapperRef.current && !clientWrapperRef.current.contains(event.target as Node)) setShowSuggestions(false);
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!formData.categoryId) return;
    const calculatePrice = async () => {
      try {
        const res = await api.post('/pricing/calculate', {
          categoryId: parseInt(formData.categoryId),
          text: debouncedText || "",
          days: formData.days,
          isBold: options.isBold,
          isFrame: options.isFrame,
          startDate: new Date().toISOString()
        });
        setPricing(res.data);
      } catch (error) { console.error(error); }
    };
    calculatePrice();
  }, [debouncedText, formData.categoryId, formData.days, options]);

  useEffect(() => {
    if (debouncedClientSearch.length > 2 && showSuggestions) {
      api.get(`/clients/search?q=${debouncedClientSearch}`)
        .then(res => setClientSuggestions(res.data))
        .catch(() => setClientSuggestions([]));
    }
  }, [debouncedClientSearch, showSuggestions]);

  const handlePaymentConfirm = async (payments: Payment[]) => {
    try {
      const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
      await api.post('/listings', {
        categoryId: parseInt(formData.categoryId),
        operationId: parseInt(formData.operationId),
        title: formData.text.substring(0, 40) + '...',
        description: formData.text,
        price: 0,
        adFee: pricing.totalPrice,
        status: 'Published',
        printText: formData.text,
        printStartDate: tomorrow.toISOString(),
        printDaysCount: formData.days,
        isBold: options.isBold,
        isFrame: options.isFrame,
        printFontSize: options.fontSize,
        printAlignment: options.alignment,
        clientName: formData.clientName,
        clientDni: formData.clientDni,
        payments
      });
      printCourtesyTicket(formData, pricing);
      setTimeout(() => { printPaymentReceipt(formData, pricing, payments); }, 500);
      setFormData({ ...formData, text: '', clientName: '', clientDni: '' });
      setOptions({ isBold: false, isFrame: false, fontSize: 'normal', alignment: 'left' });
      setShowPaymentModal(false);
      setErrors({});
      showToast('Aviso procesado correctamente.', 'success');
    } catch (err) {
      showToast('Error al procesar el cobro.', 'error');
    }
  };

  const handleSelectClient = (client: Client) => {
    setFormData(prev => ({ ...prev, clientName: client.name, clientDni: client.dniOrCuit }));
    setShowSuggestions(false);
  };

  if (sessionLoading) {
    return (
      <div className="h-full w-full flex items-center justify-center bg-slate-50">
        <RefreshCw className="animate-spin text-blue-600" size={40} />
      </div>
    );
  }


  return (
    <>
      {/* BLOQUEO DE SEGURIDAD: Si no hay sesión, mostramos el modal de apertura */}
      <AnimatePresence>
        {!session.isOpen && (
          <CashOpeningModal
            onSuccess={refreshSession}
            onCancel={() => navigate('/dashboard')} // Si cancela la apertura, lo sacamos de "Nuevo Aviso"
          />
        )}
      </AnimatePresence>

      <motion.div
        initial={{ opacity: 0, scale: 0.99 }}
        animate={{
          opacity: 1,
          scale: 1,
          // Si no hay sesión, aplicamos un filtro de desenfoque y desaturación
          filter: session.isOpen ? "blur(0px) grayscale(0)" : "blur(8px) grayscale(1)"
        }}
        transition={{ duration: 0.7, ease: "easeInOut" }}
        className={clsx(
          "w-full h-full p-5 flex gap-5 bg-slate-50/50 overflow-hidden max-h-screen",
          // Bloqueamos interacciones físicas mientras el modal esté presente
          !session.isOpen && "pointer-events-none select-none opacity-40"
        )}
      >
        {/* PANEL IZQUIERDO: FORMULARIO */}
        <div className="flex-[7] bg-white rounded-[2rem] shadow-xl shadow-slate-200/50 border border-slate-200 p-6 flex flex-col min-h-0 relative">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h2 className="text-xl font-black text-slate-900 tracking-tight uppercase flex items-center gap-3">
                <span className="bg-blue-600 w-1.5 h-6 rounded-full"></span>
                Nueva Publicación
              </h2>
              <p className="text-[9px] text-slate-500 font-bold tracking-[0.2em] mt-0.5 uppercase opacity-80">Caja 01 - Recepción de Avisos</p>
            </div>
            <div className="bg-slate-100 p-2 rounded-xl text-slate-400"><Printer size={18} /></div>
          </div>

          <div className="flex flex-col gap-6 flex-1 min-h-0">
            <div className="grid grid-cols-2 gap-6">
              <div className="relative" ref={catWrapperRef}>
                <label className={clsx("block text-[10px] font-black uppercase mb-1.5 tracking-widest transition-colors", errors.categoryId ? "text-rose-500" : "text-slate-500")}>
                  Rubro Seleccionado {errors.categoryId && "• Requerido"}
                </label>
                <div
                  className={clsx(
                    "w-full p-3.5 border-2 rounded-xl flex justify-between items-center cursor-pointer transition-all duration-300",
                    isCatDropdownOpen ? "border-blue-500 bg-blue-50/30" : errors.categoryId ? "border-rose-200 bg-rose-50/50" : "border-slate-100 bg-slate-50/50 hover:border-slate-300"
                  )}
                  onClick={() => setIsCatDropdownOpen(!isCatDropdownOpen)}
                >
                  <span className={clsx("font-extrabold text-sm tracking-tight", !formData.categoryId ? "text-slate-400" : "text-slate-800")}>
                    {selectedCategoryName || "BUSCAR RUBRO..."}
                  </span>
                  <ChevronDown size={18} className={clsx("transition-transform", isCatDropdownOpen ? "rotate-180 text-blue-500" : "text-slate-400")} />
                </div>
                <AnimatePresence>
                  {isCatDropdownOpen && (
                    <motion.div initial={{ opacity: 0, y: 5 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} className="absolute top-full left-0 right-0 bg-white border-2 border-slate-100 shadow-2xl rounded-2xl mt-2 z-[100] flex flex-col max-h-[350px] overflow-hidden">
                      <div className="p-3 bg-slate-50 border-b flex items-center gap-2">
                        <Search size={16} className="text-slate-400" />
                        <input autoFocus type="text" placeholder="Filtrar por nombre o código..." className="bg-transparent w-full outline-none text-sm font-bold text-slate-700 placeholder:text-slate-400" value={categorySearch} onChange={(e) => setCategorySearch(e.target.value)} />
                      </div>
                      <div className="overflow-y-auto flex-1 py-2 px-1 custom-scrollbar">
                        {filteredCategories.map(cat => (
                          <div key={cat.id} className={clsx("mx-1 px-4 py-2.5 text-xs cursor-pointer rounded-lg transition-all mb-1 flex items-center gap-3", !cat.isSelectable ? "text-slate-300 italic opacity-60" : "hover:bg-blue-50 text-slate-600 font-bold", parseInt(formData.categoryId) === cat.id && "bg-blue-600 text-white shadow-lg pl-6")} style={{ marginLeft: `${(cat.level * 12) + 4}px` }} onClick={() => { if (cat.isSelectable) { setFormData({ ...formData, categoryId: cat.id.toString() }); setIsCatDropdownOpen(false); setErrors({ ...errors, categoryId: false }); } }}>
                            <span className={clsx("w-1 h-1 rounded-full", parseInt(formData.categoryId) === cat.id ? "bg-white" : "bg-slate-300")}></span>
                            {cat.name}
                          </div>
                        ))}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
              <div>
                <label className={clsx("block text-[10px] font-black uppercase mb-1.5 tracking-widest transition-colors", errors.operationId ? "text-rose-500" : "text-slate-500")}>Operación {errors.operationId && "• Requerido"}</label>
                <select className={clsx("w-full p-3.5 border-2 rounded-xl outline-none font-extrabold text-sm tracking-tight transition-all appearance-none bg-[url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20width%3D%2220%22%20height%3D%2220%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22none%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%3E%3Cpath%20d%3D%22M5%207.5L10%2012.5L15%207.5%22%20stroke%3D%22%2364748B%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22/%3E%3C/svg%3E')] bg-[length:18px_18px] bg-[right_1rem_center] bg-no-repeat", formData.operationId ? "border-slate-100 bg-slate-50 text-slate-800" : errors.operationId ? "border-rose-200 bg-rose-50/50 text-rose-400" : "border-slate-100 bg-slate-50 text-slate-400")} value={formData.operationId} onChange={e => { setFormData({ ...formData, operationId: e.target.value }); setErrors({ ...errors, operationId: false }); }}>
                  <option value="">ELIJA OPERACIÓN...</option>
                  {operations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
                </select>
              </div>
            </div>

            <div className="flex flex-col flex-1 min-h-0">
              <label className={clsx("block text-[10px] font-black uppercase mb-1.5 tracking-widest transition-colors", errors.text ? "text-rose-500" : "text-slate-500")}>Cuerpo del Aviso {errors.text && "• Requerido"}</label>
              <div className="relative flex-1 group">
                <textarea ref={textInputRef} className={clsx("w-full h-full p-6 border-2 rounded-[1.5rem] resize-none outline-none font-mono text-xl tracking-tighter leading-snug transition-all duration-300", errors.text ? "border-rose-200 bg-rose-50/30" : "border-slate-100 bg-slate-50/30 group-focus-within:border-blue-400 group-focus-within:bg-white text-slate-800")} placeholder="ESCRIBA EL TEXTO AQUÍ PARA IMPRENTA..." value={formData.text} onChange={e => { setFormData({ ...formData, text: e.target.value }); setErrors({ ...errors, text: false }); }}></textarea>
                <div className="absolute top-3 right-3"><div className="bg-white/80 backdrop-blur px-2 py-1 rounded-lg border border-slate-100 shadow-sm text-[9px] font-black text-slate-400 uppercase tracking-widest">F10 para Cobrar</div></div>
              </div>
              <div className="flex justify-between items-center mt-3 bg-slate-900 px-5 py-2.5 rounded-xl shadow-lg">
                <div className="flex gap-6">
                  <div className="flex flex-col"><span className="text-[8px] text-slate-500 font-black uppercase">Palabras</span><span className={clsx("text-base font-mono font-black", pricing.wordCount > 0 ? "text-blue-400" : "text-slate-700")}>{pricing.wordCount.toString().padStart(2, '0')}</span></div>
                  <div className="flex flex-col"><span className="text-[8px] text-slate-500 font-black uppercase">Signos Especiales</span><span className={clsx("text-base font-mono font-black", pricing.specialCharCount > 0 ? "text-amber-400" : "text-slate-700")}>{pricing.specialCharCount.toString().padStart(2, '0')}</span></div>
                </div>
                <div className="text-right"><span className="text-[9px] text-slate-400 font-bold italic uppercase tracking-tighter">Vista optimizada para diario</span><div className="flex gap-1 mt-0.5 justify-end">{[1, 2, 3, 4, 5].map(i => <div key={i} className={clsx("h-0.5 w-2.5 rounded-full", formData.text.length > i * 15 ? "bg-blue-500" : "bg-slate-800")}></div>)}</div></div>
              </div>
            </div>

            <div className="grid grid-cols-4 gap-4 bg-slate-50/50 p-4 rounded-[1.5rem] border-2 border-slate-100">
              <div className="col-span-1">
                <label className="block text-[9px] font-black text-slate-500 uppercase mb-1 tracking-widest">Días</label>
                <div className="flex items-center bg-white rounded-lg border border-slate-200 overflow-hidden h-10">
                  <button onClick={() => setFormData(f => ({ ...f, days: Math.max(1, f.days - 1) }))} className="px-2.5 hover:bg-slate-50 text-slate-400 font-bold transition-colors">-</button>
                  <input type="number" className="w-full text-center font-black text-blue-600 outline-none bg-transparent text-sm" value={formData.days} onChange={e => setFormData({ ...formData, days: Math.max(1, parseInt(e.target.value) || 0) })} />
                  <button onClick={() => setFormData(f => ({ ...f, days: f.days + 1 }))} className="px-2.5 hover:bg-slate-50 text-slate-400 font-bold transition-colors">+</button>
                </div>
              </div>
              <div className="col-span-2 relative" ref={clientWrapperRef}>
                <label className="block text-[9px] font-black text-slate-500 uppercase mb-1 tracking-widest">Cliente / Razón Social</label>
                <div className="relative h-10">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
                  <input type="text" className="w-full h-full pl-10 pr-4 bg-white border border-slate-200 rounded-lg outline-none focus:border-blue-500 font-extrabold text-xs tracking-tight placeholder:text-slate-400" placeholder="NOMBRE O RAZÓN SOCIAL..." value={formData.clientName} onFocus={() => setShowSuggestions(true)} onChange={e => { setFormData({ ...formData, clientName: e.target.value }); setShowSuggestions(true); }} />
                </div>
                <AnimatePresence>{showSuggestions && clientSuggestions.length > 0 && (
                  <motion.div initial={{ opacity: 0, y: -5 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} className="absolute bottom-full mb-2 left-0 right-0 bg-white border-2 border-slate-100 shadow-2xl rounded-xl overflow-hidden z-[110]">
                    {clientSuggestions.map(client => (
                      <div key={client.id} className="p-3 hover:bg-blue-50 cursor-pointer border-b border-slate-50 flex justify-between items-center group transition-colors" onClick={() => handleSelectClient(client)}>
                        <div><div className="font-extrabold text-slate-800 text-[11px] uppercase group-hover:text-blue-600">{client.name}</div><div className="text-[9px] text-slate-500 font-mono mt-0.5">{client.dniOrCuit}</div></div>
                        <ArrowUpRight size={12} className="text-slate-300 group-hover:text-blue-400" />
                      </div>
                    ))}
                  </motion.div>
                )}</AnimatePresence>
              </div>
              <div className="col-span-1">
                <label className="block text-[9px] font-black text-slate-500 uppercase mb-1 tracking-widest">DNI / CUIT</label>
                <input type="text" className="w-full h-10 bg-white border border-slate-200 rounded-lg font-mono text-center font-black text-xs outline-none focus:border-blue-500 placeholder:text-slate-400" placeholder="S/D" value={formData.clientDni} onChange={e => setFormData({ ...formData, clientDni: e.target.value })} />
              </div>
            </div>
          </div>
        </div>

        {/* PANEL DERECHO */}
        <div className="flex-[3] flex flex-col gap-4 min-h-0 overflow-hidden">
          <div className="bg-slate-900 text-white rounded-[2rem] p-5 shadow-xl border-b-4 border-blue-600 flex-shrink-0">
            <div className="text-[9px] text-blue-400 uppercase tracking-widest mb-0.5 font-black">Total a Cobrar</div>
            <div className="text-4xl font-mono font-black text-green-400 flex items-start gap-1">
              <span className="text-lg mt-1 opacity-50">$</span>{pricing.totalPrice.toLocaleString()}
            </div>
            <div className="mt-3 pt-3 border-t border-slate-800 space-y-1.5 text-[10px] font-bold uppercase tracking-tighter">
              <div className="flex justify-between text-slate-500 italic"><span>Tarifa Base</span><span className="text-slate-300">${pricing.baseCost.toLocaleString()}</span></div>
              {pricing.extraCost > 0 && <div className="flex justify-between text-orange-500"><span>Recargos Texto</span><span>+${pricing.extraCost.toLocaleString()}</span></div>}
              {pricing.discount > 0 && <div className="mt-2 p-2 bg-green-500/10 rounded-lg text-green-400 flex flex-col border border-green-500/20"><div className="flex justify-between"><span>Descuento</span><span>-${pricing.discount.toLocaleString()}</span></div></div>}
            </div>
          </div>

          <div className="flex-1 overflow-y-auto min-h-0 flex flex-col gap-4 pr-1 custom-scrollbar">
            <div className="bg-white rounded-2xl border border-slate-200 p-2.5 flex flex-col gap-2 shadow-sm flex-shrink-0">
              <div className="flex justify-between items-center px-1">
                <div className="flex bg-slate-100 rounded-lg p-1 gap-1">
                  {['left', 'center', 'right', 'justify'].map(align => (
                    <button key={align} onClick={() => setOptions({ ...options, alignment: align })} className={clsx("p-1.5 rounded-md hover:bg-white transition-all", options.alignment === align && "bg-white text-blue-600 shadow-sm")}>
                      {align === 'left' && <AlignLeft size={14} />}{align === 'center' && <AlignCenter size={14} />}{align === 'right' && <AlignRight size={14} />}{align === 'justify' && <AlignJustify size={14} />}
                    </button>
                  ))}
                </div>
                <div className="flex bg-slate-100 rounded-lg p-1 gap-1">
                  {['small', 'normal', 'large'].map(size => (
                    <button key={size} onClick={() => setOptions({ ...options, fontSize: size })} className={clsx("p-1.5 rounded-md hover:bg-white transition-all flex items-end", options.fontSize === size && "bg-white text-blue-600 shadow-sm")}>
                      <Type size={size === 'small' ? 10 : size === 'normal' ? 14 : 18} />
                    </button>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2 mt-1">
                <button onClick={() => setOptions({ ...options, isBold: !options.isBold })} className={clsx("p-2 rounded-lg border text-[9px] font-black transition-all flex items-center justify-center gap-2", options.isBold ? "bg-blue-600 border-blue-600 text-white" : "bg-slate-50 border-slate-200 text-slate-400 hover:bg-slate-100")}><Bold size={12} /> NEGRITA</button>
                <button onClick={() => setOptions({ ...options, isFrame: !options.isFrame })} className={clsx("p-2 rounded-lg border text-[9px] font-black transition-all flex items-center justify-center gap-2", options.isFrame ? "bg-slate-800 border-slate-800 text-white" : "bg-slate-50 border-slate-200 text-slate-400 hover:bg-slate-100")}><FrameIcon size={12} /> RECUADRO</button>
              </div>
            </div>

            <div className="bg-[#fffef5] border border-yellow-200 rounded-2xl p-4 shadow-sm min-h-[140px] h-auto flex flex-col relative group flex-shrink-0">
              <div className="absolute top-0 left-0 w-full h-0.5 bg-yellow-400 opacity-20"></div>
              <h3 className="text-[8px] font-black text-yellow-700/60 uppercase mb-3 flex items-center gap-1.5 tracking-widest"><Printer size={10} /> Previsualización Real</h3>
              <div className="p-1">
                <div className={clsx("w-full leading-tight whitespace-pre-wrap break-words transition-all duration-300", options.isBold ? "font-bold text-slate-900" : "font-medium text-slate-700", options.isFrame ? "border-2 border-slate-900 p-3 bg-white shadow-sm" : "border-none", options.fontSize === 'small' ? 'text-[11px]' : options.fontSize === 'large' ? 'text-base' : 'text-xs', options.alignment === 'center' ? 'text-center' : options.alignment === 'right' ? 'text-right' : options.alignment === 'justify' ? 'text-justify' : 'text-left')}>
                  {formData.text || "(Aviso vacío)"}
                </div>
              </div>
            </div>
          </div>

          <button onClick={handleSubmit} className="bg-blue-600 hover:bg-blue-700 text-white py-4 rounded-2xl font-black shadow-xl flex flex-col items-center justify-center transition-all active:scale-95 group overflow-hidden flex-shrink-0">
            <div className="flex items-center gap-3 text-lg relative z-10"><Save size={20} /> COBRAR E IMPRIMIR</div>
            <span className="text-[8px] opacity-60 tracking-[0.3em] relative z-10 font-mono mt-0.5">SHORTCUT: F10</span>
          </button>
        </div>

        {showPaymentModal && (
          <PaymentModal totalAmount={pricing.totalPrice} onConfirm={handlePaymentConfirm} onCancel={() => setShowPaymentModal(false)} />
        )}
      </motion.div>
    </>
  );
}