/* Pages: Home, Apartments, Area, Story, Contact */

const { useState: useS, useEffect: useE } = React;

/* ============ HOME ============ */

function HomePage({ t, lang, setPage, openApt, onBook, openAreaItem }) {
  useReveal();
  return (
    <div className="page-enter">
      <section className="hero">
        <HeroPh label="HERO · PLOSE AT DUSK" src={CASA_PHOTOS.hero} />
        <div className="hero-content">
          <div className="hero-meta">
            <span>{t.hero.eyebrow}</span>
            <span className="dot"></span>
            <span>{t.hero.altitude}</span>
          </div>
          <h1 className="display display-xl serif" dangerouslySetInnerHTML={{ __html: t.hero.title }} />
          <div className="hero-foot">
            <p className="lede">{t.hero.lede}</p>
            <div className="scroll-cue">
              <span>{t.hero.scroll}</span>
              <span className="line"></span>
            </div>
          </div>
        </div>
      </section>

      <BookingBar t={t} apartments={t.apartments.list} onBook={onBook} />

      {/* Intro */}
      <section className="section shell">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow-num">
              <span className="eyebrow">{t.intro.eyebrow}</span>
            </div>
          </div>
          <div>
            <h2 className="display display-l">{t.intro.title}</h2>
            <p className="lede" style={{ marginTop: 32 }}>{t.intro.lede}</p>
          </div>
        </div>
        <div className="reveal stats-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--hair)', borderTop: '1px solid var(--hair)', borderBottom: '1px solid var(--hair)' }}>
          {t.intro.stats.map((s, i) =>
          <div key={i} style={{ background: 'var(--paper)', padding: '28px 24px' }}>
              <div className="serif" style={{ fontSize: 'clamp(40px, 4vw, 56px)', fontWeight: 300, lineHeight: 1 }}>{s.num}</div>
              <div className="eyebrow" style={{ marginTop: 12 }}>{s.lbl}</div>
            </div>
          )}
        </div>
      </section>

      {/* Apartments preview */}
      <section className="section shell" style={{ paddingTop: 0 }}>
        <SectionHead num="01" eyebrow={t.apartments.eyebrow.split('·')[1]?.trim() || ''} title={t.apartments.title} lede={t.apartments.lede} />
        <div className="apt-grid apt-grid-preview">
          {t.apartments.list.map((a, i) =>
          <ApartmentCard key={a.id} apt={a} t={t} onClick={() => openApt(a)} reveal />
          )}
        </div>
        <p className="reveal body-s" style={{ marginTop: 28, textAlign: 'center', fontStyle: 'italic', color: 'var(--mute)', whiteSpace: 'pre-line', lineHeight: 1.7 }}>{t.apartments.seasonalNote}</p>
        <div className="reveal" style={{ marginTop: 48, display: 'flex', justifyContent: 'center' }}>
          <button className="btn btn-ghost" onClick={() => setPage('apartments')}>{t.apartments.cta} →</button>
        </div>
      </section>

      {/* Story strip */}
      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="shell story-strip reveal">
          <Ph slot="story-archival" aspect="4 / 5" label="DROP PHOTO · 1915 SARTORIA" seed={3} src={CASA_PHOTOS.storyDetail} />
          <div className="story-text">
            <div className="eyebrow" style={{ marginBottom: 20 }}>{t.story.eyebrow}</div>
            <h2 className="display display-m serif">{t.story.title}</h2>
            <div style={{ marginTop: 28 }}>
              {t.story.paras.slice(0, 2).map((p, i) => <p key={i}>{p}</p>)}
            </div>
            <button className="btn btn-ghost story-cta" style={{ marginTop: 28 }} onClick={() => setPage('story')}>{t.story.cta} →</button>
          </div>
        </div>
      </section>

      {/* Big quote */}
      {t.quote && t.quote.text &&
      <section className="big-quote">
          <q className="reveal">{t.quote.text}</q>
          <div className="attrib reveal">{t.quote.attrib}</div>
        </section>
      }

      <hr className="hair shell" style={{ maxWidth: 'calc(var(--max) - var(--gutter) * 2)' }} />

      {/* Area teaser */}
      <section className="section shell">
        <SectionHead num="03" eyebrow={t.area.eyebrow.split('·')[1]?.trim() || ''} title={t.area.title} lede={t.area.lede} />
        <div className="reveal area-grid">
          {t.area.items.slice(0, 4).map((it, i) =>
          <div key={it.id || i} className="area-cell" onClick={() => openAreaItem ? openAreaItem(it) : setPage('area')}>
              <div className="num">{it.num}</div>
              <div>
                <h3>{it.t}</h3>
                <p>{it.d}</p>
              </div>
              <div className="arrow">→</div>
            </div>
          )}
        </div>
        <div className="reveal" style={{ marginTop: 32, display: 'flex', justifyContent: 'center' }}>
          <button className="btn btn-ghost" onClick={() => setPage('area')}>{t.area.cta} →</button>
        </div>
      </section>

      {/* Reviews */}
      {t.reviews.items && t.reviews.items.length > 0 && (() => {
        // Pick up to 6 reviews, balanced across apartments (round-robin from each)
        const byApt = {};
        const aptOrder = [];
        t.reviews.items.forEach((r) => {
          const m = r.from.match(/(Plose|K\u00f6nigsanger|Jochtal)/);
          const key = m ? m[1] : 'other';
          if (!byApt[key]) {byApt[key] = [];aptOrder.push(key);}
          byApt[key].push(r);
        });
        const featured = [];
        let i = 0;
        while (featured.length < 4 && aptOrder.some((k) => byApt[k][i])) {
          aptOrder.forEach((k) => {if (byApt[k][i] && featured.length < 4) featured.push(byApt[k][i]);});
          i++;
        }
        return (
          <section className="section" style={{ background: 'var(--paper-2)' }}>
            <div className="shell">
              <SectionHead num="04" eyebrow={t.reviews.eyebrow.split('·')[1]?.trim() || ''} title={t.reviews.title} />
            </div>
            <div className="reviews reveal">
              {featured.map((r, i) =>
              <div key={i} className="review">
                  <div className="stars">{r.stars}</div>
                  <q>{r.q}</q>
                  <div className="who"><strong>{r.name}</strong> · {r.from}</div>
                </div>
              )}
            </div>
          </section>);

      })()}

      {/* Press */}
      {/* Gallery */}

      {/* Map */}
      <section className="section shell">
        <SectionHead eyebrow={t.contact.address} title={t.findus?.title || 'How to find us.'} lede={<span className="addr-lede">{t.contact.address_text}</span>} />
        <div className="reveal">
          <CasaMap aspect="21 / 9" />
        </div>
      </section>
    </div>);

}

/* ============ APARTMENT CARD ============ */

function ApartmentCard({ apt, t, onClick, locked }) {
  return (
    <div className="apt-card reveal" onClick={onClick}>
      <div className="ph-inner">
        <Ph slot={`apt-${apt.id}`} aspect="4 / 5" label={`Drop photo · ${apt.name}`} seed={apt.name.charCodeAt(0)} src={CASA_PHOTOS[`apt-${apt.id}`]} locked={locked} />
      </div>
      <div className="apt-meta">
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>{apt.sub}</div>
          <h2 className="serif">{apt.name}</h2>
        </div>
        <div className="numeral" style={{ fontSize: 22, color: 'var(--ink)' }}>
          <span className="body-s" style={{ marginRight: 8, letterSpacing: '0.1em', color: 'var(--mute)' }}>{t.apartments.from}</span>
          {apt.price}
          <span className="body-s" style={{ marginLeft: 6, letterSpacing: '0.1em' }}>· {t.apartments.perNight}</span>
        </div>
      </div>
      <p className="desc">{apt.desc}</p>
      <div className="specs">
        <span>{apt.sleeps} {t.apartments.sleeps}</span>
        <span>{apt.size}</span>
        <span>{apt.bedrooms}</span>
      </div>
      <span className="apt-card-cta">{t.apartments.details} →</span>
    </div>);

}

/* ============ APARTMENTS ============ */

function ApartmentsPage({ t, openApt, onBook }) {
  useReveal();
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <div className="reveal" style={{ maxWidth: 880, marginBottom: 48 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t.apartments.eyebrow}</div>
          <h1 className="display display-l serif">{t.apartments.title}</h1>
          <p className="lede" style={{ marginTop: 28, maxWidth: '52ch' }}>{t.apartments.lede}</p>
        </div>
      </section>

      <BookingBar t={t} apartments={t.apartments.list} onBook={onBook} />

      <section className="section shell">
        <div className="apt-grid">
          {t.apartments.list.map((a) =>
          <ApartmentCard key={a.id} apt={a} t={t} onClick={() => openApt(a)} />
          )}
        </div>
        <p className="reveal body-s" style={{ marginTop: 32, textAlign: 'center', fontStyle: 'italic', color: 'var(--mute)', whiteSpace: 'pre-line', lineHeight: 1.7 }}>{t.apartments.seasonalNote}</p>
      </section>

      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="shell">
          <SectionHead eyebrow={t.apartments.common.eyebrow} title={t.apartments.common.title} lede={t.apartments.common.lede} />
          <div className="reveal cols-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'var(--hair)', border: '1px solid var(--hair)' }}>
            {t.apartments.common.items.
            map(([k, v], i) =>
            <div key={i} style={{ background: 'var(--paper)', padding: '32px 28px' }}>
                <div className="eyebrow">{k}</div>
                <p style={{ marginTop: 14, fontSize: 15, lineHeight: 1.55, color: 'var(--ink-soft)' }}>{v}</p>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>);

}

/* ============ AREA ============ */

function AreaPage({ t, openAreaItem }) {
  useReveal();
  const [season, setSeason] = useS('all');
  const filters = t.area.filters || {};
  const filterEntries = [
  ['all', filters.all || 'All seasons'],
  ['summer', filters.summer || 'Summer'],
  ['winter', filters.winter || 'Winter'],
  ['food', filters.food || 'Food & drink']];

  const visibleItems = t.area.items.filter((it) =>
  season === 'all' || it.categories && it.categories.includes(season)
  );

  const pd = t.area.perfectDay || {};
  const [dayMode, setDayMode] = useS('summer');
  const activeDays = (dayMode === 'winter' ? pd.daysWinter : pd.daysSummer) || [];
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <div className="reveal" style={{ maxWidth: 880 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t.area.eyebrow}</div>
          <h1 className="display display-l serif">{t.area.title}</h1>
          <p className="lede" style={{ marginTop: 28, maxWidth: '52ch' }}>{t.area.lede}</p>
        </div>
      </section>

      <section className="section-sm shell" style={{ paddingTop: 0 }}>
        <div className="reveal" style={{ display: 'flex', gap: 0, border: '1px solid var(--hair)' }}>
          {filterEntries.map(([id, label], i) =>
          <button key={id} onClick={() => setSeason(id)}
          style={{
            flex: 1, padding: '18px 16px',
            fontSize: 13, letterSpacing: '0.2em', textTransform: 'uppercase',
            fontWeight: 500,
            color: season === id ? 'var(--ink)' : 'var(--mute)',
            borderLeft: i === 0 ? 'none' : '1px solid var(--hair)',
            background: season === id ? 'var(--paper-2)' : 'transparent',
            transition: 'background 0.2s, color 0.2s',
            cursor: 'pointer'
          }}>{label}</button>
          )}
        </div>
      </section>

      <section className="shell" style={{ paddingBottom: 'clamp(60px, 9vw, 140px)' }}>
        <div className="reveal area-grid">
          {visibleItems.map((it, i) =>
          <div key={it.id || i} className="area-cell" style={{ minHeight: 320 }} onClick={() => openAreaItem && openAreaItem(it)}>
              <div className="num">{it.num}</div>
              <div>
                <h2>{it.t}</h2>
                <p>{it.d}</p>
              </div>
              <div className="arrow">→</div>
            </div>
          )}
        </div>
        {visibleItems.length === 0 &&
        <p className="reveal body-s" style={{ textAlign: 'center', padding: '40px 0', color: 'var(--mute)' }}>·</p>
        }
      </section>

      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="shell">
          <SectionHead eyebrow={pd.eyebrow} title={pd.title} lede={pd.lede} />
          <div className="reveal" style={{ display: 'inline-flex', marginBottom: 'clamp(36px, 5vw, 64px)', border: '1px solid var(--hair)' }}>
            {[['summer', pd.summer || 'Summer'], ['winter', pd.winter || 'Winter']].map(([id, label]) =>
            <button key={id} onClick={() => setDayMode(id)}
            style={{
              padding: '14px 32px',
              fontSize: 13, letterSpacing: '0.2em', textTransform: 'uppercase', fontWeight: 500,
              color: dayMode === id ? 'var(--ink)' : 'var(--mute)',
              background: dayMode === id ? 'var(--paper)' : 'transparent',
              borderLeft: id === 'winter' ? '1px solid var(--hair)' : 'none',
              transition: 'background 0.2s, color 0.2s', cursor: 'pointer'
            }}>{label}</button>
            )}
          </div>
          <div className="reveal cols-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'clamp(40px, 5vw, 80px)', alignItems: 'start' }}>
            {activeDays.
            map((d, i) =>
            <div key={i}>
                <h3 className="display display-s serif" style={{ marginBottom: 24 }}>{d.t}</h3>
                <div style={{ borderTop: '1px solid var(--hair)' }}>
                  {d.steps.map(([time, text], j) =>
                <div key={j} style={{ display: 'grid', gridTemplateColumns: '80px 1fr', padding: '14px 0', borderBottom: '1px solid var(--hair)', gap: 16 }}>
                      <span className="numeral" style={{ fontSize: 16, color: 'var(--mute)' }}>{time}</span>
                      <span style={{ fontSize: 14, color: 'var(--ink-soft)', lineHeight: 1.5 }}>{text}</span>
                    </div>
                )}
                </div>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>);

}

/* ============ STORY ============ */

function StoryPage({ t }) {
  useReveal();
  const timeline = t.story.timeline || [];

  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <div className="reveal" style={{ maxWidth: 880 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t.story.eyebrow}</div>
          <h1 className="display display-l serif">{t.story.title}</h1>
        </div>
      </section>

      <section className="section shell" style={{ paddingTop: 'clamp(40px, 5vw, 60px)' }}>
        <div className="story-strip reveal">
          <Ph slot="story-detail" aspect="4 / 5" label="THE HOUSE · c. 1915" seed={4} src={CASA_PHOTOS.storyHistory} locked />
          <div className="story-text">
            {t.story.paras.map((p, i) => <p key={i}>{p}</p>)}
            <dl className="meta-list">
              {t.story.meta.map(([k, v], i) =>
              <div key={i} className="row">
                  <dt>{k}</dt>
                  <dd>{v}</dd>
                </div>
              )}
            </dl>
          </div>
        </div>
      </section>

      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="shell">
          <SectionHead eyebrow={t.story.timelineHead && t.story.timelineHead.eyebrow} title={t.story.timelineHead && t.story.timelineHead.title} />
          <div className="reveal" style={{ maxWidth: 760, margin: '0 auto' }}>
            {timeline.map(([year, text], i) =>
            <div key={i} className="tl-row" style={{ display: 'grid', gridTemplateColumns: '230px 1fr', gap: 32, padding: '28px 0', borderTop: '1px solid var(--hair)', alignItems: 'baseline' }}>
                <span className="numeral" style={{ fontSize: 28, color: 'var(--accent)', lineHeight: 1.6, whiteSpace: 'nowrap' }}>{year}</span>
                <p className="tl-text" style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--ink-soft)', maxWidth: '48ch' }}>{text}</p>
              </div>
            )}
            <div style={{ borderBottom: '1px solid var(--hair)' }}></div>
          </div>
        </div>
      </section>

      <section className="big-quote">
        <q className="reveal">{t.story.quote && t.story.quote.text}</q>
        <div className="attrib reveal">{t.story.quote && t.story.quote.attrib}</div>
      </section>

      <section className="section shell">
        <SectionHead eyebrow={t.story.keptHead && t.story.keptHead.eyebrow} title={t.story.keptHead && t.story.keptHead.title} />
        <div className="reveal detail-grid">
          {(t.story.kept || []).
          map(([k, v], i) =>
          <div key={i} style={{ background: 'var(--paper)', padding: '32px 28px' }}>
              <div className="serif" style={{ fontSize: 26, fontWeight: 300, marginBottom: 12 }}>{k}</div>
              <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-soft)' }}>{v}</p>
            </div>
          )}
        </div>
      </section>
    </div>);

}

/* ============ CONTACT ============ */

/* ─── Enquiry form delivery ───────────────────────────────────────────────
   The enquiry form is delivered as a branded email from your own domain via a
   Vercel serverless function (api/enquiry.js) that calls Resend. Requires:
     1. Resend account + verified casalaudieri.com domain
     2. RESEND_API_KEY set in Vercel env vars
     3. Deployed to Vercel (the function does NOT run in the design preview —
        submitting here will show the error state; test on the live site)
*/
const ENQUIRY_ENDPOINT = "/api/enquiry";
// Cloudflare Turnstile (invisible) public site key. Matching secret is set as
// TURNSTILE_SECRET_KEY in Vercel and verified in api/enquiry.js.
const TURNSTILE_SITE_KEY = "0x4AAAAAADs7irwwFp6GIvC7";

function ContactPage({ t, tw, setTweak, setPage, lang }) {
  useReveal();
  const [sent, setSent] = useS(false);
  const [openFaq, setOpenFaq] = useS(null);
  const [consent, setConsent] = useS(false);
  const [sending, setSending] = useS(false);
  const [error, setError] = useS(false);
  const minDate = (() => {const d = new Date();d.setDate(d.getDate() + 1);return d.toISOString().split('T')[0];})();
  const minDeparture = (() => {const d = new Date();d.setDate(d.getDate() + 2);return d.toISOString().split('T')[0];})();
  const [arrival, setArrival] = useS(minDate);
  const [departure, setDeparture] = useS(minDeparture);
  const [tsToken, setTsToken] = useS('');
  const tsRef = React.useRef(null);
  const tsWidget = React.useRef(null);

  React.useEffect(() => {
    let tries = 0;
    const iv = setInterval(() => {
      if (window.turnstile && tsRef.current && tsWidget.current === null) {
        tsWidget.current = window.turnstile.render(tsRef.current, {
          sitekey: TURNSTILE_SITE_KEY,
          callback: (token) => setTsToken(token),
          'error-callback': () => setTsToken(''),
          'expired-callback': () => {setTsToken('');if (window.turnstile && tsWidget.current !== null) window.turnstile.reset(tsWidget.current);}
        });
        clearInterval(iv);
      }
      if (++tries > 150) clearInterval(iv);
    }, 100);
    return () => clearInterval(iv);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError(false);
    setSending(true);
    try {
      const data = new FormData(e.target);
      const payload = Object.fromEntries(data.entries());
      payload['cf-turnstile-response'] = tsToken;
      const res = await fetch(ENQUIRY_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload)
      });
      if (res.ok) {setSent(true);} else {setError(true);}
      if (window.turnstile && tsWidget.current !== null) {window.turnstile.reset(tsWidget.current);setTsToken('');}
    } catch (err) {
      setError(true);
    }
    setSending(false);
  };
  const mapRef = React.useRef(null);
  const mapInstance = React.useRef(null);
  const markerRef = React.useRef(null);

  const lat = tw && typeof tw.mapLat === 'number' ? tw.mapLat : 46.7156;
  const lng = tw && typeof tw.mapLng === 'number' ? tw.mapLng : 11.658;

  React.useEffect(() => {
    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], 15);
    mapInstance.current = map;
    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]
    });
    const marker = window.L.marker([lat, lng], { icon, draggable: false }).
    addTo(map).
    bindTooltip('Casa Laudieri', {
      permanent: true,
      direction: 'right',
      offset: [14, 0],
      className: 'casa-tooltip'
    });
    markerRef.current = marker;
    return () => {
      map.remove();
      if (mapRef.current) mapRef.current._init = false;
      mapInstance.current = null;
      markerRef.current = null;
    };
  }, []);

  // Sync marker + map when lat/lng tweak changes from elsewhere (numeric input)
  React.useEffect(() => {
    if (!mapInstance.current || !markerRef.current) return;
    const cur = markerRef.current.getLatLng();
    if (Math.abs(cur.lat - lat) < 1e-6 && Math.abs(cur.lng - lng) < 1e-6) return;
    markerRef.current.setLatLng([lat, lng]);
    mapInstance.current.panTo([lat, lng]);
  }, [lat, lng]);

  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <div className="reveal" style={{ maxWidth: 880 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>{t.contact.eyebrow}</div>
          <h1 className="display display-l serif">{t.contact.title}</h1>
          <p className="lede" style={{ marginTop: 28, maxWidth: '52ch' }}>{t.contact.lede}</p>
        </div>
      </section>

      <section className="section shell" style={{ paddingTop: 0 }}>
        <div className="contact-grid">
          <div className="reveal">
            {sent ?
            <div style={{ padding: '32px 0' }}>
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none" style={{ marginBottom: 20, display: 'block' }}>
                  <circle cx="20" cy="20" r="19" stroke="var(--accent)" strokeWidth="1" />
                  <path d="M13 20.5 L18 25.5 L27.5 15" stroke="var(--accent)" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <p className="serif" style={{ fontSize: 24, fontWeight: 300, lineHeight: 1.3, margin: 0, whiteSpace: 'nowrap' }}>{t.contact.form.sent}</p>
              </div> :

            <form onSubmit={handleSubmit}>
                <input type="text" name="_gotcha" tabIndex="-1" autoComplete="off" aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
                <div className="form-grid-2">
                  <div className="form-row"><label htmlFor="cl-first">{t.contact.form.firstName} <span className="req">*</span></label><input id="cl-first" type="text" name="First Name" autoComplete="given-name" required /></div>
                  <div className="form-row"><label htmlFor="cl-last">{t.contact.form.lastName} <span className="req">*</span></label><input id="cl-last" type="text" name="Last Name" autoComplete="family-name" required /></div>
                </div>
                <div className="form-row"><label htmlFor="cl-email">{t.contact.form.email} <span className="req">*</span></label><input id="cl-email" type="email" name="Email" autoComplete="email" required /></div>
                <div className="form-grid-2">
                  <div className="form-row"><label htmlFor="cl-arrival">{t.contact.form.arrival}</label><input id="cl-arrival" type="date" name="Arrival" min={minDate} value={arrival} onChange={(e) => {setArrival(e.target.value);if (departure && e.target.value && departure < e.target.value) setDeparture('');}} /></div>
                  <div className="form-row"><label htmlFor="cl-departure">{t.contact.form.departure}</label><input id="cl-departure" type="date" name="Departure" min={arrival || minDate} value={departure} onChange={(e) => setDeparture(e.target.value)} /></div>
                </div>
                <div className="form-grid-2">
                  <div className="form-row">
                    <label htmlFor="cl-guests">{t.contact.form.people}</label>
                    <FormSelect id="cl-guests" name="Guests" defaultValue="2" options={[1, 2, 3, 4, 5, 6].map((n) => ({ value: String(n), label: String(n) }))} />
                  </div>
                  <div className="form-row">
                    <label htmlFor="cl-apt">{t.contact.form.apt}</label>
                    <FormSelect id="cl-apt" name="Apartment" defaultValue={t.contact.form.any} options={[{ value: t.contact.form.any, label: t.contact.form.any }].concat(t.apartments.list.map((a) => ({ value: a.name, label: a.name })))} />
                  </div>
                </div>
                <div className="form-row">
                  <label htmlFor="cl-message">{t.contact.form.msg}</label>
                  <textarea id="cl-message" name="Message" rows="4"></textarea>
                </div>
                <label className="consent-row" style={{ display: 'flex', gap: 12, alignItems: 'flex-start', margin: '8px 0 24px', cursor: 'pointer', fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)' }}>
                  <input
                  type="checkbox"
                  required
                  checked={consent}
                  onChange={(e) => setConsent(e.target.checked)}
                  style={{
                    width: 16, height: 16, marginTop: 3,
                    accentColor: 'var(--accent)', flex: 'none', cursor: 'pointer'
                  }} />
                
                  <span>
                    {t.contact.form.consentBefore}
                    <a
                    href={casaHref('privacy', lang)}
                    onClick={(e) => {if (e.metaKey || e.ctrlKey) return;e.preventDefault();setPage && setPage('privacy');}}
                    style={{ textDecoration: 'underline', textUnderlineOffset: 3, cursor: 'pointer', color: 'var(--ink)' }}>
                    {t.contact.form.consentLink}</a>
                    {t.contact.form.consentAfter}
                  </span>
                </label>
                {error &&
              <p style={{ color: 'var(--accent)', fontSize: 13, lineHeight: 1.5, margin: '0 0 16px' }}>{t.contact.form.error}</p>
              }
                <div ref={tsRef}></div>
                <button className="btn btn-solid" type="submit" disabled={!consent || sending} style={{ opacity: !consent || sending ? 0.4 : 1, cursor: !consent || sending ? 'not-allowed' : 'pointer' }}>{sending ? t.contact.form.sending : t.contact.form.send + ' →'}</button>
                <p style={{ fontSize: 12.5, color: 'var(--mute)', margin: '16px 0 0', letterSpacing: '0.02em' }}>{t.contact.form.note}</p>
              </form>
            }
          </div>

          <div className="reveal">
            <div style={{ marginBottom: 40 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{t.contact.address}</div>
              <p className="serif" style={{ fontSize: 22, fontWeight: 300, lineHeight: 1.4, whiteSpace: 'pre-line' }}>{t.contact.address_text}</p>
            </div>
            <div style={{ marginBottom: 40 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{t.contact.direct}</div>
              <p style={{ fontSize: 16, lineHeight: 1.6, whiteSpace: 'pre-line', color: 'var(--ink-soft)' }}>
                <a href={'mailto:' + t.contact.contact_text} style={{ color: 'var(--ink-soft)', textDecoration: 'underline', textUnderlineOffset: 3 }}>{t.contact.contact_text}</a>
              </p>
            </div>
            <div style={{ marginBottom: 40 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{t.contact.hours}</div>
              <p style={{ fontSize: 16, lineHeight: 1.6, whiteSpace: 'pre-line', color: 'var(--ink-soft)' }}>{t.contact.hours_text}</p>
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 14 }}>{t.contact.languages}</div>
              <p style={{ fontSize: 16, color: 'var(--ink-soft)' }}>{t.contact.languages_text}</p>
            </div>
          </div>
        </div>
      </section>

      {/* Map */}
      {/* FAQ */}
      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="shell">
          <SectionHead eyebrow={t.faq.eyebrow.split('·')[1]?.trim() || ''} title={t.faq.title} />
          <div className="reveal faq">
            {t.faq.items.map((f, i) =>
            <div key={i} className={"faq-item" + (openFaq === i ? ' open' : '')}>
                <button className="faq-q" onClick={() => setOpenFaq(openFaq === i ? null : i)}>
                  <span>{f.q}</span>
                  <span className="plus">+</span>
                </button>
                <div className="faq-a"><p>{f.a}</p></div>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Map */}
      <section className="section-sm shell">
        <div className="reveal map-ph">
          <div ref={mapRef} className="casa-map"></div>
          <div className="map-cap">
            <small>Casa Laudieri</small>
            Fallmerayerstraße 5, Brixen
          </div>
        </div>
      </section>
    </div>);

}

/* ============ AREA DETAIL ============ */

function AreaDetailPage({ t, item, onBack, lang, setPage }) {
  useReveal();
  if (!item) return null;
  const labels = t.area.detailLabels || { highlights: 'What to see', practical: 'Practical', back: '← Back' };
  const detail = item.detail || { intro: item.d, highlights: [], practical: [] };
  /* These pages sit two levels deep, so a visitor arriving from a search result
     has no sense of where they are. The trail is also a second structured
     signal for Google (BreadcrumbList, emitted in app.jsx). */
  const home = { en: 'House', it: 'La Casa', de: 'Das Haus' }[lang] || 'House';
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section-sm shell">
        <a href={casaHref('area', lang)} onClick={(e) => {if (e.metaKey || e.ctrlKey) return;e.preventDefault();onBack && onBack();}} className="reveal" style={{
          display: 'inline-block',
          fontSize: 13, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--mute)', fontWeight: 500, marginBottom: 32,
          padding: '8px 0', textDecoration: 'none'
        }}>{labels.back}</a>

        <div className="reveal" style={{ maxWidth: 920 }}>
          <div className="eyebrow-num" style={{ marginBottom: 24 }}>
            <span className="eyebrow">{item.num} · {t.area.eyebrow.split('·')[1]?.trim() || t.area.eyebrow}</span>
          </div>
          <h1 className="display display-l serif">{item.t}</h1>
          <p className="lede" style={{ marginTop: 32, maxWidth: '58ch', fontSize: 18 }}>{detail.intro}</p>
        </div>
      </section>

      <section className="section-sm shell">
        <div className="reveal">
          <Ph slot={`area-${item.id}`} label={`Drop photo · ${item.t}`} seed={item.t.length} aspect="16 / 9" src={CASA_PHOTOS[`area-${item.id}`]} locked />
        </div>
      </section>

      {detail.highlights && detail.highlights.length > 0 &&
      <section className="section shell" style={{ paddingTop: 'clamp(40px, 5vw, 60px)' }}>
          <div className="section-head reveal">
            <div>
              <div className="eyebrow-num">
                <span className="eyebrow">{labels.highlights}</span>
              </div>
            </div>
            <div></div>
          </div>
          <div className="reveal detail-grid">
            {detail.highlights.map(([k, v], i) =>
          <div key={i} style={{ background: 'var(--paper)', padding: '36px 32px' }}>
                <h2 className="serif" style={{ fontSize: 28, fontWeight: 300, marginBottom: 14, lineHeight: 1.1 }}>{k}</h2>
                <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-soft)', maxWidth: '42ch', whiteSpace: 'pre-line' }}>{v}</p>
              </div>
          )}
          </div>
          {detail.note && <p className="reveal" style={{ marginTop: 18, fontSize: 13, lineHeight: 1.6, color: 'var(--mute)' }}>{detail.note}</p>}
        </section>
      }

      {detail.practical && detail.practical.length > 0 &&
      <section className="section" style={{ background: 'var(--paper-2)' }}>
          <div className="shell">
            <div className="section-head reveal">
              <div>
                <div className="eyebrow-num">
                  <span className="eyebrow">{labels.practical}</span>
                </div>
              </div>
              <div></div>
            </div>
            <div className="reveal" style={{ maxWidth: 720 }}>
              {detail.practical.map(([k, v], i) =>
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 32, padding: '22px 0', borderTop: '1px solid var(--hair)' }}>
                  <span className="eyebrow" style={{ paddingTop: 4 }}>{k}</span>
                  <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink-soft)', maxWidth: '52ch' }}>{v}</p>
                </div>
            )}
              <div style={{ borderBottom: '1px solid var(--hair)' }}></div>
            </div>
          </div>
        </section>
      }

      <section className="section shell" style={{ textAlign: 'center' }}>
        <button onClick={onBack} className="btn btn-ghost reveal">{labels.back}</button>
      </section>
    </div>);

}

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

Object.assign(window, { HomePage, ApartmentsPage, AreaPage, AreaDetailPage, StoryPage, ContactPage, ApartmentCard });