/* global React, BrandMark, WaveDivider, SectionHead, BrandStrip, PageHero,
   IconWaves, IconSunrise, IconColumn, IconAnchor, IconShield, IconKey,
   IconBuilding, IconBed, IconParking, IconPickleball, IconDumbbell,
   IconBike, IconPaw, IconArrow, IconLighthouse, IconMapPin, IconCheck,
   AMENITIES, HERO_HEADLINES, UNITS, TYPE_META, GALLERY_ITEMS, NEIGHBORHOOD,
   CATEGORIES, FAQ */

const { useState: useStateHome, useEffect: useEffectHome, useMemo, useRef: useRefHome } = React;

// Sample floor plan per residence type for the home-page teaser cards.
const TEASER_FP = {
  "1br": "images/floor-plans/boardwalk-house-single-401-floorplan-local.png",
  "1br_den": "images/floor-plans/boardwalk-house-single-404-floorplan-local.png",
  "2br": "images/floor-plans/boardwalk-house-double-405-floorplan-local.png",
};

// Map icon names from data.js to actual icon components
const ICON_BY_NAME = {
  IconWaves, IconSunrise, IconColumn, IconAnchor, IconShield, IconKey,
  IconBuilding, IconBed, IconParking, IconPickleball, IconDumbbell,
  IconBike, IconPaw, IconLighthouse, IconMapPin
};

// =====================================================
// HOME PAGE
// =====================================================
function HomePage({ tweaks, openTour, openApply, navTo }) {
  const headline = HERO_HEADLINES[tweaks.headlineIdx || 0];
  const heroPhoto = "images/aerial-1.jpeg";

  return (
    <div>
      {/* HERO */}
      <Hero variant={tweaks.heroVariant} headline={headline} photo={heroPhoto} openTour={openTour} navTo={navTo} />

      <BrandStrip />

      {/* INTRO — letter from the team */}
      <section className={"section " + (tweaks.colorTheme === "navy" ? "bg-navy" : "bg-cream")}>
        <div className="shell">
          <div style={{
            display: "grid",
            gridTemplateColumns: "1fr 1.2fr",
            gap: "var(--space-8)",
            alignItems: "center"
          }} className="intro-grid">
            <div>
              <span className={"eyebrow" + (tweaks.colorTheme === "navy" ? " on-dark" : "")}>About Boardwalk House</span>
              <h2 style={{ marginTop: 14 }}>Forty-seven residences. One front row to the Atlantic.</h2>
              <WaveDivider onDark={tweaks.colorTheme === "navy"} />
              <p className="lede" style={{
                marginTop: 20,
                color: tweaks.colorTheme === "navy" ? "rgba(245,242,237,0.82)" : undefined
              }}>
                Originally built in 1984 on the edge of the Atlantic City Boardwalk, Boardwalk House
                has been completely reimagined for 2026 — every apartment renovated, every system
                modernized, every view preserved.
              </p>
              <p style={{
                marginTop: 16, fontSize: 15, lineHeight: 1.7,
                color: tweaks.colorTheme === "navy" ? "rgba(245,242,237,0.7)" : "var(--muted)"
              }}>
                The result is a quieter side of Atlantic City — timeless architecture, modern finishes,
                and direct boardwalk access to everything the shore is famous for.
              </p>
              <div style={{ display: "flex", gap: 14, marginTop: 32, flexWrap: "wrap" }}>
                <a href="#residences" className={tweaks.colorTheme === "navy" ? "btn btn-ghost" : "btn btn-outline"}
                onClick={(e) => {e.preventDefault();navTo("residences");}}>
                  View Residences <IconArrow size={14} />
                </a>
                <a href="#contact" className="btn btn-primary"
                onClick={(e) => {e.preventDefault();openTour();}}>
                  Schedule a Tour
                </a>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, position: "relative" }}>
              <Stat num="47" lbl="Residences" sub="1BR | 1BR + Den | 2BR layouts" theme={tweaks.colorTheme} />
              <Stat num="12" lbl="Stories" sub="Ocean views from 4+" theme={tweaks.colorTheme} />
              <Stat num="1984" lbl="Original Build" sub="Designed for the shore; views galore" theme={tweaks.colorTheme} />
              <Stat num="2026" lbl="Renovated" sub="Top to bottom" theme={tweaks.colorTheme} />
            </div>
          </div>
        </div>
      </section>

      {/* AMENITIES STRIP */}
      <section className="section bg-linen">
        <div className="shell">
          <SectionHead
            eyebrow="Amenities & Resident Services"
            title="Designed for comfort. Built for everyday living."
            lede="From rooftop fitness to indoor pickleball, every amenity at Boardwalk House is designed to make your day easier and more enjoyable." />
          
          <div className="card-grid cols-4" style={{ background: "#fff", border: "1px solid rgba(13,27,42,0.08)" }}>
            {AMENITIES.slice(0, 4).map((a) => {
              const Ico = ICON_BY_NAME[a.icon] || IconWaves;
              return (
                <div className="amenity" key={a.label}>
                  <Ico size={42} />
                  <div className="lbl">{a.label}</div>
                  <div className="desc">{a.desc}</div>
                </div>);

            })}
          </div>
          <div className="card-grid cols-4" style={{ background: "#fff", borderLeft: "1px solid rgba(13,27,42,0.08)", borderRight: "1px solid rgba(13,27,42,0.08)", borderBottom: "1px solid rgba(13,27,42,0.08)" }}>
            {AMENITIES.slice(4, 8).map((a) => {
              const Ico = ICON_BY_NAME[a.icon] || IconWaves;
              return (
                <div className="amenity" key={a.label}>
                  <Ico size={42} />
                  <div className="lbl">{a.label}</div>
                  <div className="desc">{a.desc}</div>
                </div>);

            })}
          </div>
          <div className="center mt-7">
            <a href="#amenities" className="btn btn-outline" onClick={(e) => {e.preventDefault();navTo("amenities");}}>
              Explore All Amenities <IconArrow size={14} />
            </a>
          </div>
        </div>
      </section>

      <BrandStrip items={["Oceanfront Access", "Direct Boardwalk Entry", "The beach is your backyard"]} />

      {/* RESIDENCES TEASER */}
      <section className="section bg-cream">
        <div className="shell">
          <SectionHead
            eyebrow="The Residences"
            title="One and two bedrooms — fully renovated for 2026." />
          
          <div className="card-grid cols-3" data-comment-anchor="abd7cdbd36-div-129-11">
            {["1br", "1br_den", "2br"].map((t) => {
              const units = UNITS.filter((u) => u.type === t);
              const min = Math.min(...units.map((u) => u.rent));
              const max = Math.min(...units.map((u) => u.sqft));
              const maxSqft = Math.max(...units.map((u) => u.sqft));
              const minSqft = Math.min(...units.map((u) => u.sqft));
              const available = units.filter((u) => u.status === "available").length;
              return (
                <article key={t} style={{ background: "#fff", border: "1px solid rgba(13,27,42,0.08)" }}>
                  <div style={{
                    aspectRatio: "4/3",
                    background: "var(--linen)",
                    backgroundImage: `url(${TEASER_FP[t]})`,
                    backgroundSize: "contain",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "center",
                    borderBottom: "1px solid rgba(13,27,42,0.08)"
                  }} role="img" aria-label={`${TYPE_META[t].label} sample floor plan`} />
                  <div style={{ padding: "var(--space-5) var(--space-5) var(--space-6)" }}>
                    <div className="eyebrow" style={{ display: "block" }}>{TYPE_META[t].label}</div>
                    <div className="serif" style={{ fontSize: 32, marginTop: 6 }}>
                      ${min.toLocaleString()}<span style={{ fontSize: 14, color: "var(--muted)" }}>/mo+</span>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>
                      {minSqft === maxSqft ? `${minSqft} sq ft` : `${minSqft}–${maxSqft} sq ft`} · {units.length} residences
                    </div>
                    <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 18, paddingTop: 16, borderTop: "1px solid rgba(13,27,42,0.08)" }}>
                      <span style={{ fontSize: 11, color: "#1f7a4d", fontWeight: 600, letterSpacing: "0.06em" }}>
                        ● {available} available
                      </span>
                      <a href="#residences" onClick={(e) => {e.preventDefault();navTo("residences");}}
                      style={{ marginLeft: "auto", textDecoration: "none", display: "flex", alignItems: "center", gap: 6, color: "var(--bronze)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 600 }}>
                        View <IconArrow size={12} />
                      </a>
                    </div>
                  </div>
                </article>);

            })}
          </div>
        </div>
      </section>

      {/* LOCATION TEASER */}
      <section className="section bg-navy">
        <div className="shell">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-8)", alignItems: "center" }} className="intro-grid">
            <div>
              <span className="eyebrow on-dark">The Location</span>
              <h2 style={{ marginTop: 14, color: "var(--linen-2)" }}>Right where you want to be.</h2>
              <WaveDivider onDark />
              <p className="lede" style={{ marginTop: 20, color: "rgba(245,242,237,0.82)" }}>
                Directly on the boardwalk in the heart of Atlantic City. Steps to the beach.
                Minutes to world-class casinos, restaurants, shopping, and entertainment.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "grid", gap: 12 }}>
                {["Direct Boardwalk access", "Steps to the Atlantic", "Easy access to transit & major routes", "Walk to dining, casinos, shops"].map((t) =>
                <li key={t} style={{ display: "flex", gap: 12, alignItems: "center", color: "rgba(245,242,237,0.82)", fontSize: 14 }}>
                    <IconCheck size={16} style={{ color: "var(--bronze-soft)" }} /> {t}
                  </li>
                )}
              </ul>
              <a href="#location" className="btn btn-ghost mt-7" onClick={(e) => {e.preventDefault();navTo("location");}}>
                Explore the Neighborhood <IconArrow size={14} />
              </a>
            </div>
            <div style={{
              aspectRatio: "5/4",
              backgroundImage: "url(images/aerial-2.jpeg)",
              backgroundSize: "cover",
              backgroundPosition: "center",
              border: "1px solid rgba(245,242,237,0.18)"
            }} />
          </div>
        </div>
      </section>

      {/* WAITLIST */}
      <WaitlistBand />

      <BrandStrip />
    </div>);

}

function Stat({ num, lbl, sub, theme }) {
  const dark = theme === "navy";
  return (
    <div style={{
      padding: "32px 28px",
      background: dark ? "rgba(245,242,237,0.04)" : "rgba(139,111,77,0.07)",
      border: dark ? "1px solid rgba(245,242,237,0.14)" : "1px solid rgba(139,111,77,0.18)"
    }}>
      <div style={{ fontFamily: "var(--serif)", fontSize: 56, lineHeight: 1, color: dark ? "var(--bronze-soft)" : "var(--bronze)", fontWeight: 500 }}>
        {num}
      </div>
      <div style={{
        fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 600,
        color: dark ? "var(--linen-2)" : "var(--navy)",
        marginTop: 12
      }}>{lbl}</div>
      <div style={{ fontSize: 12, color: dark ? "rgba(245,242,237,0.65)" : "var(--muted)", marginTop: 4 }}>{sub}</div>
    </div>);

}

// =====================================================
// HERO (3 variants)
// =====================================================
function Hero({ variant, headline, photo, openTour, navTo }) {
  const titleLines = headline.title.split("\n");

  if (variant === "split") {
    return (
      <section className="hero variant-split">
        <div className="hero-inner">
          <span className="eyebrow">Atlantic City · Oceanfront Apartments</span>
          <h1 style={{ marginTop: 18 }}>
            {titleLines.map((l, i) => <React.Fragment key={i}>{l}{i < titleLines.length - 1 && <br />}</React.Fragment>)}
          </h1>
          <WaveDivider />
          <p className="lede" style={{ marginTop: 18 }}>{headline.lede}</p>
          <div className="hero-cta">
            <button className="btn btn-primary btn-lg" onClick={openTour}>Schedule a Tour</button>
            <button className="btn btn-outline btn-lg" onClick={() => navTo("residences")}>View Floor Plans</button>
          </div>
          <HeroFeats variant={variant} />
        </div>
        <div className="hero-photo" style={{ backgroundImage: `url(${photo})` }} />
      </section>);

  }

  if (variant === "card") {
    return (
      <section className="hero variant-card">
        <div className="hero-photo" style={{ backgroundImage: `url(${photo})` }} />
        <div className="hero-overlay-grad" />
        <div className="hero-inner">
          <div className="glass">
            <span className="eyebrow on-dark">Pre-Leasing · Summer 2026</span>
            <h1 style={{ marginTop: 18 }}>
              {titleLines.map((l, i) => <React.Fragment key={i}>{l}{i < titleLines.length - 1 && <br />}</React.Fragment>)}
            </h1>
            <WaveDivider onDark />
            <p className="lede" style={{ marginTop: 18, color: "rgba(245,242,237,0.86)" }}>{headline.lede}</p>
            <div className="hero-cta">
              <button className="btn btn-primary btn-lg" onClick={openTour}>Schedule a Tour</button>
              <button className="btn btn-ghost btn-lg" onClick={() => navTo("residences")}>View Floor Plans</button>
            </div>
          </div>
        </div>
      </section>);

  }

  // Default: full-bleed photo with overlay headline
  return (
    <section className="hero">
      <div className="hero-photo" style={{ backgroundImage: `url(${photo})` }} />
      <div className="hero-overlay-grad" />
      <div className="hero-inner">
        <span className="eyebrow on-dark">Atlantic City · Oceanfront Apartments</span>
        <h1 style={{ marginTop: 18 }}>
          {titleLines.map((l, i) => <React.Fragment key={i}>{l}{i < titleLines.length - 1 && <br />}</React.Fragment>)}
        </h1>
        <WaveDivider onDark />
        <p className="lede" style={{ marginTop: 18 }}>{headline.lede}</p>
        <div className="hero-cta">
          <button className="btn btn-primary btn-lg" onClick={openTour}>Schedule a Tour</button>
          <button className="btn btn-ghost btn-lg" onClick={() => navTo("residences")}>View Floor Plans</button>
        </div>
        <HeroFeats variant={variant} />
      </div>
    </section>);

}

function HeroFeats({ variant }) {
  return (
    <div className="hero-feats">
      <div className="hero-feat">
        <IconSunrise size={28} className="ico" />
        <div>
          <div className="lbl">Oceanfront</div>
          <div className="sub">Views from every apartment</div>
        </div>
      </div>
      <div className="hero-feat">
        <IconColumn size={28} className="ico" />
        <div>
          <div className="lbl">Renovated 2026</div>
          <div className="sub">Modern comfort, timeless design</div>
        </div>
      </div>
      <div className="hero-feat">
        <IconAnchor size={28} className="ico" />
        <div>
          <div className="lbl">On the Boardwalk</div>
          <div className="sub">190 S Kentucky Ave</div>
        </div>
      </div>
    </div>);

}

function WaitlistBand() {
  const [email, setEmail] = useStateHome("");
  const [done, setDone] = useStateHome(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!email.includes("@")) return;
    try {
      await window.submitForm({
        subject: "[Boardwalk House] Waitlist signup — homepage",
        formType: "waitlist",
        source: "home_band",
        email,
      });
    } catch (_) { /* silent — UI still confirms */ }
    setDone(true);
    setEmail("");
    setTimeout(() => setDone(false), 4000);
  };
  return (
    <section className="waitlist-band">
      <div className="shell center">
        <span className="eyebrow on-dark">Pre-Leasing · Summer 2026</span>
        <h2 style={{ marginTop: 14, color: "var(--linen-2)", fontSize: "clamp(36px, 4vw, 56px)" }}>
          Be first through the door.
        </h2>
        <WaveDivider onDark />
        <p className="lede" style={{ margin: "20px auto 0", color: "rgba(245,242,237,0.82)", textAlign: "center" }}>
          Join the waitlist for priority tours, early floor plan access, and our launch incentives.
        </p>
        <form onSubmit={submit} className="waitlist-form">
          <input type="email" placeholder="your@email.com" required
          value={email} onChange={(e) => setEmail(e.target.value)} />
          <button className="btn btn-primary" type="submit">
            {done ? "✓ You're on the list" : "Join Waitlist"}
          </button>
        </form>
        <p style={{ fontSize: 11, color: "rgba(245,242,237,0.5)", marginTop: 14, letterSpacing: "0.06em" }}>
          We respect your inbox. Unsubscribe any time.
        </p>
      </div>
    </section>);

}

Object.assign(window, { HomePage, Hero, WaitlistBand, ICON_BY_NAME });