// === comun.jsx — las piezas de play que repiten las escenas ===
// Dibujan play como es (Radzen Material + DinaZen, paleta de wwwroot/css/var.css): campos planos con
// fondo suave y sin borde (site.css .rz-form-field.rz-variant-flat), obligatorios en rojo con «*»
// (site.css .obli), tarjetas DnzCard con DnzCardTitle, selectores DnzRowSelector con su «+» verde.
// Todo a escala de vídeo (1920×1080): mismo aspecto, letra más grande para que se lea.

const C = {
  primario:'#1d73e2', primarioClaro:'#bcd8ff', exito:'#3a8707', peligro:'#d04547', secundario:'#5b6371',
  tinta:'#1b1d20', texto:'#45494f', gris:'#6b7280', base50:'#f8fafb', base100:'#f3f6f9', base200:'#e3eaf2',
  linea:'#dfe5ec', campo:'rgba(69,73,79,0.07)', morado:'#9c75f0', fondo:'#EEF2F6',
};
const FR = "'Roboto', system-ui, -apple-system, 'Segoe UI', Arial, sans-serif";

// Progreso suavizado de un beat: 0 antes de t0, 1 tras t0+d.
function pe(t, t0, d = 0.6, ease = Easing.easeOutCubic){ return ease(clamp((t - t0) / d, 0, 1)); }
// Un solo pulso (sube y baja) de duración d a partir de t0. Remate único, nada en bucle.
function pulso(t, t0, d = 1.2){ return (t >= t0 && t < t0 + d) ? Math.sin((t - t0) / d * Math.PI) : 0; }
// Texto que se escribe en un campo, a cps caracteres por segundo.
function tecleo(texto, t, t0, cps = 16){ return texto.slice(0, Math.max(0, Math.floor((t - t0) * cps))); }

function MI({ n, s = 22, c = 'currentColor', style }){
  return <span className="material-symbols-outlined" style={{ fontSize:s, fontVariationSettings:"'FILL' 1", color:c, lineHeight:1, display:'inline-block', width:s, overflow:'hidden', flexShrink:0, ...style }}>{n}</span>;
}

// Campo plano de play. obli: rótulo rojo con «*» y raya rosa mientras esté vacío.
function Campo({ label, valor = '', obli = false, w = '100%', h = 66, foco = 0, marca = 0, caret = false, icon, desplegable = false, mas = false, fs = 21 }){
  const vacio = !valor;
  const rojo = obli && vacio;
  return (
    <div style={{ position:'relative', width:w, height:h, borderRadius:8, flexShrink:0, minWidth:0,
                  background: rojo ? 'linear-gradient(0deg, rgba(255,5,5,0.11) 0%, rgba(255,255,255,0) 32%), ' + C.campo : C.campo,
                  borderBottom: rojo ? '2px solid #ffb0b0' : '2px solid transparent',
                  boxShadow: foco > 0 ? `inset 0 0 0 ${1.5 * foco}px ${C.primario}` : 'none',
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:3,
                  display:'flex', alignItems:'center', boxSizing:'border-box' }}>
      {icon && <MI n={icon} s={24} c={C.texto} style={{ marginLeft:14 }}/>}
      <div style={{ flex:1, minWidth:0, padding: icon ? '0 12px' : '0 16px', position:'relative', height:'100%' }}>
        <div style={{ position:'absolute', top:9, left: icon ? 12 : 16, fontFamily:FR, fontSize:15, color: rojo ? 'red' : C.texto, whiteSpace:'nowrap' }}>
          {label}{rojo && <span style={{ fontSize:'0.8em', marginLeft:4 }}>*</span>}
        </div>
        <div style={{ position:'absolute', bottom:10, left: icon ? 12 : 16, right:8, fontFamily:FR, fontSize:fs, color:C.tinta,
                      whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {valor}{caret && <span style={{ display:'inline-block', width:2, height:fs, background:C.primario, marginLeft:2, verticalAlign:'-3px' }}/>}
        </div>
      </div>
      {mas && vacio && <MI n="add" s={22} c={C.exito} style={{ marginRight:6 }}/>}
      {desplegable && <MI n="arrow_drop_down" s={28} c={C.texto} style={{ marginRight:8 }}/>}
    </div>
  );
}

// Interruptor de Radzen Material.
function Interruptor({ on = 0, label, marca = 0 }){
  return (
    <div style={{ display:'flex', alignItems:'center', gap:14, padding:'4px 8px', borderRadius:8,
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:2 }}>
      {label && <span style={{ fontFamily:FR, fontSize:20, color:C.tinta }}>{label}</span>}
      <div style={{ position:'relative', width:50, height:22, borderRadius:11, background: on > 0.5 ? C.primarioClaro : '#c8cdd3' }}>
        <div style={{ position:'absolute', top:-3, left: lerp(-2, 22, on), width:28, height:28, borderRadius:14,
                      background: on > 0.5 ? C.primario : '#fafafa', boxShadow:'0 1px 3px rgba(0,0,0,0.35)' }}/>
      </div>
    </div>
  );
}

// RadzenSelectBar: Personal / Empresa.
function BarraEleccion({ opciones, activa, marca = 0 }){
  return (
    <div style={{ display:'inline-flex', borderRadius:6, overflow:'hidden', border:`1px solid ${C.primario}`,
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:3 }}>
      {opciones.map((o, i) => (
        <div key={i} style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 26px', fontFamily:FR, fontSize:19, fontWeight:500,
                              background: activa === i ? C.primario : '#fff', color: activa === i ? '#fff' : C.primario,
                              borderLeft: i ? `1px solid ${C.primario}` : 'none' }}>
          <MI n={o.icon} s={22}/>{o.text}
        </div>
      ))}
    </div>
  );
}

function Boton({ texto, icon, tipo = 'primario', fs = 19, marca = 0, style }){
  const est = {
    primario: { background:C.primario, color:'#fff' },
    exito:    { background:C.exito, color:'#fff' },
    peligroTexto: { background:'transparent', color:C.peligro },
    base:     { background:C.base200, color:C.tinta },
    texto:    { background:'transparent', color:C.primario },
  }[tipo];
  return (
    <div style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'10px 20px', borderRadius:4, fontFamily:FR, fontSize:fs,
                  fontWeight:500, boxShadow: (tipo === 'primario' || tipo === 'exito') ? '0 1px 3px rgba(0,0,0,0.2)' : 'none',
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:3, ...est, ...style }}>
      {icon && <MI n={icon} s={fs + 3}/>}{texto}
    </div>
  );
}

// DnzCard nivel 0 + DnzCardTitle.
function Tarjeta({ titulo, icon, ayuda = false, children, style, marca = 0 }){
  return (
    <div style={{ background:'#fff', borderRadius:10, padding:'20px 24px', boxSizing:'border-box',
                  boxShadow:'0 1px 3px rgba(15,23,42,0.10), 0 1px 2px rgba(15,23,42,0.05)',
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:4, ...style }}>
      {titulo && (
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
          {icon && <MI n={icon} s={24} c={C.secundario}/>}
          <span style={{ fontFamily:FR, fontSize:21, fontWeight:500, color:C.tinta, flex:1 }}>{titulo}</span>
          {ayuda && <MI n="help_outline" s={22} c={C.gris}/>}
        </div>
      )}
      {children}
    </div>
  );
}

// TipU: icono «info» gris y el texto.
function Consejo({ texto, marca = 0 }){
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 12px', borderRadius:8, background:C.base100,
                  outline: marca > 0 ? `${3 * marca}px solid rgba(29,115,226,${0.9 * marca})` : 'none', outlineOffset:2 }}>
      <MI n="info" s={20} c="gray"/>
      <span style={{ fontFamily:FR, fontSize:17, color:C.texto }}>{texto}</span>
    </div>
  );
}

// RadzenTabs: icono + texto, la elegida subrayada.
function Pestanas({ items, activa = 0, aparece = [] }){
  return (
    <div style={{ display:'flex', gap:6, borderBottom:`1px solid ${C.linea}`, padding:'0 22px', height:56, alignItems:'flex-end' }}>
      {items.map((it, i) => {
        const a = aparece[i] === undefined ? 1 : aparece[i];
        if (a <= 0) return null;
        return (
          <div key={i} style={{ display:'flex', alignItems:'center', gap:8, padding:'0 18px', height:52, fontFamily:FR, fontSize:18,
                                fontWeight:500, color: activa === i ? C.tinta : C.gris, opacity:a, transform:`translateY(${(1 - a) * 8}px)`,
                                borderBottom: activa === i ? `2px solid ${C.secundario}` : '2px solid transparent', textTransform:'uppercase', letterSpacing:'0.4px' }}>
            <MI n={it.icon} s={21}/>{it.text}
          </div>
        );
      })}
    </div>
  );
}

// El diálogo de play (DnzDialogLayout vía AgentDialogLayout): título, Yudo en la barra, cuerpo y pie.
function Dialogo({ x, y, w, h, titulo, tituloB, mezcla = 0, icon, cierreX = false, pestanas, pie, children, op = 1, esc = 1, fondoCuerpo = C.base100 }){
  return (
    <div style={{ position:'absolute', left:x, top:y, width:w, height:h, background:'#fff', borderRadius:10, overflow:'hidden',
                  boxShadow:'0 24px 64px rgba(15,23,42,0.22)', opacity:op, transform:`scale(${esc})`, transformOrigin:'50% 40%',
                  display:'flex', flexDirection:'column' }}>
      <div style={{ height:64, flexShrink:0, display:'flex', alignItems:'center', padding:'0 26px', gap:12, borderBottom:`1px solid ${C.linea}` }}>
        {icon && <MI n={icon} s={24} c={C.primario}/>}
        <div style={{ position:'relative', flex:1, height:30 }}>
          <span style={{ position:'absolute', left:0, top:0, fontFamily:FR, fontSize:23, fontWeight:600, color:C.tinta, opacity:1 - mezcla, whiteSpace:'nowrap' }}>{titulo}</span>
          {tituloB && <span style={{ position:'absolute', left:0, top:0, fontFamily:FR, fontSize:23, fontWeight:600, color:C.tinta, opacity:mezcla, whiteSpace:'nowrap' }}>{tituloB}</span>}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <MI n="smart_toy" s={20} c={C.primario}/>
          <span style={{ fontFamily:FR, fontSize:16, fontWeight:600, color:C.tinta }}>Yudo</span>
          <div style={{ transform:'scale(0.8)' }}><Interruptor on={0}/></div>
          {cierreX && <MI n="close" s={22} c={C.gris}/>}
        </div>
      </div>
      {pestanas}
      <div style={{ flex:1, minHeight:0, background:fondoCuerpo, position:'relative', overflow:'hidden' }}>{children}</div>
      {pie && (
        <div style={{ height:76, flexShrink:0, display:'flex', alignItems:'center', padding:'0 26px', gap:10, borderTop:`1px solid ${C.linea}`, background:'#fff' }}>
          {pie}
        </div>
      )}
    </div>
  );
}

// Aviso de Radzen (NotificationService.Notify), arriba a la derecha.
function Aviso({ t, desde, hasta = 1e9, tipo = 'exito', titulo, detalle, x = 1330, y = 40 }){
  const a = pe(t, desde, 0.5) * (1 - pe(t, hasta, 0.4));
  if (a <= 0) return null;
  const col = tipo === 'exito' ? C.exito : '#b7791f';
  return (
    <div style={{ position:'absolute', left:x, top:y, width:540, background:'#fff', borderRadius:8, padding:'18px 22px', opacity:a,
                  transform:`translateX(${(1 - a) * 30}px)`, boxShadow:'0 12px 36px rgba(15,23,42,0.20)', borderLeft:`5px solid ${col}`,
                  display:'flex', gap:14, alignItems:'flex-start', zIndex:20 }}>
      <MI n={tipo === 'exito' ? 'check_circle' : 'warning'} s={28} c={col}/>
      <div style={{ fontFamily:FR }}>
        <div style={{ fontSize:20, fontWeight:700, color:C.tinta }}>{titulo}</div>
        <div style={{ fontSize:18, color:C.texto, marginTop:4 }}>{detalle}</div>
      </div>
    </div>
  );
}

// Rótulo del vídeo (no es de play): pocas palabras, abajo.
function Rotulo({ t, desde, hasta = 1e9, children, y = 996, fs = 30 }){
  const a = pe(t, desde, 0.6) * (1 - pe(t, hasta, 0.4));
  if (a <= 0) return null;
  return (
    <div style={{ position:'absolute', left:0, right:0, top:y, display:'flex', justifyContent:'center', opacity:a,
                  transform:`translateY(${(1 - a) * 12}px)`, zIndex:30, pointerEvents:'none' }}>
      <div className="f-plex" style={{ background:C.tinta, color:'#fff', borderRadius:10, padding:'10px 26px', fontSize:fs, fontWeight:600,
                                       letterSpacing:'-0.01em', whiteSpace:'nowrap' }}>{children}</div>
    </div>
  );
}

// La aplicación Pymes de play: barra de arriba, menú lateral con sus bloques y la zona de la pantalla.
const MENU = [
  { sec:'Ventas & Ingresos', color:C.exito, items:[['receipt_long','Facturas Emitidas'], ['trending_up','Otros Ingresos']] },
  { sec:'Compras & Gastos', color:C.peligro, items:[['assignment_returned','Facturas Recibidas'], ['trending_down','Otros Gastos'], ['universal_currency','Nóminas']] },
  { sec:'Entidades', color:C.morado, items:[['group','Clientes', true], ['work','Proveedores', true], ['badge','Empleados']] },
  { sec:'Tesorería', color:'#14a3a3', items:[['point_of_sale','Cajas'], ['credit_card','Cuentas Bancarias']] },
];
function AppPymes({ x = 40, y = 40, w = 1840, h = 1000, marcaBloque = 0, marcaItems = 0, marcaMas = 0, activo = 'Clientes', children, op = 1 }){
  return (
    <div style={{ position:'absolute', left:x, top:y, width:w, height:h, background:'#fff', borderRadius:12, overflow:'hidden', opacity:op,
                  boxShadow:'0 10px 40px rgba(15,23,42,0.12)', display:'flex', flexDirection:'column' }}>
      <div style={{ height:66, flexShrink:0, display:'flex', alignItems:'center', padding:'0 28px', gap:18, borderBottom:`1px solid ${C.linea}` }}>
        <DinaupLogo size={26}/>
        <span style={{ fontFamily:FR, fontSize:19, color:C.gris }}>/ Pymes</span>
        <div style={{ flex:1 }}/>
        <span style={{ fontFamily:FR, fontSize:17, color:C.gris }}>Panadería El Molino, S.L.</span>
        <div style={{ width:38, height:38, borderRadius:19, background:C.primario, color:'#fff', display:'flex', alignItems:'center',
                      justifyContent:'center', fontFamily:FR, fontWeight:700, fontSize:15 }}>MJ</div>
      </div>
      <div style={{ display:'flex', height:4, flexShrink:0 }}>
        {['#00bffe', '#f8604d', '#54de67', '#fad51b'].map(c => <div key={c} style={{ flex:1, background:c }}/>)}
      </div>
      <div style={{ flex:1, display:'flex', minHeight:0 }}>
        <div style={{ width:360, flexShrink:0, background:C.base50, borderRight:`1px solid ${C.linea}`, padding:'14px 14px' }}>
          {MENU.map(s => {
            const esEnt = s.sec === 'Entidades';
            return (
              <div key={s.sec} style={{ marginBottom:12, opacity: (marcaBloque > 0 && !esEnt) ? 1 - 0.55 * marcaBloque : 1 }}>
                <div style={{ display:'flex', alignItems:'center', gap:10, padding:'6px 10px', borderLeft:`4px solid ${s.color}`,
                              background: esEnt && marcaBloque > 0 ? `rgba(156,117,240,${0.12 * marcaBloque})` : 'transparent', borderRadius:'0 6px 6px 0' }}>
                  <span style={{ fontFamily:FR, fontSize:15, fontWeight:700, letterSpacing:'0.5px', color:C.texto, textTransform:'uppercase' }}>{s.sec}</span>
                </div>
                {s.items.map(([ic, tx, mas]) => {
                  const act = tx === activo;
                  const mi = esEnt && mas ? marcaItems : 0;
                  return (
                    <div key={tx} style={{ display:'flex', alignItems:'center', gap:14, padding:'9px 12px 9px 22px', borderRadius:8, marginTop:2,
                                           background: act ? 'rgba(29,115,226,0.10)' : (mi > 0 ? `rgba(29,115,226,${0.06 * mi})` : 'transparent') }}>
                      <MI n={ic} s={22} c={act ? C.primario : C.texto}/>
                      <span style={{ flex:1, fontFamily:FR, fontSize:19, color: act ? C.primario : C.tinta, fontWeight: act ? 500 : 400 }}>{tx}</span>
                      {mas && (
                        <div style={{ width:34, height:34, borderRadius:6, background:C.primario, display:'flex', alignItems:'center', justifyContent:'center',
                                      outline: marcaMas > 0 ? `${3 * marcaMas}px solid rgba(29,115,226,${0.8 * marcaMas})` : 'none', outlineOffset:3 }}>
                          <MI n="add" s={22} c="#fff"/>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
        <div style={{ flex:1, minWidth:0, position:'relative', background:'#fff' }}>{children}</div>
      </div>
    </div>
  );
}

// La lista (ReportTabsU): pestaña con el nombre, barra con buscador y el botón verde, y las filas.
const CLIENTES = ['Ana Ruiz Pastor', 'Cafetería La Plaza, S.L.', 'Distribuciones Turia, S.A.', 'Hotel Mediterráneo', 'Talleres Marbán, S.L.', 'Colegio San José'];
function Lista({ titulo = 'Clientes', boton = 'Cliente', marcaBoton = 0, filas = CLIENTES, filaMarcada = -1, marcaFila = 0 }){
  return (
    <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column' }}>
      <Pestanas items={[{ icon:'view_list', text:titulo }, { icon:'note_stack', text:'' }]} activa={0}/>
      <div style={{ display:'flex', alignItems:'center', gap:14, padding:'18px 26px' }}>
        <div style={{ width:420, height:46, borderRadius:8, background:C.campo, display:'flex', alignItems:'center', gap:10, padding:'0 14px' }}>
          <MI n="search" s={22} c={C.gris}/><span style={{ fontFamily:FR, fontSize:18, color:C.gris }}>Buscar...</span>
        </div>
        <div style={{ flex:1 }}/>
        <Boton texto={boton} icon="add" tipo="exito" fs={17} marca={marcaBoton} style={{ padding:'7px 14px' }}/>
      </div>
      <div style={{ padding:'0 26px' }}>
        <div style={{ height:1, background:C.linea }}/>
        {filas.map((f, i) => (
          <div key={f} style={{ display:'flex', alignItems:'center', gap:26, padding:'15px 16px', borderBottom:`1px solid ${C.base200}`,
                                background: i === filaMarcada ? `rgba(29,115,226,${0.10 * marcaFila})` : 'transparent' }}>
            <span style={{ width:420, fontFamily:FR, fontSize:19, color:C.tinta }}>{f}</span>
            <div style={{ width:140, height:10, borderRadius:5, background:C.base200 }}/>
            <div style={{ width:240, height:10, borderRadius:5, background:C.base200 }}/>
            <div style={{ width:120, height:10, borderRadius:5, background:C.base200 }}/>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { C, FR, pe, pulso, tecleo, MI, Campo, Interruptor, BarraEleccion, Boton, Tarjeta, Consejo, Pestanas, Dialogo, Aviso, Rotulo, AppPymes, Lista, CLIENTES, MENU });

// Paso 1 del alta (EntidadDialog sin id): tarjeta del título automático y tarjeta «Datos».
// v = { empresa, nombre, apellidos, nif, razon, idf, email, tel, titulo }, m = marcas de 0 a 1.
function FichaPaso1({ x = 150, y = 40, w = 1620, h = 940, v = {}, m = {}, caret = '', op = 1, esc = 1 }){
  const filaCampos = (a, b) => (
    <div style={{ display:'flex', gap:18, marginTop:16 }}>
      <div style={{ flex:1, minWidth:0 }}>{a}</div>
      <div style={{ flex:1, minWidth:0 }}>{b}</div>
    </div>
  );
  return (
    <Dialogo x={x} y={y} w={w} h={h} titulo="Agregar Entidad" op={op} esc={esc}
             pestanas={<Pestanas items={[{ icon:'badge', text:'General' }]} activa={0}/>}
             pie={<React.Fragment><div style={{ flex:1 }}/>
                   <Boton texto="Siguiente" icon="play_arrow" tipo="primario" marca={m.siguiente || 0}/>
                   <Boton texto="Cerrar" icon="close" tipo="peligroTexto"/></React.Fragment>}>
      <div style={{ position:'absolute', inset:0, padding:'22px 26px', display:'flex', flexDirection:'column', gap:18 }}>
        <Tarjeta marca={m.titulo || 0}>
          <div style={{ fontFamily:FR, fontSize:22, color:C.tinta, minHeight:30 }}>{v.titulo || ''}</div>
          <div style={{ height:1, background:C.linea, margin:'12px 0' }}/>
          <div style={{ display:'flex', alignItems:'center', gap:4 }}>
            <span style={{ fontFamily:FR, fontSize:18, color:C.texto }}>Título automático</span>
            <div style={{ transform:'scale(0.85)' }}><Interruptor on={1}/></div>
          </div>
        </Tarjeta>
        <Tarjeta titulo="Datos" icon="contact_page">
          <BarraEleccion opciones={[{ icon:'person', text:'Personal' }, { icon:'work', text:'Empresa' }]} activa={v.empresa ? 1 : 0} marca={m.barra || 0}/>
          {v.empresa ? (
            <React.Fragment>
              {filaCampos(<Campo label="Razón social" obli valor={v.razon} marca={m.razon || 0} caret={caret === 'razon'} foco={caret === 'razon' ? 1 : 0}/>,
                          <Campo label="ID fiscal" obli valor={v.idf} marca={m.idf || 0} caret={caret === 'idf'} foco={caret === 'idf' ? 1 : 0}/>)}
            </React.Fragment>
          ) : (
            <React.Fragment>
              {filaCampos(<Campo label="Nombre" obli valor={v.nombre} marca={m.nombre || 0}/>, <Campo label="Apellidos" valor={v.apellidos}/>)}
              {filaCampos(<Campo label="NIF/CIF" valor={v.nif} marca={m.nif || 0}/>, <div/>)}
            </React.Fragment>
          )}
          {filaCampos(<Campo label="Email" valor={v.email} caret={caret === 'email'} foco={caret === 'email' ? 1 : 0}/>,
                      <Campo label="Teléfono" valor={v.tel} caret={caret === 'tel'} foco={caret === 'tel' ? 1 : 0}/>)}
        </Tarjeta>
      </div>
    </Dialogo>
  );
}
Object.assign(window, { FichaPaso1 });

// Paso 2 del alta (EntidadDialog con id): «Detalles», «Configuración cliente» y, si toca, «Configuración proveedor».
// p = { mezcla (título Agregar→Editar), tabs (0-1 aparecen Firmas/Estadísticas), guardar, verFicha, fiscal (texto elegido),
//       cuenta (texto elegido), cfgCli, cfgProv (0-1), atenuaCli }, m = marcas.
function FichaPaso2({ x = 150, y = 40, w = 1620, h = 940, p = {}, m = {}, op = 1, esc = 1, scroll = 0 }){
  const tabs = p.tabs === undefined ? 1 : p.tabs;
  const sel = (label, icon, valor, mas, marca, ancho = 360) => (
    <div style={{ width:ancho, flexShrink:0 }}><Campo label={label} icon={icon} valor={valor} desplegable mas={mas} marca={marca} fs={19}/></div>
  );
  return (
    <Dialogo x={x} y={y} w={w} h={h} titulo="Agregar Entidad" tituloB="Editar Entidad" mezcla={p.mezcla === undefined ? 1 : p.mezcla} op={op} esc={esc}
             pestanas={<Pestanas items={[{ icon:'badge', text:'General' }, { icon:'draw', text:'Firmas' }, { icon:'query_stats', text:'Estadísticas' }]}
                                 activa={p.activa || 0} aparece={[1, tabs, tabs]}/>}
             pie={<React.Fragment>
                   <div style={{ opacity:p.verFicha === undefined ? 1 : p.verFicha }}><Boton texto="Ver ficha completa" icon="open_in_new" tipo="base"/></div>
                   <div style={{ flex:1 }}/>
                   {(p.guardar || 0) > 0 && <div style={{ opacity:p.guardar }}><Boton texto="Guardar" icon="check" tipo="exito" marca={m.guardar || 0}/></div>}
                   <Boton texto="Cerrar" icon="close" tipo="peligroTexto"/></React.Fragment>}>
      {p.cuerpo ? p.cuerpo : <div style={{ position:'absolute', left:0, right:0, top:-scroll, padding:'22px 26px', display:'flex', flexDirection:'column', gap:18 }}>
        <Tarjeta titulo="Detalles" icon="manufacturing" marca={m.detalles || 0}>
          <div style={{ display:'flex', gap:12 }}>
            {sel('Datos fiscales', 'badge', p.fiscal || '', true, m.fiscal || 0, 520)}
            {sel('Dirección de envío', 'location_on', '', true, 0, 520)}
          </div>
          <div style={{ display:'flex', gap:48, marginTop:24 }}>
            <Interruptor label="Es cliente" on={p.esCliente === undefined ? 1 : p.esCliente} marca={m.esCliente || 0}/>
            <Interruptor label="Es proveedor" on={p.esProveedor || 0} marca={m.esProveedor || 0}/>
          </div>
        </Tarjeta>
        {(p.cfgCli || 0) > 0 && (
          <div style={{ opacity:p.cfgCli * (1 - 0.6 * (p.atenuaCli || 0)), transform:`translateY(${(1 - p.cfgCli) * 14}px)` }}>
            <Tarjeta titulo="Configuración cliente" icon="manufacturing" ayuda marca={m.cfgCli || 0}>
              <Consejo texto="Estos datos son opcionales. Si los dejas vacíos, se aplican los valores predeterminados de la empresa." marca={m.opcional || 0}/>
              <div style={{ display:'flex', gap:12, marginTop:16 }}>
                {sel('Tipo venta', 'category', '', false, m.tipoVenta || 0)}
                {sel('Impuesto', 'local_atm', '', false, m.impuesto || 0)}
                {sel('Tipo de cliente', 'asterisk', '', true, m.tipoCliente || 0)}
                {sel('Cuenta contable (430)', 'account_balance', p.cuenta || '', true, m.cuenta || 0, 420)}
              </div>
              <div style={{ marginTop:14 }}><Consejo texto="Las retenciones y el recargo de equivalencia se configuran en la ficha del cliente, una vez guardada."/></div>
            </Tarjeta>
          </div>
        )}
        {(p.cfgProv || 0) > 0 && (
          <div style={{ opacity:p.cfgProv, transform:`translateY(${(1 - p.cfgProv) * 14}px)` }}>
            <Tarjeta titulo="Configuración proveedor" icon="manufacturing" ayuda marca={m.cfgProv || 0}>
              <div style={{ display:'flex', gap:12 }}>
                {sel('Tipo compra', 'category', '', false, m.tipoCompra || 0)}
                {sel('Impuesto', 'local_atm', '', false, 0)}
                {sel('Categoría', 'folder', '', false, m.categoria || 0)}
                {sel('Cuenta contable (400/410)', 'account_balance', '', true, m.cuentaProv || 0, 420)}
              </div>
            </Tarjeta>
          </div>
        )}
      </div>}
    </Dialogo>
  );
}

// La ventana «Datos fiscales» (DatosFiscalesDialog) que abre el «+»: llega con los datos de la entidad copiados.
function VentanaDatosFiscales({ x = 520, y = 90, w = 880, h = 880, dir = {}, m = {}, caret = '', op = 1, esc = 1 }){
  const fila = (a, b) => (<div style={{ display:'flex', gap:14, marginTop:12 }}><div style={{ flex:1, minWidth:0 }}>{a}</div>{b && <div style={{ flex:1, minWidth:0 }}>{b}</div>}</div>);
  return (
    <Dialogo x={x} y={y} w={w} h={h} titulo="Datos fiscales" icon="contact_page" cierreX op={op} esc={esc}
             pie={<React.Fragment><div style={{ flex:1 }}/>
                   <Boton texto="Guardar" icon="check" tipo="exito" marca={m.guardar || 0} fs={18}/>
                   <Boton texto="Cerrar" icon="close" tipo="peligroTexto" fs={18}/></React.Fragment>}>
      <div style={{ position:'absolute', inset:0, padding:'18px 22px', display:'flex', flexDirection:'column', gap:14 }}>
        <Tarjeta style={{ padding:'16px 20px' }}>
          <BarraEleccion opciones={[{ icon:'person', text:'Persona física' }, { icon:'work', text:'Empresa' }]} activa={1}/>
          {fila(<Campo h={60} fs={19} label="Razón social" valor="Talleres Marbán, S.L." marca={m.copia0 || 0}/>, <Campo h={60} fs={19} label="ID fiscal (NIF/CIF)" valor="B98314207" marca={m.copia1 || 0}/>)}
          {fila(<Campo h={60} fs={19} label="Email" valor="info@talleresmarban.es" marca={m.copia2 || 0}/>, <Campo h={60} fs={19} label="Teléfono" valor="961 244 180"/>)}
        </Tarjeta>
        <Tarjeta titulo="Dirección" icon="location_on" style={{ padding:'16px 20px' }} marca={m.direccion || 0}>
          {fila(<Campo h={60} fs={19} label="Dirección" obli valor={dir.linea} caret={caret === 'linea'} foco={caret === 'linea' ? 1 : 0}/>)}
          {fila(<Campo h={60} fs={19} label="Municipio" obli valor={dir.municipio}/>, <Campo h={60} fs={19} label="Provincia" obli valor={dir.provincia}/>)}
          {fila(<Campo h={60} fs={19} label="Código postal" obli valor={dir.cp}/>, <Campo h={60} fs={19} label="País" obli valor={dir.pais}/>)}
        </Tarjeta>
      </div>
    </Dialogo>
  );
}
Object.assign(window, { FichaPaso2, VentanaDatosFiscales });
