// Reusable Lucide icon — render <Icon name="calendar" />
const Icon = ({ name, size = 20, className = "", strokeWidth = 1.5 }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const i = document.createElement("i");
      i.setAttribute("data-lucide", name);
      i.style.width = size + "px";
      i.style.height = size + "px";
      i.style.display = "inline-flex";
      ref.current.appendChild(i);
      window.lucide.createIcons({
        attrs: { "stroke-width": strokeWidth, width: size, height: size },
      });
    }
  }, [name, size, strokeWidth]);
  return <span ref={ref} className={className} style={{ display: "inline-flex", width: size, height: size }} />;
};

// Reveal-on-scroll wrapper
const Reveal = ({ children, delay = 0, as: As = "div", className = "", ...rest }) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => setShown(true), delay); obs.disconnect(); }
    }, { rootMargin: "-10% 0px" });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <As ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} {...rest}>
      {children}
    </As>
  );
};

// Nav
const Nav = ({ lang, setLang, t }) => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const go = (id) => (e) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" }); };
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="container nav-inner">
        <a href="#top" className="brand brand-mark" onClick={go("top")}>
          <span className="arch" />
          <span>Rayful</span>
        </a>
        <div className="nav-links">
          <a href="#about" className="nav-link desktop-only" onClick={go("about")}>{t.nav.stay}</a>
          <a href="#gallery" className="nav-link desktop-only" onClick={go("gallery")}>{t.nav.gallery}</a>
          <a href="#location" className="nav-link desktop-only" onClick={go("location")}>{t.nav.access}</a>
          <div className="lang-toggle" role="tablist">
            {["en","ja","zh"].map(l => (
              <button key={l} className={lang === l ? "active" : ""} onClick={() => setLang(l)}>
                {l === "en" ? "EN" : l === "ja" ? "JA" : "中"}
              </button>
            ))}
          </div>
          <a href="#reserve" className="btn btn-sm" onClick={go("reserve")}>{t.nav.book}</a>
        </div>
      </div>
    </nav>
  );
};

// Hero
const Hero = ({ t }) => {
  const go = (id) => (e) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); };
  return (
    <section className="hero" id="top">
      <div className="hero-bg" style={{ backgroundImage: `url(${window.HERO_PHOTO})` }} />
      <div className="hero-side">{t.hero.side}</div>
      <div className="container hero-content">
        <div className="hero-eyebrow">{t.hero.eyebrow}</div>
        <h1>{t.hero.title}</h1>
        <p className="hero-tagline">{t.hero.tagline}</p>
        <div className="hero-cta-row">
          <a href="#reserve" className="btn btn-on-dark" onClick={go("reserve")}>
            {t.hero.cta}
            <Icon name="arrow-right" size={16} />
          </a>
          <a href="#about" className="btn btn-on-dark-ghost" onClick={go("about")}>{t.hero.ctaSecondary}</a>
        </div>
        <div className="hero-meta">
          {t.hero.meta.map((m, i) => (
            <span key={i}>
              {m.l}
              <strong>{m.v}</strong>
            </span>
          ))}
        </div>
      </div>
    </section>
  );
};

// Gallery + Lightbox
const Gallery = ({ t }) => {
  const [open, setOpen] = React.useState(null);
  const photos = window.PHOTOS;
  const close = () => setOpen(null);
  const next = (e) => { e?.stopPropagation(); setOpen((o) => (o + 1) % photos.length); };
  const prev = (e) => { e?.stopPropagation(); setOpen((o) => (o - 1 + photos.length) % photos.length); };
  React.useEffect(() => {
    if (open === null) return;
    const onKey = (e) => {
      if (e.key === "Escape") close();
      if (e.key === "ArrowRight") next();
      if (e.key === "ArrowLeft") prev();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);
  return (
    <section className="section" id="gallery">
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow-jp">{t.gallery.eyebrow}</span>
          <h2 className="h-section">{t.gallery.title}</h2>
        </Reveal>
        <Reveal>
          <div className="gallery-grid">
            {photos.slice(0, 9).map((src, i) => (
              <div
                key={i}
                className={`g-tile g-${i + 1}`}
                style={{ backgroundImage: `url(${src})` }}
                onClick={() => setOpen(i)}
              />
            ))}
          </div>
        </Reveal>
      </div>
      {open !== null && (
        <div className="lightbox" onClick={close}>
          <button className="lightbox-close" onClick={close}><Icon name="x" size={20} /></button>
          <button className="lightbox-nav prev" onClick={prev}><Icon name="chevron-left" size={20} /></button>
          <button className="lightbox-nav next" onClick={next}><Icon name="chevron-right" size={20} /></button>
          <div className="lightbox-img" style={{ backgroundImage: `url(${photos[open]})` }} />
          <div className="lightbox-counter">{String(open + 1).padStart(2, "0")} / {String(photos.length).padStart(2, "0")}</div>
        </div>
      )}
    </section>
  );
};

// About
const About = ({ t }) => (
  <section className="section" id="about" style={{ background: "var(--sand-100)" }}>
    <div className="container">
      <Reveal className="section-head">
        <span className="eyebrow-jp">{t.about.eyebrow}</span>
        <h2 className="h-section">{t.about.title}</h2>
      </Reveal>
      <div className="about-grid">
        <Reveal className="about-text">
          {t.about.body.map((p, i) => <p key={i}>{p}</p>)}
        </Reveal>
        <Reveal delay={150} className="host-card">
          <div className="host-portrait" style={{ backgroundImage: "url(https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=400&q=80)" }} />
          <div className="host-name">{t.about.host.name}</div>
          <div className="host-role">{t.about.host.role}</div>
          <div className="host-quote">{t.about.host.quote}</div>
        </Reveal>
      </div>
    </div>
  </section>
);

// Amenities
const AMENITY_ICONS = ["wifi","chef-hat","car","shower-head","bath","bed-double","waves","coffee","disc","book-open","thermometer-sun","umbrella"];
const Amenities = ({ t }) => (
  <section className="section">
    <div className="container">
      <Reveal className="section-head">
        <span className="eyebrow-jp">{t.amenities.eyebrow}</span>
        <h2 className="h-section">{t.amenities.title}</h2>
      </Reveal>
      <Reveal>
        <div className="amenity-grid">
          {t.amenities.items.map((a, i) => (
            <div className="amenity" key={i}>
              <div className="amenity-icon"><Icon name={AMENITY_ICONS[i] || "circle"} size={28} strokeWidth={1.4} /></div>
              <div className="amenity-name">{a.name}</div>
              <div className="amenity-jp">{a.jp}</div>
            </div>
          ))}
        </div>
      </Reveal>
    </div>
  </section>
);

Object.assign(window, { Icon, Reveal, Nav, Hero, Gallery, About, Amenities });
