/* booking-home.jsx — hero mini-selector + home Reservar section
   The home Reservar section now embeds the real Smoobu widget so guests
   can book directly from the landing page. Bilingual via useT. */

/* global React, useT */

// ============ MINI SELECTOR (HERO) ============
// Lightweight teaser: 3 fields → jumps to #reservar (Smoobu widget below).
function MiniBookingBar() {
  const { t } = useT();
  const { useState } = React;
  const today = new Date().toISOString().slice(0,10);
  const addDays = (iso, n) => {
    const d = new Date(iso); d.setDate(d.getDate() + n);
    return d.toISOString().slice(0,10);
  };
  const [ci, setCi] = useState(today);
  const [co, setCo] = useState(addDays(today, 2));
  const [g,  setG]  = useState(2);

  const submit = () => {
    // 1) Hand the selection to the embedded booking widget so it re-renders
    //    with the user's dates / guest count already filled in.
    window.dispatchEvent(new CustomEvent('booking:prefill', {
      detail: { checkIn: ci, checkOut: co, adults: g },
    }));
    // 2) Smooth-scroll to the widget. We avoid scrollIntoView here because it
    //    can misbehave inside framed editors; window.scrollTo is reliable.
    const el = document.getElementById('reservar');
    if (el) {
      const top = el.getBoundingClientRect().top + window.pageYOffset - 8;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  const lbl = { fontFamily:'Montserrat, sans-serif', fontSize:10,
                fontWeight:700, letterSpacing:'.18em', textTransform:'uppercase',
                color:'#9A9A9A', display:'block', marginBottom:4 };
  const inp = { width:'100%', border:'none', background:'transparent', padding:0,
                fontFamily:'Inter, sans-serif', fontSize:15, fontWeight:600, color:'#1A1A1A',
                outline:'none', cursor:'pointer' };
  const cell = { padding:'14px 18px', borderRight:'1px solid #ECECEC', minWidth:130 };

  return (
    <div style={MB.bar}>
      <div style={MB.row}>
        <div style={cell}>
          <label style={lbl}>{t('bk_check_in')}</label>
          <input type="date" value={ci} min={today}
                 onChange={e => {
                   setCi(e.target.value);
                   if (e.target.value >= co) setCo(addDays(e.target.value, 1));
                 }}
                 style={inp}/>
        </div>
        <div style={cell}>
          <label style={lbl}>{t('bk_check_out')}</label>
          <input type="date" value={co} min={addDays(ci, 1)}
                 onChange={e => setCo(e.target.value)}
                 style={inp}/>
        </div>
        <div style={{...cell, borderRight:'none'}}>
          <label style={lbl}>{t('bk_guests')}</label>
          <select value={g} onChange={e => setG(Number(e.target.value))}
                  style={{...inp, appearance:'none', cursor:'pointer'}}>
            {[1,2,3,4,5,6,7,8,9,10].map(n =>
              <option key={n} value={n}>{n === 1 ? t('bk_guests_1') : t('bk_guests_n').replace('{n}', n)}</option>
            )}
          </select>
        </div>
        <button onClick={submit} style={MB.cta}>
          {t('bk_check_avail')} →
        </button>
      </div>
      <div style={MB.savings}>★ {t('bk_direct_save')}</div>
    </div>
  );
}

const MB = {
  bar:{ background:'#fff', borderRadius:14, boxShadow:'0 20px 60px -20px rgba(0,0,0,.25), 0 4px 12px rgba(0,0,0,.06)',
        overflow:'visible', position:'relative', maxWidth:680 },
  row:{ display:'flex', alignItems:'stretch', flexWrap:'wrap' },
  cta:{ flex:1, minWidth:180, background:'#1A1A1A', color:'#F5C801',
        border:'none', cursor:'pointer', padding:'0 24px',
        fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:13,
        letterSpacing:'.1em', textTransform:'uppercase', borderRadius:'0 14px 14px 0' },
  savings:{ position:'absolute', top:-12, right:18, background:'#F5C801', color:'#1A1A1A',
            padding:'5px 11px', borderRadius:999, fontFamily:'Montserrat, sans-serif',
            fontWeight:800, fontSize:10, letterSpacing:'.12em', textTransform:'uppercase' },
};

// ============ SMOOBU WIDGET ============
function HomeSmoobuWidget() {
  const { lang } = useT();
  const ref = React.useRef(null);
  // Prefill that the MiniBookingBar pushes in via the `booking:prefill` event.
  const [prefill, setPrefill] = React.useState(null);

  React.useEffect(() => {
    const onPrefill = (e) => setPrefill(e.detail || null);
    window.addEventListener('booking:prefill', onPrefill);
    return () => window.removeEventListener('booking:prefill', onPrefill);
  }, []);

  React.useEffect(() => {
    if (!ref.current) return;
    ref.current.innerHTML = '';

    const supported = ['es','en','fr'].includes(lang) ? lang : 'es';
    // Append prefill params so the widget opens on the user's dates.
    // Show ONLY El Santo's units (whole building + 5 rooms). Excludes
    // "La Linterna de San Lorenzo" (id 3222052), which shares the account.
    const ES_APARTMENTS = ['3222532','3222537','3222542','3222547','3222552','3222557'];
    const qs = ES_APARTMENTS.map(id => 'apartmentGroups[]=' + id);
    if (prefill?.checkIn)  qs.push('arrival='   + encodeURIComponent(prefill.checkIn));
    if (prefill?.checkOut) qs.push('departure=' + encodeURIComponent(prefill.checkOut));
    if (prefill?.adults)   qs.push('adults='    + encodeURIComponent(prefill.adults));
    const url = `https://login.smoobu.com/${supported}/booking-tool/iframe/1676957?${qs.join('&')}`;

    const init = () => {
      if (window.BookingToolIframe) {
        window.BookingToolIframe.initialize({
          url, baseUrl: 'https://login.smoobu.com',
          target: '#apartmentIframeHome',
        });
      }
    };

    const SCRIPT_SRC = 'https://login.smoobu.com/js/Settings/BookingToolIframe.js';
    if (window.BookingToolIframe) {
      init();
    } else if (!document.querySelector(`script[src="${SCRIPT_SRC}"]`)) {
      const s = document.createElement('script');
      s.src = SCRIPT_SRC; s.async = true; s.onload = init;
      document.body.appendChild(s);
    } else {
      const t0 = Date.now();
      const iv = setInterval(() => {
        if (window.BookingToolIframe) { clearInterval(iv); init(); }
        else if (Date.now() - t0 > 5000) { clearInterval(iv); }
      }, 100);
    }
  }, [lang, prefill]);

  return (
    <div id="apartmentIframeHome" ref={ref}
         style={{ background:'#fff', minHeight:180 }}/>
  );
}

// ============ DIRECT-BOOKING COUPON STRIP ============
// Surfaces the SANTO6 code above the live widget so the price shown
// doesn't look more expensive than it really is.
function HomeCoupon() {
  const { lang } = useT();
  const [copied, setCopied] = React.useState(false);
  const CODE = 'SANTO6';
  const L = {
    es:{ h:'Código SANTO6', p:'10% de descuento sobre el total. Introdúcelo en el paso de pago.', copy:'Copiar', copied:'¡Copiado!' },
    en:{ h:'Code SANTO6', p:'10% off your total. Enter it at the payment step.', copy:'Copy', copied:'Copied!' },
  }[lang] || { h:'Código SANTO6', p:'10% de descuento sobre el total. Introdúcelo en el paso de pago.', copy:'Copiar', copied:'¡Copiado!' };
  const doCopy = (e) => {
    e.preventDefault();
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 1800); };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(CODE).then(done).catch(fallback);
    } else { fallback(); }
    function fallback() {
      try {
        const ta = document.createElement('textarea');
        ta.value = CODE; ta.style.position = 'fixed'; ta.style.opacity = '0';
        document.body.appendChild(ta); ta.focus(); ta.select();
        const ok = document.execCommand('copy'); document.body.removeChild(ta);
        if (ok) done();
      } catch (_) {}
    }
  };
  return (
    <div style={RH.coupon}>
      <div style={RH.couponLeft}>
        <span style={RH.couponTag}>%</span>
        <div>
          <div style={RH.couponH}>{L.h}</div>
          <div style={RH.couponP}>{L.p}</div>
        </div>
      </div>
      <button onClick={doCopy} style={RH.couponBtn} aria-label={L.copy}>
        {copied ? L.copied : L.copy}
      </button>
    </div>
  );
}

// ============ HOME RESERVAR SECTION ============
function ReservarHome() {
  const { t, lang } = useT();

  const benefits = {
    es: [
      ['%',  'Mejor precio garantizado',    'Hasta un 10% menos que en Booking, Airbnb o Expedia.'],
      ['⌂',  'Albergue completo o habitación', 'Reserva el edificio entero o solo una de las 5 habitaciones.'],
      ['⏱',  'Disponibilidad en tiempo real', 'Calendario sincronizado. Confirmación inmediata por email.'],
      ['🔒', 'Pago seguro', 'Tarjeta (Stripe) y PayPal. Cancelación flexible disponible.'],
    ],
    en: [
      ['%',  'Best price guaranteed',     'Up to 10% less than Booking, Airbnb or Expedia.'],
      ['⌂',  'Whole hostel or single room', 'Book the entire building or just one of 5 rooms.'],
      ['⏱',  'Real-time availability',   'Synced calendar. Instant email confirmation.'],
      ['🔒', 'Secure payment',            'Card (Stripe) and PayPal. Flexible cancellation available.'],
    ],
  }[lang] || [];

  return (
    <section id="reservar" style={RH.wrap}>
      {/* Decorative ribbon */}
      <div style={RH.ribbon}/>
      <div style={RH.inner}>
        <header style={RH.head}>
          <div style={RH.eyebrow}>{t('rs_eyebrow')}</div>
          <h2 style={RH.h2}>{t('rs_h_a')}<br/><span style={RH.h2Accent}>{t('rs_h_b')}</span></h2>
          <p style={RH.intro}>{t('rs_p')}</p>
        </header>

        <div style={RH.grid} data-rh-grid="1">
          {/* LEFT — benefits */}
          <aside style={RH.benefits}>
            {benefits.map(([k,h,p], i) => (
              <div key={i} style={RH.benefit}>
                <div style={RH.benefitKey}>{k}</div>
                <div>
                  <div style={RH.benefitH}>{h}</div>
                  <div style={RH.benefitP}>{p}</div>
                </div>
              </div>
            ))}
            <div style={RH.help}>
              <div style={RH.helpH}>{({en:'Need help?',fr:'Besoin d\u2019aide ?'}[lang]) || '¿Necesitas ayuda?'}</div>
              <a href="mailto:elsantohostel@gmail.com" style={RH.helpLink}>elsantohostel@gmail.com</a>
              <a href="tel:+34609087826" style={RH.helpLink}>+34 609 087 826</a>
              <a href="https://wa.me/34609087826" target="_blank" rel="noreferrer" style={RH.helpLinkWa}>
                <span style={RH.helpLinkWaDot}/>WhatsApp
              </a>
            </div>
          </aside>

          {/* RIGHT — real Smoobu widget */}
          <div style={RH.widgetCard}>
            <div style={RH.widgetHead}>
              <div style={RH.widgetDot}/>
              <span style={RH.widgetLbl}>
                {({en:'Live availability',fr:'Disponibilité en direct'}[lang]) || 'Disponibilidad en directo'}
              </span>
            </div>
            <HomeCoupon/>
            <HomeSmoobuWidget/>
            <div style={RH.widgetFoot}>
              <span>🔒 {t('bk_secure') || 'Secure payment'}</span>
              <span style={RH.widgetFootDot}>·</span>
              <span>Stripe</span>
              <span style={RH.widgetFootDot}>·</span>
              <span>PayPal</span>
            </div>
          </div>
        </div>

        {/* ROOM SHORTCUTS — let guests review each room/the whole building
            on its own detail page before opening the widget. */}
        <div style={RH.shortcuts}>
          <div style={RH.shortcutsLbl}>
            {({en:'Want to see photos and details first?',fr:'Vous voulez voir les photos et les détails d\u2019abord ?'}[lang]) || '¿Quieres ver fotos y detalles antes de reservar?'}
          </div>
          <div style={RH.shortcutsPills}>
            <a href="albergue-completo.html" style={RH.pillFeatured}>
              <span style={RH.pillFeaturedTag}>
                {({en:'Whole hostel',fr:'Auberge entière'}[lang]) || 'Albergue completo'}
              </span>
              <span style={RH.pillArrow}>→</span>
            </a>
            {['01','02','03','04','05'].map(id => (
              <a key={id} href={`habitacion-${id}.html`} style={RH.pill}>
                <span style={RH.pillNum}>{id}</span>
                <span style={RH.pillName}>{t(`r${id}_home_suffix`)}</span>
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

const RH = {
  wrap:{ position:'relative', padding:'100px 0 90px', background:'#1A1A1A', color:'#fff', overflow:'hidden' },
  ribbon:{ position:'absolute', top:0, left:0, right:0, height:6,
           background:'linear-gradient(90deg, #F5C801 0%, #F5C801 50%, #FBB700 100%)' },
  inner:{ maxWidth:1280, margin:'0 auto', padding:'0 28px', position:'relative' },

  head:{ maxWidth:760, marginBottom:48 },
  eyebrow:{ fontFamily:'Montserrat, sans-serif', fontWeight:700, fontSize:12,
            letterSpacing:'.25em', textTransform:'uppercase', color:'#F5C801' },
  h2:{ fontFamily:'Montserrat, sans-serif', fontWeight:900,
       fontSize:'clamp(40px,5vw,72px)', lineHeight:.95, letterSpacing:'-0.02em',
       margin:'14px 0 18px', textTransform:'uppercase', color:'#fff' },
  h2Accent:{ color:'#F5C801' },
  intro:{ fontFamily:'Inter, sans-serif', fontSize:17, color:'rgba(255,255,255,.78)',
          lineHeight:1.6, margin:0, maxWidth:600 },

  grid:{ display:'grid', gridTemplateColumns:'minmax(280px, 380px) 1fr', gap:36, alignItems:'start' },

  benefits:{ display:'flex', flexDirection:'column', gap:18 },
  benefit:{ display:'flex', gap:16, alignItems:'flex-start' },
  benefitKey:{ width:42, height:42, borderRadius:10, background:'#F5C801', color:'#1A1A1A',
               display:'flex', alignItems:'center', justifyContent:'center',
               fontSize:20, fontWeight:800, flexShrink:0 },
  benefitH:{ fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:15,
             textTransform:'uppercase', letterSpacing:'.02em', color:'#fff', marginBottom:4 },
  benefitP:{ fontFamily:'Inter, sans-serif', fontSize:14, color:'rgba(255,255,255,.7)',
             lineHeight:1.5 },

  help:{ marginTop:20, padding:'18px 20px', background:'rgba(255,255,255,.05)',
         border:'1px solid rgba(255,255,255,.1)', borderRadius:12 },
  helpH:{ fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:12,
          textTransform:'uppercase', letterSpacing:'.18em', color:'#F5C801', marginBottom:10 },
  helpLink:{ display:'block', fontFamily:'Inter, sans-serif', fontSize:14,
             color:'#fff', textDecoration:'none', marginBottom:6, opacity:1 },
  helpLinkWa:{ display:'inline-flex', alignItems:'center', gap:8,
               fontFamily:'Inter, sans-serif', fontSize:14, fontWeight:600,
               color:'#25D366', textDecoration:'none', marginTop:2 },
  helpLinkWaDot:{ width:8, height:8, borderRadius:999, background:'#25D366',
                  boxShadow:'0 0 0 4px rgba(37,211,102,.22)' },

  widgetCard:{ background:'#fff', borderRadius:20, overflow:'hidden',
               boxShadow:'0 30px 80px -30px rgba(0,0,0,.5), 0 8px 20px rgba(0,0,0,.2)' },
  widgetHead:{ display:'flex', alignItems:'center', gap:10, padding:'14px 22px',
               borderBottom:'1px solid #ECECEC', background:'#FAFAFA' },
  widgetDot:{ width:9, height:9, borderRadius:999, background:'#1FB05B',
              boxShadow:'0 0 0 4px rgba(31,176,91,.18)' },
  widgetLbl:{ fontFamily:'Montserrat, sans-serif', fontWeight:700, fontSize:11,
              letterSpacing:'.18em', textTransform:'uppercase', color:'#1A1A1A' },
  widgetFoot:{ display:'flex', alignItems:'center', gap:8, padding:'14px 22px',
               borderTop:'1px solid #ECECEC', background:'#FAFAFA',
               fontFamily:'ui-monospace, monospace', fontSize:12, color:'#6B6B6B',
               flexWrap:'wrap' },
  widgetFootDot:{ opacity:.4 },

  /* ============ COUPON STRIP ============ */
  coupon:{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:16,
           padding:'12px 18px', background:'#FFF7D6',
           borderBottom:'1px solid #ECECEC', flexWrap:'wrap' },
  couponLeft:{ display:'flex', alignItems:'center', gap:12, minWidth:0 },
  couponTag:{ width:30, height:30, borderRadius:8, background:'#F5C801', color:'#1A1A1A',
              display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
              fontFamily:'Montserrat, sans-serif', fontWeight:900, fontSize:15 },
  couponH:{ fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:13,
            letterSpacing:'.04em', textTransform:'uppercase', color:'#1A1A1A' },
  couponP:{ fontFamily:'Inter, sans-serif', fontSize:12.5, color:'#6B5B00', lineHeight:1.4 },
  couponBtn:{ flexShrink:0, background:'#1A1A1A', color:'#F5C801', border:'none', cursor:'pointer',
              padding:'8px 16px', borderRadius:999, fontFamily:'Montserrat, sans-serif',
              fontWeight:800, fontSize:11, letterSpacing:'.1em', textTransform:'uppercase' },

  /* ============ ROOM SHORTCUTS ============ */
  shortcuts:{ marginTop:48, paddingTop:32, borderTop:'1px solid rgba(255,255,255,.08)',
              display:'flex', flexDirection:'column', gap:18, alignItems:'flex-start' },
  shortcutsLbl:{ fontFamily:'Montserrat, sans-serif', fontWeight:700, fontSize:11,
                 letterSpacing:'.22em', textTransform:'uppercase',
                 color:'rgba(255,255,255,.7)' },
  shortcutsPills:{ display:'flex', flexWrap:'wrap', gap:10 },
  pill:{ display:'inline-flex', alignItems:'center', gap:10,
         padding:'10px 16px 10px 12px', borderRadius:999,
         background:'rgba(255,255,255,.06)', border:'1px solid rgba(255,255,255,.12)',
         textDecoration:'none', transition:'all .15s ease' },
  pillNum:{ fontFamily:'ui-monospace, monospace', fontWeight:700, fontSize:12,
            color:'#1A1A1A', background:'#F5C801', borderRadius:6,
            padding:'2px 7px', letterSpacing:'.04em' },
  pillName:{ fontFamily:'Inter, sans-serif', fontWeight:500, fontSize:14, color:'#fff' },
  pillFeatured:{ display:'inline-flex', alignItems:'center', gap:10,
                 padding:'10px 14px 10px 16px', borderRadius:999,
                 background:'#F5C801', color:'#1A1A1A',
                 textDecoration:'none', transition:'all .15s ease' },
  pillFeaturedTag:{ fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:13,
                    textTransform:'uppercase', letterSpacing:'.05em' },
  pillArrow:{ fontFamily:'Montserrat, sans-serif', fontWeight:800, fontSize:14, color:'#1A1A1A' },
};

// Inject responsive + iframe rules once.
if (typeof document !== 'undefined' && !document.getElementById('rh-styles')) {
  const st = document.createElement('style');
  st.id = 'rh-styles';
  st.textContent = `
    #apartmentIframeHome iframe { width:100% !important; border:0 !important; display:block; background:#fff }
    section#reservar a[href^="habitacion-"]:hover,
    section#reservar a[href="albergue-completo.html"]:hover { transform: translateY(-1px); filter: brightness(1.08); }
    @media (max-width: 980px) {
      section#reservar [data-rh-grid="1"] { grid-template-columns: 1fr !important }
    }
  `;
  document.head.appendChild(st);
}

window.MiniBookingBar = MiniBookingBar;
window.ReservarHome = ReservarHome;
