/* ============================================================
   HÔTEL OMÉGA — Refonte
   App React (montée dans #app)
   ============================================================ */

const { useState, useEffect, useRef, useMemo } = React;

/* ---------- DATA ---------- */
const IMG = {
  room: "assets/room-double.jpg",
  view: "assets/view-window.jpg",
  bath: "assets/bathroom.jpg",
  facade: "assets/facade-night.jpg?v=2",
};

/* Rooms — translatable fields read via t(), structural data here */
const ROOM_DATA = [
  {
    id: "D", num: "—", type: "Double", capacity: 2, price: 250,
    available: true, img: IMG.room,
    featureKeys: ["room.feat.ac", "room.feat.wifi", "room.feat.bath", "room.feat.linen"],
  },
  {
    id: "T", num: "—", type: "Family", capacity: 4, price: 300,
    available: true, img: IMG.bath,
    featureKeys: ["room.feat.ac", "room.feat.wifi", "room.feat.bath", "room.feat.linen"],
  },
];

function getRooms(t) {
  return ROOM_DATA.map(r => ({
    ...r,
    name: t(`room.${r.id}.name`),
    bed: t(`room.${r.id}.bed`),
    desc: t(`room.${r.id}.desc`),
    placeholder: t(`room.${r.id}.placeholder`),
    features: r.featureKeys.map(k => t(k)),
  }));
}

function getHeroSlides(t) {
  return [
    { eyebrow: t("hero.s1.eyebrow"), t1: t("hero.s1.t1"), tEm: t("hero.s1.tEm"), t2: t("hero.s1.t2"), sub: t("hero.s1.sub"), img: IMG.facade },
    { eyebrow: t("hero.s2.eyebrow"), t1: t("hero.s2.t1"), tEm: t("hero.s2.tEm"), t2: t("hero.s2.t2"), sub: t("hero.s2.sub"), img: IMG.room },
    { eyebrow: t("hero.s3.eyebrow"), t1: t("hero.s3.t1"), tEm: t("hero.s3.tEm"), t2: t("hero.s3.t2"), sub: t("hero.s3.sub"), img: IMG.view },
    { eyebrow: t("hero.s4.eyebrow"), t1: t("hero.s4.t1"), tEm: t("hero.s4.tEm"), t2: t("hero.s4.t2"), sub: t("hero.s4.sub"), img: IMG.bath },
  ];
}

function getNavLinks(t) {
  return [
    { id: "home",       label: t("nav.home") },
    { id: "rooms",      label: t("nav.rooms") },
    { id: "experience", label: t("nav.experience") },
    { id: "about",      label: t("nav.about") },
    { id: "faq",        label: t("nav.faq") },
    { id: "contact",    label: t("nav.contact") },
  ];
}

/* ---------- CURRENCY ---------- */
/* Indicative rates BRL → EUR / USD. Update periodically.
   Last refresh: January 2026. */
const FX = {
  EUR: 0.165, // 1 BRL ≈ 0.165 EUR
  USD: 0.180, // 1 BRL ≈ 0.180 USD
};

/* Display a price with discreet EUR/USD conversion underneath */
function Price({ brl, layout = "row", showFrom = false }) {
  const [t] = window.useT();
  const eur = Math.round(brl * FX.EUR);
  const usd = Math.round(brl * FX.USD);
  return (
    <div className={"price-tag " + (layout === "stack" ? "is-stack" : "is-row")}>
      {showFrom && <span className="price-from">{t("rooms.from")}</span>}
      <span className="price-main">
        <span className="price-amount">{brl}</span>
        <span className="price-cur">R$</span>
      </span>
      <span className="price-conv">
        <span>{t("cur.approx")} {eur}{t("cur.eur")}</span>
        <span className="price-conv-sep">·</span>
        <span>{t("cur.approx")} {usd}{t("cur.usd")}</span>
      </span>
    </div>
  );
}

/* ---------- DEFAULTS for Tweaks ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 78,
  "accentChroma": 0.11,
  "density": "comfortable",
  "showOmegaWatermark": true,
  "showImages": true,
  "heroVariant": "calm"
}/*EDITMODE-END*/;

/* ---------- PLACEHOLDER IMAGE ---------- */
function Placeholder({ label, ratio = "4/3", small = false, src = null }) {
  // If images are turned off via tweak, use striped placeholder
  const imgsOn = typeof document !== "undefined" && document.documentElement.dataset.images !== "off";
  if (src && imgsOn) {
    return (
      <div className="ph ph-img" style={{ aspectRatio: ratio }}>
        <img src={src} alt={label} loading="lazy" />
      </div>
    );
  }
  return (
    <div className="ph" style={{ aspectRatio: ratio }}>
      <svg className="ph-svg" preserveAspectRatio="none" viewBox="0 0 100 100">
        <defs>
          <pattern id={`stripes-${label}`} width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <rect width="3" height="3" fill="transparent" />
            <line x1="0" y1="0" x2="0" y2="3" stroke="currentColor" strokeWidth="0.5" opacity="0.18" />
          </pattern>
        </defs>
        <rect width="100" height="100" fill={`url(#stripes-${label})`} />
      </svg>
      <div className={"ph-label" + (small ? " ph-label-sm" : "")}>{label}</div>
    </div>
  );
}

/* ---------- HERO SLIDER ---------- */
function HeroSlider({ openBooking, go }) {
  const [t] = window.useT();
  const slides = getHeroSlides(t);
  const [idx, setIdx] = useState(0);
  const total = slides.length;

  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % total), 6500);
    return () => clearInterval(id);
  }, [total]);

  return (
    <section className="hero-slider" data-screen-label="Accueil · Hero">
      {slides.map((s, i) => (
        <div key={i} className={"hs-slide" + (i === idx ? " is-active" : "")}>
          <div className="hs-bg">
            <img src={s.img} alt="" />
          </div>
          <div className="hs-veil" />
        </div>
      ))}

      <div className="hs-watermark" aria-hidden="true">Ω</div>

      <div className="hs-grid">
        <div className="hs-meta hs-meta-left">
          <span className="meta-line"></span>
          <span className="meta-text">{t("hero.foundedIn")}</span>
        </div>
        <div className="hs-meta hs-meta-right">
          <span className="meta-text">{t("hero.location")}</span>
          <span className="meta-line"></span>
        </div>

        <div className="hs-center">
          {slides.map((s, i) => (
            <div key={i} className={"hs-content" + (i === idx ? " is-active" : "")}>
              <div className="hero-eyebrow">{s.eyebrow}</div>
              <h1 className="hero-title">{s.t1}<em>{s.tEm}</em>{s.t2}</h1>
              <div className="hero-sub">{s.sub}</div>
            </div>
          ))}
          <div className="hero-cta">
            <button className="btn btn-primary" onClick={openBooking}>
              <span>{t("hero.book")}</span>
              <span className="btn-arrow">→</span>
            </button>
            <button className="btn btn-ghost" onClick={() => go("rooms")}>
              {t("hero.discover")}
            </button>
          </div>
        </div>

        <div className="hs-foot">
          <div className="hs-dots">
            {slides.map((_, i) => (
              <button
                key={i}
                className={"hs-dot" + (i === idx ? " is-active" : "")}
                onClick={() => setIdx(i)}
                aria-label={`Aller au slide ${i + 1}`}
              />
            ))}
          </div>
          <div className="hs-counter">
            <span className="hs-cur">{String(idx + 1).padStart(2, "0")}</span>
            <span className="hs-sep">/</span>
            <span className="hs-tot">{String(total).padStart(2, "0")}</span>
          </div>
          <div className="hs-arrows">
            <button className="hs-arrow" onClick={() => setIdx((idx - 1 + total) % total)} aria-label={t("hero.prev")}>←</button>
            <button className="hs-arrow" onClick={() => setIdx((idx + 1) % total)} aria-label={t("hero.next")}>→</button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- OMEGA MARK ---------- */
function OmegaMark({ size = 1, animated = false }) {
  return (
    <span className={"omega-mark" + (animated ? " omega-anim" : "")} style={{ fontSize: `${size}em` }}>
      Ω
    </span>
  );
}

/* ---------- LANGUAGE PICKER ---------- */
const LANGS = [
  {
    code: "fr", label: "Français",
    flag: (
      <svg viewBox="0 0 24 16" className="flag-svg" aria-hidden="true">
        <rect width="8" height="16" fill="#0055A4"/>
        <rect x="8" width="8" height="16" fill="#FFFFFF"/>
        <rect x="16" width="8" height="16" fill="#EF4135"/>
      </svg>
    ),
  },
  {
    code: "en", label: "English",
    flag: (
      <svg viewBox="0 0 24 16" className="flag-svg" aria-hidden="true">
        <rect width="24" height="16" fill="#012169"/>
        <path d="M0,0 L24,16 M24,0 L0,16" stroke="#FFFFFF" strokeWidth="3"/>
        <path d="M0,0 L24,16 M24,0 L0,16" stroke="#C8102E" strokeWidth="1.5"/>
        <rect x="10" width="4" height="16" fill="#FFFFFF"/>
        <rect y="6" width="24" height="4" fill="#FFFFFF"/>
        <rect x="11" width="2" height="16" fill="#C8102E"/>
        <rect y="7" width="24" height="2" fill="#C8102E"/>
      </svg>
    ),
  },
  {
    code: "pt", label: "Português",
    flag: (
      <svg viewBox="0 0 24 16" className="flag-svg" aria-hidden="true">
        <rect width="24" height="16" fill="#009C3B"/>
        <polygon points="12,2 22,8 12,14 2,8" fill="#FFDF00"/>
        <circle cx="12" cy="8" r="3" fill="#002776"/>
      </svg>
    ),
  },
];

function LangPicker() {
  const [, lang, setLangFn] = window.useT();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  const current = LANGS.find(l => l.code === lang) || LANGS[0];
  const pick = (code) => {
    setLangFn(code);
    setOpen(false);
  };

  return (
    <div className="lang-wrap" ref={ref}>
      <button
        className={"lang-trigger" + (open ? " is-open" : "")}
        onClick={() => setOpen(o => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={"Langue : " + current.label}
      >
        {current.flag}
        <span className="lang-code">{current.code.toUpperCase()}</span>
        <span className="lang-caret" aria-hidden="true">▾</span>
      </button>
      {open && (
        <ul className="lang-menu" role="listbox">
          {LANGS.map(l => (
            <li key={l.code}>
              <button
                className={"lang-opt" + (l.code === lang ? " is-active" : "")}
                onClick={() => pick(l.code)}
                role="option"
                aria-selected={l.code === lang}
              >
                {l.flag}
                <span className="lang-opt-label">{l.label}</span>
                {l.code === lang && <span className="lang-opt-check" aria-hidden="true">✓</span>}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/* ---------- NAV ---------- */
function Nav({ current, go, openBooking }) {
  const [t] = window.useT();
  const links = getNavLinks(t);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " is-scrolled" : "")}>
      <button className="nav-brand" onClick={() => go("home")} aria-label={t("nav.brand")}>
        <span className="nav-brand-name">{t("nav.brand")}</span>
        <span className="nav-brand-mark">Ω</span>
      </button>
      <ul className="nav-links">
        {links.map(l => (
          <li key={l.id}>
            <button
              className={"nav-link" + (current === l.id ? " is-active" : "")}
              onClick={() => go(l.id)}
            >
              {l.label}
            </button>
          </li>
        ))}
      </ul>
      <div className="nav-right">
        <LangPicker />
        <button className="nav-cta" onClick={openBooking}>{t("nav.book")}</button>
      </div>
    </nav>
  );
}

/* ---------- HERO ---------- */
function Hero({ go, openBooking, variant }) {
  const [t] = window.useT();
  return (
    <section className={"hero hero-" + variant} data-screen-label="Accueil · Hero">
      <div className="hero-bg">
        <Placeholder label="HÉROS · FAÇADE DE NUIT" ratio="16/9" />
      </div>
      <div className="hero-veil" />
      <div className="hero-grid">
        <div className="hero-meta hero-meta-left">
          <span className="meta-line"></span>
          <span className="meta-text">{t("hero.metaLeft")}</span>
        </div>
        <div className="hero-meta hero-meta-right">
          <span className="meta-text">{t("hero.metaRight")}</span>
          <span className="meta-line"></span>
        </div>

        <div className="hero-center">
          <div className="hero-eyebrow">{t("hero.eyebrow")}</div>
          <h1 className="hero-title">
            {t("hero.title1")}<em>{t("hero.titleEm")}</em><br/>
            {t("hero.title2")}
          </h1>
          <div className="hero-sub">
            {t("hero.sub1")}<br className="d-none-sm"/>
            {t("hero.sub2")}
          </div>
          <div className="hero-cta">
            <button className="btn btn-primary" onClick={openBooking}>
              <span>{t("hero.book")}</span>
              <span className="btn-arrow">→</span>
            </button>
            <button className="btn btn-ghost" onClick={() => go("rooms")}>
              {t("hero.discover")}
            </button>
          </div>
        </div>

        <div className="hero-omega" aria-hidden="true">Ω</div>

        <div className="hero-foot">
          <div className="hero-foot-col">
            <div className="hf-key">{t("hero.foot.rooms")}</div>
            <div className="hf-val">{t("hero.foot.roomsVal")}</div>
          </div>
          <div className="hero-foot-col">
            <div className="hf-key">{t("rooms.from")}</div>
            <div className="hf-val">250&thinsp;R$ <span>{t("rooms.night")}</span></div>
          </div>
          <div className="hero-foot-col">
            <div className="hf-key">{t("hero.foot.rating")}</div>
            <div className="hf-val">9.4 <span>/ 10</span></div>
          </div>
          <div className="hero-foot-col hf-scroll">
            <div className="hf-scroll-line" />
            <div className="hf-key">{t("hero.foot.scroll")}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- INTRO STRIP ---------- */
function Intro() {
  const [t] = window.useT();
  return (
    <section className="strip strip-intro" data-screen-label="Accueil · Intro">
      <div className="strip-inner">
        <div className="strip-eyebrow">{t("intro.eyebrow")}</div>
        <p className="strip-quote">{t("intro.quote")}</p>
        <div className="strip-sign">
          <span className="strip-sign-rule"></span>
          <span className="strip-sign-name">{t("intro.sign")}</span>
          <span className="strip-sign-rule"></span>
        </div>
      </div>
    </section>
  );
}

/* ---------- ROOMS PREVIEW (home) ---------- */
function RoomsPreview({ openBooking, go, setSelected }) {
  const [t] = window.useT();
  const rooms = getRooms(t);
  return (
    <section className="rooms-preview" data-screen-label="Accueil · Suites">
      <header className="section-head">
        <div className="sh-left">
          <div className="sh-eyebrow">{t("rooms.eyebrow")}</div>
          <h2 className="sh-title">
            {t("rooms.preview.title1")}<em>{t("rooms.preview.titleEm")}</em>{t("rooms.preview.title2")} <br/>
            {t("rooms.preview.title3")}
          </h2>
        </div>
        <div className="sh-right">
          <button className="link-arrow" onClick={() => go("rooms")}>
            {t("rooms.preview.see")} <span>→</span>
          </button>
        </div>
      </header>

      <div className="rooms-track">
        {rooms.map((r, i) => (
          <article key={r.id} className={"room-card" + (!r.available ? " is-unavailable" : "")}>
            <div className="room-photo">
              <Placeholder label={r.placeholder} ratio="4/5" src={r.img} />
              <div className="room-num">N° {r.num}</div>
              {!r.available && <div className="room-status">{t("rooms.full")}</div>}
            </div>
            <div className="room-body">
              <div className="room-meta">
                <span className="room-type">{r.type}</span>
                <span className="room-dot">·</span>
                <span className="room-cap">{r.capacity} {t("rooms.shortPersons")}</span>
              </div>
              <h3 className="room-name">{r.name}</h3>
              <p className="room-desc">{r.desc}</p>
              <div className="room-foot">
                <Price brl={r.price} showFrom />
                <button
                  className="room-cta"
                  disabled={!r.available}
                  onClick={() => { setSelected(r.id); openBooking(); }}
                >
                  {t("rooms.book")}
                </button>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ---------- EXPERIENCE ---------- */
function getExpItems(t) {
  return [1, 2, 3, 4, 5, 6].map(i => ({
    n: String(i).padStart(2, "0"),
    t: t(`exp.${i}.t`),
    d: t(`exp.${i}.d`),
    k: t(`exp.${i}.k`),
  }));
}

function Experience() {
  const [t] = window.useT();
  const items = getExpItems(t);
  return (
    <section className="exp" data-screen-label="Accueil · Expérience">
      <header className="section-head">
        <div className="sh-left">
          <div className="sh-eyebrow">{t("exp.eyebrow")}</div>
          <h2 className="sh-title">
            {t("exp.title1")}<em>{t("exp.titleEm")}</em>{t("exp.title2")}
          </h2>
        </div>
      </header>
      <div className="exp-grid">
        {items.map(e => (
          <div key={e.n} className="exp-card">
            <div className="exp-num">{e.n}</div>
            <div className="exp-body">
              <div className="exp-key">{e.k}</div>
              <h3 className="exp-title">{e.t}</h3>
              <p className="exp-desc">{e.d}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- ROOMS PAGE ---------- */
function RoomsPage({ openBooking, setSelected }) {
  const [t] = window.useT();
  const rooms = getRooms(t);
  return (
    <section className="page rooms-page" data-screen-label="Hébergement">
      <header className="page-head">
        <div className="page-eyebrow">{t("rooms.eyebrow")}</div>
        <h1 className="page-title">{t("rooms.title1")}<em>{t("rooms.titleEm")}</em>{t("rooms.title2")}</h1>
        <p className="page-sub">{t("rooms.sub")}</p>
      </header>

      <div className="rooms-list">
        {rooms.map((r, i) => (
          <article key={r.id} className={"rooms-row" + (i % 2 ? " is-flipped" : "")}>
            <div className="rr-photo">
              <Placeholder label={r.placeholder} ratio="4/3" src={r.img} />
              <div className="rr-num">N° {r.num}</div>
            </div>
            <div className="rr-body">
              <div className="rr-eyebrow">{r.type} · {r.capacity} {t("rooms.persons")}</div>
              <h3 className="rr-title">{r.name}</h3>
              <p className="rr-desc">{r.desc}</p>
              <div className="rr-bed">
                <span className="rr-bed-key">{t("rooms.bed")}</span>
                <span className="rr-bed-val">{r.bed}</span>
              </div>
              <ul className="rr-features">
                {r.features.map(f => (
                  <li key={f}><span className="rr-bullet">·</span> {f}</li>
                ))}
              </ul>
              <div className="rr-foot">
                <Price brl={r.price} showFrom />
                <button
                  className="btn btn-primary"
                  disabled={!r.available}
                  onClick={() => { setSelected(r.id); openBooking(); }}
                >
                  {r.available ? t("rooms.book") : t("rooms.unavailable")}
                </button>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ---------- ABOUT PAGE ---------- */
function AboutPage() {
  const [t] = window.useT();
  return (
    <section className="page about-page" data-screen-label="Maison">
      <header className="page-head">
        <div className="page-eyebrow">{t("about.eyebrow")}</div>
        <h1 className="page-title">{t("about.title1")}<em>{t("about.titleEm")}</em></h1>
        <p className="page-sub">{t("about.sub")}</p>
      </header>

      <div className="about-grid">
        <div className="about-img">
          <Placeholder label="FAÇADE" ratio="4/5" src={IMG.facade} />
        </div>
        <div className="about-text">
          <h3 className="about-h">{t("about.h1")}</h3>
          <p>{t("about.p1")}</p>
          <h3 className="about-h">{t("about.h2")}</h3>
          <p>{t("about.p2")}</p>
          <h3 className="about-h">{t("about.h3")}</h3>
          <p>{t("about.p3")}</p>
        </div>
      </div>

      <div className="numbers">
        {[
          { n: "2026", l: t("about.num1.l") },
          { n: "02",   l: t("about.num2.l") },
          { n: "9.4",  l: t("about.num3.l") },
          { n: "12",   l: t("about.num4.l") },
        ].map(x => (
          <div key={x.l} className="num-card">
            <div className="num-val">{x.n}</div>
            <div className="num-lbl">{x.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- EXPERIENCE PAGE ---------- */
function ExperiencePage() {
  const [t] = window.useT();
  const items = getExpItems(t);
  return (
    <section className="page exp-page" data-screen-label="Expérience">
      <header className="page-head">
        <div className="page-eyebrow">{t("exp.eyebrow")}</div>
        <h1 className="page-title">{t("exp.page.title1")}<em>{t("exp.page.titleEm")}</em>{t("exp.page.title2")}</h1>
        <p className="page-sub">{t("exp.page.sub")}</p>
      </header>
      <div className="exp-grid exp-grid-page">
        {items.map(e => (
          <div key={e.n} className="exp-card">
            <div className="exp-num">{e.n}</div>
            <div className="exp-body">
              <div className="exp-key">{e.k}</div>
              <h3 className="exp-title">{e.t}</h3>
              <p className="exp-desc">{e.d}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- LOCATION MAP (custom SVG, always works offline) ---------- */
function LocationMap() {
  const [t] = window.useT();
  const lat = 3.8420;
  const lng = -51.8336;
  const coordsStr = `${lat}, ${lng}`;
  const addressStr = "744 Rua Getúlio Vargas, Oiapoque, AP, Brasil";

  // Multiple map providers — at least one will work for any user
  const osmUrl = `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=16/${lat}/${lng}`;
  const appleUrl = `https://maps.apple.com/?ll=${lat},${lng}&q=Hotel+Omega&z=16`;
  const wazeUrl = `https://www.waze.com/ul?ll=${lat}%2C${lng}&navigate=yes`;
  const geoUri = `geo:${lat},${lng}?q=${lat},${lng}(Hotel+Omega)`;

  const [copied, setCopied] = useState("");
  const copy = (text, key) => {
    const fallback = () => {
      const ta = document.createElement("textarea");
      ta.value = text;
      ta.style.position = "fixed"; ta.style.opacity = "0";
      document.body.appendChild(ta); ta.select();
      try { document.execCommand("copy"); } catch (e) {}
      document.body.removeChild(ta);
    };
    if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).catch(fallback);
    else fallback();
    setCopied(key);
    setTimeout(() => setCopied(""), 2000);
  };

  return (
    <div className="loc-map">
      <svg
        className="loc-map-svg"
        viewBox="0 0 400 360"
        xmlns="http://www.w3.org/2000/svg"
        preserveAspectRatio="xMidYMid slice"
      >
        <defs>
          <pattern id="locGrid" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(255,255,255,.04)" strokeWidth="0.5"/>
          </pattern>
          <linearGradient id="locRiver" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#2a3a4a" stopOpacity="0.55"/>
            <stop offset="100%" stopColor="#1a2530" stopOpacity="0.7"/>
          </linearGradient>
          <linearGradient id="locForest" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#1f2a1c" stopOpacity="0.4"/>
            <stop offset="100%" stopColor="#161e14" stopOpacity="0.6"/>
          </linearGradient>
          <radialGradient id="locPinGlow" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="rgba(189,148,90,.35)"/>
            <stop offset="100%" stopColor="rgba(189,148,90,0)"/>
          </radialGradient>
        </defs>

        <rect width="400" height="360" fill="#1a1a18"/>
        <rect width="400" height="360" fill="url(#locGrid)"/>

        <path d="M 0,260 Q 80,240 160,250 T 320,255 T 400,260 L 400,360 L 0,360 Z" fill="url(#locForest)"/>
        <path d="M -20,80 Q 60,90 120,110 Q 180,135 240,120 Q 320,100 420,130 L 420,160 Q 320,135 240,155 Q 180,170 120,145 Q 60,125 -20,115 Z" fill="url(#locRiver)"/>
        <text x="60" y="100" fill="rgba(180,200,220,.5)" fontSize="9" fontStyle="italic" fontFamily="Georgia, serif">Rio Oyapock</text>

        <text x="20" y="40" fill="rgba(189,148,90,.45)" fontSize="8" fontFamily="ui-sans-serif" letterSpacing="2">GUYANE FR. ↑</text>
        <text x="20" y="55" fill="rgba(255,255,255,.25)" fontSize="7" fontFamily="ui-sans-serif">Saint-Georges</text>
        <text x="280" y="200" fill="rgba(189,148,90,.45)" fontSize="8" fontFamily="ui-sans-serif" letterSpacing="2">BRASIL · AP</text>

        <path d="M 200,180 L 200,360" stroke="rgba(189,148,90,.18)" strokeWidth="1.5" strokeDasharray="3,3"/>
        <path d="M 80,200 L 380,210" stroke="rgba(255,255,255,.06)" strokeWidth="2"/>
        <path d="M 200,200 L 280,160" stroke="rgba(255,255,255,.06)" strokeWidth="2"/>

        <g transform="translate(280, 130)">
          <rect x="-14" y="-3" width="28" height="6" fill="rgba(189,148,90,.4)" stroke="rgba(189,148,90,.6)" strokeWidth="0.5"/>
          <text x="0" y="-8" fill="rgba(255,255,255,.55)" fontSize="7" textAnchor="middle" fontFamily="ui-sans-serif">Pont Oyapock</text>
        </g>

        <g transform="translate(340, 250)">
          <circle r="3" fill="none" stroke="rgba(255,255,255,.4)" strokeWidth="1"/>
          <path d="M -2,0 L 2,0 M 0,-2 L 0,2" stroke="rgba(255,255,255,.6)" strokeWidth="1"/>
          <text x="0" y="14" fill="rgba(255,255,255,.55)" fontSize="7" textAnchor="middle" fontFamily="ui-sans-serif">Aéroport OYK</text>
        </g>

        <g transform="translate(140, 165)">
          <rect x="-3" y="-3" width="6" height="6" fill="rgba(255,255,255,.4)"/>
          <text x="0" y="14" fill="rgba(255,255,255,.55)" fontSize="7" textAnchor="middle" fontFamily="ui-sans-serif">Embarcadère</text>
        </g>

        <g transform="translate(220, 220)">
          <circle r="14" fill="rgba(189,148,90,.05)" stroke="rgba(189,148,90,.2)" strokeWidth="0.5"/>
          <text x="0" y="3" fill="rgba(255,255,255,.4)" fontSize="6" textAnchor="middle" fontFamily="ui-sans-serif" letterSpacing="1">CENTRO</text>
        </g>

        <g transform="translate(200, 200)">
          <circle r="40" fill="url(#locPinGlow)"/>
          <circle r="22" fill="#bd945a" stroke="#f4ede2" strokeWidth="2"/>
          <text x="0" y="6" fill="#0c0d0e" fontSize="22" textAnchor="middle" fontFamily="Georgia, serif" fontWeight="300">Ω</text>
          <line x1="0" y1="22" x2="0" y2="36" stroke="#bd945a" strokeWidth="1.5"/>
          <text x="0" y="-32" fill="#f4ede2" fontSize="9" textAnchor="middle" fontFamily="Georgia, serif" letterSpacing="2">HÔTEL OMÉGA</text>
          <text x="0" y="-22" fill="rgba(189,148,90,.7)" fontSize="6" textAnchor="middle" fontFamily="ui-sans-serif" letterSpacing="2">OIAPOQUE · AP</text>
        </g>

        <g transform="translate(360, 30)" opacity="0.6">
          <circle r="14" fill="none" stroke="rgba(189,148,90,.3)" strokeWidth="0.5"/>
          <path d="M 0,-10 L 3,0 L 0,10 L -3,0 Z" fill="rgba(189,148,90,.5)"/>
          <path d="M 0,-10 L 3,0 L 0,0 Z" fill="#bd945a"/>
          <text x="0" y="-18" fill="rgba(255,255,255,.5)" fontSize="7" textAnchor="middle" fontFamily="ui-sans-serif">N</text>
        </g>

        <text x="20" y="345" fill="rgba(255,255,255,.3)" fontSize="8" fontFamily="ui-monospace, monospace">3°50&apos;31&quot;N · 51°50&apos;01&quot;W</text>
      </svg>

      <div className="loc-map-coords">
        <div className="loc-map-coord-row">
          <div>
            <div className="loc-map-coord-key">{t("loc.coords")}</div>
            <code className="loc-map-coord-val">{coordsStr}</code>
          </div>
          <button
            type="button"
            className={"loc-copy-btn" + (copied === "coords" ? " is-copied" : "")}
            onClick={() => copy(coordsStr, "coords")}
          >
            {copied === "coords" ? t("pix.copied") : t("pix.copy")}
          </button>
        </div>
        <div className="loc-map-coord-row">
          <div>
            <div className="loc-map-coord-key">{t("loc.address")}</div>
            <code className="loc-map-coord-val loc-map-coord-addr">{addressStr}</code>
          </div>
          <button
            type="button"
            className={"loc-copy-btn" + (copied === "addr" ? " is-copied" : "")}
            onClick={() => copy(addressStr, "addr")}
          >
            {copied === "addr" ? t("pix.copied") : t("pix.copy")}
          </button>
        </div>
      </div>

      <div className="loc-map-actions">
        <a href={geoUri} className="loc-map-btn loc-map-btn-primary">
          📍 {t("loc.openMyApp")}
        </a>
        <a href={osmUrl} target="_blank" rel="noopener noreferrer" className="loc-map-btn">
          OpenStreetMap ↗
        </a>
        <a href={appleUrl} target="_blank" rel="noopener noreferrer" className="loc-map-btn">
          Apple Maps ↗
        </a>
        <a href={wazeUrl} target="_blank" rel="noopener noreferrer" className="loc-map-btn">
          Waze ↗
        </a>
      </div>
    </div>
  );
}

/* ---------- LOCATION SECTION (used inside ContactPage) ---------- */
function LocationSection() {
  const [t] = window.useT();
  const landmarks = [
    { key: "loc.lm.airport",  dist: "8 min", note: "loc.lm.airportNote" },
    { key: "loc.lm.border",   dist: "12 min", note: "loc.lm.borderNote" },
    { key: "loc.lm.river",    dist: "5 min", note: "loc.lm.riverNote" },
    { key: "loc.lm.center",   dist: "3 min", note: "loc.lm.centerNote" },
  ];
  const routes = [
    { key: "loc.r.cayenne", dur: "loc.r.cayenneDur", note: "loc.r.cayenneNote" },
    { key: "loc.r.macapa",  dur: "loc.r.macapaDur",  note: "loc.r.macapaNote" },
    { key: "loc.r.belem",   dur: "loc.r.belemDur",   note: "loc.r.belemNote" },
  ];
  return (
    <div className="loc-section">
      <header className="loc-section-head">
        <div className="page-eyebrow">{t("loc.eyebrow")}</div>
        <h2 className="loc-section-title">
          {t("loc.title1")}<em>{t("loc.titleEm")}</em>{t("loc.title2")}
        </h2>
        <p className="loc-section-lead">{t("loc.lead")}</p>
      </header>

      <div className="loc-grid">
        <div className="loc-col">
          <h3 className="loc-h2">{t("loc.aroundTitle")}</h3>
          <ul className="loc-landmarks">
            {landmarks.map((l, i) => (
              <li key={i} className="loc-lm">
                <div className="loc-lm-dist">{l.dist}</div>
                <div className="loc-lm-name">{t(l.key)}</div>
                <div className="loc-lm-note">{t(l.note)}</div>
              </li>
            ))}
          </ul>
        </div>

        <div className="loc-col">
          <h3 className="loc-h2">{t("loc.routesTitle")}</h3>
          <ul className="loc-routes">
            {routes.map((r, i) => (
              <li key={i} className="loc-route">
                <div className="loc-route-from">{t(r.key)}</div>
                <div className="loc-route-dur">{t(r.dur)}</div>
                <div className="loc-route-note">{t(r.note)}</div>
              </li>
            ))}
          </ul>
        </div>
      </div>

      <div className="loc-shuttle">
        <div className="loc-shuttle-mark">Ω</div>
        <div className="loc-shuttle-body">
          <div className="loc-shuttle-eyebrow">{t("loc.shuttleEyebrow")}</div>
          <h3 className="loc-shuttle-title">{t("loc.shuttleTitle")}</h3>
          <p className="loc-shuttle-desc">{t("loc.shuttleDesc")}</p>
        </div>
      </div>
    </div>
  );
}

/* ---------- CONTACT PAGE ---------- */
function ContactPage() {
  const [t] = window.useT();
  const addr = t("contact.addressVal").split("\n");
  return (
    <section className="page contact-page" data-screen-label="Contact">
      <header className="page-head">
        <div className="page-eyebrow">{t("contact.eyebrow")}</div>
        <h1 className="page-title">{t("contact.title1")}<em>{t("contact.titleEm")}</em>{t("contact.title2")}</h1>
      </header>
      <div className="contact-grid">
        <div className="contact-info">
          <div className="ci-block">
            <div className="ci-key">{t("contact.address")}</div>
            <div className="ci-val">{addr[0]}<br/>{addr[1]}</div>
          </div>
          <div className="ci-block">
            <div className="ci-key">{t("contact.phone")}</div>
            <div className="ci-val">
              <a href="tel:+594694203624" className="ci-link">+594 6 94 20 36 24</a>
            </div>
          </div>
          <div className="ci-block">
            <div className="ci-key">{t("contact.email")}</div>
            <div className="ci-val">
              <a href="mailto:tadaniel722@gmail.com" className="ci-link">tadaniel722@gmail.com</a>
            </div>
          </div>
          <div className="ci-block">
            <div className="ci-key">{t("contact.social")}</div>
            <div className="ci-val">{t("contact.socialVal")}</div>
          </div>
          <div className="ci-block">
            <div className="ci-key">{t("contact.front")}</div>
            <div className="ci-val">{t("contact.frontVal")}</div>
          </div>
        </div>
        <div className="contact-map">
          <LocationMap />
        </div>
      </div>

      <LocationSection />
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer() {
  const [t] = window.useT();
  // Triple-click on the discreet Ω reveals admin
  const clickRef = useRef({ count: 0, timer: null });
  const onOmegaClick = () => {
    const c = clickRef.current;
    c.count += 1;
    if (c.timer) clearTimeout(c.timer);
    if (c.count >= 3) {
      c.count = 0;
      window.dispatchEvent(new CustomEvent("omega-secret-admin"));
    } else {
      c.timer = setTimeout(() => { c.count = 0; }, 700);
    }
  };
  return (
    <footer className="footer" data-screen-label="Pied de page">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="footer-omega" onClick={onOmegaClick} role="presentation">Ω</div>
          <div className="footer-name">{t("nav.brand")}</div>
          <div className="footer-tag">{t("footer.tag")}</div>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <div className="fc-h">{t("footer.colHouse")}</div>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("about"); }} href="#about">{t("footer.about")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("contact"); }} href="#contact">{t("footer.contact")}</a>
          </div>
          <div className="footer-col">
            <div className="fc-h">{t("footer.colStay")}</div>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("rooms"); }} href="#rooms">{t("footer.rooms")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("experience"); }} href="#experience">{t("footer.experience")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("faq"); }} href="#faq">{t("footer.faq")}</a>
          </div>
          <div className="footer-col">
            <div className="fc-h">{t("footer.colFollow")}</div>
            <a className="fc-a" href="https://instagram.com/omega._hotel" target="_blank" rel="noreferrer">Instagram</a>
          </div>
          <div className="footer-col">
            <div className="fc-h">{t("footer.policies")}</div>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("policies", "cancel"); }} href="#policies">{t("footer.cancel")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("policies", "terms"); }} href="#policies">{t("footer.terms")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("policies", "privacy"); }} href="#policies">{t("footer.privacy")}</a>
            <a className="fc-a" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("policies", "legal"); }} href="#policies">{t("footer.legal")}</a>
          </div>
        </div>
      </div>
      <div className="footer-rule" />
      <div className="footer-bot">
        <span>{t("footer.copy")}</span>
        <a className="footer-bot-mid" onClick={(e) => { e.preventDefault(); window.__omegaGo && window.__omegaGo("policies", "legal"); }} href="#policies">{t("footer.legal")}</a>
        <a className="footer-bot-cookies" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new CustomEvent("omega:cookies:open")); }} href="#cookies">{t("footer.cookies")}</a>
        <span>{t("footer.version")}</span>
      </div>
    </footer>
  );
}

/* ---------- PIX QR CODE ---------- */
function PixBox({ amount, txid, description }) {
  const [t] = window.useT();
  const [copied, setCopied] = useState(false);
  const cfg = window.PIX_CONFIG || {};

  const payload = useMemo(() => {
    if (!window.buildPixPayload || !cfg.key) return "";
    try {
      return window.buildPixPayload({
        key: cfg.key,
        name: cfg.name,
        city: cfg.city,
        amount: amount,
        txid: txid,
        description: description,
      });
    } catch (e) {
      console.error("Pix payload error:", e);
      return "";
    }
  }, [amount, txid, description]);

  const matrix = useMemo(() => {
    if (!payload || !window.generateQRMatrix) return null;
    try { return window.generateQRMatrix(payload); }
    catch (e) { console.error("QR error:", e); return null; }
  }, [payload]);

  const copy = () => {
    if (!payload) return;
    const fallback = () => {
      const ta = document.createElement("textarea");
      ta.value = payload;
      ta.style.position = "fixed"; ta.style.opacity = "0";
      document.body.appendChild(ta); ta.select();
      try { document.execCommand("copy"); } catch (e) {}
      document.body.removeChild(ta);
    };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(payload).catch(fallback);
    } else { fallback(); }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  if (!payload || !matrix) {
    return <div className="dp-paybox">{t("book.pixNote")}</div>;
  }

  // Render QR as SVG
  const n = matrix.length;
  const cell = 6;
  const margin = 4;
  const sz = (n + 2 * margin) * cell;
  const rects = [];
  for (let r = 0; r < n; r++) {
    for (let c = 0; c < n; c++) {
      if (matrix[r][c]) {
        rects.push(
          <rect key={r + "-" + c}
            x={(c + margin) * cell} y={(r + margin) * cell}
            width={cell} height={cell} fill="#0c0d0e" />
        );
      }
    }
  }

  return (
    <div className="pix-box">
      <div className="pix-grid">
        <div className="pix-qr-wrap">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width={sz} height={sz}
            viewBox={`0 0 ${sz} ${sz}`}
            className="pix-qr"
            shapeRendering="crispEdges"
          >
            <rect width={sz} height={sz} fill="#fff" />
            {rects}
          </svg>
          <div className="pix-qr-omega" aria-hidden="true">Ω</div>
        </div>
        <div className="pix-info">
          <div className="pix-info-eyebrow">{t("pix.scanHere")}</div>
          <div className="pix-info-title">{t("pix.title")}</div>
          <p className="pix-info-desc">{t("pix.desc")}</p>
          <ol className="pix-steps">
            <li>{t("pix.step1")}</li>
            <li>{t("pix.step2")}</li>
            <li>{t("pix.step3")}</li>
          </ol>
          <div className="pix-amount">
            <span className="pix-amount-key">{t("pix.amount")}</span>
            <span className="pix-amount-val">{Number(amount).toFixed(2)} <em>R$</em></span>
          </div>
          <div className="pix-beneficiary">
            <span>{t("pix.to")}</span>
            <strong>{cfg.name}</strong>
          </div>
        </div>
      </div>

      <div className="pix-cnc">
        <div className="pix-cnc-label">{t("pix.copyCode")}</div>
        <div className="pix-cnc-row">
          <code className="pix-cnc-code">{payload}</code>
          <button
            type="button"
            className={"pix-cnc-btn" + (copied ? " is-copied" : "")}
            onClick={copy}
          >
            {copied ? t("pix.copied") : t("pix.copy")}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------- BOOKING CONFIRMATION (printable + emailable) ---------- */
function BookingConfirmation({ room, dates, guest, nights, total, pay, close, bookingRef }) {
  const [t, lang] = window.useT();

  // Stable reference number — use the one from BookingDrawer if provided (so it matches DB + emails)
  const ref = useMemo(() => {
    if (bookingRef) return bookingRef;
    const seed = (room?.id || "X") + (dates.ci || "") + (guest.email || "") + Date.now();
    let h = 0;
    for (let i = 0; i < seed.length; i++) h = ((h << 5) - h + seed.charCodeAt(i)) | 0;
    const code = Math.abs(h).toString(36).toUpperCase().slice(0, 6).padStart(6, "0");
    const ymd = (dates.ci || "").replace(/-/g, "").slice(2);
    return `OMG-${ymd}-${code}`;
  }, [bookingRef]);

  const eur = Math.round(total * FX.EUR);
  const usd = Math.round(total * FX.USD);
  const payLabel = pay === "card" ? t("book.card") : pay === "paypal" ? "PayPal" : "Pix";

  const fmtDate = (s) => {
    if (!s) return "—";
    try {
      const d = new Date(s + "T00:00:00");
      return d.toLocaleDateString(lang === "fr" ? "fr-FR" : lang === "pt" ? "pt-BR" : "en-US",
        { weekday: "short", day: "2-digit", month: "long", year: "numeric" });
    } catch (_) { return s; }
  };

  const onPrint = () => {
    document.body.classList.add("is-printing");
    setTimeout(() => {
      window.print();
      setTimeout(() => document.body.classList.remove("is-printing"), 500);
    }, 50);
  };

  const onEmail = () => {
    const subject = t("book.emailSubject");
    const lines = [
      t("book.emailBody"),
      "",
      `${t("book.confirmedRef")}: ${ref}`,
      "",
      `${t("book.guestLbl")}: ${guest.first} ${guest.last}`,
      `${t("book.contactLbl")}: ${guest.email}${guest.phone ? " · " + guest.phone : ""}`,
      "",
      `${t("book.stayLbl")}:`,
      `  ${t("book.recapRoom")}: ${room?.name || ""} (${room?.type || ""})`,
      `  ${t("book.checkin")}: ${fmtDate(dates.ci)}`,
      `  ${t("book.checkout")}: ${fmtDate(dates.co)}`,
      `  ${t("book.nights")}: ${nights}`,
      "",
      `${t("book.payLbl")}: ${payLabel}`,
      `${t("book.recapTotal")}: ${total} R$  (≈ ${eur}€ · ≈ ${usd}$)`,
      "",
      "— Hotel Omega",
      "744 Rua Getúlio Vargas, Oiapoque, AP, Brasil",
      "tadaniel722@gmail.com",
    ].join("\n");

    const url = `mailto:${guest.email}?cc=tadaniel722@gmail.com&subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(lines)}`;
    window.location.href = url;
  };

  return (
    <div className="drawer-done bk-conf">
      <div className="bk-conf-head">
        <div className="dd-mark">Ω</div>
        <div className="dd-eyebrow">{t("book.confirmedEyebrow")}</div>
        <h3 className="dd-title">{t("book.confirmedTitle")}</h3>
        <p className="dd-text">
          {t("book.confirmedText1")}<strong>{guest.email}</strong>{t("book.confirmedText2")}
        </p>
      </div>

      <div className="bk-ref">
        <span className="bk-ref-key">{t("book.confirmedRef")}</span>
        <code className="bk-ref-val">{ref}</code>
      </div>

      <div className="bk-recap">
        <div className="bk-recap-h">{t("book.guestLbl")}</div>
        <div className="bk-recap-row">
          <span>{t("book.first")} / {t("book.last")}</span>
          <strong>{guest.first} {guest.last}</strong>
        </div>
        <div className="bk-recap-row">
          <span>{t("book.email")}</span>
          <strong>{guest.email}</strong>
        </div>
        {guest.phone && (
          <div className="bk-recap-row">
            <span>{t("book.phone")}</span>
            <strong>{guest.phone}</strong>
          </div>
        )}

        <div className="bk-recap-h">{t("book.stayLbl")}</div>
        <div className="bk-recap-row">
          <span>{t("book.recapRoom")}</span>
          <strong>{room?.name} <em>({room?.type})</em></strong>
        </div>
        <div className="bk-recap-row">
          <span>{t("book.checkin")}</span>
          <strong>{fmtDate(dates.ci)}</strong>
        </div>
        <div className="bk-recap-row">
          <span>{t("book.checkout")}</span>
          <strong>{fmtDate(dates.co)}</strong>
        </div>
        <div className="bk-recap-row">
          <span>{t("book.nights")}</span>
          <strong>{nights}</strong>
        </div>

        <div className="bk-recap-h">{t("book.payLbl")}</div>
        <div className="bk-recap-row">
          <span>{t("book.payLbl")}</span>
          <strong>{payLabel}</strong>
        </div>
        <div className="bk-recap-row bk-recap-total">
          <span>{t("book.recapTotal")}</span>
          <strong>
            {total} R$
            <em className="bk-recap-conv"> · ≈ {eur}€ · ≈ {usd}$</em>
          </strong>
        </div>

        {guest.req && (
          <>
            <div className="bk-recap-h">{t("book.requests")}</div>
            <div className="bk-recap-note">{guest.req}</div>
          </>
        )}
      </div>

      <div className="bk-next">
        <div className="bk-next-h">{t("book.confirmedNext")}</div>
        <ol className="bk-next-list">
          <li>{t("book.confirmedNext1")}</li>
          <li>{t("book.confirmedNext2")}</li>
          <li>{t("book.confirmedNext3")}</li>
        </ol>
      </div>

      <div className="bk-actions">
        <button className="btn btn-ghost" onClick={onEmail}>✉ {t("book.emailBtn")}</button>
        <button className="btn btn-ghost" onClick={onPrint}>⎙ {t("book.printBtn")}</button>
        <button className="btn btn-primary" onClick={close}>{t("book.closeBtn")}</button>
      </div>

      {/* Print-only header (visible only when window.print) */}
      <div className="bk-print-letterhead" aria-hidden="true">
        <div className="bk-print-mark">Ω</div>
        <div>
          <div className="bk-print-name">HOTEL OMEGA</div>
          <div className="bk-print-addr">744 Rua Getúlio Vargas · Oiapoque · Amapá · Brasil</div>
          <div className="bk-print-addr">tadaniel722@gmail.com · +594 6 94 20 36 24</div>
        </div>
        <div className="bk-print-title">{t("book.printTitle")}</div>
      </div>
    </div>
  );
}

/* ---------- BOOKING DRAWER ---------- */
function BookingDrawer({ open, close, selected, setSelected }) {
  const [step, setStep] = useState(1);
  const [dates, setDates] = useState({ ci: "", co: "" });
  const [guest, setGuest] = useState({ first: "", last: "", email: "", phone: "", req: "" });
  const [pay, setPay] = useState("card");
  const [done, setDone] = useState(false);
  const [bookingError, setBookingError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [bookingRef, setBookingRef] = useState(null);

  useEffect(() => {
    if (open) { setStep(1); setDone(false); setBookingError(null); setSubmitting(false); setBookingRef(null); }
  }, [open]);

  const [t] = window.useT();
  const localizedRooms = getRooms(t);
  const room = localizedRooms.find(r => r.id === selected) || null;

  const nights = useMemo(() => {
    if (!dates.ci || !dates.co) return 0;
    const a = new Date(dates.ci), b = new Date(dates.co);
    const d = Math.max(0, Math.round((b - a) / 864e5));
    return d;
  }, [dates]);

  const total = room && nights > 0 ? room.price * nights : 0;

  const canNext1 = !!room;
  const canNext2 = dates.ci && dates.co && nights > 0;
  const canConfirm = guest.first && guest.last && guest.email;

  return (
    <>
      <div className={"drawer-veil" + (open ? " is-open" : "")} onClick={close} />
      <aside className={"drawer" + (open ? " is-open" : "")} aria-hidden={!open}>
        <header className="drawer-head">
          <div>
            <div className="drawer-eyebrow">{t("book.eyebrow")}</div>
            <div className="drawer-title">{t("book.title")}</div>
          </div>
          <button className="drawer-close" onClick={close} aria-label={t("book.close")}>✕</button>
        </header>

        <div className="drawer-steps">
          {[t("book.step1"), t("book.step2"), t("book.step3"), t("book.step4")].map((s, i) => (
            <div
              key={s}
              className={"ds" + (step === i + 1 ? " is-active" : "") + (step > i + 1 ? " is-done" : "")}
            >
              <span className="ds-num">{String(i + 1).padStart(2, "0")}</span>
              <span className="ds-label">{s}</span>
            </div>
          ))}
        </div>

        <div className="drawer-body">
          {done ? (
            <BookingConfirmation
              room={room}
              dates={dates}
              guest={guest}
              nights={nights}
              total={total}
              pay={pay}
              close={close}
              bookingRef={bookingRef}
            />
          ) : (
            <>
              {/* STEP 1 — ROOM */}
              {step === 1 && (
                <div className="drawer-panel">
                  <p className="dp-help">{t("book.help1")}</p>
                  <div className="dp-rooms">
                    {localizedRooms.map(r => (
                      <button
                        key={r.id}
                        className={"dp-room" + (selected === r.id ? " is-selected" : "") + (!r.available ? " is-disabled" : "")}
                        onClick={() => r.available && setSelected(r.id)}
                        disabled={!r.available}
                      >
                        <div className="dp-room-l">
                          <div className="dp-room-name">{r.name}</div>
                          <div className="dp-room-meta">{r.type} · {r.capacity} {t("rooms.shortPersons")} · {r.bed}</div>
                        </div>
                        <div className="dp-room-r">
                          <div className="dp-room-price">{r.price}<span>R$</span></div>
                          <div className="dp-room-night">{t("rooms.night")}</div>
                          {!r.available && <div className="dp-room-tag">{t("rooms.full")}</div>}
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* STEP 2 — DATES */}
              {step === 2 && (
                <div className="drawer-panel">
                  <p className="dp-help">{t("book.help2")}</p>
                  <div className="dp-row">
                    <label className="dp-field">
                      <span>{t("book.checkin")}</span>
                      <input
                        type="date"
                        value={dates.ci}
                        onChange={e => setDates(d => ({ ...d, ci: e.target.value }))}
                      />
                    </label>
                    <label className="dp-field">
                      <span>{t("book.checkout")}</span>
                      <input
                        type="date"
                        value={dates.co}
                        onChange={e => setDates(d => ({ ...d, co: e.target.value }))}
                      />
                    </label>
                  </div>
                  <div className="dp-summary">
                    <div className="dp-sum-row"><span>{t("book.recapRoom")}</span><strong>{room?.name || "—"}</strong></div>
                    <div className="dp-sum-row"><span>{t("book.nights")}</span><strong>{nights || "—"}</strong></div>
                    <div className="dp-sum-row dp-sum-total">
                      <span>{t("book.totalEst")}</span>
                      <strong>{total ? `${total} R$` : "—"}</strong>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 3 — GUEST */}
              {step === 3 && (
                <div className="drawer-panel">
                  <p className="dp-help">{t("book.help3")}</p>
                  <div className="dp-row">
                    <label className="dp-field">
                      <span>{t("book.first")}</span>
                      <input value={guest.first} onChange={e => setGuest(g => ({ ...g, first: e.target.value }))} placeholder={t("book.firstPh")} />
                    </label>
                    <label className="dp-field">
                      <span>{t("book.last")}</span>
                      <input value={guest.last} onChange={e => setGuest(g => ({ ...g, last: e.target.value }))} placeholder={t("book.lastPh")} />
                    </label>
                  </div>
                  <label className="dp-field">
                    <span>{t("book.email")}</span>
                    <input type="email" value={guest.email} onChange={e => setGuest(g => ({ ...g, email: e.target.value }))} placeholder={t("book.emailPh")} />
                  </label>
                  <label className="dp-field">
                    <span>{t("book.phone")}</span>
                    <input value={guest.phone} onChange={e => setGuest(g => ({ ...g, phone: e.target.value }))} placeholder="+55 …" />
                  </label>
                  <label className="dp-field">
                    <span>{t("book.requests")}</span>
                    <textarea
                      rows="3"
                      value={guest.req}
                      onChange={e => setGuest(g => ({ ...g, req: e.target.value }))}
                      placeholder={t("book.requestsPh")}
                    />
                  </label>
                </div>
              )}

              {/* STEP 4 — PAYMENT */}
              {step === 4 && (
                <div className="drawer-panel">
                  <p className="dp-help">{t("book.help4")}</p>
                  <div className="dp-pay-tabs">
                    {[
                      { id: "card",   l: t("book.card") },
                      { id: "paypal", l: "PayPal" },
                      { id: "pix",    l: "Pix" },
                    ].map(p => (
                      <button
                        key={p.id}
                        className={"dp-ptab" + (pay === p.id ? " is-active" : "")}
                        onClick={() => setPay(p.id)}
                      >
                        {p.l}
                      </button>
                    ))}
                  </div>
                  {pay === "card" && (
                    <>
                      <label className="dp-field">
                        <span>{t("book.cardNum")}</span>
                        <input placeholder="•••• •••• •••• ••••" />
                      </label>
                      <div className="dp-row">
                        <label className="dp-field">
                          <span>{t("book.cardExp")}</span>
                          <input placeholder={t("book.cardExpPh")} />
                        </label>
                        <label className="dp-field">
                          <span>CVV</span>
                          <input placeholder="•••" />
                        </label>
                      </div>
                    </>
                  )}
                  {pay === "paypal" && (
                    <div className="dp-paybox">{t("book.paypalNote")}</div>
                  )}
                  {pay === "pix" && total > 0 && (
                    <PixBox
                      amount={total}
                      txid={"OMG" + (room?.id || "X") + (dates.ci || "").replace(/-/g, "").slice(2)}
                      description={"Reserva " + (room?.name || "Hotel Omega")}
                    />
                  )}
                  {pay === "pix" && total <= 0 && (
                    <div className="dp-paybox">{t("book.pixNote")}</div>
                  )}
                  <div className="dp-summary">
                    <div className="dp-sum-row"><span>{t("book.recapRoom")}</span><strong>{room?.name}</strong></div>
                    <div className="dp-sum-row"><span>{nights} {nights > 1 ? t("book.nightsP") : t("book.nightS")}</span><strong>{total} R$</strong></div>
                    <div className="dp-sum-row dp-sum-total">
                      <span>{t("book.totalDue")}</span>
                      <strong>{total} R$</strong>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {!done && (
          <footer className="drawer-foot">
            {step > 1 && (
              <button className="btn btn-ghost" onClick={() => setStep(s => s - 1)}>
                {t("book.back")}
              </button>
            )}
            {step < 4 && (
              <button
                className="btn btn-primary btn-block"
                disabled={(step === 1 && !canNext1) || (step === 2 && !canNext2)}
                onClick={() => setStep(s => s + 1)}
              >
                {t("book.continue")}
              </button>
            )}
            {step === 4 && (
              <>
                {bookingError && (
                  <div className="dp-err">
                    <div className="dp-err-icon">!</div>
                    <div className="dp-err-body">
                      <div className="dp-err-title">
                        {bookingError.kind === "booking_conflict"
                          ? t("book.err.conflict.title")
                          : bookingError.kind === "blocked"
                          ? t("book.err.blocked.title")
                          : t("book.err.generic.title")}
                      </div>
                      {bookingError.from && bookingError.to && (
                        <div className="dp-err-msg">
                          {t("book.err.conflict.dates")
                            .replace("{from}", new Date(bookingError.from + "T00:00:00").toLocaleDateString())
                            .replace("{to}", new Date(bookingError.to + "T00:00:00").toLocaleDateString())}
                        </div>
                      )}
                      <button
                        className="dp-err-back"
                        onClick={() => { setBookingError(null); setStep(1); }}
                      >
                        ← {t("book.err.changeDates")}
                      </button>
                    </div>
                  </div>
                )}
                <button
                  className="btn btn-primary btn-block"
                  disabled={!canConfirm || submitting}
                  onClick={async () => {
                  if (!window.OmegaStore || !room) return;
                  setSubmitting(true);
                  setBookingError(null);

                  // 1) Check availability before creating the booking
                  try {
                    const check = await window.OmegaStore.checkAvailability(room.type, dates.ci, dates.co);
                    if (!check.ok) {
                      setSubmitting(false);
                      if (check.reason === "booking_conflict" || check.reason === "blocked") {
                        const c = check.conflict || {};
                        setBookingError({
                          kind: check.reason,
                          from: c.from,
                          to: c.to,
                        });
                      } else {
                        setBookingError({ kind: "generic" });
                      }
                      return;
                    }
                  } catch (e) {
                    console.warn("[BookingDrawer] availability check failed:", e);
                    // Allow booking on check failure (better than blocking)
                  }

                  // 2) Push booking
                  // Generate stable booking ref now (so it's the same in DB, emails, and confirmation page)
                  const seed = (room.id || "X") + (dates.ci || "") + (guest.email || "") + Date.now();
                  let h = 0;
                  for (let i = 0; i < seed.length; i++) h = ((h << 5) - h + seed.charCodeAt(i)) | 0;
                  const code = Math.abs(h).toString(36).toUpperCase().slice(0, 6).padStart(6, "0");
                  const ymd = (dates.ci || "").replace(/-/g, "").slice(2);
                  const ref = `OMG-${ymd}-${code}`;
                  setBookingRef(ref);

                  try {
                    const bookingPayload = {
                      ref,
                      id: ref,
                      firstName: guest.first,
                      lastName: guest.last,
                      email: guest.email,
                      phone: guest.phone,
                      notes: guest.req,
                      message: guest.req,
                      roomType: room.type,
                      roomName: room.type,
                      roomNum: room.num,
                      checkIn: dates.ci,
                      checkOut: dates.co,
                      checkin: dates.ci,
                      checkout: dates.co,
                      nights,
                      total,
                      paymentMethod: pay,
                      method: pay,
                    };
                    await window.OmegaStore.pushBooking(bookingPayload);
                    // Fire-and-forget email notifications (no UI block on failure)
                    if (window.OmegaMail) {
                      window.OmegaMail.notifyManager(bookingPayload).catch(() => {});
                      window.OmegaMail.confirmClient(bookingPayload).catch(() => {});
                    }
                  } catch (e) {
                    console.warn("[BookingDrawer] push failed:", e);
                  }
                  setSubmitting(false);
                  setDone(true);
                }}
              >
                {submitting ? t("book.submitting") : t("book.confirm")}
              </button>
              </>
            )}
          </footer>
        )}
      </aside>
    </>
  );
}

/* ---------- TWEAKS PANEL ---------- */
function TweakControls() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks to :root
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--accent-h", t.accentHue);
    r.style.setProperty("--accent-c", t.accentChroma);
    r.dataset.density = t.density;
    r.dataset.images = t.showImages ? "on" : "off";
    r.dataset.heroVariant = t.heroVariant;
    r.dataset.watermark = t.showOmegaWatermark ? "on" : "off";
  }, [t]);

  return (
    <window.TweaksPanel>
      <window.TweakSection label="Accent" />
      <window.TweakSlider
        label="Teinte"
        min={0} max={360} step={1}
        value={t.accentHue}
        onChange={v => setTweak("accentHue", v)}
      />
      <window.TweakSlider
        label="Saturation"
        min={0} max={0.18} step={0.005}
        value={t.accentChroma}
        onChange={v => setTweak("accentChroma", v)}
      />
      <window.TweakSection label="Mise en page" />
      <window.TweakRadio
        label="Densité"
        options={["compact", "comfortable", "spacious"]}
        value={t.density}
        onChange={v => setTweak("density", v)}
      />
      <window.TweakRadio
        label="Hero"
        options={["calm", "editorial"]}
        value={t.heroVariant}
        onChange={v => setTweak("heroVariant", v)}
      />
      <window.TweakSection label="Affichage" />
      <window.TweakToggle
        label="Filigrane Ω"
        value={t.showOmegaWatermark}
        onChange={v => setTweak("showOmegaWatermark", v)}
      />
      <window.TweakToggle
        label="Photos / placeholders"
        value={t.showImages}
        onChange={v => setTweak("showImages", v)}
      />
    </window.TweaksPanel>
  );
}

/* ---------- ROOT ---------- */
function App() {
  const [view, setView] = useState("home");
  const [bookingOpen, setBookingOpen] = useState(false);
  const [selectedRoom, setSelectedRoom] = useState("D");

  const go = (id, tab) => {
    setView(id);
    if (id === "policies" && tab) {
      try {
        window.history.replaceState(null, "", `#policies?tab=${tab}`);
      } catch (_) {}
    }
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  useEffect(() => {
    window.__omegaGo = go;
    return () => { delete window.__omegaGo; };
  }, []);

  const openBooking = () => setBookingOpen(true);
  const closeBooking = () => setBookingOpen(false);

  // Apply default tweak vars on mount (so it works without panel open)
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--accent-h", TWEAK_DEFAULTS.accentHue);
    r.style.setProperty("--accent-c", TWEAK_DEFAULTS.accentChroma);
    r.dataset.density = TWEAK_DEFAULTS.density;
    r.dataset.images = TWEAK_DEFAULTS.showImages ? "on" : "off";
    r.dataset.heroVariant = TWEAK_DEFAULTS.heroVariant;
    r.dataset.watermark = TWEAK_DEFAULTS.showOmegaWatermark ? "on" : "off";
  }, []);

  /* ---------- ACCÈS ADMIN CACHÉ ----------
     3 méthodes (toutes silencieuses) :
     1. Tape "omega" au clavier n'importe où sur le site
     2. Ajoute #admin (ou ?admin=1) à l'URL
     3. Triple-clic sur le Ω discret du footer (handler dans Footer)
  */
  useEffect(() => {
    // 1. URL hash / query
    const checkUrl = () => {
      const h = window.location.hash.toLowerCase();
      const q = window.location.search.toLowerCase();
      if (h === "#admin" || q.includes("admin=1")) {
        setView("admin");
      }
    };
    checkUrl();
    window.addEventListener("hashchange", checkUrl);

    // 2. Keyboard sequence "omega"
    const SEQ = "omega";
    let buffer = "";
    let timer = null;
    const onKey = (e) => {
      // Ignore if user is typing in an input
      const tag = (e.target && e.target.tagName) || "";
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
      const k = (e.key || "").toLowerCase();
      if (!/^[a-z]$/.test(k)) { buffer = ""; return; }
      buffer = (buffer + k).slice(-SEQ.length);
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => { buffer = ""; }, 1500);
      if (buffer === SEQ) {
        buffer = "";
        setView("admin");
      }
    };
    window.addEventListener("keydown", onKey);

    // 3. Custom event from footer triple-click
    const onSecret = () => setView("admin");
    window.addEventListener("omega-secret-admin", onSecret);

    return () => {
      window.removeEventListener("hashchange", checkUrl);
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("omega-secret-admin", onSecret);
      if (timer) clearTimeout(timer);
    };
  }, []);

  return (
    <>
      <Nav current={view} go={go} openBooking={openBooking} />

      {view === "home" && (
        <main>
          <HeroSlider go={go} openBooking={openBooking} />
          <Intro />
        </main>
      )}
      {view === "rooms" && <main><RoomsPage openBooking={openBooking} setSelected={setSelectedRoom} /></main>}
      {view === "experience" && <main><ExperiencePage /></main>}
      {view === "about" && <main><AboutPage /></main>}
      {view === "contact" && <main><ContactPage /></main>}
      {view === "faq" && <main><window.FAQPage /></main>}
      {view === "policies" && <main><window.PoliciesPage /></main>}
      {view === "admin" && <main><window.AdminPage /></main>}

      <Footer />

      <BookingDrawer
        open={bookingOpen}
        close={closeBooking}
        selected={selectedRoom}
        setSelected={setSelectedRoom}
      />

      {window.WhatsAppFAB && <window.WhatsAppFAB />}
      {window.CookiesBanner && <window.CookiesBanner />}

      <TweakControls />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
