// components.jsx — shared UI: nav, footer, brand mark, placeholders, icons

const { useState, useEffect, useRef, useMemo, createContext, useContext, Fragment } = React;

// ─── App context ───────────────────────────────────────────────────────────
const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

const CURRENCIES = {
  PLN: { symbol: "zł", suffix: true, rate: 1, decimals: 0 },
  EUR: { symbol: "€", suffix: false, rate: 0.23, decimals: 0 },
  USD: { symbol: "$", suffix: false, rate: 0.25, decimals: 0 },
};
function formatPrice(plnAmount, currencyCode) {
  const c = CURRENCIES[currencyCode] || CURRENCIES.PLN;
  const val = Math.round(plnAmount * c.rate);
  const num = val.toLocaleString("en-US");
  return c.suffix ? `${num} ${c.symbol}` : `${c.symbol}${num}`;
}

function track(event, params = {}) {
  if (typeof window.gtag === "function") {
    window.gtag("event", event, params);
  }
}

// ─── Brand mark (logo) ─────────────────────────────────────────────────────
function BrandMark({ size = 44, onClick }) {
  const { lang } = useApp();
  const name = "Long Street";
  const mark = "L";
  return (
    <a className="brand" onClick={onClick} style={{ cursor: "pointer" }}>
      <span className="brand-mark" style={{ width: size, height: size, fontSize: size * 0.5 }}>{mark}</span>
      <span className="brand-name">
        <strong>{name}</strong>
        <span>Aparthostel · Kraków</span>
      </span>
    </a>
  );
}

// ─── Header / nav ──────────────────────────────────────────────────────────
function Header({ transparent = false }) {
  const { t, lang, setLang, page, navigate } = useApp();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    ["home", t.nav.home],
    ["rooms", t.nav.rooms],
    ["gallery", t.nav.gallery],
    ["contact", t.nav.contact],
  ];
  return (
    <header className={"header " + (transparent ? (scrolled ? "scrolled" : "") : "solid")}>
      <div className="container header-inner">
        <BrandMark onClick={() => navigate("home")} />
        <nav className="nav">
          {links.map(([k, label]) => (
            <a key={k} href={window.routeToPath(k, {}, lang)} className={page === k ? "active" : ""} onClick={(e) => { e.preventDefault(); navigate(k); }}>{label}</a>
          ))}
        </nav>
        <div className="header-actions">
          <div className="lang-toggle">
            <button className={lang === "pl" ? "active" : ""} onClick={() => setLang("pl")}>PL</button>
            <span style={{ opacity: 0.3 }}>/</span>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <button className="btn" onClick={() => navigate("reservation")}>{t.nav.reserve}</button>
        </div>
      </div>
    </header>
  );
}

// ─── Footer ────────────────────────────────────────────────────────────────
function Footer() {
  const { t, lang, navigate } = useApp();
  const yr = new Date().getFullYear();
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <BrandMark />
            <p style={{ marginTop: 24, maxWidth: "32ch", fontSize: 13 }}>
              {lang === "pl"
                ? "Aparthostel w sercu krakowskiego Starego Miasta, przy ul. Długiej. Prywatne pokoje, prywatne łazienki, wspólna kuchnia."
                : "An aparthostel in the heart of Kraków's Old Town, on Długa Street. Private rooms, private bathrooms, a shared kitchen."}
            </p>
          </div>
          <div>
            <h4>{lang === "pl" ? "Aparthostel" : "Aparthostel"}</h4>
            <ul>
              <li><a href={window.routeToPath("rooms", {}, lang)} onClick={(e) => { e.preventDefault(); navigate("rooms"); }}>{t.nav.rooms}</a></li>
              <li><a href={window.routeToPath("gallery", {}, lang)} onClick={(e) => { e.preventDefault(); navigate("gallery"); }}>{t.nav.gallery}</a></li>
              <li><a href={window.routeToPath("contact", {}, lang)} onClick={(e) => { e.preventDefault(); navigate("contact"); }}>{t.nav.contact}</a></li>
              <li><a href={window.routeToPath("reservation", {}, lang)} onClick={(e) => { e.preventDefault(); navigate("reservation"); }}>{t.nav.reserve}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.contact.addressLabel}</h4>
            <ul>
              {t.contact.address.map((l, i) => <li key={i}>{l}</li>)}
            </ul>
            <h4 style={{ marginTop: 24 }}>{t.contact.phoneLabel}</h4>
            <ul>
              <li><a href={"tel:" + t.contact.phone.replace(/\s/g, "")}>{t.contact.phone}</a></li>
              <li><a href={"mailto:" + t.contact.email}>{t.contact.email}</a></li>
            </ul>
          </div>
          <div>
            <h4>{lang === "pl" ? "Znajdź nas" : "Find us"}</h4>
            <ul>
              <li><a href="https://www.booking.com/hotel/pl/long-street-aparthostel-krakow.html" target="_blank" rel="noopener">Booking.com</a></li>
              <li><a href={t.hero.googleUrl} target="_blank" rel="noopener">Google Maps</a></li>
              <li><a>Instagram</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {yr} Long Street Aparthostel</span>
          <span>{lang === "pl" ? "Kraków, Polska" : "Kraków, Poland"}</span>
        </div>
      </div>
    </footer>
  );
}

// ─── Placeholder image ─────────────────────────────────────────────────────
// Neutral, on-palette tonal panels — used everywhere a hotel photo would go.
function PH({ tone = "warm", label, ratio = "4/3", style = {}, children, icon }) {
  return (
    <div className={"placeholder tone-" + tone} style={{ aspectRatio: ratio, ...style }}>
      {icon && <div className="ph-icon">{icon}</div>}
      {label && <div className="ph-label">{label}</div>}
      {children}
    </div>
  );
}

function Photo({ src, alt = "", ratio = "4/3", style = {}, children, objectPosition = "center" }) {
  // Serve a WebP sibling (~60% smaller) when the browser supports it; the
  // original .jpg stays as the <img> fallback. Every photo on the site renders
  // through this component, so this is the single place the swap is needed.
  const webp = /\.jpe?g$/i.test(src) ? src.replace(/\.jpe?g$/i, ".webp") : null;
  return (
    <div style={{ position: "relative", aspectRatio: ratio, overflow: "hidden", background: "var(--bg-2)", ...style }}>
      <picture>
        {webp && <source srcSet={webp} type="image/webp" />}
        <img
          src={src}
          alt={alt}
          loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition, display: "block" }}
        />
      </picture>
      {children}
    </div>
  );
}

// Each room's photos live in images/rooms/<slug>/01.jpg, 02.jpg, ...
// To add a photo: drop the next-numbered file in the folder and bump the count here.
window.ROOM_SLUGS = ["standard-1", "standard-2", "comfort-1", "comfort-2"];
window.ROOM_PHOTO_COUNTS = [4, 2, 2, 6];
window.slugFor = (idx) => window.ROOM_SLUGS[idx] || window.ROOM_SLUGS[0];
window.photosFor = (idx) => {
  const n = window.ROOM_PHOTO_COUNTS[idx] || 0;
  const slug = window.slugFor(idx);
  return Array.from({ length: n }, (_, i) => `images/rooms/${slug}/${String(i + 1).padStart(2, "0")}.jpg`);
};
window.roomImg = (idx) => window.photosFor(idx)[0] || "";

// ─── Path-based routing (real, crawlable URLs instead of #fragments) ─────────
// Single source of truth mapping a page key (+params) <-> URL path. Used by the
// router in app.jsx, the nav links below, applySeo, and the prerender build.
window.SITE_ORIGIN = "https://longstreet.pl";
window.LANGS = ["pl", "en"];        // pl = root paths, en = /en/* paths
window.DEFAULT_LANG = "pl";
window.pathToRoute = function (pathname) {
  let parts = (pathname || "/").replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
  let lang = window.DEFAULT_LANG;
  if (parts[0] === "en") { lang = "en"; parts = parts.slice(1); }
  const base = { lang, params: {} };
  if (!parts.length) return { ...base, page: "home" };
  if (parts[0] === "rooms" && parts[1]) {
    const idx = window.ROOM_SLUGS.indexOf(parts[1]);
    return { ...base, page: "room-detail", params: { roomIdx: idx >= 0 ? idx : 0 } };
  }
  const known = { rooms: "rooms", gallery: "gallery", contact: "contact", reservation: "reservation" };
  return { ...base, page: known[parts[0]] || "home" };
};
window.routeToPath = function (page, params, lang) {
  const p = params || {};
  const prefix = lang === "en" ? "/en" : "";
  let sub;
  switch (page) {
    case "rooms": sub = "/rooms"; break;
    case "room-detail": sub = "/rooms/" + (window.ROOM_SLUGS[p.roomIdx] || window.ROOM_SLUGS[0]); break;
    case "gallery": sub = "/gallery"; break;
    case "contact": sub = "/contact"; break;
    case "reservation": sub = "/reservation"; break;
    default: sub = "";
  }
  return (prefix + sub) || "/";     // "/en"+"" -> "/en"; ""+"" -> "/"
};
// Every real route the site exposes (drives the sitemap + prerender build).
window.SITE_ROUTES = ["home", "rooms", "gallery", "contact", "reservation"]
  .map((pg) => ({ page: pg, params: {} }))
  .concat(window.ROOM_SLUGS.map((_, i) => ({ page: "room-detail", params: { roomIdx: i } })));

// ─── Icons ─────────────────────────────────────────────────────────────────
const Ic = {
  arrow: (p = {}) => (
    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" {...p}>
      <path d="M1 5H13M13 5L9 1M13 5L9 9" stroke="currentColor" strokeWidth="1" strokeLinecap="square" />
    </svg>
  ),
  arrowL: (p = {}) => (
    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" {...p}>
      <path d="M13 5H1M1 5L5 1M1 5L5 9" stroke="currentColor" strokeWidth="1" strokeLinecap="square" />
    </svg>
  ),
  arrowDown: (p = {}) => (
    <svg width="10" height="14" viewBox="0 0 10 14" fill="none" {...p}>
      <path d="M5 1V13M5 13L1 9M5 13L9 9" stroke="currentColor" strokeWidth="1" strokeLinecap="square" />
    </svg>
  ),
  bed: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M3 18V8M21 18V12M3 12H21M3 18H21M7 12V10C7 9.4 7.4 9 8 9H11C11.6 9 12 9.4 12 10V12" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  ruler: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M3 8L8 3L21 16L16 21L3 8Z M6 11L8 9 M9 14L11 12 M12 17L14 15" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/>
    </svg>
  ),
  user: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <circle cx="12" cy="8" r="4" stroke="currentColor" strokeWidth="1.2"/>
      <path d="M4 21C4 16.6 7.6 13 12 13C16.4 13 20 16.6 20 21" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  window: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <rect x="4" y="4" width="16" height="16" stroke="currentColor" strokeWidth="1.2"/>
      <path d="M12 4V20M4 12H20" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  wifi: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M2 9C7.5 3.5 16.5 3.5 22 9 M5 13C9 9 15 9 19 13 M8 16.5C10 14.5 14 14.5 16 16.5 M12 20V20" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
    </svg>
  ),
  coffee: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M4 8H17V14C17 17.3 14.3 20 11 20H10C6.7 20 4 17.3 4 14V8Z M17 10H19C20.7 10 22 11.3 22 13C22 14.7 20.7 16 19 16H17 M7 4V2 M11 5V2 M15 4V2" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  bath: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M3 12H21V16C21 17.7 19.7 19 18 19H6C4.3 19 3 17.7 3 16V12Z M6 12V6C6 4.9 6.9 4 8 4C9.1 4 10 4.9 10 6 M4 20L5 21 M19 21L20 20" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
    </svg>
  ),
  key: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <circle cx="8" cy="12" r="4" stroke="currentColor" strokeWidth="1.2"/>
      <path d="M12 12H22 M19 12V15 M16 12V14" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  leaf: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M4 20C4 12 10 4 20 4C20 14 12 20 4 20Z M4 20L14 10" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/>
    </svg>
  ),
  fork: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M6 3V21 M5 3V8C5 9 6 10 7 10C8 10 8 9 8 8V3 M7 10V12 M16 3C14 3 13 5 13 7C13 9 14 11 16 11V21" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  book: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M4 5C4 4 5 3 6 3H11V20H6C5 20 4 19 4 18V5Z M20 5C20 4 19 3 18 3H13V20H18C19 20 20 19 20 18V5Z" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  pin: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 22C12 22 19 14 19 9C19 5.1 15.9 2 12 2C8.1 2 5 5.1 5 9C5 14 12 22 12 22Z" stroke="currentColor" strokeWidth="1.2"/>
      <circle cx="12" cy="9" r="2.5" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  calendar: (p = {}) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" {...p}>
      <rect x="3" y="5" width="18" height="16" stroke="currentColor" strokeWidth="1.2"/>
      <path d="M3 9H21 M8 3V7 M16 3V7" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  check: (p = {}) => (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}>
      <path d="M2 7L6 11L12 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square"/>
    </svg>
  ),
  star: (p = {}) => (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" {...p}>
      <path d="M6 0L7.4 4.3H12L8.3 6.9L9.7 11L6 8.4L2.3 11L3.7 6.9L0 4.3H4.6L6 0Z"/>
    </svg>
  ),
  close: (p = {}) => (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}>
      <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.2"/>
    </svg>
  ),
  diamond: (p = {}) => (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}>
      <path d="M7 1L13 7L7 13L1 7L7 1Z" stroke="currentColor" strokeWidth="1"/>
    </svg>
  ),
};

// ─── Decorative serif diamond divider ──────────────────────────────────────
function Divider() {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, color: "var(--accent)", margin: "20px 0" }}>
      <span style={{ width: 60, height: 1, background: "var(--accent)" }}></span>
      <Ic.diamond />
      <span style={{ width: 60, height: 1, background: "var(--accent)" }}></span>
    </div>
  );
}

// expose globally
Object.assign(window, {
  AppCtx, useApp, CURRENCIES, formatPrice,
  BrandMark, Header, Footer, PH, Ic, Divider,
});
