/* Decretando Disney — App shell, header, menú lateral y router */
(function(){
  const { useState, useEffect } = React;
  const Ic = window.DDIcons;
  const DATA = window.DD_DATA;

  const findCat = (id)=> DATA.categorias.find(c=>c.id===id);
  const findDest = (cat,id)=> cat && cat.destinos.find(d=>d.id===id);

  function Header({ nav, openMenu }){
    return (
      <header className="dd-header">
        <div className="dd-navleft">
          <div className="dd-brandmini" onClick={()=>nav({name:'home'})} title="Inicio">
            <img src="assets/logo-white.png" alt="Decretando Disney" />
          </div>
          <button className="dd-navbtn" onClick={()=>nav({name:'nosotros'})}>Nosotros</button>
          <button className="dd-navbtn" onClick={()=>nav({name:'contacto'})}>Contactanos</button>
          <button className="dd-navbtn menu" onClick={openMenu}>
            <Ic.sparkle size={17} color="#fff" stroke={2.2}/> <span>Menú</span>
          </button>
        </div>
        <div className="dd-home" onClick={()=>nav({name:'home'})} title="Ir al inicio">
          <Ic.house size={26} stroke={2.4}/>
        </div>
      </header>
    );
  }

  function Drawer({ open, close, nav }){
    return (
      <React.Fragment>
        <div className={"dd-scrim"+(open?" open":"")} onClick={close}></div>
        <nav className={"dd-drawer"+(open?" open":"")} aria-hidden={!open}>
          <div className="dd-drawer__head">
            <div>
              <h3>Nuestros destinos</h3>
              <div className="sub">ELEGÍ TU PRÓXIMA AVENTURA</div>
            </div>
            <button className="dd-x" onClick={close} aria-label="Cerrar">✕</button>
          </div>
          <div className="dd-cats">
            {DATA.categorias.map((c,i)=>{
              const Icn = Ic[c.icono];
              return (
                <div key={c.id} className="dd-cat" onClick={()=>{ nav({name:'category', catId:c.id}); close(); }}>
                  <div className="dd-cat__txt">
                    <div className="num">{String(i+1).padStart(2,'0')}</div>
                    <div className="n">{c.nombre}</div>
                  </div>
                  <span className="dd-cat__icon"><Icn size={34} color="#fff" stroke={2.2}/></span>
                </div>
              );
            })}
          </div>
        </nav>
      </React.Fragment>
    );
  }

  function MusicToggle(){
    const [on,setOn] = useState(()=> (localStorage.getItem('dd-music')||'on')==='on');
    const ref = React.useRef(null);

    useEffect(()=>{
      const a = new Audio('assets/musica-magic-of-the-land.mp3');
      a.loop = true;
      a.volume = 0.45;
      ref.current = a;
      return ()=>{ a.pause(); ref.current = null; };
    },[]);

    useEffect(()=>{
      const a = ref.current; if(!a) return;
      localStorage.setItem('dd-music', on ? 'on' : 'off');
      if(on){
        a.play().catch(()=>{
          /* el navegador bloquea autoplay: arrancamos con la primera interacción */
          const kick = ()=>{
            if(ref.current && (localStorage.getItem('dd-music')||'on')==='on'){
              ref.current.play().catch(()=>{});
            }
            window.removeEventListener('pointerdown', kick);
          };
          window.addEventListener('pointerdown', kick);
        });
      } else {
        a.pause();
      }
    },[on]);

    return (
      <button className={"dd-music"+(on?"":" off")} onClick={()=>setOn(!on)}
        title={on ? 'Pausar la música' : 'Reproducir la música'}
        aria-label={on ? 'Pausar la música' : 'Reproducir la música'}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#fff"
          strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 18V5l12-2v13"></path>
          <circle cx="6" cy="18" r="3"></circle>
          <circle cx="18" cy="16" r="3"></circle>
          {!on && <line x1="2.5" y1="2.5" x2="21.5" y2="21.5" stroke="#ff9bd0" strokeWidth="2.4"></line>}
        </svg>
      </button>
    );
  }

  function App(){
    const [view,setView] = useState({name:'home'});
    const [menu,setMenu] = useState(false);

    const nav = (v)=>{ setMenu(false); setView(v); };

    // bloquear scroll del fondo cuando el menú está abierto
    useEffect(()=>{
      const onKey = (e)=>{ if(e.key==='Escape') setMenu(false); };
      window.addEventListener('keydown', onKey);
      return ()=>window.removeEventListener('keydown', onKey);
    },[]);

    const cat = (view.catId)? findCat(view.catId) : null;
    const dest = (cat && view.destId)? findDest(cat, view.destId) : null;
    const onHome = view.name==='home';

    let screen=null;
    if(view.name==='home') screen = <Home nav={nav} openMenu={()=>setMenu(true)} />;
    else if(view.name==='nosotros') screen = <Nosotros nav={nav} />;
    else if(view.name==='contacto') screen = <Contacto nav={nav} />;
    else if(view.name==='category' && cat) screen = <CategoryScreen cat={cat} nav={nav} />;
    else if(view.name==='destination' && cat && dest) screen = <DestinationScreen cat={cat} dest={dest} nav={nav} />;
    else if(view.name==='reserva' && cat && dest) screen = <ReservaScreen cat={cat} dest={dest} nav={nav} />;
    else screen = <Home nav={nav} openMenu={()=>setMenu(true)} />;

    const screenKey = [view.name, view.catId, view.destId].filter(Boolean).join('-');

    return (
      <React.Fragment>
        <Aurora dim={!onHome} />
        <Header nav={nav} openMenu={()=>setMenu(true)} />
        <Drawer open={menu} close={()=>setMenu(false)} nav={nav} />
        <MusicToggle />
        <div key={screenKey}>{screen}</div>
      </React.Fragment>
    );
  }

  window.DDApp = App;
})();
