// Homepage

// Animated word — cinematic mask reveal (slide from below + blur-in + fade).
// Timing comes from CSS using the `--i` custom property so every word plays
// at its own delay without each needing a bespoke keyframe set.
function Word({ children, i, em }) {
  const inner = em ? <em>{children}</em> : children;
  return (
    <span className="word" style={{ "--i": i }}>
      <span className="word-inner">{inner}</span>
    </span>
  );
}

function HomePage({ lang, t, setRoute, openExperience, heroVariant, cardStyle }) {
  const featured = window.EXPERIENCES.filter((e) => e.featured);

  return (
    <div className="home">
      <Hero lang={lang} t={t} setRoute={setRoute} variant={heroVariant} />

      <section className="sec sec-featured">
        <div className="sec-head">
          <span className="eyebrow">{t.featured.eyebrow}</span>
          <h2 className="display">{t.featured.title}</h2>
        </div>

        <div className="featured-grid">
          {featured.map((exp, i) => (
            <FeaturedCard key={exp.id} exp={exp} idx={i} lang={lang} onOpen={() => openExperience(exp)} />
          ))}
        </div>
      </section>

      <SevenShadesStrip lang={lang} />

      <Atlas lang={lang} t={t} cardStyle={cardStyle} openExperience={openExperience} />

      <TerritoryMap lang={lang} t={t} openExperience={openExperience} />

      <Philosophy lang={lang} t={t} setRoute={setRoute} />

      <Testimonial t={t} lang={lang} />

      <CTABand lang={lang} setRoute={setRoute} />
    </div>
  );
}

// ────────────────────────────────────────────
// Hero — cinematic photography with big serif overlay
// ────────────────────────────────────────────
function Hero({ lang, t, setRoute, variant }) {
  const heroImg = "images/seven-shades.webp";

  if (variant === "split") {
    return (
      <section className="hero hero-split">
        <div className="hero-split-left">
          <span className="eyebrow">{t.hero.eyebrow}</span>
          <h1 className="hero-title">
            <span>{t.hero.title.split("\n").map((l, i) => <span key={i} className="line">{l}</span>)}</span>
            <em>{t.hero.titleItalic.split("\n").map((l, i) => <span key={i} className="line">{l}</span>)}</em>
          </h1>
          <p className="hero-body">{t.hero.body}</p>
          <div className="hero-ctas">
            <button className="btn btn-primary" onClick={() => setRoute("catalog")}>{t.hero.cta} →</button>
            <button className="btn btn-ghost" onClick={() => setRoute("contact")}>{t.hero.cta2}</button>
          </div>
        </div>
        <div className="hero-split-right">
          <img src={heroImg} alt="Bacalar lagoon from above" />
          <span className="hero-stamp mono">21.0107° N &nbsp; 88.3961° W</span>
        </div>
      </section>
    );
  }

  if (variant === "typographic") {
    return (
      <section className="hero hero-typo">
        <div className="hero-typo-inner">
          <span className="eyebrow eyebrow-center">{t.hero.eyebrow}</span>
          <h1 className="hero-typo-title">
            <span className="tl-1">Seven</span>
            <span className="tl-2">shades</span>
            <span className="tl-3"><em>of blue,</em></span>
            <span className="tl-4">and everything</span>
            <span className="tl-5"><em>beyond</em> them</span>
          </h1>
          <div className="hero-typo-strip">
            {[0.15, 0.28, 0.42, 0.58, 0.72, 0.85, 1].map((shade, i) => (
              <div key={i} className="shade" style={{ background: `oklch(${0.35 + shade * 0.45} 0.06 210)` }} />
            ))}
          </div>
          <p className="hero-body centered">{t.hero.body}</p>
          <div className="hero-ctas centered">
            <button className="btn btn-primary" onClick={() => setRoute("catalog")}>{t.hero.cta} →</button>
            <button className="btn btn-ghost" onClick={() => setRoute("contact")}>{t.hero.cta2}</button>
          </div>
        </div>
      </section>
    );
  }

  // Default: cinematic. Word-by-word reveal on the big headline, then the
  // supporting copy and CTAs cascade in after the last word has settled.
  const words = lang === "es"
    ? [
        [{ w: "Siete" }, { w: "tonos" }],
        [{ w: "de" }, { w: "azul,", em: true }],
        [{ w: "y" }, { w: "todo" }, { w: "lo" }, { w: "que" }],
        [{ w: "hay" }, { w: "más", em: true }, { w: "allá.", em: true }],
      ]
    : [
        [{ w: "Seven" }, { w: "shades" }],
        [{ w: "of" }, { w: "blue,", em: true }],
        [{ w: "and" }, { w: "everything" }],
        [{ w: "beyond", em: true }, { w: "them." }],
      ];
  let wordIdx = 0;

  return (
    <section className="hero hero-cinema">
      <div className="hero-img">
        <img src={heroImg} alt="Bacalar lagoon" />
        <div className="hero-gradient" />
      </div>

      <div className="hero-content">
        <div className="hero-meta-top hero-fade" style={{ "--delay": "0.15s" }}>
          <span className="mono">{t.hero.eyebrow}</span>
          <span className="mono">N 21°00'38" · W 88°23'46"</span>
        </div>

        <h1 className="hero-title cinema">
          {words.map((line, lineIdx) => (
            <span key={lineIdx} className={`line line-${lineIdx + 1}`}>
              {line.map((wordDef, j) => {
                const currentIdx = wordIdx++;
                return (
                  <Word key={`${lineIdx}-${j}`} i={currentIdx} em={wordDef.em}>
                    {wordDef.w}
                  </Word>
                );
              })}
            </span>
          ))}
        </h1>

        <div className="hero-footer">
          <div className="hero-footer-left hero-fade" style={{ "--delay": "1.6s" }}>
            <p className="hero-body">{t.hero.body}</p>
            <div className="hero-ctas">
              <button className="btn btn-primary" onClick={() => setRoute("catalog")}>{t.hero.cta} →</button>
              <button className="btn btn-ghost-light" onClick={() => setRoute("contact")}>{t.hero.cta2}</button>
            </div>
          </div>
          <div className="hero-footer-right hero-fade" style={{ "--delay": "1.85s" }}>
            <span className="scroll-indicator mono">
              {t.hero.scroll}
              <span className="scroll-line" />
            </span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────
// Featured cards — large editorial cards, asymmetric
// ────────────────────────────────────────────
function FeaturedCard({ exp, idx, lang, onOpen }) {
  const Link = window.__bbRouter.Link;
  const offset = idx === 1 ? "middle" : idx === 0 ? "top" : "bottom";
  return (
    <Link route="detail" entity={exp} className={`feat-card feat-${offset}`}>
      <div className="feat-img">
        <img src={exp.thumb} alt={exp.title[lang]} />
        <span className="feat-kicker mono">{exp.kicker}</span>
      </div>
      <div className="feat-body">
        <span className="eyebrow">{exp.type[lang]}</span>
        <h3 className="feat-title">{exp.title[lang]}</h3>
        <p className="feat-sub">{exp.subtitle[lang]}</p>
        <div className="feat-meta mono">
          <span>{exp.duration[lang]}</span>
          <span>·</span>
          <span>{exp.group[lang]}</span>
          <span>·</span>
          <span>${exp.price} USD</span>
        </div>
        <span className="feat-arrow">→</span>
      </div>
    </Link>
  );
}

// ────────────────────────────────────────────
// Seven shades strip — a visual palette moment
// ────────────────────────────────────────────
function SevenShadesStrip({ lang }) {
  const t = window.COPY[lang].shades;
  const DEPTHS = ["0.5m", "1.5m", "3m", "6m", "10m", "20m", "90m"];
  const HEXES  = ["#c7e7ea", "#8cd3d5", "#5cb3b9", "#2a8b9c", "#196b81", "#0e4f68", "#082a3d"];
  return (
    <section className="shades-strip">
      <div className="shades-head">
        <span className="eyebrow">{t.eyebrow}</span>
        <h2 className="display small">
          {t.title_1}<em>{t.title_em}</em>
        </h2>
      </div>
      <div className="shades-row">
        {t.names.map((name, i) => (
          <div key={i} className="shade-col" style={{ background: HEXES[i], color: i > 3 ? "var(--sand)" : "var(--ink)" }}>
            <span className="mono">0{i + 1}</span>
            <div className="shade-name">{name}</div>
            <span className="mono shade-depth">↓ {DEPTHS[i]}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ────────────────────────────────────────────
// Atlas — full experience catalog with filters
// ────────────────────────────────────────────
function Atlas({ lang, t, cardStyle, openExperience, showHero }) {
  const [filter, setFilter] = React.useState("all");
  const [sort, setSort] = React.useState("popular");
  const all = window.EXPERIENCES;

  const filtered = all
    .filter((e) => filter === "all" || e.category === filter)
    .sort((a, b) => {
      if (sort === "price") return a.price - b.price;
      if (sort === "duration") return a.duration[lang].localeCompare(b.duration[lang]);
      return 0;
    });

  return (
    <section className={`sec sec-atlas ${showHero ? "sec-atlas-page" : ""}`} id="atlas">
      <div className="atlas-head">
        <div>
          <span className="eyebrow">{t.catalog.eyebrow}</span>
          <h2 className={showHero ? "display" : "display"} style={showHero ? { fontSize: "clamp(3rem, 6vw, 5rem)", maxWidth: "14ch" } : {}}>
            {showHero
              ? <>{window.COPY[lang].territory.heading.line1}<em>{window.COPY[lang].territory.heading.emphasis}</em></>
              : t.catalog.title}
          </h2>
          <p className="sec-sub">{t.catalog.sub}</p>
        </div>
        <div className="atlas-controls">
          <div className="atlas-filters">
            {["all", "water", "ruins", "nature"].map((f) => (
              <button key={f} className={filter === f ? "on" : ""} onClick={() => setFilter(f)}>
                {t.catalog.filters[f]}
                <span className="mono">
                  {f === "all" ? all.length : all.filter((e) => e.category === f).length}
                </span>
              </button>
            ))}
          </div>
          <div className="atlas-sort">
            <label className="mono">{t.catalog.sort}</label>
            <select value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="popular">{t.catalog.sortOpts.popular}</option>
              <option value="price">{t.catalog.sortOpts.price}</option>
              <option value="duration">{t.catalog.sortOpts.duration}</option>
            </select>
          </div>
        </div>
      </div>

      <div className={`atlas-grid atlas-grid-${cardStyle}`}>
        {filtered.map((exp) => (
          <AtlasCard key={exp.id} exp={exp} lang={lang} onOpen={() => openExperience(exp)} style={cardStyle} />
        ))}
      </div>
    </section>
  );
}

function AtlasCard({ exp, lang, onOpen, style }) {
  const Link = window.__bbRouter.Link;
  return (
    <Link route="detail" entity={exp} className={`atlas-card atlas-card-${style}`}>
      <div className="atlas-card-img">
        <img src={exp.thumb} alt={exp.title[lang]} />
        <span className="atlas-card-cat mono">{exp.type[lang]}</span>
      </div>
      <div className="atlas-card-body">
        <div className="atlas-card-row">
          <span className="mono idx">{exp.kicker}</span>
          <span className="mono price">${exp.price}</span>
        </div>
        <h3 className="atlas-card-title">{exp.title[lang]}</h3>
        <p className="atlas-card-sub">{exp.subtitle[lang]}</p>
        <div className="atlas-card-meta">
          <span className="mono">{exp.location}</span>
          <span className="mono">·</span>
          <span className="mono">{exp.duration[lang]}</span>
          <span className="difficulty" title={`Difficulty ${exp.difficulty}/3`}>
            {[1, 2, 3].map((n) => (
              <span key={n} className={`dot ${n <= exp.difficulty ? "on" : ""}`} />
            ))}
          </span>
        </div>
      </div>
    </Link>
  );
}

// ────────────────────────────────────────────
// Territory map — illustrated region with interactive pins
// ────────────────────────────────────────────
function TerritoryMap({ lang, t, openExperience }) {
  // Pin positions calibrated against the illustrated map (images/territory-map.webp).
  // Key reference points I measured in the illustration:
  //   · Compass rose sits outside the landmass (top-right decoration).
  //   · The distinctive vertical turquoise ribbon at ~(57%, 53%) IS Laguna Bacalar.
  //   · East coast curves: at y=27% the Caribbean starts ~x=62%; at y=38% ~x=64%; at y=55% ~x=62%.
  //   · North-central jungle (Yucatán state): Chichén/Ek'Balam cluster at x=20–30%, y=10–22%.
  //   · Interior Q.Roo (Cobá): around x=44%, y=25%.
  //   · Coastal Q.Roo (Tulum→Sian Ka'an→Bacalar) runs down the right edge.
  const L = window.COPY[lang].mapLabels;
  const pins = [
    { id: "ekbalam",  expId: "ek-balam",     cat: "ruins",  x: 55.2, y: 32.4, label: "Ek' Balam",     sub: L.jaguar },
    { id: "chichen",  expId: "chichen",      cat: "ruins",  x: 40.6, y: 44.7, label: "Chichén Itzá",  sub: L.wonder },
    { id: "coba",     expId: "coba-bike",    cat: "ruins",  x: 56.4, y: 49.1, label: "Cobá",          sub: L.jungleRide },
    { id: "tulum",    expId: "tulum-dawn",   cat: "ruins",  x: 71.2, y: 42.2, label: "Tulum",         sub: L.walledCity },
    { id: "siankaan", expId: "sian-kaan",    cat: "nature", x: 68.4, y: 55.2, label: "Sian Ka'an",    sub: "UNESCO" },
    { id: "cenote",   expId: "cenote-dive",  cat: "water",  x: 53.7, y: 70.8, label: "Cenote Azul",   sub: L.cenoteSub },
    { id: "bacalar",  expId: "seven-shades", cat: "water",  x: 62.6, y: 65.2, label: L.bacalar,       sub: L.sevenShades },
  ];

  const expById = React.useMemo(() => {
    const map = {};
    (window.EXPERIENCES || []).forEach(e => { map[e.id] = e; });
    return map;
  }, []);

  const [activeId, setActiveId] = React.useState(null);

  const routePath = React.useMemo(() => {
    if (pins.length < 2) return "";
    let d = `M ${pins[0].x} ${pins[0].y}`;
    for (let i = 1; i < pins.length; i++) {
      const prev = pins[i - 1];
      const cur = pins[i];
      const midX = (prev.x + cur.x) / 2;
      const midY = (prev.y + cur.y) / 2;
      d += ` Q ${midX} ${prev.y} ${midX} ${midY} T ${cur.x} ${cur.y}`;
    }
    return d;
  }, []);

  return (
    <section className="sec sec-map">
      <div className="sec-head">
        <span className="eyebrow">{t.map.eyebrow}</span>
        <h2 className="display">{t.map.title}</h2>
      </div>

      <div className="map-wrap">
        <img className="map-illustration" src="images/territory-map.webp" alt={L.bacalar} />

        <svg className="map-routes" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
          <path d={routePath} fill="none" stroke="var(--ink)" strokeWidth="1"
            strokeDasharray="1.2 1.6" opacity="0.32" vectorEffect="non-scaling-stroke" />
        </svg>

        {pins.map((p, i) => {
          const exp = expById[p.expId];
          const isActive = activeId === p.id;
          const flipX = p.x > 72;
          const flipY = p.y > 68;
          return (
            <button
              key={p.id}
              type="button"
              className={`map-pin map-pin-${p.cat} ${isActive ? "is-active" : ""} ${flipX ? "flip-x" : ""} ${flipY ? "flip-y" : ""}`}
              style={{ left: `${p.x}%`, top: `${p.y}%` }}
              onMouseEnter={() => setActiveId(p.id)}
              onMouseLeave={() => setActiveId(null)}
              onFocus={() => setActiveId(p.id)}
              onBlur={() => setActiveId(null)}
              onClick={() => exp && openExperience(exp)}
              aria-label={`${p.label}${exp ? ` — ${exp.title[lang]}` : ""}`}
            >
              <span className="pin-dot">
                <span className="pin-num">{String(i + 1).padStart(2, "0")}</span>
                <span className="pin-pulse" />
              </span>
              <div className="pin-tip">
                <strong>{p.label}</strong>
                <span className="pin-sub mono">{p.sub}</span>
                {exp && (
                  <>
                    <span className="pin-exp-title">{exp.title[lang]}</span>
                    <span className="pin-cta mono">
                      {L.openExpedition} →
                    </span>
                  </>
                )}
              </div>
            </button>
          );
        })}

        <div className="map-legend mono">
          <div><span className="dot water" /> {L.water}</div>
          <div><span className="dot ruins" /> {L.ruins}</div>
          <div><span className="dot nature" /> {L.biosphere}</div>
          <div className="scale">0 &nbsp; 50 km &nbsp; 100 km</div>
        </div>

        <div className="map-hint mono">{L.hint}</div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────
function Philosophy({ lang, t, setRoute }) {
  const statNums = ["8", "100%", "4%", "0"];
  const statLabels = window.COPY[lang].philStats;
  return (
    <section className="sec sec-philosophy">
      <div className="phi-grid">
        <div className="phi-copy">
          <span className="eyebrow">{t.philosophy.eyebrow}</span>
          <h2 className="display">
            {t.philosophy.title_1}<br/><em>{t.philosophy.titleEm}</em>
          </h2>
          <p className="phi-body">{t.philosophy.body}</p>
          <button className="btn btn-link" onClick={() => setRoute("about")}>
            {window.COPY[lang].philReadMore} →
          </button>
        </div>
        <div className="phi-stats">
          {statNums.map((num, i) => (
            <div key={i} className="stat">
              <span className="stat-num display">{num}</span>
              <span className="stat-lab mono">{statLabels[i].label}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Testimonial({ t, lang }) {
  return (
    <section className="sec sec-testimonial">
      <div className="quote-mark">&#8220;</div>
      <blockquote className="display">
        {t.testimonial.quote}
      </blockquote>
      <cite className="mono">— {t.testimonial.who}</cite>
    </section>
  );
}

function CTABand({ lang, setRoute }) {
  const t = window.COPY[lang].ctaBand;
  return (
    <section className="cta-band">
      <div className="cta-band-inner">
        <h2 className="display">
          {t.title_1}<em>{t.title_2_em}</em>
        </h2>
        <div className="cta-band-right">
          <p>{t.body}</p>
          <button className="btn btn-primary btn-lg" onClick={() => setRoute("catalog")}>
            {t.cta} →
          </button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HomePage });
