/* Static-content pages: How to find us, FAQ, Imprint, Privacy, Cookies, Terms */

const { useState: useLS, useEffect: useLE } = React;

/* Generic chrome for a legal-style content page. */
function LegalShell({ eyebrow, title, lede, children, onBack, backLabel }) {
  useReveal();
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        {onBack && (
          <button onClick={onBack} className="reveal" style={{
            fontSize: 13, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--mute)', fontWeight: 500, marginBottom: 32,
            padding: '8px 0', cursor: 'pointer'
          }}>{backLabel || '← Back'}</button>
        )}
        <div className="reveal" style={{ maxWidth: 920 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{eyebrow}</div>
          <h1 className="display display-l serif">{title}</h1>
          {lede && <p className="lede" style={{ marginTop: 32, maxWidth: '58ch', fontSize: 18 }}>{lede}</p>}
        </div>
      </section>
      <section className="section shell" style={{ paddingTop: 'clamp(40px, 5vw, 60px)' }}>
        <div className="reveal" style={{ maxWidth: 720 }}>
          {children}
        </div>
      </section>
    </div>
  );
}

/* Renders an array of {h, body} blocks (h is section heading, body is array of paragraphs or
   ['def', term, def] entries for definition rows). */
function LegalSections({ blocks }) {
  if (!blocks) return null;
  return blocks.map((b, i) => (
    <div key={i} style={{ borderTop: '1px solid var(--hair)', padding: '32px 0' }}>
      {b.h && <h2 className="serif" style={{ fontSize: 26, fontWeight: 300, marginBottom: 16, lineHeight: 1.2 }}>{b.h}</h2>}
      {b.body && b.body.map((row, j) => {
        if (Array.isArray(row) && row[0] === 'cookie-button') {
          return (
            <button key={j} onClick={() => window.dispatchEvent(new CustomEvent('cookie-reopen'))} className="btn btn-outline" style={{ marginTop: 4 }}>{row[1]}</button>
          );
        }
        if (Array.isArray(row) && row[0] === 'def') {
          return (
            <div key={j} style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 24, padding: '8px 0', borderBottom: '1px dotted var(--hair)' }}>
              <span className="eyebrow" style={{ paddingTop: 3 }}>{row[1]}</span>
              <span style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-soft)', whiteSpace: 'pre-line' }}>
                {/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(row[2]).trim())
                  ? <a href={'mailto:' + String(row[2]).trim()} style={{ color: 'var(--ink-soft)', textDecoration: 'underline', textUnderlineOffset: 3 }}>{row[2]}</a>
                  : row[2]}
              </span>
            </div>
          );
        }
        if (Array.isArray(row) && row[0] === 'list') {
          return (
            <ul key={j} style={{ listStyle: 'none', padding: 0, margin: '4px 0 14px', maxWidth: '64ch' }}>
              {row[1].map((item, k) => (
                <li key={k} style={{ display: 'grid', gridTemplateColumns: '20px 1fr', gap: 4, padding: '7px 0', borderBottom: '1px dotted var(--hair)', fontSize: 15, lineHeight: 1.6, color: 'var(--ink-soft)' }}>
                  <span style={{ color: 'var(--accent)' }}>·</span>
                  <span dangerouslySetInnerHTML={{ __html: item }} />
                </li>
              ))}
            </ul>
          );
        }
        const prev = b.body[j - 1];
        const afterDef = Array.isArray(prev) && prev[0] === 'def';
        return <p key={j} style={{ fontSize: 15, lineHeight: 1.7, color: 'var(--ink-soft)', marginTop: afterDef ? 22 : 0, marginBottom: 14, maxWidth: '64ch' }}>{row}</p>;
      })}
    </div>
  ));
}

/* ============ HOW TO FIND US ============ */

function FindUsPage({ t, tw, setTweak, onBack }) {
  useReveal();
  const mapRef = React.useRef(null);
  const lat = (tw && typeof tw.mapLat === 'number') ? tw.mapLat : 46.71362;
  const lng = (tw && typeof tw.mapLng === 'number') ? tw.mapLng : 11.65426;

  useLE(() => {
    if (!window.L || !mapRef.current || mapRef.current._init) return;
    mapRef.current._init = true;
    const map = window.L.map(mapRef.current, {
      scrollWheelZoom: false, zoomControl: true, attributionControl: true
    }).setView([lat, lng], 16);
    window.L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; OpenStreetMap contributors', className: 'map-soft-tiles',
      subdomains: 'abcd', maxZoom: 19
    }).addTo(map);
    const icon = window.L.divIcon({
      className: 'casa-pin',
      html: '<div class="pin-pulse"></div><div class="pin-dot"></div><span class="sr-only">Casa Laudieri, Fallmerayerstraße 5, Brixen</span>',
      iconSize: [16, 16], iconAnchor: [8, 8]
    });
    window.L.marker([lat, lng], { icon }).addTo(map).bindTooltip('Casa Laudieri', {
      permanent: true, direction: 'right', offset: [14, 0], className: 'casa-tooltip'
    });
    return () => { map.remove(); if (mapRef.current) mapRef.current._init = false; };
  }, []);

  const fu = t.findus || {};

  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <button onClick={onBack} className="reveal" style={{
          fontSize: 13, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--mute)', fontWeight: 500, marginBottom: 32,
          padding: '8px 0', cursor: 'pointer'
        }}>{fu.back || '← Back'}</button>
        <div className="reveal" style={{ maxWidth: 920 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{fu.eyebrow}</div>
          <h1 className="display display-l serif">{fu.title}</h1>
          <p className="lede" style={{ marginTop: 32, maxWidth: '58ch', fontSize: 18 }}>{fu.lede}</p>
        </div>
      </section>

      <section className="section-sm shell">
        <div className="reveal map-ph" style={{ aspectRatio: '16 / 9' }}>
          <div ref={mapRef} className="casa-map"></div>
          <div className="map-cap">
            <small>Casa Laudieri</small>
            Fallmerayerstraße 5, Brixen
          </div>
        </div>
      </section>

      <section className="section shell" style={{ paddingTop: 'clamp(40px, 5vw, 60px)' }}>
        <div className="reveal" style={{ maxWidth: 720 }}>
          <LegalSections blocks={fu.blocks} />
        </div>
      </section>
    </div>
  );
}

/* ============ STANDALONE FAQ ============ */

function FaqPage({ t, onBack }) {
  useReveal();
  const [open, setOpen] = useLS(null);
  return (
    <LegalShell
      eyebrow={t.faqPage?.eyebrow || t.faq.eyebrow}
      title={t.faqPage?.title || t.faq.title}
      lede={t.faqPage?.lede}
      onBack={onBack}
      backLabel={t.findus?.back}
    >
      <div className="faq" style={{ maxWidth: 'none' }}>
        {t.faq.items.map((f, i) => (
          <div key={i} className={"faq-item" + (open === i ? ' open' : '')}>
            <button className="faq-q" onClick={() => setOpen(open === i ? null : i)}>
              <span>{f.q}</span>
              <span className="plus">+</span>
            </button>
            <div className="faq-a"><p>{f.a}</p></div>
          </div>
        ))}
      </div>
    </LegalShell>
  );
}

/* ============ BOOKING CONFIRMED ============ */

function BookedPage({ t, setPage }) {
  useReveal();
  const b = t.booked || {};
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <div className="reveal" style={{ maxWidth: 720 }}>
          <svg width="44" height="44" viewBox="0 0 44 44" fill="none" style={{ marginBottom: 28, display: 'block' }}>
            <circle cx="22" cy="22" r="21" stroke="var(--accent)" strokeWidth="1" />
            <path d="M14 22.5 L19.5 28 L30 16.5" stroke="var(--accent)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{b.eyebrow}</div>
          <h1 className="display display-l serif">{b.title}</h1>
          {b.lede && <p className="lede" style={{ marginTop: 32, maxWidth: '54ch', fontSize: 18 }}>{b.lede}</p>}
          <div style={{ display: 'flex', gap: 16, marginTop: 40, flexWrap: 'wrap' }}>
            <button className="btn btn-solid" onClick={() => setPage('home')}>{b.cta}</button>
            {b.secondary && <button className="btn btn-outline" onClick={() => setPage('area')}>{b.secondary}</button>}
          </div>
        </div>
      </section>
    </div>);

}

/* ============ GENERIC LEGAL PAGE ============ */

function LegalPage({ pageData, onBack, backLabel }) {
  return (
    <LegalShell
      eyebrow={pageData.eyebrow}
      title={pageData.title}
      lede={pageData.lede}
      onBack={onBack}
      backLabel={backLabel}
    >
      <LegalSections blocks={pageData.blocks} />
      {pageData.lastUpdated && (
        <p style={{ marginTop: 48, paddingTop: 24, borderTop: '1px solid var(--hair)', fontSize: 13, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--mute)' }}>
          {pageData.lastUpdated}
        </p>
      )}
    </LegalShell>
  );
}

Object.assign(window, { FindUsPage, FaqPage, LegalPage, BookedPage });
