/* global React, COMMUNITIES, AGENTS, COMMUNITY_DETAIL, COPY, listingsFor, agentsFor, communityById,
   HeadlineFragments, Arrow, ArrowDown, WhatsAppIcon, PinIcon, PhoneIcon, VideoIcon,
   SecHead, Crumbs, ViewingForm, ValuationForm, ListingCard, AgentCard, CommunityCard, CommunitiesGrid */

// ============================================================
// PAGE: HOME
// ============================================================
function HomePage({ setRoute }) {
  return (
    <div className="page" data-screen-label="01 Home">
      {/* HERO */}
      <section className="hero">
        <div className="hero-media">
          <img src="media/hero-home-01.webp" alt="Dubai villa community" />
        </div>
        <div className="wrap hero-content">
          <div className="hero-meta-top">
            <span>{COPY.en.hero.eyebrow}</span>
            <span>{COPY.en.hero.meta}</span>
          </div>
          <h1 className="h-display h1 hero-headline">
            <HeadlineFragments parts={COPY.en.hero.headline} />
          </h1>
          <div className="hero-footer">
            <p className="hero-blurb">{COPY.en.hero.blurb}</p>
            <div className="hero-ctas">
              <button className="btn btn-primary btn-lg" onClick={() => setRoute({ name: "communities" })}>
                {COPY.en.hero.cta1} <Arrow />
              </button>
              <button className="btn btn-ghost-light btn-lg" onClick={() => setRoute({ name: "sell" })}>
                {COPY.en.hero.cta2}
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* TICKER */}
      <Ticker items={COPY.en.ticker} />

      {/* PROPOSITION STRIP */}
      <section className="section">
        <div className="wrap">
          <div className="prop-strip">
            <div>
              <div className="eyebrow" style={{ marginBottom: 28 }}>{COPY.en.propStrip.eyebrow}</div>
              <h2 className="strip-headline">
                <HeadlineFragments parts={COPY.en.propStrip.headline} />
              </h2>
              <p className="lead" style={{ marginTop: 28 }}>{COPY.en.propStrip.copy}</p>
              <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn-ink" onClick={() => setRoute({ name: "team" })}>Meet the team <Arrow /></button>
                <button className="btn btn-outline" onClick={() => setRoute({ name: "contact" })}>Visit the office</button>
              </div>
            </div>
            <div className="prop-stats">
              {COPY.en.propStrip.stats.map((s, i) => (
                <div className="prop-stat" key={i}>
                  <div className="stat-num">{s.num}</div>
                  <div className="stat-label">{s.label}</div>
                  <div className="stat-note">{s.note}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <div className="wrap"><hr className="rule" /></div>

      {/* COMMUNITIES GRID */}
      <section className="section">
        <div className="wrap">
          <SecHead
            eyebrow={COPY.en.communities.eyebrow}
            headlineParts={COPY.en.communities.headline}
            lead={COPY.en.communities.lead}
            rightMeta={<span>22 communities in this prototype<br/>Click any tile to open its microsite →</span>}
          />
          <CommunitiesGrid items={COMMUNITIES} onOpen={(id) => setRoute({ name: "community", id })} />
        </div>
      </section>

      {/* VALUATION BAND */}
      <section className="valuation-band">
        <div className="wrap">
          <div className="inner" style={{ paddingBlock: "clamp(64px, 9vw, 128px)" }}>
            <div>
              <div className="eyebrow eyebrow-paper">{COPY.en.valuation.eyebrow}</div>
              <h2 className="h-display-roman h2" style={{ color: "#fff", margin: "16px 0 24px" }}>
                <HeadlineFragments parts={COPY.en.valuation.headline} />
              </h2>
              <p className="lead" style={{ color: "rgba(255,255,255,.84)" }}>{COPY.en.valuation.copy}</p>
              <ul style={{ listStyle: "none", padding: 0, margin: "32px 0 0", display: "grid", gap: 12, color: "rgba(255,255,255,.7)", fontSize: 13 }}>
                <li>✓ Replied to within one business day</li>
                <li>✓ Realistic range, not a computed figure</li>
                <li>✓ Backed by comps from the last 90 days on your street</li>
              </ul>
            </div>
            <div>
              <ValuationForm dark />
            </div>
          </div>
        </div>
      </section>

      {/* AGENTS PREVIEW */}
      <section className="section">
        <div className="wrap">
          <SecHead
            eyebrow={COPY.en.agents.eyebrow}
            headlineParts={COPY.en.agents.headline}
            lead={COPY.en.agents.lead}
            rightMeta={
              <button className="btn-link" onClick={() => setRoute({ name: "team" })}>
                All consultants <Arrow />
              </button>
            }
          />
          <div className="agents-grid">
            {AGENTS.slice(0, 4).map(a => (
              <AgentCard key={a.id} agent={a} onOpen={(id) => setRoute({ name: "agent", id })} />
            ))}
          </div>
        </div>
      </section>

      {/* OVERSEAS BUYER BAND */}
      <section className="section" style={{ background: "var(--stone)" }}>
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "clamp(40px,6vw,96px)", alignItems: "center" }}>
            <div>
              <div className="eyebrow">Overseas buyers</div>
              <h2 className="h-display-roman h2" style={{ margin: "16px 0 24px" }}>
                Buying from abroad? <em style={{ color: "var(--accent)" }}>Book a video viewing.</em>
              </h2>
              <p className="lead">We'll walk you through the property live — in English, Arabic, Russian or Mandarin — and answer the questions a brochure can't.</p>
              <div style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn-ink">
                  <VideoIcon /> Book a video viewing <Arrow />
                </button>
                <a className="btn btn-outline" href="https://wa.me/971568296862" target="_blank" rel="noopener">
                  <WhatsAppIcon size={14} /> Chat first
                </a>
              </div>
            </div>
            <div style={{ aspectRatio: "4/3", overflow: "hidden" }}>
              <img src="media/about-lifestyle-01.webp" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============================================================
// PAGE: COMMUNITIES INDEX
// ============================================================
function CommunitiesPage({ setRoute }) {
  const [filter, setFilter] = React.useState("All");
  const filtered = filter === "All" ? COMMUNITIES : COMMUNITIES.filter(c => c.type === filter);

  return (
    <div className="page" data-screen-label="02 Communities">
      <section className="section-compact" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <Crumbs items={[
            { label: "Home", onClick: () => setRoute({ name: "home" }) },
            { label: "Communities" },
          ]} />
          <SecHead
            eyebrow="Dubai · 22 areas"
            headlineParts={[{ em: "Every community," }, " its own page."]}
            lead="Per-community microsites with area guides, local agents and a filtered slice of our live listings feed. Built for buyers researching one neighbourhood at a time — not scrolling through every listing in Dubai."
          />
          <div className="chips">
            {["All","Villas","Apartments","Off-plan"].map(t => (
              <button key={t} className={`chip ${filter === t ? "active" : ""}`} onClick={() => setFilter(t)}>{t}</button>
            ))}
            <span className="chip" style={{ background: "var(--stone)", borderColor: "var(--line)", cursor: "default", fontFamily: "var(--font-mono)", fontSize: 10 }}>
              {filtered.length} of {COMMUNITIES.length}
            </span>
          </div>
          <CommunitiesGrid items={filtered} onOpen={(id) => setRoute({ name: "community", id })} layout="bento" />
        </div>
      </section>
    </div>
  );
}

// ============================================================
// PAGE: COMMUNITY MICROSITE (Arabian Ranches demo)
// ============================================================
function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 70;
  window.scrollTo({ top, behavior: "smooth" });
}

function CommunityPage({ id, setRoute }) {
  const community = communityById(id);
  if (!community) return <div className="wrap section">Community not found.</div>;
  const detail = COMMUNITY_DETAIL[id] || COMMUNITY_DETAIL["arabian-ranches"];
  const listings = listingsFor(id, 6);
  const localAgents = agentsFor(id, 4);

  return (
    <div className="page" data-screen-label={`03 Community — ${community.name}`}>
      {/* HERO */}
      <section className="hero">
        <div className="hero-media">
          <img src={community.img} alt={community.name} />
        </div>
        <div className="wrap hero-content">
          <div className="hero-meta-top">
            <span>Community microsite · Dubai</span>
            <span>{community.type} · {community.agents} consultants</span>
          </div>
          <h1 className="h-display h1 hero-headline">
            <em style={{ fontStyle: "italic" }}>{community.name}</em>
          </h1>
          <div className="hero-footer">
            <p className="hero-blurb">{detail.intro}</p>
            <div className="hero-ctas">
              <button className="btn btn-primary btn-lg" onClick={() => scrollToId("viewing")}>
                Book a viewing <Arrow />
              </button>
              <button className="btn btn-ghost-light btn-lg" onClick={() => scrollToId("listings")}>
                See available homes <ArrowDown />
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* CRUMBS */}
      <div className="wrap" style={{ paddingTop: 28 }}>
        <Crumbs items={[
          { label: "Home", onClick: () => setRoute({ name: "home" }) },
          { label: "Communities", onClick: () => setRoute({ name: "communities" }) },
          { label: community.name },
        ]} />
      </div>

      {/* AREA GUIDE */}
      <section className="section">
        <div className="wrap">
          <SecHead
            eyebrow="Area guide"
            headlineParts={["The street view,", { em: "from us" }, "."]}
            rightMeta={<span>Updated quarterly<br/>Espace community team</span>}
          />
          <div className="area-guide">
            <div className="map">
              {/* Stylised area map placeholder */}
              <svg viewBox="0 0 400 500" xmlns="http://www.w3.org/2000/svg">
                <rect width="400" height="500" fill="#EFEBE4" />
                {/* roads */}
                <path d="M0 120 Q200 100 400 140" stroke="#D4CEC2" strokeWidth="14" fill="none" />
                <path d="M0 280 Q200 260 400 300" stroke="#D4CEC2" strokeWidth="14" fill="none" />
                <path d="M100 0 Q120 250 80 500" stroke="#D4CEC2" strokeWidth="10" fill="none" />
                <path d="M280 0 Q300 250 320 500" stroke="#D4CEC2" strokeWidth="10" fill="none" />
                {/* parks */}
                <ellipse cx="200" cy="200" rx="60" ry="40" fill="#CBD9C0" opacity="0.7" />
                <ellipse cx="320" cy="400" rx="50" ry="40" fill="#CBD9C0" opacity="0.7" />
                <ellipse cx="80" cy="380" rx="40" ry="30" fill="#CBD9C0" opacity="0.7" />
                {/* hatch villas */}
                <g fill="#fff" stroke="#D4CEC2">
                  {[...Array(40)].map((_, i) => {
                    const x = 30 + (i % 8) * 45;
                    const y = 50 + Math.floor(i / 8) * 80;
                    return <rect key={i} x={x} y={y} width="18" height="18" />;
                  })}
                </g>
                {/* pin */}
                <g transform="translate(200,250)">
                  <circle r="32" fill="#F44842" opacity="0.18" />
                  <circle r="14" fill="#F44842" />
                  <circle r="4" fill="#fff" />
                </g>
                <text x="200" y="290" textAnchor="middle" fontFamily="monospace" fontSize="10" fill="#1A1919" letterSpacing="2">{community.name.toUpperCase()}</text>
              </svg>
            </div>
            <div>
              <div className="flow">
                {detail.paragraphs.map((p, i) => <p key={i} className="lead">{p}</p>)}
              </div>
              <div className="facts">
                {detail.facts.map((f, i) => (
                  <div className="fact" key={i}>
                    <div className="k">{f.k}</div>
                    <div className="v">{f.v}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      <div className="wrap"><hr className="rule" /></div>

      {/* MARKET SNAPSHOT */}
      <section className="section-compact">
        <div className="wrap">
          <div className="market-snapshot" style={{ position: "relative" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32, gap: 24, flexWrap: "wrap" }}>
              <div>
                <div className="eyebrow">Market snapshot</div>
                <h3 className="h-display-roman h3" style={{ margin: "10px 0 0" }}>{community.name} <em style={{ fontStyle: "italic", color: "var(--accent)" }}>at a glance</em></h3>
              </div>
              <div className="feed-banner"><span className="pulse"></span> attributed · refreshed quarterly</div>
            </div>
            <div className="market-grid">
              {detail.market.map((m, i) => (
                <div className="market-cell" key={i}>
                  <div className="k">{m.k}</div>
                  <div className="v">{m.v}</div>
                  <div className={`delta ${m.down ? "down" : ""}`}>{m.delta}</div>
                </div>
              ))}
            </div>
            <div className="market-attribution">{detail.marketAttribution}</div>
          </div>
        </div>
      </section>

      {/* LISTINGS */}
      <section className="section" id="listings">
        <div className="wrap">
          <SecHead
            eyebrow={COPY.en.listings.eyebrow}
            headlineParts={[`Properties in `, { em: community.name }]}
            lead={COPY.en.listings.lead}
            rightMeta={
              <div className="feed-banner">
                <span className="pulse"></span> {COPY.en.listings.note}
              </div>
            }
          />
          <div style={{ position: "relative" }}>
            <div className="listings-grid">
              {listings.length > 0 ? listings.map(l => (
                <ListingCard key={l.ref} listing={l} onBook={() => scrollToId("viewing")} />
              )) : (
                <div className="listing-card" style={{ gridColumn: "1 / -1", padding: 48, textAlign: "center" }}>
                  <p className="text-muted">No live feed entries for {community.name} in this demo. In production this slice would render whatever's available in the brokerage feed today.</p>
                </div>
              )}
            </div>
          </div>
          <div style={{ marginTop: 24, textAlign: "center" }}>
            <button className="btn-link">Load more from feed <ArrowDown /></button>
          </div>
        </div>
      </section>

      <div className="wrap"><hr className="rule" /></div>

      {/* LOCAL AGENTS */}
      <section className="section">
        <div className="wrap">
          <SecHead
            eyebrow="Local consultants"
            headlineParts={["Talk to someone who", { em: "knows the streets" }, "."]}
            lead={`The ${community.name} team — direct lines, multilingual where indicated.`}
          />
          <div className="agents-grid">
            {localAgents.map(a => (
              <AgentCard key={a.id} agent={a} onOpen={(id) => setRoute({ name: "agent", id })} />
            ))}
          </div>
        </div>
      </section>

      {/* VIEWING FORM BAND */}
      <section className="valuation-band" id="viewing">
        <div className="wrap">
          <div className="inner" style={{ paddingBlock: "clamp(64px, 9vw, 128px)" }}>
            <div>
              <div className="eyebrow eyebrow-paper">Book a viewing</div>
              <h2 className="h-display-roman h2" style={{ color: "#fff" }}>
                See {community.name} <em style={{ color: "var(--accent)", fontStyle: "italic" }}>in person.</em>
              </h2>
              <p className="lead" style={{ color: "rgba(255,255,255,.84)" }}>
                Pick a slot — we'll confirm in the hour during office hours, or message us on WhatsApp for instant.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "24px 0 0", display: "grid", gap: 8, color: "rgba(255,255,255,.7)", fontSize: 13 }}>
                <li>✓ Multiple homes in one visit, no juggling agents</li>
                <li>✓ Overseas? Switch to a video viewing instead</li>
                <li>✓ No price pressure — we'll bring the data</li>
              </ul>
            </div>
            <div>
              <ViewingForm dark communityId={id} />
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.HomePage = HomePage;
window.CommunitiesPage = CommunitiesPage;
window.CommunityPage = CommunityPage;
