const CollectionIcon=({name,size=22})=>{
  const icons={
    arrow:<><path d="M5 12h13M13 6l6 6-6 6"/></>,
    menu:<><path d="M4 7h16M4 12h16M4 17h16"/></>,
    close:<><path d="m6 6 12 12M18 6 6 18"/></>,
    shirt:<><path d="m8 4-5 3 2 5 3-1v9h8v-9l3 1 2-5-5-3c-.7 1.2-2 2-4 2s-3.3-.8-4-2Z"/></>,
    print:<><path d="M6 9V3h12v6M6 17H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2"/><path d="M6 14h12v7H6z"/></>,
    box:<><path d="m4 7 8-4 8 4-8 4-8-4Z"/><path d="M4 7v10l8 4 8-4V7M12 11v10"/></>,
    truck:<><path d="M3 6h11v10H3zM14 9h4l3 3v4h-7z"/><circle cx="7" cy="18" r="2"/><circle cx="18" cy="18" r="2"/></>,
    thread:<><path d="M8 3h8M8 21h8M9 3c2 5 2 13 0 18M15 3c-2 5-2 13 0 18M9 8h6M9 16h6"/></>,
    spark:<><path d="m12 3 1.4 5.6L19 10l-5.6 1.4L12 17l-1.4-5.6L5 10l5.6-1.4L12 3Z"/></>,
    check:<><path d="m5 12 4 4L19 6"/></>,
    ruler:<><path d="m4 17 13-13 3 3L7 20l-3-3Z"/><path d="m14 7 3 3M11 10l2 2M8 13l3 3"/></>,
    quote:<><path d="M7 17H4a2 2 0 0 1-2-2v-3a6 6 0 0 1 6-6v3a3 3 0 0 0-3 3h2v5ZM19 17h-3a2 2 0 0 1-2-2v-3a6 6 0 0 1 6-6v3a3 3 0 0 0-3 3h2v5Z"/></>
  };
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{icons[name]||icons.spark}</svg>;
};

function CLBrand({tenant}){
  return <a className="cl-brand" href="#inicio" aria-label={tenant.businessName+", inicio"}>
    {tenant.logoUrl?<img src={tenant.logoUrl} alt=""/>:<span>{(tenant.businessName||"L").slice(0,1)}</span>}
    <span><strong>{tenant.businessName}</strong><small>Producción e impresión</small></span>
  </a>;
}

function CLHeader({tenant,onQuote}){
  const[open,setOpen]=React.useState(false);
  return <header className="cl-header"><div className="cl-shell cl-header-inner"><CLBrand tenant={tenant}/><button type="button" className="cl-menu" onClick={()=>setOpen(value=>!value)} aria-expanded={open} aria-controls="cl-navigation" aria-label={open?"Cerrar menú":"Abrir menú"}><CollectionIcon name={open?"close":"menu"}/></button><nav id="cl-navigation" className={open?"is-open":""} aria-label="Navegación principal"><a href="#catalogo">Productos</a><a href="#servicios">Servicios</a><a href="#proceso">Proceso</a><a href="#contacto">Contacto</a><button type="button" onClick={onQuote}>Solicitar cotización <CollectionIcon name="arrow" size={17}/></button></nav></div></header>;
}

function CLMotifs({kind}){
  if(kind==="none")return null;
  const names=kind==="thread"?["thread","shirt","spark"]:kind==="print"?["print","ruler","spark"]:kind==="pack"?["box","truck","spark"]:kind==="tools"?["ruler","print","thread"]:["thread","print","box"];
  return <div className="cl-motifs" aria-hidden="true">{names.map((name,index)=><span className={"cl-motif cl-motif-"+(index+1)} key={name+index}><CollectionIcon name={name} size={index===0?34:26}/></span>)}</div>;
}

function CLHeroVisual({tenant,products,config}){
  const images=products.filter(product=>product.imageUrl).slice(0,3);
  return <div className={"cl-hero-visual cl-layout-"+config.heroLayout}>
    <CLMotifs kind={config.decorativeSet}/>
    {tenant.heroImageUrl?<figure className="cl-hero-main"><img src={tenant.heroImageUrl} alt="Muestra del trabajo de la empresa"/><figcaption>Producción hecha para tu marca</figcaption></figure>:images.length?<div className="cl-product-composition">{images.map((product,index)=><figure className={"cl-product-shot cl-shot-"+index} key={product.id}><img src={product.imageUrl} alt={product.name}/><figcaption><span>{String(index+1).padStart(2,"0")}</span>{product.name}</figcaption></figure>)}</div>:<div className="cl-hero-placeholder"><CollectionIcon name="shirt" size={92}/><strong>Tu proyecto</strong><span>del concepto a producción</span></div>}
    <div className="cl-production-note"><span>Control de producción</span><strong>Material · técnica · entrega</strong></div>
  </div>;
}

function CLHero({tenant,products,config,onQuote}){
  const Core=window.LANACollectionCore;
  return <section id="inicio" className="cl-hero cl-shell"><div className="cl-hero-copy"><span className="cl-kicker">{config.heroEyebrow}</span><h1>{config.heroTitle}</h1><p>{config.heroDescription}</p><div className="cl-actions"><a className="cl-button cl-button-primary" href={Core.catalogHref(tenant)}>{config.primaryCtaLabel}<CollectionIcon name="arrow" size={18}/></a><button className="cl-button cl-button-secondary" type="button" onClick={onQuote}>{config.secondaryCtaLabel}</button></div><div className="cl-trust"><span><CollectionIcon name="check" size={16}/>Asesoría especializada</span><span><CollectionIcon name="check" size={16}/>Revisión antes de producir</span><span><CollectionIcon name="check" size={16}/>Seguimiento humano</span></div></div><CLHeroVisual tenant={tenant} products={products} config={config}/></section>;
}

function CLSectionHeading({eyebrow,title,text,action}){
  return <div className="cl-heading"><div><span className="cl-kicker">{eyebrow}</span><h2>{title}</h2>{text&&<p>{text}</p>}</div>{action&&<a href={action.href}>{action.label}<CollectionIcon name="arrow" size={17}/></a>}</div>;
}

function CLIntent({tenant,config}){
  const Core=window.LANACollectionCore;
  const items=[
    {id:"textil",code:"TX",title:"Uniformes y textil",text:"Prendas, gorras y promocionales",icon:"shirt",href:Core.catalogHref(tenant)},
    {id:"impresion",code:"IM",title:"Impresión",text:"Papelería, gran formato y exhibición",icon:"print",href:"#servicios"},
    {id:"empaque",code:"PK",title:"Empaque y entrega",text:"Presentación, armado y envío",icon:"box",href:"#servicios"},
    {id:"idea",code:"ID",title:"Tengo una idea",text:"Te ayudamos a elegir el proceso",icon:"spark",href:"#contacto"}
  ];
  return <section className="cl-intent cl-shell"><div className="cl-intent-panel"><div className="cl-intent-intro"><span className="cl-kicker">Punto de partida</span><h2>{config.intentTitle}</h2><p>Elige una ruta. Puedes combinar productos, técnicas y entregas en la misma solicitud.</p></div><div className="cl-intent-grid">{items.map(item=><a href={item.href} key={item.id}><span><CollectionIcon name={item.icon}/></span><small>{item.code}</small><strong>{item.title}</strong><p>{item.text}</p><CollectionIcon name="arrow" size={18}/></a>)}</div></div></section>;
}

function CLEmpty({title,text}){return <div className="cl-empty"><CollectionIcon name="box" size={36}/><strong>{title}</strong><p>{text}</p></div>}

function CLCategories({tenant,products,config}){
  const Core=window.LANACollectionCore;
  const categories=React.useMemo(()=>[...new Set(products.map(product=>product.category).filter(Boolean))].slice(0,6),[products]);
  return <section id="catalogo" className="cl-section cl-categories-section"><div className="cl-shell"><CLSectionHeading eyebrow="Catálogo vivo" title={config.catalogTitle} text="Categorías reales publicadas por el negocio, siempre vinculadas al catálogo del tenant." action={{href:Core.catalogHref(tenant),label:"Ver catálogo completo"}}/>{categories.length?<div className="cl-categories">{categories.map((category,index)=>{const image=products.find(product=>product.category===category&&product.imageUrl)?.imageUrl;return <a className={"cl-category cl-category-"+index} href={Core.catalogHref(tenant,"catalogo.html?cat="+encodeURIComponent(category))} key={category}>{image?<img src={image} alt=""/>:<span className="cl-category-icon"><CollectionIcon name={index%2?"print":"shirt"} size={48}/></span>}<span className="cl-category-index">{String(index+1).padStart(2,"0")}</span><strong>{category}</strong><small>Explorar <CollectionIcon name="arrow" size={16}/></small></a>})}</div>:<CLEmpty title="Catálogo en preparación" text="Cuando publiques categorías aparecerán aquí automáticamente."/>}</div></section>;
}

function CLProductCard({tenant,product,index}){
  const Core=window.LANACollectionCore;
  const price=product.direct&&Number.isFinite(product.price)?new Intl.NumberFormat("es-MX",{style:"currency",currency:"MXN"}).format(product.price):"Cotización personalizada";
  const href=Core.catalogHref(tenant,"catalogo.html?producto="+encodeURIComponent(product.id));
  return <article className="cl-product"><a className="cl-product-media" href={href}>{product.imageUrl?<img src={product.imageUrl} alt={product.name}/>:<CollectionIcon name="shirt" size={58}/>}<span>{String(index+1).padStart(2,"0")}</span></a><div><small>{product.category||"Producto"}</small><h3>{product.name}</h3><p>{price}</p><a href={href}>Ver opciones <CollectionIcon name="arrow" size={16}/></a></div></article>;
}

function CLProducts({tenant,products,config}){
  const list=(products.some(product=>product.featured)?products.filter(product=>product.featured):products).slice(0,8);
  return <section className="cl-section cl-products-section"><div className="cl-shell"><CLSectionHeading eyebrow="Selección destacada" title={config.productsTitle} text="Una vitrina visual construida con los productos activos del negocio."/>{list.length?<div className="cl-products">{list.map((product,index)=><CLProductCard tenant={tenant} product={product} index={index} key={product.id}/>)}</div>:<CLEmpty title="Productos por publicar" text="Los productos destacados aparecerán en esta selección."/>}</div></section>;
}

function CLSocialRail({tenant,products}){
  const rail=React.useRef(null);
  const Core=window.LANACollectionCore;
  const list=products.filter(product=>product.imageUrl).slice(0,8);
  if(!list.length)return null;
  const move=direction=>rail.current&&rail.current.scrollBy({left:direction*340,behavior:"smooth"});
  return <section className="cl-social"><div className="cl-shell"><div className="cl-social-head"><div><span className="cl-kicker">Carrusel visual</span><h2>Historias de producto listas para inspirar</h2><p>Una selección dinámica con imágenes reales del catálogo publicado.</p></div><div><button type="button" onClick={()=>move(-1)} aria-label="Ver elementos anteriores">←</button><button type="button" onClick={()=>move(1)} aria-label="Ver elementos siguientes">→</button></div></div><div className="cl-social-rail" ref={rail}>{list.map((product,index)=><a href={Core.catalogHref(tenant,"catalogo.html?producto="+encodeURIComponent(product.id))} className="cl-social-card" key={product.id}><span>{tenant.businessName}</span><img src={product.imageUrl} alt={product.name}/><div><small>{String(index+1).padStart(2,"0")} / {String(list.length).padStart(2,"0")}</small><strong>{product.name}</strong><em>Descubrir producto</em></div></a>)}</div></div></section>;
}

function CLServices({services,config,onQuote}){
  const iconNames=["print","shirt","ruler","spark"];
  return <section id="servicios" className="cl-section cl-services-section"><div className="cl-shell"><CLSectionHeading eyebrow="Capacidades conectadas" title={config.servicesTitle} text="Cada técnica se explica con claridad para elegir según material, cantidad, uso y fecha."/><div className="cl-services">{services.map((service,index)=><article key={service.id}><span className="cl-service-number">{String(index+1).padStart(2,"0")}</span><span className="cl-service-icon"><CollectionIcon name={iconNames[index%iconNames.length]} size={28}/></span><div><small>{service.icon}</small><h3>{service.name}</h3><p>{service.description}</p></div><button type="button" onClick={onQuote}>Agregar a solicitud <CollectionIcon name="arrow" size={16}/></button></article>)}</div></div></section>;
}

function CLQuoteStory({config,onQuote}){
  return <section className="cl-quote-story"><div className="cl-shell cl-quote-grid"><div><span className="cl-kicker">Una solicitud, todo el proyecto</span><h2>{config.quoteTitle}</h2><p>Organiza productos, técnicas, cantidades y entregas bajo una misma conversación. El negocio valida los detalles antes de cotizar.</p><button className="cl-button cl-button-primary" type="button" onClick={onQuote}>Preparar mi solicitud <CollectionIcon name="arrow" size={18}/></button></div><div className="cl-quote-board"><div className="cl-board-head"><span>Proyecto corporativo</span><b>En preparación</b></div><article><span>01</span><CollectionIcon name="shirt"/><div><strong>Producto</strong><small>Prendas y cantidades</small></div></article><article><span>02</span><CollectionIcon name="thread"/><div><strong>Personalización</strong><small>Técnica y ubicaciones</small></div></article><article><span>03</span><CollectionIcon name="box"/><div><strong>Entrega</strong><small>Fecha, empaque y destino</small></div></article><footer><span>Revisión humana incluida</span><CollectionIcon name="check"/></footer></div></div></section>;
}

function CLProcess({config}){
  const steps=[{title:"Define",text:"Objetivo, cantidad y fecha",icon:"spark"},{title:"Selecciona",text:"Producto, material y técnica",icon:"shirt"},{title:"Comparte",text:"Archivos y referencias",icon:"print"},{title:"Revisa",text:"Propuesta y especificaciones",icon:"ruler"},{title:"Produce",text:"Validación y seguimiento",icon:"box"}];
  return <section id="proceso" className="cl-section cl-process-section"><div className="cl-shell"><CLSectionHeading eyebrow="Método claro" title={config.processTitle} text="El mismo orden para proyectos pequeños, campañas o producciones recurrentes."/><ol className="cl-process">{steps.map((step,index)=><li key={step.title}><span>{String(index+1).padStart(2,"0")}</span><CollectionIcon name={step.icon}/><strong>{step.title}</strong><p>{step.text}</p></li>)}</ol></div></section>;
}

function CLBenefits({config}){
  const items=[{title:"Orientación real",text:"Las opciones se explican sin depender de términos técnicos."},{title:"Diseño verificable",text:"Materiales, medidas y ubicaciones quedan claros antes de producir."},{title:"Entrega coordinada",text:"El proyecto mantiene contexto desde la solicitud hasta la entrega."}];
  return <section className="cl-benefits"><div className="cl-shell cl-benefits-grid"><div><span className="cl-kicker">Confianza operativa</span><h2>{config.benefitsTitle}</h2><p>Más que una vitrina: una forma profesional de presentar cómo trabaja el negocio.</p></div><div>{items.map((item,index)=><article key={item.title}><span>{String(index+1).padStart(2,"0")}</span><div><strong>{item.title}</strong><p>{item.text}</p></div></article>)}</div></div></section>;
}

function CLContact({tenant,config,onClose}){
  const[name,setName]=React.useState("");
  const[need,setNeed]=React.useState("");
  const quantityRef=React.useRef(null);
  const send=event=>{
    event.preventDefault();
    const quantity=quantityRef.current?.value||"Por definir";
    const text=`Hola, soy ${name}. Me interesa ${need}. Cantidad: ${quantity}.`;
    const phone=(tenant.whatsapp||tenant.phone||"").replace(/\D/g,"");
    if(phone)window.open(`https://wa.me/${phone}?text=${encodeURIComponent(text)}`,"_blank","noopener,noreferrer");
    else if(tenant.email)window.location.href=`mailto:${tenant.email}?subject=${encodeURIComponent("Solicitud de cotización")}&body=${encodeURIComponent(text)}`;
    else window.location.href=window.LANACollectionCore.catalogHref(tenant);
  };
  return <div className="cl-contact" role="dialog" aria-modal="true" aria-labelledby="cl-contact-title"><button className="cl-contact-backdrop" onClick={onClose} aria-label="Cerrar formulario"/><div className="cl-contact-panel"><header><div><span className="cl-kicker">Nueva solicitud</span><h2 id="cl-contact-title">Cuéntanos qué necesitas</h2></div><button type="button" onClick={onClose} aria-label="Cerrar"><CollectionIcon name="close"/></button></header><form onSubmit={send}><label><span>Nombre</span><input required value={name} onChange={event=>setName(event.target.value)} autoComplete="name"/></label><label><span>Producto o proyecto</span><textarea required value={need} onChange={event=>setNeed(event.target.value)} placeholder="Ej. 50 polos bordados para el equipo"/></label><label><span>Cantidad aproximada</span><input ref={quantityRef} inputMode="numeric" placeholder="Ej. 50"/></label><button className="cl-button cl-button-primary" type="submit">Enviar solicitud <CollectionIcon name="arrow" size={18}/></button></form><p>La empresa confirmará disponibilidad, técnica, precio y fecha de entrega.</p></div></div>;
}

function CLFinal({tenant,config,onQuote}){
  return <section id="contacto" className="cl-final"><div className="cl-shell"><div><span className="cl-kicker">Tu siguiente proyecto empieza aquí</span><h2>{config.finalCtaTitle}</h2></div><div><button className="cl-button cl-button-light" type="button" onClick={onQuote}>Solicitar cotización <CollectionIcon name="arrow" size={18}/></button>{tenant.whatsapp&&<a className="cl-button cl-button-outline" href={`https://wa.me/${tenant.whatsapp.replace(/\D/g,"")}`} target="_blank" rel="noreferrer">Hablar por WhatsApp</a>}</div></div></section>;
}

function CLFooter({tenant}){
  const Core=window.LANACollectionCore;
  return <footer className="cl-footer"><div className="cl-shell cl-footer-grid"><div><CLBrand tenant={tenant}/><p>{tenant.description}</p></div><div><strong>Explora</strong><a href={Core.catalogHref(tenant)}>Catálogo</a><a href="#servicios">Servicios</a><a href="#proceso">Proceso</a></div><div><strong>Contacto</strong>{tenant.phone&&<a href={`tel:${tenant.phone}`}>{tenant.phone}</a>}{tenant.email&&<a href={`mailto:${tenant.email}`}>{tenant.email}</a>}{tenant.address&&<span>{tenant.address}</span>}{!tenant.phone&&!tenant.email&&!tenant.address&&<span>Información disponible al cotizar</span>}</div></div><div className="cl-shell cl-footer-bottom"><span>© {new Date().getFullYear()} {tenant.businessName}</span><span>Experiencia desarrollada con LANA</span></div></footer>;
}

function CollectionLandingPage({tenant,products,services,templateOverride}){
  const Core=window.LANACollectionCore;
  const[landing,setLanding]=React.useState(()=>({...tenant.landing,templateId:templateOverride||tenant.templateId}));
  const[contactOpen,setContactOpen]=React.useState(false);
  React.useEffect(()=>{
    const receive=event=>{if(event.data&&event.data.type==="lana-landing-preview"&&event.data.landing)setLanding(event.data.landing)};
    window.addEventListener("message",receive);return()=>window.removeEventListener("message",receive);
  },[]);
  const config=Core.normalize({...landing,templateId:templateOverride||landing.templateId});
  const liveTenant={...tenant,...config,landing:landing,businessName:landing.businessName||tenant.businessName,logoUrl:landing.logoUrl||tenant.logoUrl,heroImageUrl:landing.heroImageUrl||tenant.heroImageUrl,phone:landing.phone||tenant.phone,whatsapp:landing.whatsapp||tenant.whatsapp,email:landing.email||tenant.email,address:landing.address||tenant.address};
  React.useEffect(()=>{
    const root=document.documentElement;
    root.style.setProperty("--tenant-primary",config.primaryColor);root.style.setProperty("--tenant-accent",config.accentColor);root.style.setProperty("--tenant-background",config.backgroundColor);root.style.setProperty("--tenant-radius",config.borderRadius);root.style.setProperty("--tenant-font",`'${config.fontFamily}', Manrope, sans-serif`);root.dataset.template=config.templateId;root.dataset.buttonStyle=config.buttonStyle;root.dataset.density=config.density;
  },[config.templateId,config.primaryColor,config.accentColor,config.backgroundColor,config.borderRadius,config.fontFamily,config.buttonStyle,config.density]);
  React.useEffect(()=>{document.body.style.overflow=contactOpen?"hidden":"";return()=>{document.body.style.overflow=""}},[contactOpen]);
  const quote=()=>setContactOpen(true);
  return <div className={"cl-page cl-template-"+config.templateId}><a className="cl-skip" href="#contenido">Saltar al contenido</a><CLHeader tenant={liveTenant} onQuote={quote}/><main id="contenido"><CLHero tenant={liveTenant} products={products} config={config} onQuote={quote}/>{config.showIntent&&<CLIntent tenant={liveTenant} config={config}/>} {config.showCategories&&<CLCategories tenant={liveTenant} products={products} config={config}/>} {config.showProducts&&<CLProducts tenant={liveTenant} products={products} config={config}/>} {config.showSocial&&<CLSocialRail tenant={liveTenant} products={products}/>} {config.showServices&&<CLServices services={services} config={config} onQuote={quote}/>} {config.showQuote&&<CLQuoteStory config={config} onQuote={quote}/>} {config.showProcess&&<CLProcess config={config}/>} {config.showBenefits&&<CLBenefits config={config}/>}<CLFinal tenant={liveTenant} config={config} onQuote={quote}/></main><CLFooter tenant={liveTenant}/>{contactOpen&&<CLContact tenant={liveTenant} config={config} onClose={()=>setContactOpen(false)}/>}</div>;
}

window.LANACollectionTemplates={CollectionLandingPage};
