const StoryIcon=({name,size=20})=>{
  const icons={arrow:<><path d="M5 12h14M14 7l5 5-5 5"/></>,menu:<><path d="M4 7h16M4 12h16M4 17h16"/></>,close:<><path d="m6 6 12 12M18 6 6 18"/></>,bag:<><path d="M6 8h12l1 13H5L6 8ZM9 9V6a3 3 0 0 1 6 0v3"/></>,check:<><path d="m5 12 4 4L19 6"/></>,box:<><path d="m4 7 8-4 8 4-8 4-8-4ZM4 7v10l8 4 8-4V7M12 11v10"/></>};
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{icons[name]||icons.arrow}</svg>;
};

function StoryBrand({tenant}){
  return <a className="story-brand" href="#inicio" aria-label={`Inicio de ${tenant.businessName}`}>{tenant.logoUrl?<img src={tenant.logoUrl} alt=""/>:<span aria-hidden="true">{String(tenant.businessName||"L").slice(0,1)}</span>}<strong>{tenant.businessName}</strong></a>;
}

function StoryHeader({tenant,onQuote}){
  const[open,setOpen]=React.useState(false);
  const close=()=>setOpen(false);
  return <><div className="story-announcement"><span>Productos personalizados para hacer visible tu marca</span><a href="#seleccion">Ver selección <StoryIcon name="arrow" size={15}/></a></div><header className="story-header"><div className="story-header-inner"><button className="story-menu" type="button" aria-expanded={open} aria-controls="story-navigation" aria-label={open?"Cerrar menú":"Abrir menú"} onClick={()=>setOpen(value=>!value)}><StoryIcon name={open?"close":"menu"} size={24}/></button><StoryBrand tenant={tenant}/><nav id="story-navigation" className={open?"is-open":""} aria-label="Navegación principal"><a href="#seleccion" onClick={close}>Destacados</a><a href="#colecciones" onClick={close}>Colecciones</a><a href="#servicios" onClick={close}>Personalización</a></nav><button className="story-order" type="button" onClick={()=>{close();onQuote()}}>Cotizar <StoryIcon name="arrow" size={17}/></button></div></header></>;
}

function StoryHero({tenant,products,onQuote}){
  const Core=window.LANACollectionCore;
  const featured=products.find(product=>product.featured&&product.imageUrl)||products.find(product=>product.imageUrl);
  const image=tenant.heroImageUrl||featured?.imageUrl;
  return <section id="inicio" className="story-hero"><div className="story-hero-visual">{image?<img src={image} alt={tenant.heroImageUrl?`Proyecto destacado de ${tenant.businessName}`:(featured?.name||"Producto destacado")}/>:<div className="story-media-empty"><StoryIcon name="bag" size={78}/><span>Agrega una imagen principal o publica productos para completar esta campaña.</span></div>}<span className="story-edition">Colección de marca</span></div><div className="story-hero-message"><span className="story-kicker">{tenant.heroEyebrow}</span><h1>{tenant.heroTitle}</h1><p>{tenant.description}</p><div className="story-actions"><a className="story-button story-button-primary" href={Core.catalogHref(tenant)}>{tenant.primaryCtaLabel}<StoryIcon name="arrow" size={18}/></a><button className="story-button story-button-secondary" type="button" onClick={onQuote}>{tenant.secondaryCtaLabel}</button></div></div></section>;
}

function StorySectionTitle({eyebrow,title,text,action}){
  return <div className="story-section-title"><span className="story-kicker">{eyebrow}</span><h2>{title}</h2>{text&&<p>{text}</p>}{action&&<a href={action.href}>{action.label}<StoryIcon name="arrow" size={18}/></a>}</div>;
}

function StoryFeatured({tenant,products,onQuote}){
  const Core=window.LANACollectionCore;
  const list=(products.some(item=>item.featured)?products.filter(item=>item.featured):products).slice(0,6);
  return <section id="seleccion" className="story-featured"><div className="story-shell"><StorySectionTitle eyebrow="Selección destacada" title={tenant.productsTitle} text="Piezas reales del catálogo, presentadas como una colección para descubrirlas de un vistazo."/>{list.length?<div className="story-feature-grid">{list.map((product,index)=>{const href=Core.catalogHref(tenant,"catalogo.html?producto="+encodeURIComponent(product.id));const price=product.direct&&Number.isFinite(product.price)?new Intl.NumberFormat("es-MX",{style:"currency",currency:"MXN"}).format(product.price):"Cotización personalizada";return <article className={`story-feature story-feature-${index%4}`} key={product.id}><a className="story-feature-image" href={href}>{product.imageUrl?<img src={product.imageUrl} alt={product.name}/>:<span><StoryIcon name="bag" size={62}/>Imagen en preparación</span>}<small>{index<2?"Recomendado":"Disponible"}</small></a><div><span>{product.category||"Producto personalizable"}</span><h3>{product.name}</h3><p>{price}</p><div><a href={href}>Conocer producto</a><button type="button" onClick={()=>onQuote(product.name)}>Cotizar</button></div></div></article>})}</div>:<StoryEmpty title="Tu selección está en preparación" text="Publica productos o marca tus favoritos para mostrarlos aquí."/>}</div></section>;
}

function StoryCollections({tenant,products}){
  const Core=window.LANACollectionCore;
  const categories=[...new Set(products.map(product=>product.category).filter(Boolean))].slice(0,4);
  return <section id="colecciones" className="story-collections-section"><div className="story-shell"><StorySectionTitle eyebrow="Siempre disponibles" title={tenant.catalogTitle} text="Explora por tipo de producto y encuentra una base para tu siguiente proyecto." action={{href:Core.catalogHref(tenant),label:"Ver catálogo completo"}}/>{categories.length?<div className="story-collection-row">{categories.map((category,index)=>{const product=products.find(item=>item.category===category&&item.imageUrl);return <a className="story-collection" href={Core.catalogHref(tenant,"catalogo.html?cat="+encodeURIComponent(category))} key={category}><div>{product?<img src={product.imageUrl} alt=""/>:<StoryIcon name="box" size={54}/>}</div><span>{String(index+1).padStart(2,"0")}</span><strong>{category}</strong><small>Explorar <StoryIcon name="arrow" size={15}/></small></a>})}</div>:<StoryEmpty title="Catálogo en preparación" text="Las colecciones aparecerán al publicar productos."/>}</div></section>;
}

function StoryServices({tenant,services,onQuote}){
  if(!services.length)return null;
  return <section id="servicios" className="story-services-section"><div className="story-shell"><StorySectionTitle eyebrow="Hazlo tuyo" title={tenant.servicesTitle} text="Elige una pieza y combínala con la técnica que mejor representa tu marca."/><div className="story-services">{services.slice(0,6).map((service,index)=><article key={service.id}><span>{String(index+1).padStart(2,"0")}</span><div><h3>{service.name}</h3><p>{service.description}</p></div><button type="button" onClick={()=>onQuote(service.name)}>Cotizar servicio <StoryIcon name="arrow" size={18}/></button></article>)}</div></div></section>;
}

function StoryProcess({tenant}){
  const steps=[{title:"Elige tu producto",text:"Explora el catálogo o comparte una referencia."},{title:"Personaliza la idea",text:"Define técnica, colores, posiciones y cantidades."},{title:"Aprueba y produce",text:"Revisa los detalles antes de iniciar producción."}];
  return <section className="story-process"><div className="story-shell"><StorySectionTitle eyebrow="Así de simple" title={tenant.processTitle}/><ol>{steps.map((step,index)=><li key={step.title}><span>{String(index+1).padStart(2,"0")}</span><h3>{step.title}</h3><p>{step.text}</p></li>)}</ol></div></section>;
}

function StoryEmpty({title,text}){return <div className="story-empty"><StoryIcon name="bag" size={42}/><strong>{title}</strong><p>{text}</p></div>}

function StoryContact({tenant,initialNeed,onClose}){
  const[name,setName]=React.useState("");const[need,setNeed]=React.useState(initialNeed||"");const[quantity,setQuantity]=React.useState("");const closeRef=React.useRef(null);
  React.useEffect(()=>{closeRef.current?.focus();const handle=event=>event.key==="Escape"&&onClose();document.addEventListener("keydown",handle);return()=>document.removeEventListener("keydown",handle)},[onClose]);
  const send=event=>{event.preventDefault();const text=`Hola, soy ${name}. Quiero cotizar ${need}. Cantidad aproximada: ${quantity||"por definir"}.`;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="story-contact" role="dialog" aria-modal="true" aria-labelledby="story-contact-title"><button className="story-contact-backdrop" type="button" onClick={onClose} aria-label="Cerrar formulario"/><div className="story-contact-panel"><header><div><span className="story-kicker">Nueva solicitud</span><h2 id="story-contact-title">Hablemos de tu proyecto</h2></div><button ref={closeRef} type="button" onClick={onClose} aria-label="Cerrar"><StoryIcon name="close" size={22}/></button></header><p>Comparte lo esencial. El equipo confirmará opciones, tiempos y precio antes de producir.</p><form onSubmit={send}><label><span>Tu nombre</span><input required autoComplete="name" value={name} onChange={event=>setName(event.target.value)}/></label><label><span>¿Qué necesitas?</span><textarea required rows="4" value={need} onChange={event=>setNeed(event.target.value)} placeholder="Ej. polos bordados para el equipo comercial"/></label><label><span>Cantidad aproximada</span><input inputMode="numeric" value={quantity} onChange={event=>setQuantity(event.target.value)} placeholder="Ej. 50"/></label><button className="story-button story-button-primary" type="submit">Enviar solicitud <StoryIcon name="arrow" size={18}/></button></form></div></div>;
}

function StoryFinal({tenant,onQuote}){return <section id="contacto" className="story-final"><div className="story-shell"><span className="story-kicker">Tu siguiente proyecto</span><h2>{tenant.finalCtaTitle}</h2><p>Cuéntanos qué quieres crear y te ayudamos a convertirlo en una producción clara y bien resuelta.</p><button className="story-button story-button-light" type="button" onClick={()=>onQuote("")}>Comenzar cotización <StoryIcon name="arrow" size={18}/></button></div></section>}

function StoryFooter({tenant}){
  const Core=window.LANACollectionCore;
  return <footer className="story-footer"><div className="story-shell story-footer-grid"><div><StoryBrand tenant={tenant}/><p>{tenant.description}</p></div><nav aria-label="Navegación secundaria"><strong>Explora</strong><a href={Core.catalogHref(tenant)}>Catálogo</a><a href="#seleccion">Destacados</a><a href="#servicios">Personalización</a></nav><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="story-shell story-footer-bottom"><span>© {new Date().getFullYear()} {tenant.businessName}</span><span>Experiencia desarrollada con LANA</span></div></footer>;
}

function ProductStoryPage({tenant,products,services}){
  const[contact,setContact]=React.useState(null);
  React.useEffect(()=>{document.body.style.overflow=contact===null?"":"hidden";return()=>{document.body.style.overflow=""}},[contact]);
  React.useEffect(()=>{const root=document.documentElement;root.dataset.template="product-story";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||"16px")},[tenant.primaryColor,tenant.accentColor,tenant.backgroundColor,tenant.borderRadius]);
  const quote=(need="")=>setContact(need);
  return <div className="story-page"><a className="story-skip" href="#story-content">Saltar al contenido</a><StoryHeader tenant={tenant} onQuote={()=>quote("")}/><main id="story-content"><StoryHero tenant={tenant} products={products} onQuote={()=>quote("")}/>{tenant.showProducts!==false&&<StoryFeatured tenant={tenant} products={products} onQuote={quote}/>} {tenant.showCategories!==false&&<StoryCollections tenant={tenant} products={products}/>} {tenant.showServices!==false&&<StoryServices tenant={tenant} services={services} onQuote={quote}/>} {tenant.showProcess!==false&&<StoryProcess tenant={tenant}/>}<StoryFinal tenant={tenant} onQuote={quote}/></main><StoryFooter tenant={tenant}/><button className="story-mobile-cta" type="button" onClick={()=>quote("")}>Cotizar proyecto <StoryIcon name="arrow" size={17}/></button>{contact!==null&&<StoryContact tenant={tenant} initialNeed={contact} onClose={()=>setContact(null)}/>}</div>;
}

window.LANAProductStoryTemplate={ProductStoryPage};
