/* global React */
const { useState, useEffect, useRef } = React;

/* ============================================================
   PUBLIC CONTACT DETAILS — edit here, used everywhere
   ============================================================ */
const FULL_NAME       = "Gislaine Davini";
const LEGAL_NAME      = "Gislaine D. Silva";                    // shown where the client asked for it (intro caption, footer)
const BRAND_SUB       = "Florida Real Estate";
const BROKER          = "Elite International Realty";          // required by her broker/association rules
const TITLE           = "Real Estate Advisor";                  // never "Realtor®" — she is not allowed to use the mark
const EMAIL           = "davinimiamihomes@gmail.com";
const EMAIL_HREF      = `mailto:${EMAIL}?subject=Miami%20real%20estate%20inquiry`;
const INSTAGRAM_HANDLE = "@gigidavinimiami";
const INSTAGRAM_URL   = "https://www.instagram.com/gigidavinimiami/";
// Gislaine's mobile (digits only, with country code) — used for WhatsApp + SMS
const PHONE_DIGITS    = "13053180090";
const PHONE_DISPLAY   = "+1 (305) 318-0090";
const WHATSAPP_HREF   = `https://wa.me/${PHONE_DIGITS}?text=${encodeURIComponent("Hi Gislaine! I'd like to talk about real estate in Miami.")}`;
const SMS_HREF        = `sms:+${PHONE_DIGITS}`;

/* Hero video clips — generated with Higgsfield (Seedance 2.5), 6s, 720p, self-hosted in
   assets/video/ (re-encode recipe in the README). Each clip has a 16:9 file and a 3:4 centre
   crop ("-portrait") for phones: same framing under object-fit: cover, about half the bytes. */
const CLIP_NIGHTLIFE = "assets/video/ocean-drive"; // also the "Why Miami" background
const HERO_CLIPS = [
  "assets/video/brickell",  // 1 — Brickell skyline over Biscayne Bay, sunset
  "assets/video/villa",     // 2 — Waterfront villa, dusk
  CLIP_NIGHTLIFE,           // 3 — Ocean Drive nightlife
  "assets/video/yacht",     // 4 — Yacht on Biscayne Bay
];
const HERO_POSTER = "assets/video/poster.jpg"; // still from the yacht clip — shown until the reel plays (and to reduced-motion / data-saver users)
const CLIP_SECONDS = 4.4; // play only the first seconds of each clip — keeps the reel moving
const PORTRAIT = window.matchMedia("(max-aspect-ratio: 3/4)");
const clipSrc = (clip) => `${clip}${PORTRAIT.matches ? "-portrait" : ""}.mp4`;

/* ---------- inline line-icons ---------- */
const Ic = {
  home:  <path d="M3 11.5 12 4l9 7.5M5 10v9h14v-9M9.5 19v-5h5v5"/>,
  tag:   <path d="M20 12l-8 8-9-9V3h8zM7.5 7.5h.01"/>,
  key:   <path d="M14 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM14 3l-1 0M12 17l-9 4v-3l2-2h2v-2h2l1.5-1.5"/>,
  chart: <path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/>,
  check: <path d="M20 6 9 17l-5-5"/>,
  phone: <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L16 12l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z"/>,
  mail:  <path d="M3 6h18v12H3zM3 7l9 6 9-6"/>,
  chat:  <path d="M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z"/>,
  instagram: <path d="M7 3h10a4 4 0 0 1 4 4v10a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4zM12 8.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7zM17.3 6.7h.01"/>,
  arrowDown: <path d="M12 4v16m0 0l-6-6m6 6l6-6"/>,
  arrowR: <path d="M5 12h14m0 0l-6-6m6 6l-6 6"/>,
  sun:   <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"/>,
  globe: <path d="M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18"/>,
  wave:  <path d="M3 8c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2M3 14c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2M3 20c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2"/>,
  percent: <path d="M19 5 5 19M7.5 5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM16.5 14a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z"/>,
  building: <path d="M4 21V5a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16M14 9h5a1 1 0 0 1 1 1v11M2 21h20M8 8h2M8 12h2M8 16h2M17 13h1M17 17h1"/>,
  glass: <path d="M8 3h8l-1 7a3 3 0 0 1-6 0zM12 13v6M8 21h8"/>,
  lang:  <path d="M4 5h9M8.5 3v2M10 5c-.5 4-3 7-6 9M6 8c1 2.5 3 4.5 5 6M13 20l4-9 4 9M14.5 17h5"/>,
  plane: <path d="M10.5 20.5 12 15l6-4 3-6-6 3-4 6-5.5 1.5L8 17z"/>,
};
function Svg({ d, style }) {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={style}>{d}</svg>;
}

/* =================== HEADER =================== */
function Header() {
  const [solid, setSolid] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => { document.body.style.overflow = open ? "hidden" : ""; }, [open]);
  const links = [["#about", "About"], ["#services", "Services"], ["#miami", "Why Miami"], ["#neighborhoods", "Neighborhoods"], ["#contact", "Contact"]];
  return (
    <header className={`nav${solid ? " nav--solid" : ""}${open ? " nav--open" : ""}`}>
      <div className="container nav__inner">
        <a className="brand" href="#top" onClick={() => setOpen(false)}>
          <span className="brand__name">{FULL_NAME}</span>
          <span className="brand__sub">{BRAND_SUB}</span>
        </a>
        <nav className="nav__links">
          {links.map(([h, l]) => <a key={h} href={h}>{l}</a>)}
        </nav>
        <div className="nav__right">
          <a className="nav__ig" href={INSTAGRAM_URL} target="_blank" rel="noopener" aria-label="Gislaine on Instagram"><Svg d={Ic.instagram} /></a>
          <a className="btn btn--gold" href={WHATSAPP_HREF} target="_blank" rel="noopener">WhatsApp</a>
          <button className="nav__burger" aria-label="Menu" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
            <span /><span /><span />
          </button>
        </div>
      </div>
      <div className="nav__drawer">
        {links.map(([h, l]) => <a key={h} href={h} onClick={() => setOpen(false)}>{l}</a>)}
        <a href={WHATSAPP_HREF} target="_blank" rel="noopener" onClick={() => setOpen(false)}>Chat on WhatsApp</a>
        <a href={INSTAGRAM_URL} target="_blank" rel="noopener">{INSTAGRAM_HANDLE}</a>
      </div>
    </header>
  );
}

/* =================== HERO (video) =================== */
/* Two stacked <video> elements: the active one plays, the other pre-loads the
   next clip. On "ended" we swap them with a crossfade — a seamless reel of
   Miami without a single heavy file. The poster (a real still) covers the wait
   on slow connections. */
function HeroVideo({ clips, poster }) {
  const vA = useRef(null), vB = useRef(null);
  const [active, setActive] = useState(0);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const conn = navigator.connection;
    const lite = conn && (conn.saveData || /2g/.test(conn.effectiveType || "")); // data saver / 2G: poster only
    if (reduce || lite || !clips.length) return;
    const els = [vA.current, vB.current];
    const idx = { current: 0 };
    els.forEach((el) => { el.muted = true; el.setAttribute("muted", ""); el.defaultMuted = true; });
    // play() can be rejected while the tab is hidden or before data arrives — retry on those signals.
    const safePlay = (el) => el.play().catch(() => {
      el.addEventListener("canplay", () => el.play().catch(() => {}), { once: true });
    });
    els[0].src = clipSrc(clips[0]);
    safePlay(els[0]);
    // Give the first clip the whole connection; start buffering the next one once it plays.
    const onPlaying = () => {
      setReady(true);
      if (clips.length > 1) { els[1].src = clipSrc(clips[1]); els[1].load(); }
    };
    els[0].addEventListener("playing", onPlaying, { once: true });
    let activeK = 0, pending = null;
    const resume = () => {
      const cur = els.find((el) => el.classList.contains("is-active")) || els[0];
      if (cur.paused && !cur.ended) safePlay(cur);
      if (pending && pending.paused) safePlay(pending);
    };
    document.addEventListener("visibilitychange", resume);
    ["pointerdown", "touchstart", "keydown", "scroll"].forEach((ev) => window.addEventListener(ev, resume, { passive: true, once: true }));
    const handlers = els.map((el, k) => {
      const advance = () => {
        if (k !== activeK || pending) return;            // only the visible clip drives the reel
        if (clips.length === 1) { el.currentTime = 0; el.play().catch(() => {}); return; }
        const next = (idx.current + 1) % clips.length;
        const nk = 1 - k, nel = els[nk];
        // Crossfade only once the next clip is actually playing — if it is still buffering,
        // the current one runs on (or holds its last frame) instead of fading to black.
        pending = nel;
        nel.addEventListener("playing", () => {
          pending = null;
          idx.current = next;
          activeK = nk;
          setActive(nk);
          const after = (next + 1) % clips.length;
          setTimeout(() => { el.pause(); el.src = clipSrc(clips[after]); el.load(); }, 1500);
        }, { once: true });
        nel.currentTime = 0;
        safePlay(nel);
      };
      const onTime = () => { if (el.currentTime >= CLIP_SECONDS) advance(); };
      el.addEventListener("ended", advance);
      el.addEventListener("timeupdate", onTime);
      return { advance, onTime };
    });
    return () => { document.removeEventListener("visibilitychange", resume); els.forEach((el, k) => { if (!el) return; el.removeEventListener("ended", handlers[k].advance); el.removeEventListener("timeupdate", handlers[k].onTime); }); };
  }, []);
  return (
    <div className={`hero__video${ready ? " is-ready" : ""}`} aria-hidden="true">
      <img className="hero__poster" src={poster} alt="" />
      <video ref={vA} className={`hero__clip${active === 0 ? " is-active" : ""}`} muted playsInline preload="auto" />
      <video ref={vB} className={`hero__clip${active === 1 ? " is-active" : ""}`} muted playsInline preload="auto" />
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <HeroVideo clips={HERO_CLIPS} poster={HERO_POSTER} />
      <div className="hero__shade" />
      {/* No big title and the copy sits low — the client wants the video to stay clear. The small eyebrow is the page's h1. */}
      <div className="container hero__content">
        <h1 className="hero__eyebrow" data-reveal>Miami · South Florida Real Estate</h1>
        <p className="hero__sub" data-reveal>
          Buy, sell or rent in Miami with a realtor who is personally involved in every step.
          Personalized service in Portuguese, English and Spanish.
        </p>
        <div className="hero__cta" data-reveal>
          <a className="btn btn--gold" href={WHATSAPP_HREF} target="_blank" rel="noopener"><Svg d={Ic.chat} /> Chat with Gislaine</a>
          <a className="btn btn--outline" href="#contact">Send a message</a>
        </div>
      </div>
      <div className="hero__foot">
        <div className="container hero__foot-inner">
          <span className="hero__agent">{FULL_NAME} <i>·</i> {TITLE} with <b className="broker">{BROKER}</b></span>
          <a className="hero__scroll" href="#intro" aria-label="Scroll down"><Svg d={Ic.arrowDown} /></a>
        </div>
      </div>
    </section>
  );
}

/* =================== INTRO (photo + phrases) =================== */
/* PLACEHOLDER COPY — Gislaine will send her final presentation phrases. */
function Intro() {
  const lines = [
    "Your Brazilian realtor in Miami.",
    "Personally involved in every step — from the first message to the keys.",
    "Portuguese · English · Spanish.",
  ];
  return (
    <section className="section intro" id="intro">
      <div className="container intro__grid">
        <figure className="intro__photo" data-reveal>
          <img src="assets/gigi-black-laptop.jpg" alt="Gislaine Davini working on her laptop" loading="lazy" />
          <figcaption><span>{LEGAL_NAME}</span><small>{TITLE} with <b className="broker">{BROKER}</b></small></figcaption>
        </figure>
        <div className="intro__text">
          <span className="eyebrow" data-reveal>Meet Gislaine</span>
          <h2 data-reveal>Real estate, <em>the personal way.</em></h2>
          <ul className="intro__lines">
            {lines.map((l, i) => <li key={i} data-reveal style={{ transitionDelay: `${i * 90}ms` }}>{l}</li>)}
          </ul>
          <a className="link-arrow" href="#about" data-reveal>About {FULL_NAME} <Svg d={Ic.arrowR} /></a>
        </div>
      </div>
    </section>
  );
}

/* =================== ABOUT =================== */
function About() {
  const facts = [
    { n: "5", l: "years in Miami real estate" },
    { n: "3", l: "languages — PT · EN · ES" },
    { n: "2", l: "backgrounds — Law & Marketing" },
  ];
  return (
    <section className="section about" id="about">
      <div className="container about__grid">
        <div className="about__text">
          <span className="eyebrow" data-reveal>About me</span>
          <h2 data-reveal>About <em>Gislaine Davini</em></h2>
          <div className="about__body" data-reveal>
            <p>Originally from Brazil and based in South Florida, I have nearly five years of experience in Miami real estate, with a background in Law and Marketing.</p>
            <p>I am dedicated, attentive, and personally involved in every step. My work is built on trust, excellent client references, and a genuine commitment to always giving my best.</p>
            <p>Personalized service in Portuguese, English, and Spanish.</p>
          </div>
          <p className="about__broker" data-reveal>{TITLE} with <b className="broker">{BROKER}</b></p>
          <div className="about__facts">
            {facts.map((f, i) => (
              <div key={f.l} data-reveal style={{ transitionDelay: `${i * 90}ms` }}>
                <strong>{f.n}</strong><span>{f.l}</span>
              </div>
            ))}
          </div>
          <div className="about__cta" data-reveal>
            <a className="btn btn--gold" href={WHATSAPP_HREF} target="_blank" rel="noopener"><Svg d={Ic.chat} /> Chat on WhatsApp</a>
            <a className="btn btn--outline" href={SMS_HREF}>Text message</a>
          </div>
        </div>
        <figure className="about__photo" data-reveal>
          <img src="assets/gigi-blazer-bw.jpg" alt="Gislaine 'Gigi' Davini" loading="lazy" />
        </figure>
      </div>
    </section>
  );
}

/* =================== SERVICES =================== */
function Services() {
  const items = [
    { ic: Ic.home, t: "Buy", d: "Homes, condos and new developments. I curate the search, book the showings and negotiate on your side." },
    { ic: Ic.tag, t: "Sell", d: "Pricing strategy, professional presentation and marketing that reaches local and international buyers." },
    { ic: Ic.key, t: "Rent", d: "Looking to rent in Miami? Annual and seasonal rentals, application and move-in — handled end to end." },
    { ic: Ic.chart, t: "Invest & Relocate", d: "Guidance for investors and families moving from Brazil or abroad: neighborhoods, numbers, next steps." },
  ];
  return (
    <section className="section services" id="services">
      <div className="container">
        <div className="section__head section__head--center">
          <span className="eyebrow" data-reveal>How I can help</span>
          <h2 data-reveal>Every step, <em>with you.</em></h2>
        </div>
        <div className="svc-grid">
          {items.map((s, i) => (
            <article className="svc" key={s.t} data-reveal style={{ transitionDelay: `${i * 80}ms` }}>
              <span className="svc__ic"><Svg d={s.ic} /></span>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
              <a href="#contact" className="link-arrow">Let's talk <Svg d={Ic.arrowR} /></a>
            </article>
          ))}
        </div>
        <div className="rent-band" data-reveal>
          <img src="assets/gigi-flyer.jpg" alt="Looking to rent in Miami? Let me help you!" loading="lazy" />
          <div>
            <span className="eyebrow">Rentals</span>
            <h3>Looking to <em>rent</em> in Miami?</h3>
            <p>From your first search to your signed lease, I'll guide you every step of the way.</p>
            <a className="btn btn--gold" href={WHATSAPP_HREF} target="_blank" rel="noopener">Let me help you</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* =================== WHY MIAMI =================== */
function WhyMiami() {
  // Load and play the background clip only near/on screen (saves battery/data and keeps
  // the connection free for the hero reel on first load).
  const bg = useRef(null);
  useEffect(() => {
    const el = bg.current;
    if (!el) return;
    el.muted = true; el.setAttribute("muted", "");
    if (!("IntersectionObserver" in window)) { el.play().catch(() => {}); return; }
    let visible = false;
    const io = new IntersectionObserver(([en]) => {
      visible = en.isIntersecting;
      if (visible) el.play().catch(() => {}); else el.pause();
    }, { threshold: 0, rootMargin: "200px 0px" });
    // Some browsers pause background media on their own; nudge it back while on screen.
    el.addEventListener("pause", () => { if (visible && !el.ended) setTimeout(() => { if (visible && el.paused) el.play().catch(() => {}); }, 600); });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const reasons = [
    { ic: Ic.sun, t: "Sunshine, all year", d: "Warm weather and outdoor living twelve months a year." },
    { ic: Ic.wave, t: "Waterfront lifestyle", d: "From oceanfront residences to private marinas, Miami brings luxury closer to the water." },
    { ic: Ic.globe, t: "A global destination", d: "Miami connects lifestyle, international business and real estate opportunities in one of the world's most desirable destinations." },
    { ic: Ic.plane, t: "International connectivity", d: "Easy access to Latin America, Europe and major U.S. cities makes Miami a global gateway." },
    { ic: Ic.building, t: "A growing skyline", d: "New developments, world-class architecture and strong long-term demand." },
    { ic: Ic.glass, t: "Dining & nightlife", d: "From waterfront dining and rooftop lounges to live music and vibrant cultural hotspots, every part of Miami offers its own flavor and energy." },
  ];
  return (
    <section className="section miami" id="miami">
      <video ref={bg} className="miami__bg" src={`${CLIP_NIGHTLIFE}.mp4`} muted loop playsInline preload="none" aria-hidden="true" />
      <div className="miami__shade" />
      <div className="container">
        <div className="section__head section__head--center">
          <span className="eyebrow" data-reveal>Why Miami?</span>
          <h2 data-reveal>Where the world <em>comes to live.</em></h2>
        </div>
        <div className="why-grid">
          {reasons.map((r, i) => (
            <div className="why" key={r.t} data-reveal style={{ transitionDelay: `${i * 70}ms` }}>
              <span className="why__ic"><Svg d={r.ic} /></span>
              <h3>{r.t}</h3>
              <p>{r.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* =================== NEIGHBORHOODS =================== */
function Neighborhoods() {
  const hoods = [
    ["Brickell", "Financial district, high-rise living, rooftops and bay views"],
    ["Miami Beach", "Ocean, Art Deco, iconic addresses"],
    ["Sunny Isles", "Beachfront towers and resort-style living"],
    ["Aventura", "Family-friendly, shopping, golf and marinas"],
    ["Coral Gables", "Mediterranean charm, tree-lined streets, top schools"],
    ["Coconut Grove", "Lush, bohemian, waterfront and walkable"],
    ["Key Biscayne", "Island living minutes from downtown"],
    ["Doral", "Modern communities, golf and business hub"],
  ];
  return (
    <section className="section hoods" id="neighborhoods">
      <div className="container">
        <div className="section__head">
          <span className="eyebrow" data-reveal>Neighborhoods</span>
          <h2 data-reveal>Find your <em>place</em> in Miami</h2>
          <p data-reveal>Every neighborhood has its own character. Tell me about your lifestyle and goals, and I'll help you find the one that feels right for you.</p>
        </div>
        <ul className="hood-list">
          {hoods.map(([n, d], i) => (
            <li key={n} data-reveal style={{ transitionDelay: `${i * 50}ms` }}>
              <a href="#contact">
                <span className="hood__idx">{String(i + 1).padStart(2, "0")}</span>
                <span className="hood__name">{n}</span>
                <span className="hood__desc">{d}</span>
                <span className="hood__arrow"><Svg d={Ic.arrowR} /></span>
              </a>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* =================== PROCESS =================== */
function Process() {
  const steps = [
    { t: "Let's talk", d: "Message me on WhatsApp or text. Tell me what you're looking for, your timeline and budget." },
    { t: "Curated options", d: "I hand-pick properties that truly fit, schedule showings and walk you through each one." },
    { t: "Negotiation to keys", d: "Offers, contracts, inspections and closing — I'm by your side until you have the keys." },
  ];
  return (
    <section className="section process">
      <div className="container">
        <div className="section__head section__head--center">
          <span className="eyebrow" data-reveal>How it works</span>
          <h2 data-reveal>Simple, <em>personal,</em> clear.</h2>
        </div>
        <ol className="steps">
          {steps.map((s, i) => (
            <li key={s.t} data-reveal style={{ transitionDelay: `${i * 100}ms` }}>
              <span className="steps__n">{String(i + 1).padStart(2, "0")}</span>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* =================== INSTAGRAM =================== */
function Instagram() {
  return (
    <section className="section insta">
      <div className="container insta__grid">
        <div className="insta__photos" data-reveal>
          <img src="assets/gigi-white-jumpsuit.jpg" alt="Gislaine Davini" loading="lazy" />
        </div>
        <div className="insta__text">
          <span className="eyebrow" data-reveal>Follow along</span>
          <h2 data-reveal>Miami, <em>daily.</em></h2>
          <p data-reveal>New listings, neighborhood tours and life in South Florida — follow me on Instagram.</p>
          <a className="btn btn--outline btn--lg" href={INSTAGRAM_URL} target="_blank" rel="noopener" data-reveal><Svg d={Ic.instagram} /> {INSTAGRAM_HANDLE}</a>
        </div>
      </div>
    </section>
  );
}

/* =================== CONTACT FORM =================== */
const PHONE_RE = /^\([2-9]\d{2}\) [2-9]\d{2}-\d{4}$/;
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;
const NAME_RE  = /^[A-Za-zÀ-ÿ' .-]{2,60}$/;

function formatUSPhone(raw) {
  let d = String(raw).replace(/\D/g, "");
  if (d[0] === "1") d = d.slice(1);   // drop a leading +1
  d = d.slice(0, 10);
  if (d.length === 0) return "";
  if (d.length < 4) return `(${d}`;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
}

function validateContact({ name, phone, email, interest, area, details }) {
  const errs = {};
  if (!NAME_RE.test((name || "").trim())) errs.name = "Please enter your full name (letters only).";
  if (!PHONE_RE.test(phone || "")) errs.phone = "Enter a valid US number, e.g. (305) 555-0123.";
  if (!EMAIL_RE.test((email || "").trim())) errs.email = "Please enter a valid email address.";
  if (!(interest || "").trim()) errs.interest = "Please tell me what you're looking for.";
  if ((area || "").trim().length < 3) errs.area = "Please enter a neighborhood, city or ZIP code.";
  if ((details || "").trim().length < 10) errs.details = "Tell me a bit more (at least 10 characters).";
  return errs;
}

function Contact() {
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(false);
  const [phone, setPhone] = useState("");
  const [errs, setErrs] = useState({});
  const clearErr = (k) => setErrs((e) => (e[k] ? { ...e, [k]: undefined } : e));
  const interests = ["Buying a home", "Selling my property", "Renting in Miami", "Investing", "Relocating to Miami", "Something else"];

  const handleSubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    const data = Object.fromEntries(fd);
    for (const k of ["name", "email", "interest", "area", "details"]) data[k] = (data[k] || "").trim();
    const v = validateContact(data);
    if (Object.keys(v).length) {
      setErrs(v);
      const first = e.target.querySelector(`[name="${Object.keys(v)[0]}"]`);
      if (first) first.focus();
      return;
    }
    setSending(true);
    setError(false);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (res.ok) setSent(true); else setError(true);
    } catch {
      setError(true);
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="section contact" id="contact">
      <div className="container contact__grid">
        <div className="contact__intro">
          <span className="eyebrow" data-reveal>Contact</span>
          <h2 data-reveal>Let's find your <em>place in Miami.</em></h2>
          <p data-reveal>Send a few details and I'll personally get back to you — usually the same day. Or chat with me right now on WhatsApp or text message.</p>
          <div className="contact__list">
            <a href={WHATSAPP_HREF} target="_blank" rel="noopener" data-reveal>
              <span className="ic"><Svg d={Ic.chat} /></span>
              <span><b>WhatsApp</b><small>Chat with Gislaine — PT · EN · ES</small></span>
            </a>
            <a href={SMS_HREF} data-reveal>
              <span className="ic"><Svg d={Ic.phone} /></span>
              <span><b>Text message</b><small>{PHONE_DISPLAY}</small></span>
            </a>
            <a href={EMAIL_HREF} data-reveal>
              <span className="ic"><Svg d={Ic.mail} /></span>
              <span><b>{EMAIL}</b><small>Prefer email? Write me anytime</small></span>
            </a>
            <a href={INSTAGRAM_URL} target="_blank" rel="noopener" data-reveal>
              <span className="ic"><Svg d={Ic.instagram} /></span>
              <span><b>{INSTAGRAM_HANDLE}</b><small>Follow me on Instagram</small></span>
            </a>
          </div>
          <p className="contact__broker" data-reveal>{FULL_NAME} · {TITLE} with <b className="broker">{BROKER}</b></p>
        </div>

        <div className="form" data-reveal>
          {sent ? (
            <div className="form__success">
              <div className="check"><Svg d={Ic.check} /></div>
              <h3>Thank you — I'll be in touch!</h3>
              <p>Your message is in. I'll personally reach out shortly to talk about your plans in Miami.</p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate>
              <div className="form__row">
                <div className={`field${errs.name ? " field--err" : ""}`}>
                  <label>Full name</label>
                  <input name="name" required placeholder="Your name" maxLength={60} autoComplete="name" onChange={() => clearErr("name")} />
                  {errs.name && <small className="field__err">{errs.name}</small>}
                </div>
                <div className={`field${errs.phone ? " field--err" : ""}`}>
                  <label>Phone</label>
                  <input name="phone" required type="tel" placeholder="(305) 000-0000" inputMode="tel" autoComplete="tel-national" maxLength={14}
                    value={phone}
                    onChange={(e) => { setPhone(formatUSPhone(e.target.value)); clearErr("phone"); }}
                    onBlur={() => { if (phone && !PHONE_RE.test(phone)) setErrs((er) => ({ ...er, phone: "Enter a valid US number, e.g. (305) 555-0123." })); }} />
                  {errs.phone && <small className="field__err">{errs.phone}</small>}
                </div>
              </div>
              <div className="form__row">
                <div className={`field${errs.email ? " field--err" : ""}`}>
                  <label>Email</label>
                  <input name="email" required type="email" placeholder="you@email.com" maxLength={120} autoComplete="email" onChange={() => clearErr("email")} />
                  {errs.email && <small className="field__err">{errs.email}</small>}
                </div>
                <div className={`field${errs.interest ? " field--err" : ""}`}>
                  <label>I'm interested in</label>
                  <select name="interest" defaultValue="" required onChange={() => clearErr("interest")}>
                    <option value="" disabled>Select an option</option>
                    {interests.map((s) => <option key={s}>{s}</option>)}
                  </select>
                  {errs.interest && <small className="field__err">{errs.interest}</small>}
                </div>
              </div>
              <div className={`field${errs.area ? " field--err" : ""}`}>
                <label>Neighborhood, city or ZIP</label>
                <input name="area" required placeholder="Brickell, Miami Beach, 33131…" minLength={3} maxLength={120} onChange={() => clearErr("area")} />
                {errs.area && <small className="field__err">{errs.area}</small>}
              </div>
              <div className={`field${errs.details ? " field--err" : ""}`}>
                <label>Message</label>
                <textarea name="details" required minLength={10} maxLength={2000} placeholder="Tell me about your plans — bedrooms, budget, timeline…" onChange={() => clearErr("details")}></textarea>
                {errs.details && <small className="field__err">{errs.details}</small>}
              </div>
              <button className="btn btn--gold btn--lg" type="submit" disabled={sending}>
                {sending ? "Sending…" : "Send message"}
              </button>
              {error && (
                <p className="form__error">
                  Something went wrong — please <a href={WHATSAPP_HREF} target="_blank" rel="noopener">message me on WhatsApp</a> or try again.
                </p>
              )}
              <p className="form__fine">No obligation · Portuguese, English &amp; Spanish · Miami &amp; South Florida</p>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

/* =================== FOOTER =================== */
function Footer() {
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot__top">
          <div className="foot__brand">
            <span className="brand__name">{LEGAL_NAME}</span>
            <p>Real Estate Advisor with <b className="broker">{BROKER}</b>. Personalized real estate service in South Florida, in Portuguese, English and Spanish.</p>
          </div>
          <div className="foot__col">
            <h5>Explore</h5>
            <a href="#about">About</a>
            <a href="#services">Services</a>
            <a href="#miami">Why Miami</a>
            <a href="#neighborhoods">Neighborhoods</a>
          </div>
          <div className="foot__col">
            <h5>Get in touch</h5>
            <a href={WHATSAPP_HREF} target="_blank" rel="noopener">WhatsApp</a>
            <a href={SMS_HREF}>Text message</a>
            <a href={EMAIL_HREF}>{EMAIL}</a>
            <a className="foot__ig" href={INSTAGRAM_URL} target="_blank" rel="noopener"><Svg d={Ic.instagram} />{INSTAGRAM_HANDLE}</a>
          </div>
        </div>
        <div className="foot__bar">
          <span>© 2026 {FULL_NAME} · <b className="broker">{BROKER}</b>. All rights reserved.</span>
          <span>Equal Housing Opportunity</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Header, Hero, Intro, About, Services, WhyMiami, Neighborhoods, Process, Instagram, Contact, Footer });
