'use client';

import MainLayout from '@/components/layout/MainLayout';
import ModalPortal from '@/components/common/ModalPortal';
import { useState, useEffect, useCallback } from 'react';
import * as XLSX from 'xlsx';

type Product = {
  id: string;
  code: string;
  name: string;
  tariffCode?: string;
  htsCode?: string;
  nandina?: string;
  dutyRate?: number;
  declaredValue?: number;
  country?: string;
  originCity?: string;
  service?: string;
  productType?: string;
  packType?: string;
  boxType?: string;
  length?: number;
  width?: number;
  height?: number;
  dimWeight?: number;
  realWeight?: number;
  recipeFormat?: string;
  recipes?: RecipeRow[];
};

type HtsProduct = {
  id: string;
  name: string;
  htsCode: string;
  nandina: string;
  dutyRate: number;
  costPerStem?: number | null;
};

type BoxTypeData = {
  id: number;
  code: string;
  name: string;
  length?: number | null;
  width?: number | null;
  height?: number | null;
  dimWeight?: number | null;
  realWeight?: number | null;
};

type CityFilter = {
  id: number;
  city: string;
  state?: string | null;
  country: string;
};

type FlowerColor = {
  id: number;
  code: string;
  name: string;
};

type Farm = {
  id: string;
  name: string;
  farmCode?: string;
};

type RecipeRow = {
  id: string; // local temp id or DB id
  quantity?: string | null;
  pack?: string | null;
  productList?: string | null;
  length?: string | null;
  hts?: string | null;
  nandina?: string | null;
  color?: string | null;
  stemValueDeclared?: string | null;
  totalValue?: string | null;
  dclValue?: string | null;
};

const emptyForm = {
  code: '', name: '', htsCategory: '', htsCode: '', nandina: '', tariffCode: '',
  dutyRate: '', declaredValue: '', country: 'EC', originCity: '',
  service: 'ES', productType: 'GENERICO', packType: 'CP', boxType: '',
  length: '', width: '', height: '', dimWeight: '', realWeight: '',
  farmId: '', recipeFormat: 'Bouquet', stems: '0',
};

const emptyRecipeRow: Omit<RecipeRow, 'id'> = {
  quantity: '', pack: '', productList: '', length: '', hts: '', nandina: '',
  color: '', stemValueDeclared: '', totalValue: '', dclValue: '',
};

const SERVICES = ['ES', 'SV', 'EP'];
const PRODUCT_TYPES = ['GENERICO', 'EXCLUSIVO'];

const LENGTHS = [
  '50 CM','60 CM','70 CM','80 CM','90 CM',
  '20 CM','30 CM','40 CM','24 CM','35 CM',
  'N/A','2-3 BLOOMS','3-5 BLOOMS','SELECT','FANCY','JUMBO','MINI','BAG 400 GR.',
];

function truncate35(str: string) {
  return str.substring(0, 35);
}

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [htsCatalog, setHtsCatalog] = useState<HtsProduct[]>([]);
  const [boxTypes, setBoxTypes] = useState<BoxTypeData[]>([]);
  const [cities, setCities] = useState<CityFilter[]>([]);
  const [colors, setColors] = useState<FlowerColor[]>([]);
  const [farms, setFarms] = useState<Farm[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [showDeleteAllModal, setShowDeleteAllModal] = useState(false);
  const [deleteAllConfirm, setDeleteAllConfirm] = useState('');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [nameTooLong, setNameTooLong] = useState(false);
  const [recipeFilter, setRecipeFilter] = useState<'ALL' | 'NO_RECIPE'>('ALL');

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search);
      if (params.get('filter') === 'no-recipe') {
        setRecipeFilter('NO_RECIPE');
      }
    }
  }, []);

  // Recipe sub-modal
  const [showRecipeModal, setShowRecipeModal] = useState(false);
  const [recipes, setRecipes] = useState<RecipeRow[]>([]);
  const [recipeForm, setRecipeForm] = useState<Omit<RecipeRow, 'id'>>(emptyRecipeRow);
  const [editingRecipeId, setEditingRecipeId] = useState<string | null>(null);

  const [form, setForm] = useState(emptyForm);

  const fetchAll = useCallback(async () => {
    setLoading(true);
    try {
      const [resProd, resHts, resBox, resCities, resFarms, resColors] = await Promise.all([
        fetch('/api/products'),
        fetch('/api/parametros/hts'),
        fetch('/api/parametros/boxtype'),
        fetch('/api/parametros/cities'),
        fetch('/api/farms'),
        fetch('/api/parametros/colors'),
      ]);
      if (resProd.ok) setProducts(await resProd.json());
      if (resHts.ok) setHtsCatalog(await resHts.json());
      if (resBox.ok) setBoxTypes(await resBox.json());
      if (resCities.ok) setCities(await resCities.json());
      if (resFarms.ok) setFarms(await resFarms.json());
      if (resColors.ok) setColors(await resColors.json());
    } catch (e) { console.error(e); }
    setLoading(false);
  }, []);

  useEffect(() => { fetchAll(); }, [fetchAll]);

  // Unique countries from cities
  const countries = Array.from(new Set(cities.map(c => c.country))).sort();
  // Cities filtered by selected country
  const filteredCities = cities.filter(c => c.country === form.country);

  const openNew = () => {
    setForm(emptyForm);
    setEditingId(null);
    setError(null);
    setNameTooLong(false);
    setRecipes([]);
    setShowModal(true);
  };

  const openEdit = (p: Product) => {
    // Load saved recipes from the product
    const recs = (p.recipes && p.recipes.length > 0)
      ? p.recipes.map(r => ({ ...r, id: r.id || Date.now().toString() }))
      : [];
    setRecipes(recs);

    const totalStems = recs.reduce((sum, r) => {
      const q = parseFloat(r.quantity || '0') || 0;
      const pk = parseFloat(r.pack || '0') || 0;
      return sum + (q * pk);
    }, 0);
    const firstHts = recs.find(r => r.hts?.trim())?.hts?.trim() || '';
    const firstNandina = recs.find(r => r.nandina?.trim())?.nandina?.trim() || '';

    setForm({
      code: p.code, name: p.name,
      htsCategory: '',
      tariffCode: p.tariffCode || '',
      htsCode: firstHts || p.htsCode || '',
      nandina: firstNandina || p.nandina || '',
      dutyRate: p.dutyRate?.toString() || '', declaredValue: p.declaredValue?.toString() || '',
      country: p.country || 'EC', originCity: p.originCity || '', service: p.service || 'ES',
      productType: p.productType || 'GENERICO', packType: p.packType || 'CP', boxType: p.boxType || '',
      length: p.length?.toString() || '', width: p.width?.toString() || '', height: p.height?.toString() || '',
      dimWeight: p.dimWeight?.toString() || '', realWeight: p.realWeight?.toString() || '',
      farmId: '', recipeFormat: p.recipeFormat || 'Bouquet',
      stems: totalStems > 0 ? totalStems.toString() : '0',
    });
    setEditingId(p.id);
    setError(null);
    setNameTooLong(false);
    setShowModal(true);
  };

  const handleNameChange = (val: string) => {
    setNameTooLong(val.length > 35);
    setForm(f => ({ ...f, name: val }));
  };

  const handleBoxTypeChange = (code: string) => {
    const bt = boxTypes.find(b => b.code === code);
    if (bt) {
      setForm(f => ({
        ...f,
        boxType: code,
        length: bt.length?.toString() || f.length,
        width: bt.width?.toString() || f.width,
        height: bt.height?.toString() || f.height,
        dimWeight: bt.dimWeight?.toString() || f.dimWeight,
        realWeight: bt.realWeight?.toString() || f.realWeight,
      }));
    } else {
      setForm(f => ({ ...f, boxType: code }));
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.name.length > 35) {
      setError('El nombre del producto no puede exceder 35 caracteres para cumplir con FedEx/UPS.');
      return;
    }
    setSaving(true);
    setError(null);
    try {
      const payload = { ...form, recipes };
      const url = editingId ? `/api/products/${editingId}` : '/api/products';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al guardar'); }
      setShowModal(false);
      setForm(emptyForm);
      setEditingId(null);
      setRecipes([]);
      fetchAll();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Error al guardar');
    }
    setSaving(false);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('¿Seguro que deseas eliminar este producto?')) return;
    setDeletingId(id);
    try {
      const res = await fetch(`/api/products/${id}`, { method: 'DELETE' });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al eliminar'); }
      fetchAll();
    } catch (err: unknown) { alert(err instanceof Error ? err.message : 'Error'); }
    setDeletingId(null);
  };

  const handleDeleteAll = async () => {
    if (deleteAllConfirm.toLowerCase() !== 'borrar') return;
    setSaving(true);
    try {
      const res = await fetch('/api/products/clear', { method: 'DELETE' });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error al limpiar la tabla'); }
      setShowDeleteAllModal(false);
      setDeleteAllConfirm('');
      fetchAll();
    } catch (err: unknown) { alert(err instanceof Error ? err.message : 'Error'); }
    setSaving(false);
  };

  const handleExport = () => {
    const data = filtered.map(p => ({
      'Item Code': p.code, 'Nombre / Descripción': p.name, 'HTS Code': p.htsCode || '',
      'NANDINA': p.nandina || '', 'Duty Rate (%)': p.dutyRate || '', 'Declared Value ($)': p.declaredValue || '',
      'País': p.country || '', 'Ciudad Origen': p.originCity || '', 'Servicio': p.service || '',
      'Tipo de Producto': p.productType || '', 'Tipo Empaque': p.packType || '', 'Tipo Caja': p.boxType || '',
      'Largo (cm)': p.length || '', 'Ancho (cm)': p.width || '', 'Alto (cm)': p.height || '',
      'Dim Weight (Kg)': p.dimWeight || '', 'Real Weight (Kg)': p.realWeight || '',
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Productos');
    XLSX.writeFile(wb, 'productos_usfloral.xlsx');
  };

  // ── Recipe Modal handlers ──────────────────────────────────────────
  const openAddRecipe = () => {
    setRecipeForm(emptyRecipeRow);
    setEditingRecipeId(null);
    setShowRecipeModal(true);
  };

  const openEditRecipe = (r: RecipeRow) => {
    setRecipeForm({
      quantity: r.quantity, pack: r.pack, productList: r.productList,
      length: r.length, hts: r.hts, nandina: r.nandina, color: r.color,
      stemValueDeclared: r.stemValueDeclared, totalValue: r.totalValue, dclValue: r.dclValue,
    });
    setEditingRecipeId(r.id);
    setShowRecipeModal(true);
  };

  const handleRecipeChange = (field: keyof Omit<RecipeRow, 'id'>, value: string) => {
    setRecipeForm(f => {
      const updated = { ...f, [field]: value };
      
      // Calculate totals if quantity, pack, or stem changes
      if (['quantity', 'pack', 'stemValueDeclared'].includes(field)) {
        const qty = parseFloat(updated.quantity || '') || 0;
        const pack = parseFloat(updated.pack || '') || 0;
        const stem = parseFloat(updated.stemValueDeclared || '') || 0;
        const computedTotal = (qty * pack * stem).toFixed(2);
        updated.totalValue = computedTotal;
        updated.dclValue = computedTotal;
      }
      
      return updated;
    });
  };

  const updateFormTotals = (currentRecipes: RecipeRow[], format: string) => {
    const totalDcl = currentRecipes.reduce((sum, r) => sum + (parseFloat(r.dclValue || '') || 0), 0);
    let totalPack = 0;
    if (format === 'ComboBox') {
      totalPack = currentRecipes.reduce((sum, r) => sum + (parseFloat(r.pack || '') || 0), 0);
    } else {
      totalPack = currentRecipes.length > 0 ? (parseFloat(currentRecipes[0].pack || '') || 0) : 0;
    }
    const totalStems = currentRecipes.reduce((sum, r) => {
      const q = parseFloat(r.quantity || '0') || 0;
      const pk = parseFloat(r.pack || '0') || 0;
      return sum + (q * pk);
    }, 0);

    const firstHts = currentRecipes.find(r => r.hts?.trim())?.hts?.trim() || '';
    const firstNandina = currentRecipes.find(r => r.nandina?.trim())?.nandina?.trim() || '';

    setForm(f => ({
      ...f,
      declaredValue: totalDcl.toFixed(2),
      packType: totalPack.toString(),
      stems: totalStems.toString(),
      htsCode: firstHts || f.htsCode,
      nandina: firstNandina || f.nandina,
    }));
  };

  const handleInsertRecipe = () => {
    if (!recipeForm.quantity || !recipeForm.productList) return;
    
    const qty = parseFloat(recipeForm.quantity || '') || 0;
    const pack = parseFloat(recipeForm.pack || '') || 0;
    const stem = parseFloat(recipeForm.stemValueDeclared || '') || 0;
    const computedTotal = (qty * pack * stem).toFixed(2);
    
    const rowToInsert = { 
      ...recipeForm, 
      totalValue: recipeForm.totalValue || computedTotal,
      dclValue: recipeForm.dclValue || computedTotal,
      id: editingRecipeId || Date.now().toString() 
    };

    let newRecipes;
    if (editingRecipeId) {
      newRecipes = recipes.map(r => r.id === editingRecipeId ? rowToInsert : r);
    } else {
      newRecipes = [...recipes, rowToInsert];
    }
    
    setRecipes(newRecipes);
    updateFormTotals(newRecipes, form.recipeFormat);
    setRecipeForm(emptyRecipeRow);
    setEditingRecipeId(null);
  };

  const handleDeleteRecipe = (id: string) => {
    const newRecipes = recipes.filter(r => r.id !== id);
    setRecipes(newRecipes);
    updateFormTotals(newRecipes, form.recipeFormat);
  };

  const noRecipeCount = products.filter(p => !p.recipes || p.recipes.length === 0).length;

  const filtered = products.filter(p => {
    if (recipeFilter === 'NO_RECIPE' && (p.recipes && p.recipes.length > 0)) {
      return false;
    }
    const s = search.toLowerCase();
    const recipeHts = p.recipes?.find(r => r.hts?.trim())?.hts || '';
    return p.name.toLowerCase().includes(s) ||
      p.code.toLowerCase().includes(s) ||
      (p.htsCode || '').toLowerCase().includes(s) ||
      recipeHts.toLowerCase().includes(s) ||
      (p.recipeFormat || '').toLowerCase().includes(s);
  });

  const labelStyle: React.CSSProperties = {
    display: 'block', fontSize: '0.72rem', fontWeight: 700,
    marginBottom: '0.35rem', color: 'var(--primary-color)',
    textTransform: 'uppercase', letterSpacing: '0.05em'
  };
  const selectStyle: React.CSSProperties = {
    width: '100%', padding: '0.625rem 0.875rem',
    border: '1.5px solid var(--border-color)', borderRadius: 'var(--radius-md)',
    fontSize: '0.875rem', background: 'white', color: 'var(--text-primary)',
  };

  return (
    <MainLayout>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '2rem', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h1>Catálogo de Productos</h1>
          <p className="page-subtitle">Gestión de items, tarifas arancelarias, HTS y medidas.</p>
        </div>
        <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
          <button className="btn-secondary" style={{ color: '#dc2626', borderColor: '#fca5a5' }} onClick={() => setShowDeleteAllModal(true)}>
            Borrar Todos
          </button>
          <button className="btn-secondary" onClick={handleExport}>Exportar Excel</button>
          <button className="btn-primary" onClick={openNew}>+ Nuevo Producto</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: '1rem', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', justifyContent: 'space-between' }}>
        <input placeholder="Buscar por Item Code, Nombre, HTS Code o Formato..." value={search}
          onChange={(e) => setSearch(e.target.value)} style={{ maxWidth: '420px', flex: 1, minWidth: '260px' }} />

        <div style={{ display: 'flex', gap: '0.4rem', background: '#f1f5f9', padding: '0.25rem', borderRadius: '8px' }}>
          <button
            type="button"
            onClick={() => { setRecipeFilter('ALL'); setSearch(''); }}
            style={{
              padding: '0.4rem 0.9rem',
              borderRadius: '6px',
              border: 'none',
              background: recipeFilter === 'ALL' ? '#1c5236' : 'transparent',
              color: recipeFilter === 'ALL' ? '#fff' : '#475569',
              fontWeight: 700,
              fontSize: '0.82rem',
              cursor: 'pointer'
            }}
          >
            Todos ({products.length})
          </button>
          <button
            type="button"
            onClick={() => { setRecipeFilter('NO_RECIPE'); setSearch(''); }}
            style={{
              padding: '0.4rem 0.9rem',
              borderRadius: '6px',
              border: 'none',
              background: recipeFilter === 'NO_RECIPE' ? '#dc2626' : 'transparent',
              color: recipeFilter === 'NO_RECIPE' ? '#fff' : '#dc2626',
              fontWeight: 700,
              fontSize: '0.82rem',
              cursor: 'pointer'
            }}
          >
            ⚠️ Sin Recetas ({noRecipeCount})
          </button>
        </div>
      </div>

      {recipeFilter === 'NO_RECIPE' && (
        <div style={{
          padding: '0.75rem 1rem',
          background: '#fef2f2',
          border: '1px solid #fecaca',
          borderRadius: '8px',
          marginBottom: '1rem',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '0.5rem'
        }}>
          <span style={{ fontSize: '0.85rem', color: '#991b1b', fontWeight: 600 }}>
            ⚠️ Mostrando {filtered.length} de {noRecipeCount} producto(s) sin recetas configuradas.
          </span>
          {search && (
            <button
              onClick={() => setSearch('')}
              style={{ fontSize: '0.75rem', padding: '0.25rem 0.6rem', background: '#fff', border: '1px solid #dc2626', color: '#dc2626', borderRadius: '4px', cursor: 'pointer', fontWeight: 700 }}
            >
              Mostrar todos los sin receta
            </button>
          )}
        </div>
      )}

      <div className="table-container">
        <table>
          <thead>
            <tr>
              <th>Código (Item)</th>
              <th>Formato</th>
              <th>Descripción</th>
              <th>HTS Code</th>
              <th>Box Type</th>
              <th>Caja (LxWxH)</th>
              <th>Peso Real</th>
              <th>Tipo</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>Cargando...</td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>
                {search ? (
                  <div>
                    <p style={{ margin: 0, fontSize: '0.95rem' }}>
                      No se encontraron resultados para &ldquo;<strong>{search}</strong>&rdquo; {recipeFilter === 'NO_RECIPE' ? 'en productos sin receta.' : '.'}
                    </p>
                    <div style={{ marginTop: '0.85rem', display: 'flex', gap: '0.5rem', justifyContent: 'center' }}>
                      <button
                        type="button"
                        onClick={() => setSearch('')}
                        style={{ padding: '0.35rem 0.85rem', background: '#64748b', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontSize: '0.8rem', fontWeight: 700 }}
                      >
                        Limpiar búsqueda
                      </button>
                      {recipeFilter === 'NO_RECIPE' && (
                        <button
                          type="button"
                          onClick={() => setRecipeFilter('ALL')}
                          style={{ padding: '0.35rem 0.85rem', background: 'var(--primary-color)', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontSize: '0.8rem', fontWeight: 700 }}
                        >
                          Buscar en Todos los Productos
                        </button>
                      )}
                    </div>
                  </div>
                ) : recipeFilter === 'NO_RECIPE' ? (
                  <div>
                    <p style={{ fontSize: '1rem', color: '#15803d', fontWeight: 700, marginBottom: '0.5rem' }}>
                      🎉 ¡Excelente! Todos los productos registrados tienen recetas configuradas.
                    </p>
                    <button
                      type="button"
                      onClick={() => setRecipeFilter('ALL')}
                      style={{ padding: '0.35rem 0.85rem', background: 'var(--primary-color)', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontSize: '0.8rem', fontWeight: 700 }}
                    >
                      Ver catálogo completo ({products.length})
                    </button>
                  </div>
                ) : 'No hay productos registrados.'}
              </td></tr>
            ) : filtered.map(p => {
              const displayHts = p.recipes?.find(r => r.hts?.trim())?.hts || p.htsCode || '—';
              const isCombo = p.recipeFormat === 'ComboBox';
              const hasNoRecipe = !p.recipes || p.recipes.length === 0;

              return (
                <tr key={p.id}>
                  <td style={{ fontWeight: 600, color: 'var(--primary-color)' }}>{p.code}</td>
                  <td>
                    <span style={{
                      padding: '0.15rem 0.5rem',
                      borderRadius: '12px',
                      fontSize: '0.72rem',
                      fontWeight: 700,
                      background: isCombo ? '#ede9fe' : '#f0fdf4',
                      color: isCombo ? '#6d28d9' : '#15803d',
                      border: `1px solid ${isCombo ? '#c4b5fd' : '#bbf7d0'}`
                    }}>
                      {isCombo ? 'ComboBox' : 'Bouquet'}
                    </span>
                    {hasNoRecipe && (
                      <span style={{
                        display: 'block',
                        marginTop: '0.25rem',
                        fontSize: '0.68rem',
                        color: '#dc2626',
                        fontWeight: 700
                      }}>
                        ⚠️ Sin receta
                      </span>
                    )}
                  </td>
                  <td style={{ maxWidth: '200px' }}>
                    <span title={p.name}>{p.name}</span>
                    {p.name.length > 35 && <span style={{ marginLeft: 4, color: '#dc2626', fontSize: '0.7rem' }}>⚠ +35</span>}
                  </td>
                  <td><code style={{ fontSize: '0.8rem', background: '#f1f5f9', padding: '0.1rem 0.4rem', borderRadius: '4px' }}>{displayHts}</code></td>
                  <td><span style={{ fontSize: '0.8rem', fontWeight: 600 }}>{p.boxType || '—'}</span></td>
                  <td style={{ fontSize: '0.85rem' }}>
                    {p.length && p.width && p.height ? `${p.length}x${p.width}x${p.height} cm` : '—'}
                  </td>
                  <td>{p.realWeight ? `${p.realWeight} Kg` : '—'}</td>
                  <td>
                    <span style={{ padding: '0.15rem 0.5rem', borderRadius: '12px', fontSize: '0.72rem', fontWeight: 700,
                      background: p.productType === 'EXCLUSIVO' ? '#fef3c7' : '#eff6ff',
                      color: p.productType === 'EXCLUSIVO' ? '#d97706' : '#1d4ed8' }}>
                      {p.productType || 'GENERICO'}
                    </span>
                  </td>
                  <td>
                    <div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
                      {hasNoRecipe ? (
                        <button
                          type="button"
                          className="btn-primary"
                          style={{ padding: '0.25rem 0.75rem', fontSize: '0.75rem', background: '#dc2626', borderColor: '#b91c1c' }}
                          onClick={() => openEdit(p)}
                        >
                          + Crear Receta
                        </button>
                      ) : (
                        <button className="btn-secondary" style={{ padding: '0.25rem 0.75rem', fontSize: '0.75rem' }} onClick={() => openEdit(p)}>Editar</button>
                      )}
                      <button className="btn-secondary"
                        style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem', color: '#dc2626', borderColor: '#fca5a5' }}
                        onClick={() => handleDelete(p.id)} disabled={deletingId === p.id}>
                        {deletingId === p.id ? '...' : '🗑'}
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* ──────── Delete All Modal ──────── */}
      {showDeleteAllModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '400px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)' }}>
              <h2 style={{ color: '#dc2626', fontWeight: 700, marginBottom: '1rem' }}>Borrar Todos los Productos</h2>
              <p style={{ fontSize: '0.9rem', marginBottom: '1rem', color: 'var(--text-secondary)' }}>
                Escribe <strong>borrar</strong> para confirmar:
              </p>
              <input type="text" className="input-field" placeholder="Escribe 'borrar'" value={deleteAllConfirm}
                onChange={(e) => setDeleteAllConfirm(e.target.value)} style={{ marginBottom: '1.5rem', width: '100%' }} />
              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
                <button className="btn-secondary" onClick={() => setShowDeleteAllModal(false)}>Cancelar</button>
                <button className="btn-primary" style={{ background: '#dc2626', borderColor: '#dc2626' }}
                  disabled={deleteAllConfirm.toLowerCase() !== 'borrar' || saving} onClick={handleDeleteAll}>
                  {saving ? 'Borrando...' : 'Borrar Todos'}
                </button>
              </div>
            </div>
          </div>
        </ModalPortal>
      )}

      {/* ──────── Recipe Sub-Modal (wide split: form left, table right) ──────── */}
      {showRecipeModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
          <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', width: '100%', maxWidth: '1100px', boxShadow: '0 30px 60px rgba(0,0,0,0.35)', animation: 'slideUp 0.3s ease', maxHeight: '92vh', display: 'flex', flexDirection: 'column' }}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '1.25rem 1.5rem', borderBottom: '1px solid var(--border-color)', background: 'linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%)', borderRadius: 'var(--radius-lg) var(--radius-lg) 0 0' }}>
              <h3 style={{ color: 'white', fontWeight: 700, fontSize: '1.1rem', margin: 0 }}>📋 Crear Receta del Producto</h3>
              <button onClick={() => { setShowRecipeModal(false); setRecipeForm(emptyRecipeRow); setEditingRecipeId(null); }} style={{ color: 'white', fontSize: '1.5rem', lineHeight: 1, background: 'none', border: 'none', cursor: 'pointer', opacity: 0.8 }}>×</button>
            </div>

            {/* Body: two columns */}
            <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 0, flex: 1, overflow: 'hidden' }}>
              {/* Left: Form */}
              <div style={{ padding: '1.25rem', borderRight: '1px solid var(--border-color)', overflowY: 'auto', background: '#f8fafc' }}>
                <p style={{ fontSize: '0.7rem', fontWeight: 700, color: '#1d4ed8', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '1rem' }}>
                  {editingRecipeId ? '✏️ Editando Línea' : '➕ Nueva Línea'}
                </p>

                {/* Formato de Receta (Bouquet / ComboBox) */}
                <div style={{ marginBottom: '1rem' }}>
                  <label style={{ ...labelStyle, color: '#1d4ed8' }}>Formato del Producto</label>
                  <select
                    style={{ ...selectStyle, borderColor: '#93c5fd' }}
                    value={form.recipeFormat}
                    onChange={e => {
                      const newFormat = e.target.value;
                      setForm(f => ({ ...f, recipeFormat: newFormat }));
                      updateFormTotals(recipes, newFormat);
                    }}
                  >
                    <option value="Bouquet">Bouquet</option>
                    <option value="ComboBox">ComboBox</option>
                  </select>
                </div>

                {/* Cantidad + Pack */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>Cantidad</label>
                    <input className="input-field" type="number" placeholder="0" value={recipeForm.quantity || ''}
                      onChange={e => handleRecipeChange('quantity', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>Pack</label>
                    <input className="input-field" type="number" placeholder="0" value={recipeForm.pack || ''}
                      onChange={e => handleRecipeChange('pack', e.target.value)} />
                  </div>
                </div>

                {/* Lista de Productos (HTS Dropdown) */}
                <div style={{ marginBottom: '0.75rem' }}>
                  <label style={{ ...labelStyle, color: '#1d4ed8' }}>Lista de Productos</label>
                  <select
                    style={{ ...selectStyle, borderColor: '#93c5fd' }}
                    value={recipeForm.productList || ''}
                    onChange={e => {
                      const selectedName = e.target.value;
                      const entry = htsCatalog.find(h => h.name === selectedName);
                      
                      setRecipeForm(f => {
                        const updated = {
                          ...f,
                          productList: selectedName,
                          hts: entry?.htsCode || f.hts,
                          nandina: entry?.nandina || f.nandina,
                          stemValueDeclared: entry?.costPerStem?.toString() || f.stemValueDeclared,
                        };
                        
                        const qty = parseFloat(updated.quantity || '') || 0;
                        const pack = parseFloat(updated.pack || '') || 0;
                        const stem = parseFloat(updated.stemValueDeclared || '') || 0;
                        const computedTotal = (qty * pack * stem).toFixed(2);
                        updated.totalValue = computedTotal;
                        updated.dclValue = computedTotal;
                        
                        return updated;
                      });
                    }}
                  >
                    <option value="">— Seleccionar producto —</option>
                    {htsCatalog.map(h => (
                      <option key={h.id} value={h.name}>{h.name}</option>
                    ))}
                  </select>
                </div>

                {/* Longitud */}
                <div style={{ marginBottom: '0.75rem' }}>
                  <label style={{ ...labelStyle, color: '#1d4ed8' }}>Longitud</label>
                  <select
                    style={{ ...selectStyle, borderColor: '#93c5fd' }}
                    value={recipeForm.length || ''}
                    onChange={e => setRecipeForm(f => ({ ...f, length: e.target.value }))}
                  >
                    <option value="">— Seleccionar longitud —</option>
                    {LENGTHS.map(l => <option key={l} value={l}>{l}</option>)}
                  </select>
                </div>

                {/* Color */}
                <div style={{ marginBottom: '0.75rem' }}>
                  <label style={{ ...labelStyle, color: '#1d4ed8' }}>Color</label>
                  <select
                    style={{ ...selectStyle, borderColor: '#93c5fd' }}
                    value={recipeForm.color || ''}
                    onChange={e => handleRecipeChange('color', e.target.value)}
                  >
                    <option value="">— Seleccionar color —</option>
                    {colors.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
                  </select>
                </div>

                {/* HTS + Nandina (auto-filled, editable) */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>HTS</label>
                    <input className="input-field" placeholder="Auto" style={{ fontFamily: 'monospace', fontSize: '0.82rem' }} value={recipeForm.hts || ''}
                      onChange={e => setRecipeForm(f => ({ ...f, hts: e.target.value }))} />
                  </div>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>Nandina</label>
                    <input className="input-field" placeholder="Auto" style={{ fontFamily: 'monospace', fontSize: '0.82rem' }} value={recipeForm.nandina || ''}
                      onChange={e => setRecipeForm(f => ({ ...f, nandina: e.target.value }))} />
                  </div>
                </div>

                {/* Stem/Value + DclValue + Total */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '1.25rem' }}>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>Stem/Val Declared</label>
                    <input className="input-field" type="number" step="0.01" placeholder="0.00" value={recipeForm.stemValueDeclared || ''}
                      onChange={e => handleRecipeChange('stemValueDeclared', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ ...labelStyle, color: '#1d4ed8' }}>DclValue</label>
                    <input className="input-field" type="number" step="0.01" placeholder="0.00" value={recipeForm.dclValue || ''}
                      onChange={e => handleRecipeChange('dclValue', e.target.value)} />
                  </div>
                </div>
                <div style={{ marginBottom: '1.25rem' }}>
                  <label style={{ ...labelStyle, color: '#1d4ed8' }}>Valor Total</label>
                  <input className="input-field" type="number" step="0.01" placeholder="0.00" value={recipeForm.totalValue || ''}
                    onChange={e => handleRecipeChange('totalValue', e.target.value)} />
                </div>

                <div style={{ display: 'flex', gap: '0.75rem' }}>
                  <button className="btn-secondary" style={{ flex: 1, fontSize: '0.82rem' }} onClick={() => { setRecipeForm(emptyRecipeRow); setEditingRecipeId(null); }}>🔄 Limpiar</button>
                  <button className="btn-primary" style={{ flex: 2, fontSize: '0.82rem' }} onClick={handleInsertRecipe}>
                    {editingRecipeId ? '✅ Actualizar' : '➕ Insertar'}
                  </button>
                </div>
              </div>

              {/* Right: Table of current recipe lines */}
              <div style={{ padding: '1.25rem', overflowY: 'auto' }}>
                <p style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--primary-color)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.75rem' }}>
                  📄 Líneas de Receta ({recipes.length})
                </p>
                {recipes.length === 0 ? (
                  <div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-secondary)', border: '2px dashed var(--border-color)', borderRadius: 'var(--radius-md)', fontSize: '0.85rem' }}>
                    Aún no hay líneas. Completa el formulario y haz clic en Insertar.
                  </div>
                ) : (
                  <div style={{ overflowX: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.75rem' }}>
                      <thead>
                        <tr style={{ background: '#1d4ed8', color: 'white' }}>
                          {['#','Qty','Pack','Total Stems','Producto','Long.','HTS','Nandina','Color','Stem/Val','Total','Dcl','',''].map((h, i) => (
                            <th key={i} style={{ padding: '0.4rem 0.5rem', fontWeight: 700, textAlign: 'left', whiteSpace: 'nowrap' }}>{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {recipes.map((r, idx) => {
                          const itemStems = ((parseFloat(r.quantity || '0') || 0) * (parseFloat(r.pack || '0') || 0));
                          return (
                            <tr key={r.id} style={{ borderTop: '1px solid var(--border-color)', background: editingRecipeId === r.id ? '#eff6ff' : idx % 2 === 0 ? 'white' : '#f8fafc' }}>
                              <td style={{ padding: '0.35rem 0.5rem', color: '#6b7280', fontWeight: 600 }}>{idx + 1}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.quantity}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.pack}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontWeight: 700, color: '#15803d', textAlign: 'center' }}>
                                {itemStems > 0 ? itemStems : '—'}
                              </td>
                              <td style={{ padding: '0.35rem 0.5rem', fontWeight: 600 }}>{r.productList}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.length}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontFamily: 'monospace' }}>{r.hts}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontFamily: 'monospace' }}>{r.nandina}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.color}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.stemValueDeclared}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.totalValue}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.dclValue}</td>
                              <td style={{ padding: '0.35rem 0.25rem' }}>
                                <button type="button" title="Editar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#3b82f6', fontSize: '0.9rem' }} onClick={() => openEditRecipe(r)}>✏️</button>
                              </td>
                              <td style={{ padding: '0.35rem 0.25rem' }}>
                                <button type="button" title="Eliminar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#dc2626', fontSize: '0.9rem' }} onClick={() => handleDeleteRecipe(r.id)}>🗑</button>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>

            {/* Footer */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', padding: '1rem 1.5rem', borderTop: '1px solid var(--border-color)' }}>
              <button className="btn-secondary" onClick={() => { setShowRecipeModal(false); setRecipeForm(emptyRecipeRow); setEditingRecipeId(null); }}>Cerrar y Guardar</button>
            </div>
          </div>
        </div>
        </ModalPortal>
      )}

      {/* ──────── Product Modal ──────── */}
      {showModal && (
        <ModalPortal>
          <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
          <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '760px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease', maxHeight: '92vh', overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
              <h2 style={{ color: 'var(--primary-color)', fontSize: '1.25rem', fontWeight: 700 }}>{editingId ? 'Editar Producto' : 'Nuevo Producto'}</h2>
              <button onClick={() => setShowModal(false)} style={{ color: 'var(--text-secondary)', fontSize: '1.5rem', lineHeight: 1 }}>×</button>
            </div>

            <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>

              {/* Code + Name */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>Item (Código) *</label>
                  <input required placeholder="Ej: 1137452" value={form.code}
                    onChange={e => setForm(f => ({ ...f, code: e.target.value }))} />
                  <small style={{ color: 'var(--text-secondary)', fontSize: '0.7rem' }}>Máx. 14 caracteres</small>
                </div>
                <div>
                  <label style={labelStyle}>Nombre del Producto *</label>
                  <input
                    required
                    placeholder="Ej: Freedom Rose 50cm PK200"
                    value={form.name}
                    onChange={e => handleNameChange(e.target.value)}
                    style={{ borderColor: nameTooLong ? '#dc2626' : undefined, outline: nameTooLong ? '2px solid #dc2626' : undefined }}
                  />
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <small style={{ color: nameTooLong ? '#dc2626' : 'var(--text-secondary)', fontSize: '0.7rem', fontWeight: nameTooLong ? 700 : 400 }}>
                      {form.name.length}/35 caracteres {nameTooLong ? '⚠ Excede límite FedEx/UPS' : ''}
                    </small>
                    {nameTooLong && (
                      <button type="button"
                        style={{ fontSize: '0.68rem', padding: '0.15rem 0.5rem', background: '#fff7ed', color: '#d97706', border: '1px solid #fbbf24', borderRadius: '6px', cursor: 'pointer' }}
                        onClick={() => handleNameChange(truncate35(form.name))}>
                        ✂ Recortar a 35
                      </button>
                    )}
                  </div>
                </div>
              </div>



              {/* Origen: País (select from DB) + Ciudad (filtered by país) + Servicio */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>País Origen</label>
                  <select value={form.country} onChange={e => setForm(f => ({ ...f, country: e.target.value, originCity: '' }))} style={selectStyle}>
                    <option value="">— País —</option>
                    {countries.length > 0 ? countries.map(c => <option key={c} value={c}>{c}</option>) : <option value="EC">EC</option>}
                  </select>
                </div>
                <div>
                  <label style={labelStyle}>Ciudad Origen</label>
                  <select value={form.originCity} onChange={e => setForm(f => ({ ...f, originCity: e.target.value }))} style={selectStyle}>
                    <option value="">— Seleccionar —</option>
                    {filteredCities.map(c => (
                      <option key={c.id} value={c.city}>{c.city}{c.state ? ` (${c.state})` : ''}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label style={labelStyle}>Servicio</label>
                  <select value={form.service} onChange={e => setForm(f => ({ ...f, service: e.target.value }))} style={selectStyle}>
                    {SERVICES.map(s => <option key={s}>{s}</option>)}
                  </select>
                </div>
              </div>

              {/* Tipo Producto, Pack Type (readonly si exclusivo), Box Type (select from DB) */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 2fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>Tipo Producto</label>
                  <select value={form.productType} onChange={e => setForm(f => ({ ...f, productType: e.target.value }))} style={selectStyle}>
                    {PRODUCT_TYPES.map(s => <option key={s}>{s}</option>)}
                  </select>
                  {form.productType === 'EXCLUSIVO' && (
                    <div style={{ marginTop: '0.5rem' }}>
                      <label style={{ ...labelStyle, fontSize: '0.68rem' }}>Finca (Exclusivo)</label>
                      <select value={form.farmId} onChange={e => setForm(f => ({ ...f, farmId: e.target.value }))} style={{ ...selectStyle, fontSize: '0.8rem' }}>
                        <option value="">— Seleccionar finca —</option>
                        {farms.map(farm => <option key={farm.id} value={farm.id}>{farm.name}</option>)}
                      </select>
                    </div>
                  )}
                </div>
                <div>
                  <label style={labelStyle}>Pack Type</label>
                  <input
                    value={form.packType}
                    readOnly={form.productType === 'EXCLUSIVO'}
                    onChange={e => setForm(f => ({ ...f, packType: e.target.value }))}
                    style={{ background: form.productType === 'EXCLUSIVO' ? '#f1f5f9' : 'white', color: 'var(--text-primary)' }}
                  />
                  {form.productType === 'EXCLUSIVO' && (
                    <small style={{ color: '#6b7280', fontSize: '0.68rem' }}>Valor fijo para producto exclusivo</small>
                  )}
                </div>
                <div>
                  <label style={labelStyle}>Box Type</label>
                  <select value={form.boxType} onChange={e => handleBoxTypeChange(e.target.value)} style={selectStyle}>
                    <option value="">— Seleccionar tipo de caja —</option>
                    {boxTypes.map(bt => (
                      <option key={bt.id} value={bt.code}>{bt.code} — {bt.name}</option>
                    ))}
                  </select>
                  {form.boxType && (() => {
                    const bt = boxTypes.find(b => b.code === form.boxType);
                    return bt ? (
                      <small style={{ color: '#059669', fontSize: '0.68rem' }}>
                        {bt.length}×{bt.width}×{bt.height} cm • Dim: {bt.dimWeight} kg
                      </small>
                    ) : null;
                  })()}
                </div>
              </div>

              {/* Dimensiones y Pesos (sin Stems) */}
              <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: 'var(--radius-md)', display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                <p style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--primary-color)', margin: 0, textTransform: 'uppercase' }}>📦 Dimensiones y Pesos</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr', gap: '1rem' }}>
                  {[
                    ['Largo (cm)', 'length'],
                    ['Ancho (cm)', 'width'],
                    ['Alto (cm)', 'height'],
                    ['Dim. Weight', 'dimWeight'],
                    ['Peso Real (kg)', 'realWeight'],
                  ].map(([label, key]) => (
                    <div key={key}>
                      <label style={labelStyle}>{label}</label>
                      <input
                        type="number" step="0.01" placeholder="0"
                        value={form[key as keyof typeof form]}
                        readOnly={key !== 'realWeight' && !!form.boxType && key !== 'dimWeight'}
                        style={{ background: (key !== 'realWeight' && !!form.boxType && key !== 'dimWeight') ? '#f1f5f9' : 'white' }}
                        onChange={e => {
                          if (key !== 'realWeight' && !!form.boxType && key !== 'dimWeight') return;
                          const val = e.target.value;
                          const newForm = { ...form, [key]: val };
                          // auto-calc dim weight if L/W/H change
                          const l = parseFloat(key === 'length' ? val : newForm.length) || 0;
                          const w = parseFloat(key === 'width' ? val : newForm.width) || 0;
                          const h = parseFloat(key === 'height' ? val : newForm.height) || 0;
                          if (l && w && h && key !== 'dimWeight') {
                            newForm.dimWeight = ((l * w * h) / 6000).toFixed(2);
                          }
                          setForm(newForm);
                        }}
                      />
                    </div>
                  ))}
                </div>
              </div>

              {/* Botón Crear Receta */}
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <label style={{ ...labelStyle, margin: 0 }}>Recetas del Producto</label>
                    <span style={{
                      fontSize: '0.7rem', fontWeight: 700, padding: '0.15rem 0.5rem',
                      borderRadius: '999px',
                      background: form.recipeFormat === 'ComboBox' ? '#fef3c7' : '#eff6ff',
                      color: form.recipeFormat === 'ComboBox' ? '#92400e' : '#1d4ed8',
                      border: `1px solid ${form.recipeFormat === 'ComboBox' ? '#fbbf24' : '#93c5fd'}`,
                    }}>{form.recipeFormat || 'Bouquet'}</span>
                  </div>
                  <button type="button" className="btn-secondary" style={{ fontSize: '0.78rem', padding: '0.3rem 0.8rem', borderColor: '#3b82f6', color: '#1d4ed8' }} onClick={openAddRecipe}>
                    + Crear Receta
                  </button>
                </div>
                {recipes.length > 0 ? (
                  <div style={{ overflowX: 'auto', border: '1px solid var(--border-color)', borderRadius: 'var(--radius-md)' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.78rem' }}>
                      <thead>
                        <tr style={{ background: 'var(--bg-secondary)' }}>
                          {['Qty', 'Pack', 'Total Stems', 'Producto', 'Long.', 'HTS', 'Nandina', 'Color', 'Stem/Val', 'Total', 'Dcl', 'edit', 'del'].map((h, i) => (
                            <th key={i} style={{ padding: '0.4rem 0.5rem', fontWeight: 700, textAlign: 'left', whiteSpace: 'nowrap' }}>{h !== 'edit' && h !== 'del' ? h : ''}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {recipes.map(r => {
                          const itemStems = ((parseFloat(r.quantity || '0') || 0) * (parseFloat(r.pack || '0') || 0));
                          return (
                            <tr key={r.id} style={{ borderTop: '1px solid var(--border-color)' }}>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.quantity}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.pack}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontWeight: 700, color: '#15803d', textAlign: 'center' }}>
                                {itemStems > 0 ? itemStems : '—'}
                              </td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.productList}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.length}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontFamily: 'monospace' }}>{r.hts}</td>
                              <td style={{ padding: '0.35rem 0.5rem', fontFamily: 'monospace' }}>{r.nandina}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.color}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.stemValueDeclared}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.totalValue}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>{r.dclValue}</td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>
                                <button type="button" title="Editar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#3b82f6', fontSize: '1rem' }} onClick={() => openEditRecipe(r)}>✏️</button>
                              </td>
                              <td style={{ padding: '0.35rem 0.5rem' }}>
                                <button type="button" title="Eliminar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#dc2626', fontSize: '1rem' }} onClick={() => handleDeleteRecipe(r.id)}>🗑</button>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div style={{ padding: '0.75rem 1rem', background: '#f8fafc', borderRadius: 'var(--radius-md)', color: 'var(--text-secondary)', fontSize: '0.8rem', border: '1px dashed var(--border-color)' }}>
                    Sin recetas. Haz clic en &quot;Crear Receta&quot; para agregar.
                  </div>
                )}
              </div>

              {/* Valor declarado, pack total y tallos totales */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>Valor Declarado ($)</label>
                  <input type="number" step="0.01" placeholder="0.00" value={form.declaredValue}
                    onChange={e => setForm(f => ({ ...f, declaredValue: e.target.value }))} />
                </div>
                <div>
                  <label style={labelStyle}>Total Pack</label>
                  <input type="number" placeholder="0" value={form.packType} readOnly style={{ background: '#f1f5f9' }} />
                  <div style={{ marginTop: '0.75rem' }}>
                    <label style={labelStyle}>Total Stems</label>
                    <input type="number" placeholder="0" value={form.stems || '0'} readOnly style={{ background: '#f0fdf4', fontWeight: 700, color: '#15803d', border: '1.5px solid #86efac' }} />
                    <small style={{ color: 'var(--text-secondary)', fontSize: '0.7rem' }}>Calculado de las recetas (Qty × Pack)</small>
                  </div>
                </div>
              </div>

              {error && (
                <div style={{ padding: '0.75rem 1rem', background: '#fef2f2', color: '#dc2626', borderRadius: 'var(--radius-md)', fontSize: '0.875rem' }}>
                  {error}
                </div>
              )}

              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end', marginTop: '0.5rem' }}>
                <button type="button" className="btn-secondary" onClick={() => setShowModal(false)}>Cancelar</button>
                <button type="submit" className="btn-primary" disabled={saving || nameTooLong}>
                  {saving ? 'Guardando...' : editingId ? 'Actualizar Producto' : 'Guardar Producto'}
                </button>
              </div>
            </form>
          </div>
        </div>
        </ModalPortal>
      )}

      <style>{`@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </MainLayout>
  );
}
