/* global React, ReactDOM, MP_CONTENT, MP_FLOORS, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, TweakColor */

const { useState, useEffect, useRef, useMemo } = React;

// Real images
const HERO_IMG = "img/hero-night.png";
const BEFORE_IMG = "img/office-before.jpg";
const AFTER_IMG = "img/office-after.png";
const G_PARKING = "img/g-parking.jpg";
const G_TOWER_DAY = "img/g-tower-day.jpg";
const G_LOBBY_CORRIDOR = "img/g-lobby-corridor.jpg";
const G_LOBBY_MAIN = "img/g-lobby-main.jpg";
const G_ELEV_BANK = "img/g-elev-bank.jpg";
const G_ELEV_HALL = "img/g-elev-hall.jpg";
const G_VIEW_CANO = "img/g-view-cano.jpg";

// Google Street View panorama (provided by user)
const SV_EMBED = "https://www.google.com/maps/embed?pb=!4v1748400000000!6m8!1m7!1sjH93p3IlZ4V3pOIjk08YGQ!2m2!1d18.4076!2d-66.0707!3f277.16983!4f0!5f0.7820865974627469";
const SV_LINK = "https://www.google.com/maps/@18.4076,-66.0707,3a,75y,277.16983h,90t/data=!3m6!1e1!3m4!1sjH93p3IlZ4V3pOIjk08YGQ!2e0!7i16384!8i8192";

// ====================================================
// Top Bar
// ====================================================
function TopBar({ lang, setLang, t, onBook }) {
  return (
    <header className="topbar">
      <div className="wrap topbar-inner">
        <a href="#top" className="brand">
          <img className="brand-img brand-img-dark" src="img/logo-dark.png" alt="Mercantil Plaza" />
          <img className="brand-img brand-img-light" src="img/logo-light.png" alt="Mercantil Plaza" />
        </a>
        <nav className="nav">
          <a href="#spaces">{t.nav.spaces}</a>
          <a href="#building">{t.nav.building}</a>
          <a href="#location">{t.nav.location}</a>
          <a href="#gallery">{t.nav.gallery}</a>
          <a href="#contact">{t.nav.contact}</a>
        </nav>
        <div className="topright">
          <div className="langswitch" role="group" aria-label="Language">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "es" ? "on" : ""} onClick={() => setLang("es")}>ES</button>
          </div>
          <button className="cta accent" onClick={onBook}>
            <span>{t.nav.book}</span>
            <span className="arrow" aria-hidden="true"></span>
          </button>
        </div>
      </div>
    </header>
  );
}

// ====================================================
// Hero (3 variants)
// ====================================================
function Hero({ t, variant, onBook }) {
  const now = new Date();
  const time = now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
  return (
    <section id="top" className="hero">
      <div className="wrap">
        <div className="hero-eyebrow">
          <span className="blink">{t.hero.eyebrow}</span>
          <span>18.4076° N · 66.0707° W · AST {time}</span>
        </div>

        <div className="hero-inner" data-variant={variant}>
          {variant === "tower" && (
            <>
              <h1 className="hero-title">
                <span className="row">{t.hero.title1}</span>
                <span className="row stretch italic">{t.hero.title2}</span>
              </h1>
              <div className="hero-image color">
                <img src={HERO_IMG} alt="Mercantil Plaza at night" />
                <div className="tag">Hato Rey · Milla de Oro · 2026</div>
                <div className="corner">
                  <div className="lat">18.4076° N</div>
                  <div className="lat">66.0707° W</div>
                </div>
              </div>
              <div className="hero-foot">
                <div>
                  <p className="hero-sub">{t.hero.sub}</p>
                  <div className="hero-ctas">
                    <button className="cta accent" onClick={onBook}>
                      {t.hero.cta1} <span className="arrow"></span>
                    </button>
                    <a className="cta ghost" href="#spaces">
                      {t.hero.cta2} <span className="arrow"></span>
                    </a>
                  </div>
                </div>
                <div className="hero-meta">
                  <div className="row"><span>Address</span><strong>2 Av. Ponce de León</strong></div>
                  <div className="row"><span>District</span><strong>Hato Rey · 00918</strong></div>
                  <div className="row"><span>Status</span><strong>Now Leasing</strong></div>
                  <div className="row"><span>Established</span><strong>{t.hero.tag.split("·")[0]}</strong></div>
                </div>
              </div>
            </>
          )}

          {variant === "grid" && (
            <>
              <div className="cell-title">
                <h1 className="hero-title">
                  <span className="row">{t.hero.title1}</span>
                  <span className="row italic stretch">{t.hero.title2}</span>
                </h1>
              </div>
              <div className="cell-img hero-image color">
                <img src={HERO_IMG} alt="Mercantil Plaza at night" />
                <div className="tag">15 floors · 1974</div>
              </div>
              <div className="cell-sub">
                <p className="hero-sub">{t.hero.sub}</p>
                <div className="hero-ctas">
                  <button className="cta accent" onClick={onBook}>
                    {t.hero.cta1} <span className="arrow"></span>
                  </button>
                  <a className="cta ghost" href="#spaces">{t.hero.cta2} <span className="arrow"></span></a>
                </div>
              </div>
              <div className="cell-meta">
                <div className="hero-meta">
                  <div className="row"><span>Address</span><strong>2 Av. Ponce de León</strong></div>
                  <div className="row"><span>District</span><strong>Hato Rey</strong></div>
                  <div className="row"><span>Status</span><strong>Now Leasing</strong></div>
                </div>
              </div>
            </>
          )}

          {variant === "marquee" && (
            <>
              <div>
                <h1 className="hero-title" style={{ fontSize: "clamp(72px, 22vw, 360px)" }}>
                  <span className="row stretch italic">{t.hero.title1} {t.hero.title2}</span>
                </h1>
                <div className="hero-subgrid">
                  <p className="hero-sub">{t.hero.sub}</p>
                  <div className="hero-meta">
                    <div className="row"><span>Address</span><strong>2 Av. Ponce de León</strong></div>
                    <div className="row"><span>District</span><strong>Hato Rey · 00918</strong></div>
                    <div className="row"><span>Status</span><strong>Now Leasing</strong></div>
                  </div>
                </div>
                <div className="hero-ctas">
                  <button className="cta accent" onClick={onBook}>{t.hero.cta1} <span className="arrow"></span></button>
                  <a className="cta ghost" href="#spaces">{t.hero.cta2} <span className="arrow"></span></a>
                </div>
                <div className="hero-image color" style={{ marginTop: 32, aspectRatio: "21/9" }}>
                  <img src={HERO_IMG} alt="Mercantil Plaza at night" />
                  <div className="tag">Tower elevation</div>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Ticker band
// ====================================================
function Ticker({ items }) {
  const content = items.concat(items).map((s, i) => <span key={i}>{s}</span>);
  return (
    <div className="tickerband" aria-hidden="true">
      <div className="track">{content}</div>
    </div>
  );
}

// ====================================================
// Pitch
// ====================================================
function Pitch({ t }) {
  return (
    <section className="pitch">
      <div className="wrap">
        <div className="pitch-inner">
          <div>
            <div className="eyebrow">{t.pitch.eyebrow}</div>
            <div className="pitch-lede reveal">
              {t.pitch.lede.split(" ").map((w, i, arr) =>
                i === arr.length - 1
                  ? <span key={i} className="italic">{w}</span>
                  : <span key={i}>{w} </span>
              )}
            </div>
          </div>
          <div className="pitch-body">
            <p className="reveal">{t.pitch.body}</p>
            <p className="reveal">{t.pitch.body2}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Stats
// ====================================================
function Stats({ t }) {
  return (
    <section className="section" id="building">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.stats.eyebrow}</div>
          </div>
          <h2 className="h2">{t.stats.title.split(" ").slice(0, -1).join(" ")} <span className="serif" style={{ fontStyle: "italic" }}>{t.stats.title.split(" ").slice(-1)}</span></h2>
          <div className="aside">{t.stats.aside}</div>
        </div>
        <div className="stats-grid">
          {t.stats.items.map((s, i) => (
            <div className="stat reveal" key={i} style={{ transitionDelay: `${i * 60}ms` }}>
              <span className="ord">0{i + 1}</span>
              <div className="n">{s.n}</div>
              <div className="label">{s.label}</div>
              <div className="sub">{s.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Location diagram
// ====================================================
function LocationSection({ t }) {
  // Position landmarks around a center with hand-tuned coords
  const positions = [
    { x: 50, y: 18 },   // N - Popular Corp
    { x: 78, y: 28 },   // NE - ORO
    { x: 22, y: 42 },   // W - Banco Popular
    { x: 52, y: 84 },   // S - Tren Urbano
    { x: 80, y: 60 },   // E - Cano
    { x: 18, y: 78 },   // SW - Plaza Las Americas
    { x: 88, y: 14 },   // NE - SJU
    { x: 12, y: 22 },   // N - Old SJ
  ];
  return (
    <section className="section" id="location">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.location.eyebrow}</div>
          </div>
          <h2 className="h2">{t.location.title.split(" ").slice(0, -1).join(" ")} <span className="serif" style={{ fontStyle: "italic" }}>{t.location.title.split(" ").slice(-1)}</span></h2>
          <div className="aside">{t.location.body}</div>
        </div>

        <div className="loc-grid">
          <div className="loc-canvas">
            <div className="grid-overlay" />
            <div className="compass">N ↑</div>
            {/* rays */}
            {positions.map((p, i) => {
              const dx = p.x - 50;
              const dy = p.y - 50;
              const len = Math.sqrt(dx * dx + dy * dy);
              const angle = Math.atan2(dy, dx) * 180 / Math.PI;
              return (
                <div
                  key={i}
                  className="ray"
                  style={{
                    width: `${len}%`,
                    transform: `rotate(${angle}deg)`,
                  }}
                />
              );
            })}
            {/* center */}
            <div className="label-mp">
              <div className="dot" />
              <div className="name">Mercantil Plaza</div>
              <div className="mono" style={{ marginTop: 4 }}>You are here</div>
            </div>
            {/* pins */}
            {positions.map((p, i) => (
              <div key={i} className="pin" style={{ left: `${p.x}%`, top: `${p.y}%` }}>
                <div className="marker" />
                <div className="pname">{t.location.landmarks[i].name}</div>
                <div className="pdist">{t.location.landmarks[i].dist} · {t.location.landmarks[i].dir}</div>
              </div>
            ))}
          </div>

          <div className="loc-list">
            {t.location.landmarks.map((l, i) => (
              <div className="row" key={i}>
                <span className="ord">{String(i + 1).padStart(2, "0")}</span>
                <span className="nm">{l.name}</span>
                <span className="dm">{l.dist} · {l.dir}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Street View (Google Maps 360)
// ====================================================
function StreetView({ t }) {
  return (
    <section className="section" id="streetview">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.streetview.eyebrow}</div>
          </div>
          <h2 className="h2">{t.streetview.title.split(" ")[0]} <span className="serif" style={{ fontStyle: "italic" }}>{t.streetview.title.split(" ").slice(1).join(" ")}</span></h2>
          <div className="aside">{t.streetview.body}</div>
        </div>
        <div className="sv-frame">
          <div className="sv-corner">Live · 360°</div>
          <iframe
            src={SV_EMBED}
            title="Mercantil Plaza 360° street view"
            allow="accelerometer; gyroscope"
            allowFullScreen
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
          />
        </div>
        <div className="sv-meta">
          <span>Drag · pinch · double-tap</span>
          <a href={SV_LINK} target="_blank" rel="noopener noreferrer">{t.streetview.cta} →</a>
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Floor stack + suite list
// ====================================================
function Spaces({ t, onBook }) {
  const [filter, setFilter] = useState("all");
  const [activeFloor, setActiveFloor] = useState(null);
  const floors = MP_FLOORS;

  const filterMap = ["all", "office", "retail", "full"];
  const labels = t.spaces.filters;

  const filteredFloors = useMemo(() => {
    if (filter === "all") return floors;
    if (filter === "full") return floors.filter(f =>
      f.suites.filter(s => s.status === "available").length >= 3 ||
      f.suites.every(s => s.status === "available")
    );
    return floors.filter(f => f.type === filter);
  }, [filter, floors]);

  const totalAvailable = floors.reduce(
    (acc, f) => acc + f.suites.filter(s => s.status === "available").reduce((a, b) => a + b.size, 0),
    0
  );

  return (
    <section className="section" id="spaces">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.spaces.eyebrow}</div>
          </div>
          <h2 className="h2">{t.spaces.title.split(",")[0]}, <span className="serif" style={{ fontStyle: "italic" }}>{t.spaces.title.split(",")[1]}</span></h2>
          <div className="aside">{t.spaces.body}</div>
        </div>

        <div className="stack">
          <div>
            <div className="stack-viz">
              {floors.map(f => {
                const av = f.suites.filter(s => s.status === "available").reduce((a, b) => a + b.size, 0);
                const pct = Math.min(100, Math.round((av / f.total) * 100));
                const isActive = activeFloor === f.floor;
                return (
                  <div
                    className={"floor" + (isActive ? " active" : "")}
                    key={f.floor}
                    onMouseEnter={() => setActiveFloor(f.floor)}
                    onMouseLeave={() => setActiveFloor(null)}
                    onClick={() => {
                      const el = document.getElementById(`floor-${f.floor}`);
                      if (el) {
                        const offset = el.getBoundingClientRect().top + window.scrollY - 100;
                        window.scrollTo({ top: offset, behavior: "smooth" });
                      }
                    }}
                  >
                    <span className="lvl">Lvl {String(f.floor).padStart(2, "0")}</span>
                    <div className="bar">
                      <div className="seg leased" style={{ left: "0%", right: `${pct}%` }} />
                      <div className="seg" style={{ left: `${100 - pct}%`, right: "0%" }} />
                    </div>
                    <span className="meta">{pct}% open · {f.type}</span>
                  </div>
                );
              })}
              <div className="ground">Plaza Level · Retail Frontage</div>
            </div>
          </div>

          <div>
            <div className="suite-filter">
              {filterMap.map((k, i) => (
                <button key={k} className={filter === k ? "on" : ""} onClick={() => setFilter(k)}>
                  {labels[i]}
                </button>
              ))}
            </div>

            <div style={{
              display: "flex",
              justifyContent: "space-between",
              padding: "16px 0",
              borderTop: "1px solid var(--hair-strong)",
              borderBottom: "1px solid var(--hair-strong)",
              marginBottom: 16,
              fontFamily: "var(--f-mono)",
              fontSize: 11,
              letterSpacing: "0.14em",
              textTransform: "uppercase",
              color: "var(--muted)",
            }}>
              <span>Total available · {(totalAvailable / 1000).toFixed(1)}k sq ft</span>
              <span>{filteredFloors.length} floors shown</span>
            </div>

            {filteredFloors.map(f => (
              <div className="suite-floor" key={f.floor} id={`floor-${f.floor}`}>
                <div className="head">
                  <span className="h">Floor {String(f.floor).padStart(2, "0")}</span>
                  <span className="s">{f.type} · {f.total.toLocaleString()} sq ft total</span>
                </div>
                <div className="suites">
                  {f.suites.map(s => (
                    <div className={"suite " + s.status} key={s.id} onClick={s.status === "available" ? onBook : undefined}>
                      <span className="dot" />
                      <div className="id">Suite {s.id}</div>
                      <div className="sz">{s.size.toLocaleString()}</div>
                      <div className={"st " + (s.status === "available" ? "av" : "lz")}>
                        {s.status === "available"
                          ? (s.type === "retail" ? "Retail · Open" : "Office · Open")
                          : (s.type === "retail" ? "Retail · Leased" : "Office · Leased")}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 48, display: "flex", justifyContent: "center" }}>
          <button className="cta accent" onClick={onBook}>
            {t.spaces.contact} <span className="arrow"></span>
          </button>
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Amenities
// ====================================================
function Amenities({ t, onBook }) {
  return (
    <section className="section">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.amenities.eyebrow}</div>
          </div>
          <h2 className="h2">{t.amenities.title.split(",")[0]}, <span className="serif" style={{ fontStyle: "italic" }}>{t.amenities.title.split(",")[1]}</span></h2>
          <div className="aside">{t.amenities.body}</div>
        </div>
        <div className="amen-grid">
          {t.amenities.items.map((a, i) => (
            <div className="row" key={i}>
              <span className="ord">{String(i + 1).padStart(2, "0")}</span>
              <span className="k">{a.k}</span>
              <span className={"v " + (a.v.toLowerCase().includes("add") || a.v.toLowerCase().includes("adicional") ? "add" : "")}>{a.v}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Gallery
// ====================================================
function Gallery({ t }) {
  const cells = [
    { cls: "g1", src: G_TOWER_DAY, cap: t.gallery.captions[0], color: true },
    { cls: "g2", src: G_LOBBY_MAIN, cap: t.gallery.captions[2], color: true },
    { cls: "g3", src: G_LOBBY_CORRIDOR, cap: t.gallery.captions[3], color: true },
    { cls: "g4", src: AFTER_IMG, cap: t.reimagined.after, color: true },
    { cls: "g5", src: G_ELEV_BANK, cap: t.gallery.captions[4], color: true },
    { cls: "g6", src: G_ELEV_HALL, cap: t.gallery.captions[5], color: true },
    { cls: "g7", src: G_VIEW_CANO, cap: t.gallery.captions[6], color: true },
    { cls: "g8", src: G_PARKING, cap: t.gallery.captions[7], color: true },
    { cls: "g9", src: BEFORE_IMG, cap: t.reimagined.before },
    { cls: "g10", src: HERO_IMG, cap: t.gallery.captions[8], color: true },
  ];
  return (
    <section className="section" id="gallery">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.gallery.eyebrow}</div>
          </div>
          <h2 className="h2">{t.gallery.title.split(",").slice(0, -1).join(",")}, <span className="serif" style={{ fontStyle: "italic" }}>{t.gallery.title.split(",").slice(-1).join(",").trim()}</span></h2>
          <div className="aside">{t.gallery.aside}</div>
        </div>
        <div className="gallery">
          {cells.map((c, i) =>
            c.placeholder ? (
              <div key={i} className={"bldg-img placeholder " + c.cls}>
                <div className="lbl">{c.placeholder}</div>
              </div>
            ) : (
              <div key={i} className={"bldg-img " + c.cls + (c.color ? " color" : "")}>
                <img src={c.src} alt={c.cap} />
                <div className="cap">{c.cap}</div>
              </div>
            )
          )}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Neighborhood
// ====================================================
function Hood({ t }) {
  return (
    <section className="section">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.neighborhood.eyebrow}</div>
          </div>
          <h2 className="h2">{t.neighborhood.title.split(", ").slice(0, -1).join(", ")}, <span className="serif" style={{ fontStyle: "italic" }}>{t.neighborhood.title.split(", ").slice(-1)}</span></h2>
          <div className="aside">{t.neighborhood.body}</div>
        </div>
        <div className="hood">
          {t.neighborhood.categories.map((c, i) => (
            <div className="hood-col" key={i}>
              <div className="mono">0{i + 1} · {c.name}</div>
              <h4>{c.name}</h4>
              <ul>
                {c.items.map((it, j) => <li key={j}>{it}</li>)}
              </ul>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Contact / Form
// ====================================================
function Contact({ t, formRef }) {
  const [submitted, setSubmitted] = useState(false);
  return (
    <section className="section" id="contact" ref={formRef}>
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.contact.eyebrow}</div>
          </div>
          <h2 className="h2">{t.contact.title.split(" ")[0]} <span className="serif" style={{ fontStyle: "italic" }}>{t.contact.title.split(" ").slice(1).join(" ")}</span></h2>
          <div className="aside">{t.contact.body}</div>
        </div>

        <div className="contact">
          <div className="contact-lhs">
            <h3 className="h3">{t.contact.lhsTitle}</h3>
            <p>{t.contact.lhsBody}</p>
            <div className="contact-direct">
              <div className="lbl">{t.contact.direct}</div>
              <div className="ph">{t.contact.phone}</div>
              <div className="em">{t.contact.email}</div>
            </div>
          </div>

          {submitted ? (
            <div style={{
              border: "1px solid var(--hair-strong)",
              padding: 48,
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              gap: 16,
            }}>
              <div className="eyebrow">Received</div>
              <h3 className="h3">Thanks. We'll be in touch within one business day.</h3>
            </div>
          ) : (
            <form className="form" onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}>
              <div className="field">
                <label>{t.contact.fields.name}</label>
                <input type="text" placeholder="Jane Doe" required />
              </div>
              <div className="field">
                <label>{t.contact.fields.company}</label>
                <input type="text" placeholder="Acme LLC" />
              </div>
              <div className="field">
                <label>{t.contact.fields.email}</label>
                <input type="email" placeholder="jane@acme.com" required />
              </div>
              <div className="field">
                <label>{t.contact.fields.phone}</label>
                <input type="tel" placeholder="(787) 555-0100" />
              </div>
              <div className="field">
                <label>{t.contact.fields.sqft}</label>
                <input type="text" placeholder="2,500" />
              </div>
              <div className="field">
                <label>{t.contact.fields.type}</label>
                <select>
                  {t.contact.types.map(ty => <option key={ty}>{ty}</option>)}
                </select>
              </div>
              <div className="field full">
                <label>{t.contact.fields.when}</label>
                <input type="text" placeholder="Next week, mornings" />
              </div>
              <div className="field full">
                <label>{t.contact.fields.message}</label>
                <textarea placeholder="Anything we should know" />
              </div>
              <div className="form-submit">
                <span className="note">We respond in 1 business day.</span>
                <button type="submit">{t.contact.submit} <span className="arrow"></span></button>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

// ====================================================
// Footer
// ====================================================
function Footer({ t }) {
  return (
    <footer>
      <div className="wrap">
        <div className="foot-wm-wrap">
          <img className="foot-wm-img" src="img/logo-light.png" alt="Mercantil Plaza" />
        </div>
        <div className="foot-grid">
          <div className="foot-col">
            <h5>Address</h5>
            <p>{t.footer.address}</p>
          </div>
          <div className="foot-col">
            <h5>Hours</h5>
            <p>{t.footer.hours}</p>
          </div>
          <div className="foot-col">
            <h5>Leasing</h5>
            <p>787-753-0310<br />leasing@mercantilplaza.com</p>
          </div>
          <div className="foot-col">
            <h5>More</h5>
            <ul>
              {t.footer.links.map((l, i) => <li key={i}><a href="#">{l}</a></li>)}
            </ul>
          </div>
        </div>
        <div className="foot-legal">
          <span>{t.footer.legal}</span>
          <span>18.4076° N · 66.0707° W</span>
        </div>
      </div>
    </footer>
  );
}

// ====================================================
// Before / After slider
// ====================================================
function BeforeAfter({ before, after, t }) {
  const [pct, setPct] = useState(50);
  const [dragging, setDragging] = useState(false);
  const ref = useRef(null);

  const updateFromClientX = (clientX) => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = ((clientX - rect.left) / rect.width) * 100;
    setPct(Math.max(0, Math.min(100, x)));
  };

  useEffect(() => {
    if (!dragging) return;
    const onMove = (e) => {
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      updateFromClientX(x);
    };
    const onUp = () => setDragging(false);
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    window.addEventListener("touchmove", onMove, { passive: false });
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onUp);
    };
  }, [dragging]);

  const onDown = (e) => {
    setDragging(true);
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    updateFromClientX(x);
  };

  return (
    <>
      <div
        className={"ba" + (dragging ? " dragging" : "")}
        ref={ref}
        onMouseDown={onDown}
        onTouchStart={onDown}
        style={{ "--pct": pct + "%" }}
      >
        <img className="ba-before" src={before} alt={t.reimagined.before} />
        <img className="ba-after" src={after} alt={t.reimagined.after} />
        <div className="ba-label before">← {t.reimagined.before}</div>
        <div className="ba-label after">{t.reimagined.after} →</div>
        <div className="ba-divider" />
        <div className="ba-knob" aria-label="Drag to compare" />
        <div className="ba-hint">↔ Drag</div>
      </div>
      <div className="ba-meta">
        <div className="col">
          <strong>{t.reimagined.before}</strong>
          As leased · shell space · ready for build-out
        </div>
        <div className="col" style={{ textAlign: "right" }}>
          <strong>{t.reimagined.after}</strong>
          Open plan · collaboration zones · light-filled
        </div>
      </div>
    </>
  );
}

function Reimagined({ t }) {
  return (
    <section className="section">
      <div className="wrap">
        <div className="section-head">
          <div className="meta">
            <div className="eyebrow">{t.reimagined.eyebrow}</div>
          </div>
          <h2 className="h2">{t.reimagined.title} <span className="serif" style={{ fontStyle: "italic" }}>{t.reimagined.title2}</span></h2>
          <div className="aside">{t.reimagined.body}</div>
        </div>
        <BeforeAfter before={BEFORE_IMG} after={AFTER_IMG} t={t} />
      </div>
    </section>
  );
}

// ====================================================
// Cursor blob
// ====================================================
function CursorBlob() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf;
    let tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      tx = e.clientX;
      ty = e.clientY;
      el.style.opacity = 0.9;
    };
    const onLeave = () => { el.style.opacity = 0; };
    const tick = () => {
      cx += (tx - cx) * 0.18;
      cy += (ty - cy) * 0.18;
      el.style.transform = `translate(${cx}px, ${cy}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseleave", onLeave);
    raf = requestAnimationFrame(tick);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseleave", onLeave);
      cancelAnimationFrame(raf);
    };
  }, []);
  return <div className="cursor-blob" ref={ref} />;
}

// ====================================================
// Reveal-on-scroll (disabled, kept as no-op to preserve API)
// ====================================================
function useRevealOnScroll() {
  useEffect(() => {
    document.querySelectorAll(".reveal").forEach(el => el.classList.add("in"));
  }, []);
}

// ====================================================
// App
// ====================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "bone",
  "theme": "light",
  "type": "editorial",
  "heroVariant": "tower",
  "lang": "en"
}/*EDITMODE-END*/;

function App() {
  const [t, setT] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useState(t.lang || "en");
  const formRef = useRef(null);

  // Apply data attrs to body for CSS
  useEffect(() => {
    document.documentElement.setAttribute("data-palette", t.palette);
    document.documentElement.setAttribute("data-theme", t.theme);
    document.documentElement.setAttribute("data-type", t.type);
  }, [t.palette, t.theme, t.type]);

  // Sync lang
  useEffect(() => { setLang(t.lang); }, [t.lang]);
  const setLangBoth = (l) => { setLang(l); setT("lang", l); };

  useRevealOnScroll();

  const tx = MP_CONTENT[lang] || MP_CONTENT.en;

  const onBook = () => {
    const el = formRef.current;
    if (el) {
      const offset = el.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top: offset, behavior: "smooth" });
    }
  };

  return (
    <>
      <CursorBlob />

      <TopBar lang={lang} setLang={setLangBoth} t={tx} onBook={onBook} />
      <Hero t={tx} variant={t.heroVariant} onBook={onBook} />
      <Ticker items={tx.ticker} />
      <Pitch t={tx} />
      <Stats t={tx} />
      <Spaces t={tx} onBook={onBook} />
      <Reimagined t={tx} />
      <Gallery t={tx} />
      <LocationSection t={tx} />
      <Amenities t={tx} onBook={onBook} />
      <Hood t={tx} />
      <StreetView t={tx} />
      <Contact t={tx} formRef={formRef} />
      <Footer t={tx} />

      <button className="float-cta" onClick={onBook}>
        {tx.nav.book} <span className="arrow"></span>
      </button>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette">
          <TweakRadio
            label="Accent"
            value={t.palette}
            onChange={(v) => setT("palette", v)}
            options={[
              { value: "bone", label: "Bone" },
              { value: "lime", label: "Lime" },
              { value: "cobalt", label: "Cobalt" },
              { value: "mono", label: "Mono" },
            ]}
          />
          <TweakToggle
            label="Dark mode"
            value={t.theme === "dark"}
            onChange={(v) => setT("theme", v ? "dark" : "light")}
          />
        </TweakSection>
        <TweakSection label="Typography">
          <TweakRadio
            label="Pairing"
            value={t.type}
            onChange={(v) => setT("type", v)}
            options={[
              { value: "editorial", label: "Editorial" },
              { value: "grotesk", label: "Grotesk" },
              { value: "serif", label: "Serif" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Hero layout">
          <TweakRadio
            label="Variant"
            value={t.heroVariant}
            onChange={(v) => setT("heroVariant", v)}
            options={[
              { value: "tower", label: "Tower" },
              { value: "grid", label: "Grid" },
              { value: "marquee", label: "Marquee" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Language">
          <TweakRadio
            label="Locale"
            value={t.lang}
            onChange={(v) => { setT("lang", v); setLang(v); }}
            options={[
              { value: "en", label: "English" },
              { value: "es", label: "Español" },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
