// Homepage-only section compositions for The Vivaan Hotel & Resorts.
// Depends on shared/vivaan-sections.jsx being loaded first.

const { Button } = window.VivaanDesignSystem_b1c8ba;
const { PhotoBlock, PhotoSlideshow, HoverImageSwap, SectionLabel, EditorialHeading, BodyCopy } = window;

/* ---------------------------------------------------------------------- */
/* 2. Welcome                                                              */
/* ---------------------------------------------------------------------- */

const METRICS = window.METRICS;

// Count-up animation for the metrics row: parses "100,000+", "5.5", "43" etc.
// into a numeric target + decimal precision + suffix, then animates from 0
// once the row scrolls into view (fires once, eased, ~1.8s).
function CountUpMetric({ value, style }) {
  const ref = React.useRef(null);
  const [display, setDisplay] = React.useState(null);

  const parsed = React.useMemo(() => {
    const m = String(value).match(/^([\d,]*\.?\d+)(\+?)$/);
    if (!m) return null;
    const numStr = m[1].replace(/,/g, "");
    const decimals = numStr.includes(".") ? numStr.split(".")[1].length : 0;
    return { target: parseFloat(numStr), decimals, suffix: m[2] };
  }, [value]);

  React.useEffect(() => {
    if (!parsed || !ref.current) return;
    setDisplay(parsed.target === Math.round(parsed.target) && parsed.decimals === 0 ? "0" : (0).toFixed(parsed.decimals));

    const el = ref.current;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const duration = 1800;
          const start = performance.now();
          const animate = (now) => {
            const t = Math.min((now - start) / duration, 1);
            const eased = 1 - Math.pow(1 - t, 3);
            const current = parsed.target * eased;
            setDisplay(
              parsed.decimals > 0
                ? current.toFixed(parsed.decimals)
                : Math.round(current).toLocaleString("en-US")
            );
            if (t < 1) requestAnimationFrame(animate);
          };
          requestAnimationFrame(animate);
          observer.disconnect();
        }
      });
    }, { threshold: 0.4 });
    observer.observe(el);
    return () => observer.disconnect();
  }, [parsed]);

  if (!parsed) return <div ref={ref} style={style}>{value}</div>;
  return <div ref={ref} style={style}>{display}{parsed.suffix}</div>;
}

function WelcomeSection() {
  const wrap = { padding: "var(--space-2xl) var(--space-xl)", backgroundColor: "var(--color-surface-page)" };
  const metricsRow = { display: "flex", gap: "var(--space-xl)", marginTop: "var(--space-xl)", flexWrap: "wrap", borderTop: "1px solid var(--color-border-hairline)", paddingTop: "var(--space-lg)" };
  const metricValue = { fontFamily: "var(--font-serif)", fontSize: 36, color: "var(--vivaan-gold)" };
  const metricLabel = { fontFamily: "var(--font-serif)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--color-text-secondary)", marginTop: 6 };

  return (
    <section style={wrap} data-screen-label="welcome">
      <div className="welcome-grid">
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
          <SectionLabel>Welcome to The Vivaan</SectionLabel>
          <EditorialHeading
            size={44}
            parts={[{ text: "A destination where " }, { text: "celebrations", italic: true }, { text: " become memories." }]}
          />
          <BodyCopy style={{ maxWidth: 460, color: "var(--color-text-secondary)" }}>
            Set across 5.5 acres in Karnal, The Vivaan brings together quiet luxury stays,
            grand celebrations and thoughtful hospitality — a private estate built for
            occasions that deserve to be remembered.
          </BodyCopy>
          <div style={metricsRow}>
            {METRICS.map((m) => (
              <div key={m.label}>
                <CountUpMetric value={m.value} style={metricValue} />
                <div style={metricLabel}>{m.label}</div>
              </div>
            ))}
          </div>
        </div>
        <PhotoSlideshow
          ratio="4 / 5"
          images={[
            "assets/estate-wedding.jpg",
            "assets/estate-banquet.jpg",
            "assets/estate-drone.jpg",
            "assets/estate-lobby.jpg",
            "assets/estate-room.jpg",
          ]}
        />
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------------- */
/* 3. Wedding                                                              */
/* ---------------------------------------------------------------------- */

const VENUES = window.VENUES;

function VenueCard({ v }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ display: "flex", flexDirection: "column", gap: 14, cursor: "pointer" }}
    >
      <div style={{ overflow: "hidden" }}>
        {v.images ? (
          <HoverImageSwap images={v.images} tone={v.tone} ratio="4 / 5" />
        ) : (
          <PhotoBlock
            tone={v.tone}
            ratio="4 / 5"
            style={{ transform: hover ? "scale(1.04)" : "scale(1)", transition: "transform 0.6s ease" }}
          />
        )}
      </div>
      <div>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 20 }}>{v.name}</div>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 13, color: "var(--color-text-secondary)", marginTop: 4 }}>{v.tag}</div>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 12, letterSpacing: "0.05em", color: "var(--color-text-secondary)", marginTop: 10 }}>
          {v.capacity} &nbsp;&middot;&nbsp; {v.area}
        </div>
      </div>
    </div>
  );
}

function WeddingSection() {
  const wrap = { padding: "var(--space-2xl) var(--space-xl)", backgroundColor: "var(--vivaan-cream)" };
  const head = { display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 40, marginBottom: "var(--space-xl)", flexWrap: "wrap" };
  return (
    <section style={wrap} data-screen-label="wedding">
      <div style={head}>
        <div style={{ display: "flex", flexDirection: "column", gap: 20, maxWidth: 560 }}>
          <SectionLabel>Wedding &amp; Events</SectionLabel>
          <EditorialHeading size={44} parts={[{ text: "Where " }, { text: "forever", italic: true }, { text: " begins." }]} />
          <BodyCopy style={{ color: "var(--color-text-secondary)" }}>
            Eight distinct venues, from candlelit ballrooms to open lawns beneath the sky —
            each one shaped around the story you want to tell.
          </BodyCopy>
        </div>
        <Button variant="outline-white" as="a" href="wedding.html" style={{ color: "var(--color-text-primary)", border: "1px solid var(--color-text-primary)" }}>
          View All Venues
        </Button>
      </div>
      <div className="grid-4">
        {VENUES.map((v) => <VenueCard key={v.name} v={v} />)}
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------------- */
/* 4. Stay                                                                 */
/* ---------------------------------------------------------------------- */

const ROOMS = window.ROOMS;

function StaySection() {
  const wrap = { padding: "var(--space-2xl) var(--space-xl)", backgroundColor: "var(--color-surface-page)", display: "flex", flexDirection: "column", gap: "var(--space-2xl)" };
  const head = { display: "flex", flexDirection: "column", gap: 20, maxWidth: 560, marginBottom: "var(--space-md)" };
  return (
    <section style={wrap} data-screen-label="stay">
      <div style={head}>
        <SectionLabel>Stay</SectionLabel>
        <EditorialHeading size={44} parts={[{ text: "Rooms shaped by " }, { text: "quiet", italic: true }, { text: " comfort." }]} />
        <BodyCopy style={{ color: "var(--color-text-secondary)" }}>
          Six room categories, each composed for a different rhythm of travel — from
          family suites to intimate singles, every stay begins with stillness.
        </BodyCopy>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2xl)" }}>
        {[0, 1, 2].map((row) => (
          <div key={row} className="grid-2">
            {[ROOMS[row * 2], ROOMS[row * 2 + 1]].map((r) => (
              <div key={r.name} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                <HoverImageSwap images={r.images} tone={r.tone} ratio="5 / 4" />
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 24 }}>{r.name}</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--color-text-secondary)" }}>
                  {r.size}
                </div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 16px" }}>
                  {r.usps.map((u) => (
                    <li key={u} style={{ fontFamily: "var(--font-serif)", fontSize: 13, color: "var(--color-text-primary)", borderTop: "1px solid var(--color-border-hairline)", paddingTop: 6 }}>
                      {u}
                    </li>
                  ))}
                </ul>
                <a href="rooms.html" style={{ fontFamily: "var(--font-serif)", fontSize: "var(--text-cta-size)", letterSpacing: "var(--text-cta-letter-spacing)", textTransform: "uppercase", color: "var(--vivaan-gold)", textDecoration: "none", marginTop: 4 }}>
                  Check Availability &rarr;
                </a>
              </div>
            ))}
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { METRICS, WelcomeSection, VENUES, WeddingSection, ROOMS, StaySection });
