/* global React, BrandStrip, SectionHead, PageHero, WaveDivider, ICON_BY_NAME,
   IconBed, IconWaves, IconArrow, IconCheck, IconColumn, IconShield, IconAnchor,
   IconSunrise, IconCalendar, AMENITIES, UNITS, TYPE_META */

const { useState: useStateRes, useMemo: useMemoRes } = React;

// Existing preliminary floor plan PNG exports — keyed by layout code.
// Final dimensions confirmed at lease signing.
const FP_IMAGES = {
  "A-01": "images/floor-plans/boardwalk-house-single-401-floorplan-local.png",
  "A-02": "images/floor-plans/boardwalk-house-single-402-floorplan-local.png",
  "A-03": "images/floor-plans/boardwalk-house-single-403-floorplan-local.png",
  "A-04": "images/floor-plans/boardwalk-house-single-404-floorplan-local.png",
  "A-05": "images/floor-plans/boardwalk-house-double-405-floorplan-local.png",
  "A-06": "images/floor-plans/boardwalk-house-single-406-floorplan-local.png",
  "A-07": "images/floor-plans/boardwalk-house-single-407-floorplan-local.png",
  "PH-1": "images/floor-plans/boardwalk-house-floor10-ph-1-double-floorplan-local.png",
  "PH-2": "images/floor-plans/boardwalk-house-floor10-ph-2-double-floorplan-local.png",
  "PH-3": "images/floor-plans/boardwalk-house-floor10-ph-3-double-floorplan-local.png",
  "PH-4": "images/floor-plans/boardwalk-house-floor10-ph-4-double-floorplan-local.png",
  "PH-5": "images/floor-plans/boardwalk-house-floor10-ph-5-single-floorplan-local.png",
};

// =====================================================
// RESIDENCES PAGE
// =====================================================
function ResidencesPage({ openTour, openApply }) {
  const [activeType, setActiveType] = useStateRes("1br");
  const [selectedUnitId, setSelectedUnitId] = useStateRes(null);

  const units = useMemoRes(
    () => UNITS.filter((u) => u.type === activeType),
    [activeType]
  );

  // First available unit selected by default per type
  const selectedUnit = useMemoRes(() => {
    if (selectedUnitId) {
      const found = units.find((u) => u.unit === selectedUnitId);
      if (found) return found;
    }
    return units.find((u) => u.status === "available") || units[0];
  }, [selectedUnitId, units]);

  const totalAvailable = UNITS.filter((u) => u.status === "available").length;
  const typeAvailable = units.filter((u) => u.status === "available").length;

  return (
    <div>
      <PageHero
        eyebrow="The Residences"
        title="Availability & Floor Plans"
        lede="One bedroom, one bedroom + den, and two bedroom residences — fully renovated for 2026. Ocean views from floor four and above, plus five top-floor penthouses."
        photoUrl="images/aerial-1.jpeg"
      />

      <section className="section bg-cream">
        <div className="shell">
          {/* Availability counter strip */}
          <div style={{
            display: "flex", alignItems: "center", gap: "var(--space-6)", flexWrap: "wrap",
            paddingBottom: "var(--space-6)", marginBottom: "var(--space-6)",
            borderBottom: "1px solid rgba(13,27,42,0.08)"
          }}>
            <div className="avail-counter">
              <span className="num">{totalAvailable}</span>
              <span className="lbl">of 47 residences available</span>
            </div>
            <p style={{ fontSize: 13, color: "var(--muted)", margin: 0, maxWidth: 460 }}>
              Live availability updates daily. Reserve a unit by joining the waitlist or scheduling a tour —
              available residences move fast as our Summer 2026 opening approaches.
            </p>
          </div>

          {/* Type tabs */}
          <div className="fp-tabs">
            {["1br", "1br_den", "2br"].map((t) => {
              const count = UNITS.filter((u) => u.type === t).length;
              return (
                <button
                  key={t}
                  className={"fp-tab" + (activeType === t ? " active" : "")}
                  onClick={() => { setActiveType(t); setSelectedUnitId(null); }}>
                  <IconBed size={18} className="ico" />
                  {TYPE_META[t].label} <span style={{ opacity: 0.6, marginLeft: 6 }}>({count})</span>
                </button>
              );
            })}
          </div>

          {/* Two-column unit list + diagram */}
          <div style={{
            display: "grid",
            gridTemplateColumns: "1.3fr 1fr",
            gap: "var(--space-7)",
            paddingTop: "var(--space-5)"
          }} className="res-grid">
            <div>
              <h3 style={{ fontSize: 28, marginBottom: 6 }}>{TYPE_META[activeType].label} Availability</h3>
              <p style={{ color: "var(--muted)", fontSize: 14, marginBottom: 24 }}>
                {typeAvailable} of {units.length} available · ocean living in a space that fits your lifestyle.
              </p>
              <table className="unit-table">
                <thead>
                  <tr>
                    <th>Unit</th>
                    <th>Floor</th>
                    <th>Layout</th>
                    <th>Balcony</th>
                    <th>Sq Ft</th>
                    <th>Status</th>
                    <th style={{ textAlign: "right" }}>Est. Rent*</th>
                  </tr>
                </thead>
                <tbody>
                  {units.map((u) => (
                    <tr key={u.unit}
                        className={"unit-row" + (selectedUnit && selectedUnit.unit === u.unit ? " selected" : "")}
                        onClick={() => setSelectedUnitId(u.unit)}>
                      <td><strong>{u.unit}</strong></td>
                      <td>{u.floor}{u.ph ? " · PH" : ""}</td>
                      <td>{u.layout}</td>
                      <td>{u.balcony ? "Yes" : "\u2014"}</td>
                      <td>{u.sqft.toLocaleString()}</td>
                      <td>
                        <span className={"status-pill " + (u.status === "available" ? "" : u.status === "waitlist" ? "waitlist" : "leased")}>
                          {u.status === "available" ? "● Available" : u.status === "waitlist" ? "● Waitlist" : "○ Leased"}
                        </span>
                      </td>
                      <td style={{ textAlign: "right", fontWeight: 600 }}>
                        ${u.rent.toLocaleString()}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{
                marginTop: 24, padding: "14px 18px",
                background: "rgba(125,143,161,0.1)",
                border: "1px solid rgba(125,143,161,0.25)",
                fontSize: 12.5, color: "var(--muted)",
                display: "flex", gap: 10, alignItems: "flex-start"
              }}>
                <IconCalendar size={16} style={{ color: "var(--bronze)", flexShrink: 0, marginTop: 2 }} />
                <span>Units update daily. Rent shown is the estimated launch rate; final pricing is confirmed at lease signing. Contact our leasing team for current incentives.</span>
              </div>
            </div>

            {/* Detail panel */}
            <div style={{ position: "sticky", top: 100, alignSelf: "start" }}>
              {selectedUnit && (
                <article style={{ background: "#fff", border: "1px solid rgba(13,27,42,0.08)", padding: "var(--space-6)" }}>
                  <span className="eyebrow" style={{ display: "block" }}>{TYPE_META[selectedUnit.type].label}</span>
                  <h3 style={{ marginTop: 6, fontSize: 28 }}>Unit {selectedUnit.unit}</h3>
                  <div style={{ fontSize: 12.5, letterSpacing: "0.06em", color: "var(--muted)", marginTop: 6 }}>
                    {selectedUnit.layout} ·
                    {" "}{selectedUnit.beds === 1.5 ? "1 Bed + Den" : `${selectedUnit.beds} Bed`} ·
                    {" "}{selectedUnit.baths} Bath ·
                    {" "}{selectedUnit.sqft.toLocaleString()} sq ft ·
                    {" "}Floor {selectedUnit.floor}{selectedUnit.ph ? " (Penthouse)" : ""}
                  </div>

                  {/* Floor plan diagram (preliminary export) */}
                  {FP_IMAGES[selectedUnit.layout] ? (
                    <div className="fp-diagram" style={{
                      margin: "20px 0", aspectRatio: "5/4",
                      background: "var(--linen)",
                      border: "1px solid rgba(13,27,42,0.1)",
                      backgroundImage: `url(${FP_IMAGES[selectedUnit.layout]})`,
                      backgroundSize: "contain",
                      backgroundRepeat: "no-repeat",
                      backgroundPosition: "center"
                    }} role="img" aria-label={`Unit ${selectedUnit.unit} floor plan`} />
                  ) : (
                    <div className="placeholder fp-diagram" style={{ margin: "20px 0", aspectRatio: "5/4" }}>
                      <div className="ph-tag">UNIT {selectedUnit.unit} · FLOOR PLAN</div>
                    </div>
                  )}

                  <h4 style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--navy)", fontWeight: 600, marginBottom: 14 }}>
                    Features
                  </h4>
                  <ul className="fp-feature-list">
                    <li><IconWaves className="ico" /> {selectedUnit.view}</li>
                    <li><IconColumn className="ico" /> Floor-to-ceiling windows</li>
                    <li><IconAnchor className="ico" /> Fully renovated 2026</li>
                    <li><IconCheck className="ico" /> Stainless appliances · Quartz counters</li>
                    {selectedUnit.balcony && <li><IconCheck className="ico" /> Private balcony</li>}
                    <li><IconCheck className="ico" /> In-unit washer & dryer</li>
                    <li><IconCheck className="ico" /> Central air conditioning</li>
                    {selectedUnit.ph && <li><IconCheck className="ico" /> Top-floor penthouse residence</li>}
                  </ul>

                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 24, paddingTop: 20, borderTop: "1px solid rgba(13,27,42,0.08)" }}>
                    <div>
                      <div className="eyebrow" style={{ fontSize: 10 }}>Est. Rent*</div>
                      <div className="serif" style={{ fontSize: 36, color: "var(--navy)", fontWeight: 600 }}>
                        ${selectedUnit.rent.toLocaleString()}<span style={{ fontSize: 14, color: "var(--muted)", fontFamily: "var(--sans)", fontWeight: 400 }}>/mo</span>
                      </div>
                    </div>
                  </div>
                  <div style={{ display: "grid", gap: 10, marginTop: 18 }}>
                    {selectedUnit.status === "available" ? (
                      <>
                        <button className="btn btn-navy" onClick={openTour}>Schedule a Tour</button>
                        <button className="btn btn-bronze-outline" onClick={openApply}>Apply Now</button>
                      </>
                    ) : selectedUnit.status === "waitlist" ? (
                      <button className="btn btn-primary" onClick={openTour}>Join Waitlist for {selectedUnit.unit}</button>
                    ) : (
                      <button className="btn btn-outline" disabled style={{ opacity: 0.5 }}>Leased — See similar units</button>
                    )}
                  </div>
                </article>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Resident benefits row */}
      <section className="section-tight bg-linen">
        <div className="shell">
          <div className="card-grid cols-4" style={{ gap: 0 }}>
            {[
              { ico: IconWaves, lbl: "Oceanfront Living", sub: "Steps from beach and Boardwalk." },
              { ico: IconColumn, lbl: "Timeless Architecture", sub: "Classic design with modern comfort." },
              { ico: IconShield, lbl: "Security & Service", sub: "Attentive on-site management." },
              { ico: IconAnchor, lbl: "Anchor Stability", sub: "Built on a legacy of quality." },
            ].map((it) => (
              <div className="amenity" key={it.lbl}>
                <it.ico size={36} />
                <div className="lbl">{it.lbl}</div>
                <div className="desc">{it.sub}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <BrandStrip />
    </div>
  );
}

// =====================================================
// AMENITIES PAGE
// =====================================================
function AmenitiesPage({ openTour, navTo }) {
  return (
    <div>
      <PageHero
        eyebrow="Amenities & Resident Services"
        title="Designed for comfort.\nBuilt for everyday living."
        photoUrl="images/aerial-1.jpeg"
      />

      <section className="section bg-cream">
        <div className="shell">
          <SectionHead
            eyebrow="Resident Privileges"
            title="Every detail considered."
            lede="From a rooftop fitness center to indoor pickleball, secure parking with a car elevator, and pet-friendly policies — our amenities are designed for the way you actually live."
          />

          <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 0, border: "1px solid rgba(13,27,42,0.08)", background: "#fff" }} className="amenities-grid">
            {AMENITIES.map((a, i) => {
              const Ico = ICON_BY_NAME[a.icon] || IconWaves;
              return (
                <div key={a.label}
                     style={{
                       display: "grid",
                       gridTemplateColumns: "auto 1fr",
                       gap: 24,
                       padding: 36,
                       borderRight: i % 2 === 0 ? "1px solid rgba(13,27,42,0.08)" : "none",
                       borderBottom: i < AMENITIES.length - 2 ? "1px solid rgba(13,27,42,0.08)" : "none"
                     }}>
                  <div style={{
                    width: 64, height: 64,
                    border: "1px solid var(--bronze)",
                    color: "var(--bronze)",
                    display: "grid", placeItems: "center",
                    flexShrink: 0
                  }}>
                    <Ico size={32} />
                  </div>
                  <div>
                    <h3 style={{ fontSize: 22, color: "var(--navy)", marginBottom: 8 }}>{a.label}</h3>
                    <p style={{ fontSize: 14, color: "var(--muted)", lineHeight: 1.6, margin: 0 }}>{a.desc}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Rooftop feature */}
      <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 className="placeholder dark" style={{ aspectRatio: "5/4" }}>
              <div className="ph-tag">ROOFTOP FITNESS · OCEAN-VIEW</div>
            </div>
            <div>
              <span className="eyebrow on-dark">Top of the House</span>
              <h2 style={{ marginTop: 14, color: "var(--linen-2)" }}>A rooftop made for residents.</h2>
              <WaveDivider onDark />
              <p className="lede" style={{ marginTop: 20, color: "rgba(245,242,237,0.82)" }}>
                The full top floor is yours. A modern fitness center looks out across the Atlantic.
                A year-round indoor pickleball court means no rain delays, no wait lists, no club fees.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "grid", gap: 12 }}>
                {[
                  "Cardio & strength equipment with ocean views",
                  "Year-round indoor pickleball court",
                  "Yoga and stretching area",
                  "Resident-only access · Open 5am – 11pm"
                ].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>
            </div>
          </div>
        </div>
      </section>

      {/* Parking feature */}
      <section className="section bg-cream">
        <div className="shell">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-8)", alignItems: "center" }} className="intro-grid">
            <div>
              <span className="eyebrow">Parking & Transit</span>
              <h2 style={{ marginTop: 14 }}>Three stories of secure parking.</h2>
              <WaveDivider />
              <p className="lede" style={{ marginTop: 20 }}>
                A dedicated three-story garage with a car elevator means your space is reserved,
                covered, and steps from your door — a rarity on the boardwalk.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "grid", gap: 12 }}>
                {[
                  "Reserved resident spaces",
                  "Three-story secure garage with car elevator",
                  "Indoor bike storage on the ground floor",
                  "Easy access to NJ Transit and the Atlantic City Expressway"
                ].map((t) => (
                  <li key={t} style={{ display: "flex", gap: 12, alignItems: "center", fontSize: 14 }}>
                    <IconCheck size={16} style={{ color: "var(--bronze)" }} /> {t}
                  </li>
                ))}
              </ul>
            </div>
            <div className="placeholder" style={{ aspectRatio: "5/4" }}>
              <div className="ph-tag">PARKING GARAGE · CAR ELEVATOR</div>
            </div>
          </div>
        </div>
      </section>

      <BrandStrip />
    </div>
  );
}

Object.assign(window, { ResidencesPage, AmenitiesPage });
