/* Yogavibe, the places we host retreats in: overview (/villas) and one page
   per place (/villas/<slug>). Data comes from villas.js (YOGAVIBE_VILLAS),
   copy from translations under villas.page and villas.items.<id>. The same
   data feeds prerender.js, which writes the crawler HTML and JSON-LD for
   these routes, so keep the visible facts and the FAQ in sync with it by
   editing the data / translations, never the markup. */

const VILLA_ORIGIN = 'https://yogavibe.eu';
const VILLA_ARROW = <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true"><path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" /></svg>;

function villaIds({ withSoon = false } = {}) {
  const villas = window.YOGAVIBE_VILLAS;
  return Object.keys(villas).filter((id) => withSoon || !villas[id].comingSoon);
}

/* "De riad in Essaouira": the display name without the closing full stop,
   for running text, tables and breadcrumbs. */
function villaName(t, id) {
  return `${t(`villas.items.${id}.nameL1`)} ${t(`villas.items.${id}.nameEm`)}`.replace(/\.$/, '');
}

function retreatsIn(villaId) {
  return Object.values(window.YOGAVIBE_RETREATS).filter((r) => r.villa === villaId);
}

/* Absolute URL for og:image (the SPA only updates it for link previews made
   after hydration; the prerendered HTML carries the real one). */
const villaAbsUrl = (src) => src && (/^https?:/.test(src) ? src : `${VILLA_ORIGIN}/${src}`);

/* ============ COMPARISON TABLE ============
   Also used on the custom-retreats page. A real <table>: easy to scan, and
   the format search engines and AI assistants quote most reliably. */
function PlacesCompare({ setPage }) {
  const t = useT();
  const locale = useLocale();
  const villas = window.YOGAVIBE_VILLAS;
  const head = t('villas.page.compareHead');
  return (
    <div className="places-compare">
      <table role="table">
        <thead role="rowgroup">
          <tr role="row">{head.map((h, i) => <th key={i} scope="col" role="columnheader">{h}</th>)}</tr>
        </thead>
        <tbody role="rowgroup">
          {villaIds().map((id) => {
            const v = villas[id];
            return (
              <tr key={id} role="row">
                <th scope="row" role="rowheader">
                  <a {...linkProps(`villa-${id}`, setPage, locale)}>{villaName(t, id)}</a>
                </th>
                <td role="cell" data-label={head[1]}>{v.city}</td>
                <td role="cell" data-label={head[2]}>{v.bedrooms}</td>
                <td role="cell" data-label={head[3]}>{v.maxGuests}</td>
                <td role="cell" data-label={head[4]}>{v.airportMinutes} {t('villas.page.minutes')}</td>
                <td role="cell" data-label={head[5]}>{t(`villas.items.${id}.compareNote`)}</td>
              </tr>);
          })}
          {villaIds({ withSoon: true }).filter((id) => villas[id].comingSoon).map((id) =>
          <tr key={id} className="is-soon" role="row">
              <th scope="row" role="rowheader">{t('villas.page.soonTitle')}</th>
              <td role="cell" data-label={head[1]}>{villas[id].city}</td>
              <td role="cell" colSpan={4}>{t('villas.soon')}</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>);
}

/* FAQ with every answer in the DOM (<details>), so search engines that render
   the page see the same Q&A as the FAQPage JSON-LD. */
function VillaFAQ({ items }) {
  const t = useT();
  return (
    <section className="section faq-section">
      <div className="container faq-grid">
        <div className="faq-left">
          <div className="eyebrow">{t('villas.page.faqEyebrow')}</div>
          <h2 className="h1" style={{ marginTop: 16 }}>{t('villas.page.faqTitleL1')}<br /><em>{t('villas.page.faqTitleEm')}</em></h2>
        </div>
        <div className="faq-list">
          {(Array.isArray(items) ? items : []).map((it, i) =>
          <details key={i} className="faq-row villa-faq-row" open={i === 0}>
              <summary className="faq-q">
                <span className="caption">{String(i + 1).padStart(2, '0')}</span>
                <span className="h3" style={{ fontFamily: 'var(--font-display)' }}>{it.q}</span>
                <span className="faq-icon" aria-hidden="true"></span>
              </summary>
              <div className="faq-a">{it.a}</div>
            </details>
          )}
        </div>
      </div>
    </section>);
}

function VillaCustomCTA({ setPage }) {
  const t = useT();
  const locale = useLocale();
  return (
    <section className="section villa-custom">
      <div className="container villa-custom-inner">
        <div>
          <div className="eyebrow">{t('villas.page.customEyebrow')}</div>
          <h2 className="h1" style={{ marginTop: 16 }}>{t('villas.page.customTitleL1')}<br /><em>{t('villas.page.customTitleEm')}</em></h2>
        </div>
        <div>
          <p className="lead" style={{ maxWidth: 480 }}>{t('villas.page.customBody')}</p>
          <a className="btn btn-primary" style={{ marginTop: 28 }} {...linkProps('custom', setPage, locale)}>
            <span className="dot"></span> {t('villas.page.customCta')}
          </a>
        </div>
      </div>
    </section>);
}

/* ============ OVERVIEW: /villas ============ */
function VillasPage({ setPage }) {
  const t = useT();
  const locale = useLocale();
  const villas = window.YOGAVIBE_VILLAS;
  usePageSEO({
    title: t('villas.page.seoTitle'),
    description: t('villas.page.seoDescription'),
    canonical: `${VILLA_ORIGIN}/villas`,
    ogImage: villaAbsUrl(villas.marrakechVilla.poster),
  });
  const soon = villaIds({ withSoon: true }).filter((id) => villas[id].comingSoon);

  return (
    <>
      <section className="section retreats-hero">
        <div className="container">
          <div className="caption">{t('villas.page.caption')}</div>
          <h1 className="h-display" style={{ marginTop: 28, maxWidth: 1100 }}>
            {t('villas.page.titleL1')}<br /><em>{t('villas.page.titleEm')}</em>
          </h1>
          <p className="lead" style={{ marginTop: 36, maxWidth: 640 }}>{t('villas.page.lead')}</p>
        </div>
      </section>

      <section className="section-tight">
        <div className="container retreats-list-page">
          {villaIds().map((id) => {
            const v = villas[id];
            const vt = (k) => t(`villas.items.${id}.${k}`);
            const next = retreatsIn(id).find((r) => !r.soldOut);
            return (
              <article key={id} className="retreat-row villa-row" onClick={() => setPage(`villa-${id}`)}>
                <div className="retreat-row-img">
                  <Placeholder coords={v.coords} label={vt('posterAlt')} tag={vt('kindLabel').toUpperCase()} ratio={4 / 3} src={v.poster} pos="center" />
                </div>
                <div className="retreat-row-meta">
                  <div className="caption">{vt('kindLabel')} · {vt('cityLabel')}</div>
                  <h2 className="h2" style={{ marginTop: 12 }}>{vt('nameL1')} <em>{vt('nameEm')}</em></h2>
                  <p className="body" style={{ marginTop: 10, fontSize: 14, color: 'var(--ink-soft)', maxWidth: 480 }}>{vt('lead')}</p>
                  <div className="retreat-row-tags" style={{ flexWrap: 'wrap' }}>
                    <span className="caption">{v.bedrooms} {t('villas.page.bedroomsKey').toLowerCase()}</span>
                    <span className="dot-sep"></span>
                    <span className="caption">{t('villas.page.maxPrefix')} {v.maxGuests} {t('villas.page.guestsKey').toLowerCase()}</span>
                    <span className="dot-sep"></span>
                    <span className="caption" style={{ color: 'var(--accent-2)' }}>
                      {next ? `${t('villas.nextLabel')} · ${t(`${next.tKey}.datesVal`)}` : t('villas.page.noRetreat')}
                    </span>
                  </div>
                </div>
                <div className="retreat-row-tag">
                  <a className="btn btn-ghost" {...linkProps(`villa-${id}`, setPage, locale)}>
                    {vt('cta')}
                  </a>
                </div>
              </article>);
          })}
          {soon.map((id) =>
          <article key={id} className="retreat-row villa-row is-soon">
              <div className="retreat-row-img">
                <Placeholder coords={villas[id].city.toUpperCase()} label={t('villas.soon')} tag="SOON" ratio={4 / 3} />
              </div>
              <div className="retreat-row-meta">
                <div className="caption">{t(`villas.items.${id}.tab`)}</div>
                <h2 className="h2" style={{ marginTop: 12 }}>{t('villas.page.soonTitle')}</h2>
                <p className="body" style={{ marginTop: 10, fontSize: 14, color: 'var(--ink-soft)', maxWidth: 480 }}>{t('villas.page.soonBody')}</p>
              </div>
              <div className="retreat-row-tag">
                <span className="status-pill">{t('villas.soon')}</span>
              </div>
            </article>
          )}
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="eyebrow">{t('villas.page.compareEyebrow')}</div>
          <h2 className="h1" style={{ marginTop: 16 }}>{t('villas.page.compareTitleL1')}<br /><em>{t('villas.page.compareTitleEm')}</em></h2>
          <div style={{ marginTop: 48 }}><PlacesCompare setPage={setPage} /></div>
        </div>
      </section>

      <VillaFAQ items={t('villas.page.faq')} />
      <VillaCustomCTA setPage={setPage} />
    </>);
}

/* ============ ONE PLACE: /villas/<slug> ============ */
function VillaDetailPage({ villaId, setPage }) {
  const t = useT();
  const locale = useLocale();
  const villas = window.YOGAVIBE_VILLAS;
  const v = villas[villaId];
  const vt = (k) => t(`villas.items.${villaId}.${k}`);
  usePageSEO({
    title: vt('seoTitle'),
    description: vt('seoDescription'),
    canonical: `${VILLA_ORIGIN}/villas/${v.slug}`,
    ogImage: villaAbsUrl(v.poster),
  });
  const [playing, setPlaying] = React.useState(false);
  const videoId = v.video && window.YOGAVIBE_CONFIG.integrations.youtube[v.video];
  const labels = vt('placeImages');
  const images = v.images.map(([src], i) => ({ src, label: (labels && labels[i]) || '' }));
  const highlights = vt('highlights');
  const retreats = retreatsIn(villaId);
  const others = villaIds({ withSoon: true }).filter((id) => id !== villaId);

  return (
    <>
      <section className="detail-hero villa-hero">
        <div className="detail-hero-inner">
          <div className="detail-hero-text">
            <nav className="caption villa-crumbs" aria-label={locale === 'nl' ? 'Kruimelpad' : 'Breadcrumb'}>
              <a {...linkProps('home', setPage, locale)}>{t('villas.page.breadcrumbHome')}</a>
              <span aria-hidden="true">/</span>
              <a {...linkProps('villas', setPage, locale)}>{t('villas.page.breadcrumbVillas')}</a>
              <span aria-hidden="true">/</span>
              <span aria-current="page">{villaName(t, villaId)}</span>
            </nav>
            <div className="eyebrow" style={{ marginTop: 32 }}>{vt('kindLabel')} · {vt('cityLabel')}</div>
            <h1 className="h-display" style={{ marginTop: 24, fontSize: 'clamp(56px, 8.5vw, 132px)' }}>
              {vt('nameL1')}<br /><em>{vt('nameEm')}</em>
            </h1>
            <p className="lead" style={{ marginTop: 28, maxWidth: 560 }}>{vt('summary')}</p>
            <div className="detail-meta-row">
              <div><div className="caption">{t('villas.page.cityKey')}</div><div className="body" style={{ color: 'var(--ink)' }}>{v.city}</div></div>
              <div><div className="caption">{t('villas.page.bedroomsKey')}</div><div className="body" style={{ color: 'var(--ink)' }}>{v.bedrooms}</div></div>
              <div><div className="caption">{t('villas.page.guestsKey')}</div><div className="body" style={{ color: 'var(--ink)' }}>{t('villas.page.maxPrefix')} {v.maxGuests}</div></div>
              <div><div className="caption">{t('villas.page.airportKey')}</div><div className="body" style={{ color: 'var(--ink)' }}>{v.airportMinutes} {t('villas.page.minutes')}</div></div>
            </div>
          </div>
          <div className="detail-hero-img">
            <Placeholder coords={v.coords} label={vt('posterAlt')} tag={vt('kindLabel').toUpperCase()} src={v.poster} pos="center" priority />
          </div>
        </div>
      </section>

      <section className="section-tight">
        <div className="container villa-intro">
          <div>
            <div className="eyebrow">{t('villas.page.highlightsEyebrow')}</div>
            <h2 className="h2" style={{ marginTop: 16 }}>{vt('placeTitleL1')}<br /><em>{vt('placeTitleEm')}</em></h2>
            <p className="body" style={{ marginTop: 24, fontSize: 17, color: 'var(--ink)', maxWidth: '60ch' }}>{vt('placeBody')}</p>
          </div>
          <div className="included-grid">
            {(Array.isArray(highlights) ? highlights : []).map(([title, d], i) =>
            <div key={i} className="included-item">
                <span className="caption">{String(i + 1).padStart(2, '0')}</span>
                <div>
                  <h3 className="h3" style={{ fontFamily: 'var(--font-display)', fontSize: 22 }}>{title}</h3>
                  <div className="body" style={{ marginTop: 6, fontSize: 14 }}>{d}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </section>

      {videoId &&
      <section className="section-tight">
          <div className="container">
            <div className="eyebrow" style={{ marginBottom: 24 }}>{t('villas.page.tourEyebrow')}</div>
            <div className="inside-video" onClick={() => setPlaying(true)}>
              {!playing &&
              <React.Fragment>
                  <div className="inside-poster"><img src={v.images[2] ? v.images[2][0] : v.poster} alt={vt('posterAlt')} loading="lazy" /></div>
                  <button className="inside-play" type="button" aria-label={t('villas.playLabel')}>
                    <svg width="22" height="24" viewBox="0 0 22 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M21 11.134a1 1 0 0 1 0 1.732L1.5 24.124a1 1 0 0 1-1.5-.866V.742a1 1 0 0 1 1.5-.866L21 11.134Z" fill="currentColor" />
                    </svg>
                    <span>{t('villas.play')}</span>
                  </button>
                  <div className="inside-meta">
                    <span className="caption">{t('villas.metaFilm')}</span>
                    <span className="caption">{v.coords}</span>
                  </div>
                </React.Fragment>
              }
              {playing &&
              <iframe
                src={`https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0&modestbranding=1`}
                title={`${vt('nameL1')} ${vt('nameEm')}`}
                frameBorder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen />
              }
            </div>
          </div>
        </section>
      }

      <section className="section-tight">
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t('villas.page.galleryEyebrow')}</div>
          <div className="place-grid">
            {images.map((img, i) =>
            <Placeholder key={i} coords={v.images[i][1]} label={img.label} tag={`P·${String(i + 1).padStart(2, '0')}`} src={img.src} pos="center"
              group={`villa-${villaId}`} groupImages={images} groupIndex={i} />
            )}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="eyebrow">{t('villas.page.retreatsEyebrow')}</div>
          <div className="villa-retreats">
            {retreats.length === 0 && <p className="body" style={{ marginTop: 24, maxWidth: 560 }}>{t('villas.page.retreatsNone')}</p>}
            {retreats.map((r) =>
            <a key={r.page} className="villa-retreat" {...linkProps(r.page, setPage, locale)}>
                <span className="h3" style={{ fontFamily: 'var(--font-display)' }}>{t(`${r.tKey}.name`)}</span>
                <span className="caption">{t(`${r.tKey}.datesVal`)}</span>
                <span className={r.soldOut ? 'status-pill' : 'status-pill status-pill--open'}>
                  {r.soldOut ? t('soldOut.tag') : t('retreatsPage.tagOpen')}
                </span>
                <span className="link-arrow">{t('villas.page.seeRetreat')} {VILLA_ARROW}</span>
              </a>
            )}
          </div>
        </div>
      </section>

      <VillaCustomCTA setPage={setPage} />
      <VillaFAQ items={vt('faq')} />

      <section className="section-tight villa-others">
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t('villas.page.otherEyebrow')}</div>
          <div className="villa-others-list">
            {others.map((id) => villas[id].comingSoon ?
            <span key={id} className="villa-other is-soon">
                <span className="caption">{t(`villas.items.${id}.tab`)}</span>
                <span className="h3">{t('villas.page.soonTitle')}</span>
                <span className="caption" style={{ color: 'var(--accent)' }}>{t('villas.soon')}</span>
              </span> :
            <a key={id} className="villa-other" {...linkProps(`villa-${id}`, setPage, locale)}>
                <span className="caption">{t(`villas.items.${id}.tab`)}</span>
                <span className="h3">{t(`villas.items.${id}.nameL1`)} <em>{t(`villas.items.${id}.nameEm`)}</em></span>
                <span className="link-arrow">{t(`villas.items.${id}.cta`)} {VILLA_ARROW}</span>
              </a>
            )}
            <a className="villa-other" {...linkProps('villas', setPage, locale)}>
              <span className="caption">{t('villas.page.caption')}</span>
              <span className="h3">{t('villas.page.titleL1')} <em>{t('villas.page.titleEm')}</em></span>
              <span className="link-arrow">{t('villas.page.back').replace('← ', '')} {VILLA_ARROW}</span>
            </a>
          </div>
        </div>
      </section>
    </>);
}

Object.assign(window, { VillasPage, VillaDetailPage, PlacesCompare });
