const {useEffect,useMemo,useState}=React;

const Arrow=()=> <svg className="icon-arrow" viewBox="0 0 20 20" aria-hidden="true"><path d="M4 10h11M11 6l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>;
const MenuIcon=()=> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>;
function storefrontHref(tenant,moduleName="promo",extra={}){
  const params=new URLSearchParams({cat:moduleName,...extra});
  if(tenant.id)params.set("tenant",tenant.id);
  else if(tenant.slug)params.set("t",tenant.slug);
  return `catalogo.html?${params.toString()}`;
}
const catalogHref=(tenant,extra={})=>storefrontHref(tenant,"promo",extra);
const printHref=tenant=>storefrontHref(tenant,"impresion");

function Brand({tenant}){
  return <a className="brand" href="#inicio">
    {tenant.logoUrl?<img src={tenant.logoUrl} alt={`Logotipo de ${tenant.businessName}`}/>:<span>{tenant.businessName[0]}</span>}
    <span className="brand-copy"><strong>{tenant.businessName}</strong><small>{tenant.modules.promo&&tenant.modules.impresion?"Productos e impresión":tenant.modules.impresion?"Impresión a medida":"Productos personalizados"}</small></span>
  </a>;
}

function Header({tenant,quoteCount,onOpenQuote}){
  const[open,setOpen]=useState(false);
  return <header className="public-header"><div className="shell header-inner">
    <Brand tenant={tenant}/>
    <button className="menu" onClick={()=>setOpen(!open)} aria-expanded={open} aria-controls="public-nav" aria-label={open?"Cerrar menú":"Abrir menú"}><MenuIcon/></button>
    <nav id="public-nav" className={open?"open":""} aria-label="Navegación principal">
      <a href="#inicio">Inicio</a>{tenant.modules.promo&&<a href="#catalogo">Productos</a>}{tenant.modules.impresion&&<a href="#servicios">Impresión</a>}<a href="#proceso">Cómo funciona</a><a href="#contacto">Contacto</a>
      <button className="nav-cta" onClick={onOpenQuote}>Cotización <b>{quoteCount}</b></button>
    </nav>
  </div></header>;
}

function Heading({eyebrow,title,text,link}){
  return <div className="heading"><div><span className="eyebrow">{eyebrow}</span><h2>{title}</h2>{text&&<p>{text}</p>}</div>{link&&<a href={link.href}>{link.label} <Arrow/></a>}</div>;
}

function Hero({tenant,products}){
  const images=products.filter(product=>product.imageUrl).slice(0,3);
  const primaryHref=tenant.modules.promo?catalogHref(tenant):printHref(tenant);
  return <section id="inicio" className="hero shell">
    <div className="hero-copy"><span className="eyebrow">{tenant.heroEyebrow}</span><h1>{tenant.slogan}</h1><p>{tenant.description}</p>
      <div className="actions"><a className="btn primary" href={primaryHref}>{tenant.primaryCtaLabel} <Arrow/></a><a className="btn secondary" href="#servicios">{tenant.secondaryCtaLabel}</a></div>
      <div className="trust"><span>✓ Asesoría especializada</span><span>✓ Cotización integrada</span><span>✓ Revisión humana</span></div>
    </div>
    <div className={`hero-art hero-${tenant.heroLayout}`}>
      {tenant.heroImageUrl?<img className="hero-photo" src={tenant.heroImageUrl} alt="Productos destacados"/>:images.length?images.map((product,index)=><figure className={`hero-product p${index}`} key={product.id}><img src={product.imageUrl} alt={product.name}/><figcaption>{product.name}</figcaption></figure>):<div className="hero-placeholder"><i></i><b>Tu idea</b><span>lista para producir</span></div>}
      <aside><b>✓</b> Todo en una sola cotización</aside>
    </div>
  </section>;
}

function Marquee({tenant}){
  const items=String(tenant.marqueeTexto||"").split(",").map(text=>text.trim()).filter(Boolean);
  if(!items.length)return null;
  const set=(key)=>items.map((text,index)=><React.Fragment key={key+"-"+index}><span>{text}</span><span className="marquee-sep">◆</span></React.Fragment>);
  return <div className="marquee" aria-hidden="true"><div className="marquee-track"><div className="marquee-set">{set("a")}</div><div className="marquee-set">{set("b")}</div></div></div>;
}

function IntentSelector({tenant,services}){
  const intents=[];
  if(tenant.modules.promo)intents.push(["productos","PR","Productos publicados","Explora las categorías disponibles",catalogHref(tenant)]);
  if(tenant.modules.impresion)intents.push(["impresion","IM","Impresión y gran formato",services.filter(service=>service.kind==="impresion").slice(0,3).map(service=>service.name).join(", ")||"Configura medidas y acabados",printHref(tenant)]);
  services.slice(0,Math.max(0,5-intents.length)).forEach(service=>intents.push(["servicio-"+service.id,service.icon,service.name,service.description,"#servicios"]));
  intents.push(["asesoria","?","Necesito asesoría","Cuéntanos tu proyecto y te orientamos",tenant.modules.promo?catalogHref(tenant):printHref(tenant)]);
  const[selected,setSelected]=useState(intents[0]?.[0]||"asesoria");
  return <section className="intent shell"><div className="intent-box">
    <div className="intent-head"><div><span className="eyebrow">Empieza por aquí</span><h2>{tenant.intentTitle}</h2></div><p>Puedes combinar productos y servicios. Tu selección permanecerá disponible mientras navegas.</p></div>
    <div className="intent-grid">{intents.map(([id,icon,title,description,href])=><a href={href} onMouseEnter={()=>setSelected(id)} onFocus={()=>setSelected(id)} className={`intent-card ${selected===id?"active":""} ${id==="asesoria"?"ai-intent":""}`} key={id}><span>{icon}</span><strong>{title}</strong><small>{description}</small></a>)}</div>
  </div></section>;
}

function Empty({title,text}){return <div className="empty"><span aria-hidden="true">□</span><strong>{title}</strong><p>{text}</p></div>}

function Categories({tenant,products}){
  const categories=useMemo(()=>[...new Set(products.map(product=>product.category).filter(Boolean))].slice(0,6),[products]);
  return <section id="catalogo" className="section white"><div className="shell">
    <Heading eyebrow="Catálogo" title={tenant.catalogTitle} text="Explora categorías reales del negocio y combínalas con la técnica adecuada." link={{href:catalogHref(tenant),label:"Ver catálogo completo"}}/>
    {categories.length?<div className="categories">{categories.map((category,index)=>{const image=products.find(product=>product.category===category&&product.imageUrl)?.imageUrl;return <a href={catalogHref(tenant,{buscar:category})} className={`category c${index}`} key={category}>{image?<img src={image} alt=""/>:<em>{String(index+1).padStart(2,"0")}</em>}<strong>{category}</strong><span>Explorar <Arrow/></span></a>})}</div>:<Empty title="Catálogo pendiente" text="Este tenant aún no tiene categorías públicas."/>}
  </div></section>;
}

function Product({tenant,product,onPreviewAdd}){
  const price=product.direct&&Number.isFinite(product.price)?`Desde ${new Intl.NumberFormat("es-MX",{style:"currency",currency:"MXN"}).format(product.price)}`:"Precio según configuración";
  const href=catalogHref(tenant,{producto:product.id});
  return <article className="product"><a className="product-media" href={href}>{product.imageUrl?<img src={product.imageUrl} alt={product.name}/>:<span>{product.name.slice(0,2).toUpperCase()}</span>}{product.customizable&&<b>Personalizable</b>}</a><div><small>{product.category}</small><h3>{product.name}</h3><p>{price}</p><footer><a href={href}>Ver producto</a><button onClick={()=>onPreviewAdd({id:`product-${product.id}`,name:product.name,meta:"Configuración pendiente",icon:"PR"})}>Agregar +</button></footer></div></article>;
}

function Products({tenant,products,onPreviewAdd}){
  const list=(products.some(product=>product.featured)?products.filter(product=>product.featured):products).slice(0,4);
  return <section className="section"><div className="shell"><Heading eyebrow="Selección destacada" title={tenant.productsTitle} text="Opciones reales del catálogo activo, listas para personalizar."/>{list.length?<div className="products">{list.map(product=><Product tenant={tenant} product={product} onPreviewAdd={onPreviewAdd} key={product.id}/>)}</div>:<Empty title="Sin productos destacados" text="El negocio todavía no publica productos en esta sección."/>}</div></section>;
}

function Services({tenant,services,onPreviewAdd}){
  return <section id="servicios" className="section white"><div className="shell"><Heading eyebrow="Servicios de producción" title={tenant.servicesTitle} text="Servicios configurados y disponibles actualmente."/>{services.length?<div className="services">{services.map((service,index)=><article key={service.id}><em>{String(index+1).padStart(2,"0")}</em><b>{service.icon}</b><div><h3>{service.name}</h3><p>{service.description}</p><a href={service.kind==="impresion"?printHref(tenant):catalogHref(tenant)}>Solicitar cotización <Arrow/></a></div></article>)}</div>:<Empty title="Servicios por publicar" text="Este negocio aún no tiene servicios públicos configurados."/>}</div></section>;
}

function UnifiedQuote({tenant,products,services,onOpenQuote}){
  const concepts=[...products.slice(0,2).map(product=>({icon:"PR",name:product.name,meta:product.category})),...services.slice(0,1).map(service=>({icon:service.icon,name:service.name,meta:service.description}))].slice(0,3);
  return <section className="bundle"><div className="shell bundle-grid"><div><span className="eyebrow">Cotización unificada</span><h2>{tenant.quoteTitle}</h2><p>Selecciona productos publicados y servicios activos. LANA conserva cada concepto dentro de una misma solicitud.</p><button className="btn primary" onClick={onOpenQuote}>Iniciar cotización <Arrow/></button></div><div className="bundle-example">{concepts.length?concepts.map((concept,index)=><div className="bundle-item" key={index}><span>{concept.icon}</span><div><strong>{concept.name}</strong><small>{concept.meta}</small></div></div>):<div className="bundle-item"><span>01</span><div><strong>Tu proyecto</strong><small>Agrega el primer concepto para comenzar</small></div></div>}<div className="bundle-total"><span>{concepts.length||1} {concepts.length===1?"concepto":"conceptos"}</span><strong>Una solicitud</strong></div></div></div></section>;
}

function Ai({tenant,products,services}){
  const examples=[products[0]&&["Producto",products[0].name],services[0]&&["Servicio",services[0].name],["Pendiente","Cantidad, medidas y fecha"]].filter(Boolean);
  const names=examples.slice(0,2).map(item=>item[1]);
  const prompt=names.length?`Quiero cotizar ${names.join(" y ")}. Necesito ayuda para definir cantidades y entrega.`:"Cuéntanos qué necesitas producir y te ayudaremos a ordenar la solicitud.";
  const href=tenant.modules.promo?catalogHref(tenant):printHref(tenant);
  return <section className="ai"><div className="shell ai-grid"><div><span className="eyebrow">Asistente inteligente</span><h2>{tenant.aiTitle}</h2><p>Describe tu proyecto como se lo explicarías a una persona. El asistente organiza conceptos y señala información pendiente antes de enviarla al negocio.</p><a className="btn light" href={href}>Cuéntanos tu proyecto <Arrow/></a></div><div className="ai-demo"><span className="ai-demo-label">Ejemplo con opciones disponibles</span><p>{prompt}</p><div className="ai-demo-grid">{examples.map(([label,value])=><span key={label}><b>{label}</b>{value}</span>)}</div></div></div></section>;
}

function Process({tenant}){const steps=[["Elige","Producto, servicio o describe tu idea"],["Configura","Cantidad, medidas y opciones"],["Adjunta","Comparte tu diseño"],["Revisa","Completa la información"],["Confirma","El negocio valida"]];return <section id="proceso" className="section white"><div className="shell"><Heading eyebrow="Proceso sencillo" title={tenant.processTitle} text="Un flujo claro aunque no conozcas los términos técnicos."/><ol className="process">{steps.map(([title,text],index)=><li key={title}><b>0{index+1}</b><strong>{title}</strong><span>{text}</span></li>)}</ol></div></section>}

function Benefits({tenant}){return <section className="benefits"><div className="shell benefit-grid"><div><span className="eyebrow">Por qué elegirnos</span><h2>{tenant.benefitsTitle}</h2></div><div><article><b>01</b><span><strong>Orientación especializada</strong><small>Opciones explicadas sin complicaciones.</small></span></article><article><b>02</b><span><strong>Soluciones a tu medida</strong><small>La recomendación parte de tu objetivo.</small></span></article><article><b>03</b><span><strong>Seguimiento confiable</strong><small>Tu solicitud llega lista para validación.</small></span></article></div></div></section>}

function Cta({tenant,onOpenQuote}){return <section className="cta shell"><div><span className="eyebrow">Empecemos</span><h2>{tenant.finalCtaTitle}</h2><p>Explora el catálogo o cuéntanos qué necesitas producir.</p></div><div><button className="btn light" onClick={onOpenQuote}>Iniciar cotización <Arrow/></button>{tenant.whatsapp&&<a className="btn outline" href={`https://wa.me/${tenant.whatsapp.replace(/\D/g,"")}`}>WhatsApp</a>}</div></section>}

function Footer({tenant}){return <footer id="contacto" className="site-footer"><div className="shell footer-grid"><div><Brand tenant={tenant}/><p>{tenant.description}</p></div><div><h3>Explora</h3>{tenant.modules.promo&&<a href="#catalogo">Productos</a>}{tenant.modules.impresion&&<a href="#servicios">Impresión</a>}<a href="#proceso">Cómo funciona</a></div><div><h3>Contacto</h3>{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>Consulta disponibilidad al cotizar</span>}</div></div><div className="shell copyright">© {new Date().getFullYear()} {tenant.businessName}</div></footer>}

function QuoteDrawer({open,items,onClose,tenant}){
  return <><button className={`quote-backdrop ${open?"open":""}`} onClick={onClose} aria-label="Cerrar cotización"/><aside className={`quote-drawer ${open?"open":""}`} aria-label="Resumen de cotización" aria-hidden={!open}><div className="drawer-head"><div><span className="eyebrow">Resumen</span><h2>Tu cotización</h2></div><button onClick={onClose} aria-label="Cerrar">×</button></div><div className="drawer-items">{items.length?items.map(item=><article className="drawer-item" key={item.id}><span>{item.icon}</span><div><strong>{item.name}</strong><small>{item.meta}</small><em>Requiere información</em></div></article>):<Empty title="Aún no hay conceptos" text="Agrega productos o servicios para comenzar."/>}</div><div className="drawer-total"><div><span>Total estimado</span><strong>Por calcular</strong></div><p>No mostraremos un precio final hasta que la configuración sea validada.</p><a className="btn primary" href={catalogHref(tenant)}>Continuar cotización <Arrow/></a></div></aside></>;
}

function Loading(){return <div className="state" role="status"><i></i><p>Preparando el catálogo…</p></div>}

function applyTheme(tenant){
  const root=document.documentElement;
  root.style.setProperty("--tenant-primary",tenant.primaryColor);
  root.style.setProperty("--tenant-accent",tenant.accentColor);
  root.style.setProperty("--tenant-background",tenant.backgroundColor);
  root.style.setProperty("--tenant-radius",tenant.borderRadius);
  root.style.setProperty("--tenant-font",`'${tenant.fontFamily}', Manrope, sans-serif`);
  root.dataset.buttonStyle=tenant.buttonStyle;
  root.dataset.density=tenant.density;
  root.dataset.template=tenant.templateId;
  document.title=`${tenant.businessName} — Productos, impresión y personalización`;
}

function mergePreviewTenant(tenant,form){
  return{...tenant,...form,slogan:form.heroTitle??tenant.slogan,description:form.heroDescription??tenant.description,
    logoUrl:form.logoUrl||tenant.logoUrl,heroImageUrl:form.heroImageUrl||null,
    primaryColor:form.primaryColor||tenant.primaryColor,accentColor:form.accentColor||tenant.accentColor,
    backgroundColor:form.backgroundColor||tenant.backgroundColor};
}

function App(){
  const[state,setState]=useState({loading:true,error:false,data:null});
  const[quoteOpen,setQuoteOpen]=useState(false);
  const[previewItems,setPreviewItems]=useState([]);
  function load(){setState({loading:true,error:false,data:null});window.LANAPublicData.loadLanding().then(data=>{applyTheme(data.tenant);setState({loading:false,error:false,data})}).catch(()=>setState({loading:false,error:true,data:null}))}
  useEffect(load,[]);
  useEffect(()=>{
    const receive=event=>{
      if(event.origin!==window.location.origin||event.data?.type!=="lana:landing-preview")return;
      setState(current=>{
        if(!current.data)return current;
        const tenant=mergePreviewTenant(current.data.tenant,event.data.payload||{});
        applyTheme(tenant);
        return{...current,data:{...current.data,tenant}};
      });
    };
    window.addEventListener("message",receive);
    return()=>window.removeEventListener("message",receive);
  },[]);
  useEffect(()=>{document.body.style.overflow=quoteOpen?"hidden":"";return()=>{document.body.style.overflow=""}},[quoteOpen]);
  if(state.loading)return <Loading/>;
  if(state.error)return <div className="state"><h1>No pudimos cargar esta página</h1><button className="btn primary" onClick={load}>Volver a intentar</button></div>;
  const{tenant,products,services}=state.data;
  const previewTemplate=new URLSearchParams(window.location.search).get("preview_template");
  const activeTemplate=previewTemplate||tenant.templateId;
  if(activeTemplate==="production-studio"&&window.LANAProductionTemplate){
    const ProductionStudioPage=window.LANAProductionTemplate.ProductionStudioPage;
    return <ProductionStudioPage tenant={tenant} products={products} services={services}/>;
  }
  if(activeTemplate==="product-story"&&window.LANAProductStoryTemplate){
    const ProductStoryPage=window.LANAProductStoryTemplate.ProductStoryPage;
    return <ProductStoryPage tenant={tenant} products={products} services={services}/>;
  }
  if(window.LANACollectionCore&&window.LANACollectionTemplates&&window.LANACollectionCore.TEMPLATE_IDS.includes(activeTemplate)){
    const CollectionLandingPage=window.LANACollectionTemplates.CollectionLandingPage;
    return <CollectionLandingPage tenant={tenant} products={products} services={services} templateOverride={previewTemplate}/>;
  }
  const addPreviewItem=item=>{setPreviewItems(current=>current.some(existing=>existing.id===item.id)?current:[...current,item]);setQuoteOpen(true)};
  return <><Header tenant={tenant} quoteCount={previewItems.length} onOpenQuote={()=>setQuoteOpen(true)}/><main><Hero tenant={tenant} products={products}/>{tenant.showMarquee&&<Marquee tenant={tenant}/>}<IntentSelector tenant={tenant} services={services}/>{tenant.modules.promo&&tenant.showCategories&&products.length>0&&<Categories tenant={tenant} products={products}/>} {tenant.modules.promo&&tenant.showProducts&&<Products tenant={tenant} products={products} onPreviewAdd={addPreviewItem}/>} {tenant.showServices&&<Services tenant={tenant} services={services} onPreviewAdd={addPreviewItem}/>}<UnifiedQuote tenant={tenant} products={products} services={services} onOpenQuote={()=>setQuoteOpen(true)}/>{tenant.showAi&&<Ai tenant={tenant} products={products} services={services}/>} {tenant.showProcess&&<Process tenant={tenant}/>} {tenant.showBenefits&&<Benefits tenant={tenant}/>}<Cta tenant={tenant} onOpenQuote={()=>setQuoteOpen(true)}/></main><Footer tenant={tenant}/><QuoteDrawer open={quoteOpen} items={previewItems} onClose={()=>setQuoteOpen(false)} tenant={tenant}/></>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
