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

// ============================================================
// PAGE: AGENT MICROSITE (John Lyons demo)
// ============================================================
function AgentPage({ id, setRoute }) {
  const agent = AGENTS.find(a => a.id === id) || AGENTS[0];
  // Pull listings from communities this agent covers
  const agentListings = [];
  agent.communities.forEach(cid => {
    listingsFor(cid).forEach(l => {
      if (!agentListings.find(x => x.ref === l.ref)) agentListings.push(l);
    });
  });

  return (
    <div className="page" data-screen-label={`04 Agent — ${agent.name}`}>
      <section className="section-compact" style={{ paddingTop: 56 }}>
        <div className="wrap">
          <Crumbs items={[
            { label: "Home", onClick: () => setRoute({ name: "home" }) },
            { label: "Team", onClick: () => setRoute({ name: "team" }) },
            { label: agent.name },
          ]} />
          <div className="agent-hero">
            <div className="portrait-lg">
              <img src={agent.img} alt={agent.name} />
            </div>
            <div className="info">
              <div className="role">{agent.role}</div>
              <h1 className="name">
                {agent.name.split(" ")[0]} <em>{agent.name.split(" ").slice(1).join(" ")}</em>
              </h1>
              <p className="bio">
                {agent.id === "john-lyons"
                  ? "John has led Espace since October 2019 as Managing Director, building on a career running sales and leasing teams across Dubai's premium villa communities. Scottish, UK-trained, and a believer in the unfashionable idea that a Dubai brokerage can be measured, advisory and answer its phone."
                  : `Senior consultant focused on ${agent.focus.toLowerCase()}, with deep network access across ${agent.communities.length} of Dubai's premium communities. Multilingual where indicated, available for video viewings, and a direct line for sellers and landlords.`
                }
              </p>
              <div className="meta-grid">
                <div>
                  <div className="k">Languages</div>
                  <div className="v">{agent.langs}</div>
                </div>
                <div>
                  <div className="k">Communities</div>
                  <div className="v">{agent.communities.length}</div>
                </div>
                <div>
                  <div className="k">{agent.brn ? "RERA" : "Focus"}</div>
                  <div className="v">{agent.brn || agent.focus}</div>
                </div>
              </div>
              <div className="ctas">
                <button className="btn btn-primary" onClick={() => scrollToId("agent-viewing")}>Book a viewing <Arrow /></button>
                <a className="btn btn-outline" href="https://wa.me/971568296862" target="_blank" rel="noopener">
                  <WhatsAppIcon size={14} /> WhatsApp {agent.name.split(" ")[0]}
                </a>
                <a className="btn btn-outline" href="tel:+97143069999">
                  <PhoneIcon /> Call office
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>

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

      {/* COMMUNITIES COVERED */}
      <section className="section-compact">
        <div className="wrap">
          <SecHead
            eyebrow="Communities covered"
            headlineParts={[{ em: "Where" }, " ", agent.name.split(" ")[0], " ", "works."]}
            rightMeta={<span>Click a community to open its microsite →</span>}
          />
          <div className="communities-grid">
            {agent.communities.map(cid => {
              const c = communityById(cid);
              if (!c) return null;
              return <CommunityCard key={c.id} community={c} span={3} onOpen={(id) => setRoute({ name: "community", id })} />;
            })}
          </div>
        </div>
      </section>

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

      {/* AGENT'S LISTINGS */}
      <section className="section">
        <div className="wrap">
          <SecHead
            eyebrow="Live feed"
            headlineParts={[agent.name.split(" ")[0] + "'s", { em: " properties" }]}
            lead={`Filtered to ${agent.name.split(" ")[0]}'s communities. Pricing & availability come from the live brokerage feed — never hardcoded.`}
            rightMeta={<div className="feed-banner"><span className="pulse"></span>Sample / live feed in production</div>}
          />
          <div className="listings-grid">
            {agentListings.slice(0, 6).map(l => (
              <ListingCard key={l.ref} listing={l} onBook={() => scrollToId("agent-viewing")} />
            ))}
          </div>
        </div>
      </section>

      {/* CONTACT BAND */}
      <section className="valuation-band" id="agent-viewing">
        <div className="wrap">
          <div className="inner" style={{ paddingBlock: "clamp(64px, 9vw, 128px)" }}>
            <div>
              <div className="eyebrow eyebrow-paper">Direct line</div>
              <h2 className="h-display-roman h2" style={{ color: "#fff" }}>
                Skip the form. <em style={{ color: "var(--accent)", fontStyle: "italic" }}>Talk to {agent.name.split(" ")[0]}.</em>
              </h2>
              <p className="lead" style={{ color: "rgba(255,255,255,.84)" }}>
                Phone, WhatsApp, video call, or in-person at Marina Plaza. {agent.name.split(" ")[0]} reads every message that comes via this page personally.
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "24px 0 0", display: "grid", gap: 14, color: "rgba(255,255,255,.85)" }}>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}>
                  <PhoneIcon /> <span>+971 4 306 9999 — switchboard, ask for {agent.name.split(" ")[0]}</span>
                </li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}>
                  <WhatsAppIcon size={14} /> <span>+971 56 829 6862 — usually replies in minutes</span>
                </li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}>
                  <VideoIcon /> <span>Video viewings for overseas buyers</span>
                </li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}>
                  <PinIcon size={14} /> <span>Office 2702 &amp; 2703, Marina Plaza · Mon–Fri 9am–6pm</span>
                </li>
              </ul>
            </div>
            <div>
              <ViewingForm dark agentId={agent.id} />
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============================================================
// PAGE: TEAM / ALL CONSULTANTS
// ============================================================
function TeamPage({ setRoute }) {
  return (
    <div className="page" data-screen-label="05 Team">
      <section className="section-compact" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <Crumbs items={[
            { label: "Home", onClick: () => setRoute({ name: "home" }) },
            { label: "Team" },
          ]} />
          <SecHead
            eyebrow="Leadership"
            headlineParts={[{ em: "Eight directors." }, " ", "One direct line each."]}
            lead="Verified leadership team. Each director has their own microsite, their listings (from the live feed), and their direct WhatsApp. The full roster of consultants — multilingual, by community — comes next in the build."
          />
          <div className="agents-grid">
            {AGENTS.map(a => (
              <AgentCard key={a.id} agent={a} onOpen={(id) => setRoute({ name: "agent", id })} />
            ))}
          </div>
          <div style={{ marginTop: 48, padding: 32, background: "var(--stone)", border: "1px solid var(--line)" }}>
            <div className="eyebrow">Build note</div>
            <p className="lead" style={{ margin: "8px 0 0" }}>
              Per the brief, only the eight verified directors are shown — the remaining ~90+ consultants need permissioned bios + portraits before they ship.
              Each agent microsite reads from the same listings feed as the community pages, so John's "5-bed Saheel" and Arabian Ranches's "5-bed Saheel" stay in lockstep.
            </p>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============================================================
// PAGE: SELL / VALUATION
// ============================================================
function SellPage({ setRoute }) {
  return (
    <div className="page" data-screen-label="06 Sell">
      <section className="section-compact" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <Crumbs items={[
            { label: "Home", onClick: () => setRoute({ name: "home" }) },
            { label: "Sell" },
          ]} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "clamp(40px,6vw,96px)", alignItems: "start" }}>
            <div>
              <div className="eyebrow">Sell or let with us</div>
              <h1 className="h-display-roman h1" style={{ fontSize: "clamp(40px,5.5vw,84px)", margin: "20px 0 24px", lineHeight: 0.98 }}>
                Free, no-obligation <em style={{ color: "var(--accent)", fontStyle: "italic" }}>valuation</em>.
              </h1>
              <p className="lead">
                Thinking of selling or letting? Get a realistic range from a consultant who knows your community.
                No bots, no guesswork — a human who transacts on your street every week.
              </p>
              <div style={{ marginTop: 48 }}>
                <h3 className="h-display-roman h4" style={{ marginBottom: 16 }}>What happens next</h3>
                <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 20, counterReset: "step" }}>
                  {[
                    "We confirm a window to come and walk the property (or do it remotely).",
                    "Your consultant brings comparable evidence from the last 90 days in your community.",
                    "You get a realistic range — written, attributed, and honest about what could push it either way.",
                    "If you decide to list, we agree marketing strategy and timing. If not, no follow-up emails.",
                  ].map((s, i) => (
                    <li key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 16, alignItems: "start", borderTop: "1px solid var(--line)", paddingTop: 16 }}>
                      <span className="serif italic" style={{ fontSize: 28, color: "var(--accent)", lineHeight: 1 }}>0{i+1}</span>
                      <span>{s}</span>
                    </li>
                  ))}
                </ol>
              </div>
              <div style={{ marginTop: 48, padding: 24, background: "var(--stone)", border: "1px solid var(--line)" }}>
                <div className="eyebrow">Listing your property?</div>
                <p style={{ margin: "8px 0 16px", fontSize: 14 }}>If you've already made the call to sell or let, you can skip the valuation step and brief us directly.</p>
                <button className="btn btn-outline btn-sm">List my property <Arrow /></button>
              </div>
            </div>
            <div style={{ position: "sticky", top: 88 }}>
              <div style={{ padding: 32, background: "var(--paper)", border: "1px solid var(--line)" }}>
                <h3 className="h-display-roman h4" style={{ margin: "0 0 8px" }}>Request my valuation</h3>
                <p className="text-muted body-sm" style={{ margin: "0 0 24px" }}>Typically replied to within one business day.</p>
                <ValuationForm />
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============================================================
// PAGE: CONTACT
// ============================================================
function ContactPage({ setRoute }) {
  return (
    <div className="page" data-screen-label="07 Contact">
      <section className="section-compact" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <Crumbs items={[
            { label: "Home", onClick: () => setRoute({ name: "home" }) },
            { label: "Contact" },
          ]} />
          <SecHead
            eyebrow="Find us"
            headlineParts={["27th floor,", { em: "Marina Plaza" }, "."]}
            lead="Office 2702 & 2703 on Al Marsa Street, looking out over the Marina. Mon–Fri only; the kettle's on from 9."
          />
          <div className="contact-grid">
            <div>
              <ul className="contact-list">
                <li>
                  <div className="k">Phone</div>
                  <div className="v"><a href="tel:+97143069999">+971 4 306 9999</a></div>
                  <div className="note">Mon–Fri 9am–6pm · Sat &amp; Sun closed</div>
                </li>
                <li>
                  <div className="k">WhatsApp</div>
                  <div className="v"><a href="https://wa.me/971568296862" target="_blank" rel="noopener">+971 56 829 6862</a></div>
                  <div className="note">Usually replies within minutes during office hours.</div>
                </li>
                <li>
                  <div className="k">Email</div>
                  <div className="v"><a href="mailto:info@espace.ae">info@espace.ae</a></div>
                  <div className="note">Sales / leasing / valuation routed by topic.</div>
                </li>
                <li>
                  <div className="k">Address</div>
                  <div className="v">Office 2702 &amp; 2703, Marina Plaza<br/>Tower 74, Al Marsa Street<br/>Dubai Marina · PO Box 282391</div>
                  <div className="note">⚠ Confirm exact entrance on day of visit. Public-holiday hours may vary.</div>
                </li>
              </ul>
              <div style={{ marginTop: 40, display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="btn btn-ink">Book a video viewing <VideoIcon /></button>
                <a className="btn btn-outline" href="https://wa.me/971568296862" target="_blank" rel="noopener"><WhatsAppIcon size={14} /> Message us</a>
              </div>
            </div>
            <div>
              <div className="map-block">
                {/* Stylised marina map */}
                <svg viewBox="0 0 400 500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" style={{ width: "100%", height: "100%" }}>
                  <rect width="400" height="500" fill="#EFEBE4" />
                  {/* water */}
                  <path d="M0 100 Q60 90 120 110 T240 130 T400 160 L400 280 Q300 270 200 290 T0 320 Z" fill="#C9D8E0" opacity="0.6" />
                  {/* roads */}
                  <path d="M0 380 L400 380" stroke="#D4CEC2" strokeWidth="6" />
                  <path d="M0 440 L400 440" stroke="#D4CEC2" strokeWidth="6" />
                  <path d="M180 0 L180 500" stroke="#D4CEC2" strokeWidth="4" />
                  {/* towers */}
                  <g fill="#fff" stroke="#D4CEC2">
                    {[...Array(14)].map((_, i) => {
                      const x = 30 + (i % 7) * 50;
                      const y = i < 7 ? 380 - 30 - (i*4 % 80) : 440 - 30 - (i*4 % 60);
                      const h = 30 + (i*7) % 60;
                      return <rect key={i} x={x} y={y - h + 30} width="20" height={h} />;
                    })}
                  </g>
                  {/* pin Marina Plaza */}
                  <g transform="translate(210,355)">
                    <circle r="34" fill="#F44842" opacity="0.18" />
                    <circle r="15" fill="#F44842" />
                    <path d="M0,0 L0,18" stroke="#F44842" strokeWidth="3" />
                    <circle r="5" fill="#fff" />
                  </g>
                  <text x="210" y="335" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="#1A1919" letterSpacing="1.5">MARINA PLAZA · 27F</text>
                  <text x="20" y="490" fontFamily="monospace" fontSize="8" fill="#6A6864" letterSpacing="1.5">25.0751°N  55.1402°E</text>
                </svg>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.AgentPage = AgentPage;
window.TeamPage = TeamPage;
window.SellPage = SellPage;
window.ContactPage = ContactPage;
