/* Decretando Disney — pantallas. Exporta Home, Nosotros, Contacto,
   CategoryScreen, DestinationScreen, ReservaScreen */
(function(){
  const { useState } = React;
  const Ic = window.DDIcons;

  /* Gestor global: solo UN video se reproduce a la vez (el más visible,
     o el que el usuario señala con el mouse). Evita que compitan por CPU/GPU. */
  const VM = {
    vids: new Map(),   // el -> ratio de visibilidad
    hovered: null,
    update(){
      let best = null;
      if(this.hovered && (this.vids.get(this.hovered) || 0) > 0){
        best = this.hovered;
      } else {
        let max = 0.2;   // mínimo para arrancar
        this.vids.forEach((r, el)=>{ if(r > max){ max = r; best = el; } });
      }
      this.vids.forEach((r, el)=>{
        if(el === best){ el.play().catch(()=>{}); }
        else if(!el.paused){ el.pause(); }
      });
    }
  };

  function lazyVideo(el){
    if(!el || el.__ddio) return;
    el.muted = true;
    const io = new IntersectionObserver((entries)=>{
      entries.forEach(e=>{ VM.vids.set(el, e.isIntersecting ? e.intersectionRatio : 0); });
      VM.update();
    }, {threshold:[0,.2,.4,.6,.8,1]});
    io.observe(el);
    el.__ddio = io;
    el.addEventListener('pointerenter', ()=>{ VM.hovered = el; VM.update(); });
    el.addEventListener('pointerleave', ()=>{ if(VM.hovered === el) VM.hovered = null; VM.update(); });
  }

  /* ===================== INICIO ===================== */
  function Home({ nav, openMenu }){
    const cats = window.DD_DATA.categorias;
    const scrollCats = ()=>{
      const el = document.getElementById('home-cats');
      if(el) el.scrollIntoView ? el.parentNode.scrollTo({top:el.offsetTop-90, behavior:'smooth'}) : null;
    };
    return (
      <div className="dd-screen" id="screen-home">
        <div className="dd-hero">
          <img className="logo" src="assets/logo-clean.png" alt="Decretando Disney" />
          <div className="kicker">Con Martín &amp; Mica · Agencia de viajes</div>
          <h1>Decretá tu próxima <em>aventura</em></h1>
          <p className="lead">Armamos el viaje de tus sueños a medida. Parques, playas paradisíacas
            y ciudades increíbles te esperan. ¿Empezamos a planear?</p>
          <div className="dd-cta">
            <button className="btn btn-primary" onClick={openMenu}>
              Explorá los destinos <Ic.arrow size={20} color="#fff" stroke={2.6}/>
            </button>
            <button className="btn btn-ghost" onClick={()=>nav({name:'contacto'})}>Hablá con nosotros</button>
          </div>
          <div className="dd-scrollhint" onClick={scrollCats}>
            <span>Mirá los destinos</span>
            <Ic.arrow size={20} color="#9db4e8" stroke={2.4} />
          </div>
        </div>

        <div className="dd-wrap dd-homecats" id="home-cats" style={{paddingTop:'10px',paddingBottom:'40px'}}>
          <h2>¿A dónde querés ir?</h2>
          <p className="sub">Elegí un destino y dejá que la magia haga el resto.</p>
          <div className="dd-grid">
            {cats.map(c=>{
              const Icn = Ic[c.icono];
              return (
              <div key={c.id} className="dd-chip" onClick={()=>nav({name:'category', catId:c.id})}>
                <span className="ic"><Icn size={42} color="rgba(255,255,255,.92)" stroke={2.2}/></span>
                <span className="nm">{c.nombre}</span>
                <span className="tg">{c.tagline}</span>
              </div>
            );})}
          </div>

          <window.Mickey3D />

          <div className="dd-videoshome">
            <h2>Mirá lo que te espera</h2>
            <p className="sub">Un adelanto en movimiento de la magia que vas a vivir.</p>
            <div className="dd-videogrid">
              <div className="dd-vcard" onClick={()=>nav({name:'destination', catId:'disney-world', destId:'magic-kingdom'})}>
                <video src="assets/destinos/video-magic-kingdom.mp4" muted loop playsInline preload="metadata"
                  ref={lazyVideo}></video>
                <div className="cap">
                  <h3>Magic Kingdom · Disney World</h3>
                  <span className="go">Ver destino</span>
                </div>
              </div>
              <div className="dd-vcard" onClick={()=>nav({name:'destination', catId:'disney-world', destId:'epcot'})}>
                <video src="assets/destinos/video-epcot.mp4" muted loop playsInline preload="metadata"
                  ref={lazyVideo}></video>
                <div className="cap">
                  <h3>EPCOT · Disney World</h3>
                  <span className="go">Ver destino</span>
                </div>
              </div>
              <div className="dd-vcard" onClick={()=>nav({name:'destination', catId:'universal', destId:'universal-florida'})}>
                <video src="assets/destinos/video-universal.mp4" muted loop playsInline preload="metadata"
                  ref={lazyVideo}></video>
                <div className="cap">
                  <h3>Universal Studios</h3>
                  <span className="go">Ver destino</span>
                </div>
              </div>
              <div className="dd-vcard" onClick={()=>nav({name:'destination', catId:'disney-world', destId:'animal-kingdom'})}>
                <video src="assets/destinos/video-animal-kingdom.mp4" muted loop playsInline preload="metadata"
                  ref={lazyVideo}></video>
                <div className="cap">
                  <h3>Animal Kingdom · Disney World</h3>
                  <span className="go">Ver destino</span>
                </div>
              </div>
            </div>
          </div>
          <div className="dd-testis">
            <h2>Lo que dicen nuestros viajeros</h2>
            <p className="sub">Historias reales de quienes ya decretaron su viaje con nosotros.</p>
            <div className="dd-testigrid">
              {window.DD_DATA.testimonios.map((t,i)=>(
                <div key={i} className="dd-card dd-cardneon dd-testi">
                  <span className="stars">★★★★★</span>
                  <blockquote>“{t.texto}”</blockquote>
                  <div className="who">
                    <span className="nm">{t.nombre}</span>
                    <span className="src">vía {t.fuente}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ===================== NOSOTROS ===================== */
  function Nosotros({ nav }){
    const n = window.DD_DATA.nosotros;
    return (
      <div className="dd-screen">
        <div className="dd-wrap">
          <button className="dd-back" onClick={()=>nav({name:'home'})}>
            <Ic.arrow size={18} color="#cdd9ff" stroke={2.6} style={{transform:'rotate(180deg)'}}/> Volver al inicio
          </button>
          <div><span className="dd-eyebrow"><Ic.heart size={16} color="#fff" stroke={2.6}/> Nosotros</span></div>
          <h1 className="dd-pagetitle">{n.titulo}</h1>
          <p className="dd-pagelead">Detrás de cada viaje hay dos personas que aman lo que hacen.</p>

          <div className="dd-about">
            <div className="dd-card dd-about__text">
              {n.parrafos.map((p,i)=><p key={i}>{p}</p>)}
            </div>
            <div className="dd-values">
              <div className="dd-card dd-photocard">
                <img src="assets/micaymartin.png" alt="Martín y Mica junto a Mickey" />
                <div className="tag">Martín &amp; Mica</div>
              </div>
              {n.valores.map((v,i)=>(
                <div key={i} className="dd-card dd-value">
                  <span className="dot"><Ic.sparkle size={22} color="#fff" stroke={2.2}/></span>
                  <div><h4>{v.t}</h4><p>{v.d}</p></div>
                </div>
              ))}
              <button className="btn btn-primary" style={{justifyContent:'center'}}
                onClick={()=>nav({name:'contacto'})}>Contactanos</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ===================== CONTACTANOS ===================== */
  function Contacto({ nav }){
    const c = window.DD_DATA.contacto;
    const igUser = c.instagram.replace('@','');
    return (
      <div className="dd-screen">
        <div className="dd-wrap">
          <button className="dd-back" onClick={()=>nav({name:'home'})}>
            <Ic.arrow size={18} color="#cdd9ff" stroke={2.6} style={{transform:'rotate(180deg)'}}/> Volver al inicio
          </button>
          <div><span className="dd-eyebrow"><Ic.phone size={15} color="#fff" stroke={2.8}/> Contactanos</span></div>
          <h1 className="dd-pagetitle">Hablemos de tu viaje</h1>
          <p className="dd-pagelead">Escribinos por donde te quede más cómodo. Te respondemos con toda la onda
            para empezar a armar tu plan.</p>

          <div className="dd-contact">
            <div className="dd-card dd-contact__item">
              <div className="lbl"><span className="ic"><Ic.mail size={24} color="#005DA8" stroke={2.4}/></span> Mail</div>
              {c.mails.map((m,i)=><a key={i} href={'mailto:'+m}>{m}</a>)}
              <span className="muted">Te respondemos dentro de las 24 hs.</span>
            </div>

            <div className="dd-card dd-contact__item">
              <div className="lbl"><span className="ic"><Ic.phone size={22} color="#005DA8" stroke={2.6}/></span> Teléfono / WhatsApp</div>
              {c.telefonos.map((t,i)=>(
                <a key={i} href={'https://wa.me/'+t.wa} target="_blank" rel="noreferrer">
                  {t.quien}: {t.num}
                </a>
              ))}
              <span className="muted">Tocá para escribirnos por WhatsApp.</span>
            </div>

            <div className="dd-card dd-contact__item">
              <div className="lbl"><span className="ic"><Ic.instagram size={24} color="#005DA8" stroke={2.4}/></span> Instagram</div>
              <a href={'https://instagram.com/'+igUser} target="_blank" rel="noreferrer">{c.instagram}</a>
              <span className="muted">Seguinos para inspirarte con cada destino.</span>
            </div>
          </div>

          <div style={{marginTop:'26px',display:'flex',gap:'14px',flexWrap:'wrap'}}>
            <button className="btn btn-primary" onClick={()=>nav({name:'home'})}>Ver destinos</button>
            <button className="btn btn-ghost" onClick={()=>nav({name:'nosotros'})}>Conocé la agencia</button>
          </div>
        </div>
      </div>
    );
  }

  /* ===================== CATEGORÍA ===================== */
  function CategoryScreen({ cat, nav }){
    const Icn = Ic[cat.icono];
    return (
      <div className="dd-screen">
        <div className="dd-wrap">
          <button className="dd-back" onClick={()=>nav({name:'home'})}>
            <Ic.arrow size={18} color="#cdd9ff" stroke={2.6} style={{transform:'rotate(180deg)'}}/> Inicio
          </button>
          <div style={{display:'flex',alignItems:'center',gap:'16px',flexWrap:'wrap'}}>
            <span className="dd-eyebrow"><Icn size={16} color="#fff" stroke={2.4}/> {cat.tagline}</span>
          </div>
          <h1 className="dd-pagetitle">{cat.nombre}</h1>
          <p className="dd-pagelead">{cat.hero} Elegí tu destino y descubrí todo lo que te espera.</p>

          <div className="dd-dests">
            {cat.destinos.map(d=>(
              <article key={d.id} className="dd-dest" onClick={()=>nav({name:'destination', catId:cat.id, destId:d.id})}>
                <div className="dd-dest__img">
                  <span className="dd-dest__badge">{cat.nombre}</span>
                  {d.img
                    ? <img className="dd-photo" src={d.img} alt={d.nombre} loading="lazy" />
                    : <image-slot id={'slot-'+d.id} shape="rect" fit="cover"
                        placeholder={'Subí una foto de '+d.nombre}></image-slot>}
                </div>
                <div className="dd-dest__body">
                  <h3>{d.nombre}</h3>
                  <p>{d.resumen}</p>
                  <span className="dd-dest__more">Ver destino <Ic.arrow size={18} color="#E42083" stroke={2.6}/></span>
                </div>
              </article>
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* ===================== DETALLE DESTINO ===================== */
  function DestinationScreen({ cat, dest, nav }){
    return (
      <div className="dd-screen">
        <div className="dd-wrap dd-detail">
          <button className="dd-back" onClick={()=>nav({name:'category', catId:cat.id})}>
            <Ic.arrow size={18} color="#cdd9ff" stroke={2.6} style={{transform:'rotate(180deg)'}}/> {cat.nombre}
          </button>

          <div className="dd-detailhero">
            {dest.img
              ? <img className="dd-detailhero__photo" src={dest.img} alt={dest.nombre} />
              : <image-slot id={'slot-'+dest.id} shape="rect" fit="cover"
                  placeholder={'Subí una foto de '+dest.nombre}></image-slot>}
            <div className="veil"></div>
            <div className="cap">
              <span className="crumb" onClick={()=>nav({name:'category', catId:cat.id})}>
                <Ic.pin size={16} color="#bcd0ff" stroke={2.4}/> {cat.nombre}
              </span>
              <h1>{dest.nombre}</h1>
            </div>
          </div>

          <div className="dd-detailbody">
            <div className="dd-card dd-cardneon prose">
              <h2>Sobre este destino</h2>
              <p>{dest.desc}</p>
            </div>
            <aside className="dd-card dd-cardneon dd-reservebox">
              <Ic.sparkle size={34} color="#ff9bd0" stroke={2} style={{margin:'0 auto 6px'}}/>
              <h3>¿Te tentaste?</h3>
              <p>Reservá tu lugar y armamos juntos cada detalle de tu viaje a {dest.nombre}.</p>
              <button className="btn btn-primary" onClick={()=>nav({name:'reserva', catId:cat.id, destId:dest.id})}>
                Reservá tu lugar ahora
              </button>
            </aside>
          </div>

          {dest.video && (
            <div className="dd-videowrap">
              <h2 className="dd-videotitle">Viví un adelanto ✨</h2>
              <video className="dd-video" src={dest.video} controls playsInline muted loop preload="metadata" ref={lazyVideo}></video>
            </div>
          )}

          {/* barra fija en mobile */}
          <div className="dd-reservebar">
            <button className="btn btn-primary" style={{width:'100%',justifyContent:'center',boxShadow:'0 -8px 30px -10px rgba(228,32,131,.6)'}}
              onClick={()=>nav({name:'reserva', catId:cat.id, destId:dest.id})}>
              Reservá tu lugar ahora
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ===================== RESERVA ===================== */
  function ReservaScreen({ cat, dest, nav }){
    const [f,setF] = useState({nombre:'',apellido:'',telefono:'',mail:'',obs:''});
    const [errs,setErrs] = useState({});
    const [sent,setSent] = useState(false);
    const mails = window.DD_DATA.contacto.mails;

    const set = (k)=>(e)=>{ setF({...f,[k]:e.target.value}); if(errs[k]) setErrs({...errs,[k]:false}); };

    const validate = ()=>{
      const e={};
      if(!f.nombre.trim()) e.nombre=true;
      if(!f.apellido.trim()) e.apellido=true;
      if(!f.telefono.trim()) e.telefono=true;
      if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.mail.trim())) e.mail=true;
      setErrs(e);
      return Object.keys(e).length===0;
    };

    const submit = (ev)=>{
      ev.preventDefault();
      if(!validate()) return;
      const asunto = `Nueva reserva: ${dest.nombre} (${cat.nombre})`;
      const cuerpo =
`¡Hola Martín & Mica! Quiero reservar mi lugar.

Destino: ${dest.nombre} — ${cat.nombre}

Nombre: ${f.nombre}
Apellido: ${f.apellido}
Teléfono: ${f.telefono}
Mail: ${f.mail}
Observaciones: ${f.obs || '—'}

¡Gracias!`;
      const url = `mailto:${mails.join(',')}?subject=${encodeURIComponent(asunto)}&body=${encodeURIComponent(cuerpo)}`;
      window.location.href = url;
      setSent(true);
    };

    if(sent){
      return (
        <div className="dd-screen">
          <div className="dd-wrap" style={{maxWidth:'620px'}}>
            <div className="dd-card dd-success">
              <div className="ring"><Ic.check size={48} color="#fff" stroke={5}/></div>
              <h2>¡Reserva enviada!</h2>
              <p>Se abrió tu correo con todos los datos listos para enviar a la agencia.
                 Apenas lo recibamos, Martín o Mica te contactan para armar tu viaje a <b>{dest.nombre}</b>.</p>
              <div style={{display:'flex',gap:'12px',justifyContent:'center',flexWrap:'wrap'}}>
                <button className="btn btn-primary" onClick={()=>nav({name:'category', catId:cat.id})}>Ver más destinos</button>
                <button className="btn btn-ghost" style={{color:'var(--azul)',borderColor:'rgba(0,93,168,.3)',background:'rgba(0,93,168,.06)'}}
                  onClick={()=>nav({name:'home'})}>Volver al inicio</button>
              </div>
            </div>
          </div>
        </div>
      );
    }

    const field = (k,label,type,opts={})=>(
      <div className={"dd-field"+(opts.full?" full":"")}>
        <label>{label} {opts.req && <span className="req">*</span>}</label>
        {opts.area
          ? <textarea className={errs[k]?'err':''} value={f[k]} onChange={set(k)} placeholder={opts.ph}></textarea>
          : <input className={errs[k]?'err':''} type={type} value={f[k]} onChange={set(k)} placeholder={opts.ph}
              inputMode={opts.inputMode}/>}
        {errs[k] && <span className="hint">{opts.errMsg||'Completá este campo'}</span>}
      </div>
    );

    return (
      <div className="dd-screen">
        <div className="dd-wrap" style={{maxWidth:'760px'}}>
          <button className="dd-back" onClick={()=>nav({name:'destination', catId:cat.id, destId:dest.id})}>
            <Ic.arrow size={18} color="#cdd9ff" stroke={2.6} style={{transform:'rotate(180deg)'}}/> {dest.nombre}
          </button>
          <div><span className="dd-eyebrow"><Ic.star size={15} color="#fff" stroke={2.4}/> Reservá tu lugar</span></div>
          <h1 className="dd-pagetitle" style={{fontSize:'clamp(28px,4.4vw,46px)'}}>Casi listo para viajar</h1>

          <form className="dd-card dd-formcard" onSubmit={submit} noValidate style={{marginTop:'26px'}}>
            <div className="dd-summary">
              <Ic.pin size={20} color="#005DA8" stroke={2.4}/>
              <span>Reservás: <b>{dest.nombre}</b> · {cat.nombre}</span>
            </div>
            <h2>Tus datos</h2>
            <p className="formsub">Completá la ficha y te contactamos para armar tu plan. Los campos con * son obligatorios.</p>
            <div className="dd-fieldgrid">
              {field('nombre','Nombre','text',{req:true,ph:'Ej: María'})}
              {field('apellido','Apellido','text',{req:true,ph:'Ej: González'})}
              {field('telefono','Teléfono','tel',{req:true,ph:'+54 9 11 ...',inputMode:'tel'})}
              {field('mail','Email','email',{req:true,ph:'tucorreo@mail.com',inputMode:'email',errMsg:'Ingresá un email válido'})}
              {field('obs','Observaciones','text',{full:true,area:true,ph:'Fechas tentativas, cantidad de personas, lo que quieras contarnos... (opcional)'})}
            </div>
            <div className="dd-formfoot">
              <button type="submit" className="btn btn-primary">
                Enviar reserva <Ic.arrow size={20} color="#fff" stroke={2.6}/>
              </button>
              <span className="note">Al enviar, tus datos llegan por mail a la agencia para que te contactemos. No se comparten con nadie más.</span>
            </div>
          </form>
        </div>
      </div>
    );
  }

  Object.assign(window, { Home, Nosotros, Contacto, CategoryScreen, DestinationScreen, ReservaScreen });
})();
