/* Sections: Estate, Provenance, Quote, Gallery, Specifications, Enquiry, Footer */
const { useState, useEffect, useRef } = React;

const Reveal = ({ children, delay = 0, as: Tag = "div", className = "", ...rest }) => {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setTimeout(() => el.classList.add("in"), delay); io.unobserve(el); } });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={`reveal ${className}`} {...rest}>{children}</Tag>;
};

const Estate = () => (
  <section className="section" id="estate">
    <div className="container">
      <Reveal className="section-head">
        <div className="section-num">I — The Estate</div>
        <h2 className="section-title">One level,<br/>set beneath the oaks.</h2>
      </Reveal>

      <div className="estate-grid">
        <Reveal className="estate-text" delay={120}>
          <p>Villa Francesca is a single-story residence of 4,654 square feet under air, set on 0.78 acre in the equestrian corridor of South Miami. Six ensuite bedrooms, eight baths, a detached cabana and a separate staff suite are arranged along one axis, from the covered entry through the foyer and great room to the rear loggia.</p>
          <p>The plan turns toward its own grounds. Floor-to-ceiling black-framed glass opens the great room, dining room and primary suite to the garden; a cedar-ceilinged loggia leads to a 2,884-square-foot pool deck and the cabana beyond, all shaded by mature oaks.</p>
          <p>Built by The Calta Group to drawings by Castillo Architecture &amp; Planning, with walnut and stone cabinetry by Mia Cucina. Completed 2026. Never occupied.</p>

          <dl className="estate-meta">
            <div><dt>Plan</dt><dd>Single story · 7,209 sf under roof</dd></div>
            <div><dt>Parcel</dt><dd>0.78 acre</dd></div>
            <div><dt>Offered at</dt><dd>$5,399,000</dd></div>
          </dl>
        </Reveal>

        <Reveal delay={240}>
          <Plate aspect="4-5" label="The Loggia · toward the pool and cabana" corner="Plate · I" src="images/loggia-pool.jpg" />
        </Reveal>
      </div>
    </div>
  </section>
);

const Provenance = () => (
  <section className="section" id="provenance">
    <div className="container">
      <Reveal className="section-head">
        <div className="section-num">II — Provenance</div>
        <h2 className="section-title">Built quietly,<br/>by hands that know.</h2>
      </Reveal>

      <Reveal className="prov-grid">
        <div className="prov-card">
          <div className="num">01 · The Builder</div>
          <h3>The Calta Group</h3>
          <p>A South Florida builder of custom residences. Every joint considered, every transition resolved; built in small numbers, to an exacting standard.</p>
          <div className="prov-tags"><span>South Florida</span><span>Custom residences</span><span>New construction</span></div>
        </div>
        <div className="prov-card">
          <div className="num">02 · The Architect</div>
          <h3>Castillo Architecture &amp; Planning</h3>
          <p>A single-axis plan under a hipped roof: covered entry, foyer, great room and loggia in one line, with the primary suite to the west and the service wing and three-car garage to the east.</p>
          <div className="prov-tags"><span>Single story</span><span>Stamped plan set</span><span>Hipped roofline</span></div>
        </div>
        <div className="prov-card">
          <div className="num">03 · The Cabinetry</div>
          <h3>Mia Cucina</h3>
          <p>Walnut and stone in the kitchen, floating walnut vanities in the primary bath, and a dressing room in floor-to-ceiling walnut. Quiet hardware, integrated stone, Italian sensibility.</p>
          <div className="prov-tags"><span>Walnut</span><span>Stone</span><span>Italian cabinetry</span></div>
        </div>
      </Reveal>
    </div>
  </section>
);

const Quote = () => (
  <section className="quote">
    <Reveal>
      <blockquote>"The villas of the Italian lakes are not built; they are <em>placed</em> — among the cypresses and the water, as if they had always been there."</blockquote>
      <div className="cite">— Marella Agnelli, on Bellagio</div>
    </Reveal>
  </section>
);

/* ---------- Photographs ---------- */
const chapters = [
  { num: "I", title: "The Approach", items: [
    ["twilight", "Twilight over the front lawn", "wide"],
    ["front-lawn", "The lawn runs the full width of the lot", "half"],
    ["front-drive", "Covered entry and three-car garage", "half"],
    ["front-angle", "Hipped roofline, cedar soffits", "half"],
    ["front-oak", "Set well back from the street", "half"],
    ["grounds-1", "0.78 acre beneath mature oaks", "half"],
    ["grounds-2", "The motor court", "half"],
    ["grounds-3", "East elevation", "half"],
    ["grounds-4", "From the lawn", "half"],
  ]},
  { num: "II", title: "Loggia, Pool & Cabana", items: [
    ["loggia-pool", "The loggia, toward the pool and cabana", "wide"],
    ["loggia-1", "Cedar ceiling, black-framed glass", "half"],
    ["loggia-2", "Outdoor dining", "half"],
    ["loggia-seating", "The seating terrace", "half"],
    ["loggia-3", "Covered terrace", "half"],
    ["pool-1", "A 2,884 sf pool deck edged in turf", "half"],
    ["pool-cabana", "The detached cabana, 736 sf with its own bath", "half"],
    ["pool-2", "The pool, from the cabana", "half"],
    ["view-slider", "The view from the great room", "half"],
  ]},
  { num: "III", title: "Kitchen & Dining", items: [
    ["kitchen-1", "Walnut and stone by Mia Cucina", "wide"],
    ["kitchen-2", "The island seats five", "half"],
    ["kitchen-3", "Toward the breakfast room", "half"],
    ["dining", "Dining room, glass on three sides", "wide"],
  ]},
  { num: "IV", title: "The Great Room", items: [
    ["great-2", "One axis from the foyer to the loggia", "wide"],
    ["great-1", "Lit tray ceilings throughout", "half"],
    ["great-3", "Toward the gallery", "half"],
    ["great-4", "Family seating", "half"],
    ["media-1", "The media room", "half"],
    ["media-2", "A second living room off the family wing", "half"],
    ["study-1", "The study, opening to the lawn", "half"],
    ["study-2", "The study", "half"],
  ]},
  { num: "V", title: "The Primary Suite", items: [
    ["primary-1", "Tray ceiling, garden views on two sides", "wide"],
    ["primary-2", "The primary bedroom", "half"],
    ["primary-3", "The west wing to itself", "half"],
    ["primary-4", "Toward the dressing room", "half"],
    ["closet", "The dressing room, floor-to-ceiling walnut", "half"],
    ["pbath-1", "Twin walnut vanities and a freestanding tub", "wide"],
    ["pbath-2", "The primary bath", "half"],
    ["gbath-1", "Each of five bedrooms is ensuite", "half"],
  ]},
  { num: "VI", title: "The Details", items: [
    ["gbath-2", "A guest bath", "third"],
    ["gallery-hall", "Light at the end of every corridor", "third"],
    ["laundry", "Mudroom and laundry, east wing", "third"],
    ["garage", "Three-car garage, epoxy floor", "wide"],
  ]},
];
const galleryItems = [];
chapters.forEach((c) => c.items.forEach(([key, caption, size]) => {
  galleryItems.push({ idx: galleryItems.length, key, caption, size, chapter: c.title, src: `images/${key}.jpg`, thumb: `images/${key}-s.jpg` });
}));

const Gallery = ({ onOpen }) => (
  <section className="section" id="gallery">
    <div className="container">
      <Reveal className="section-head">
        <div className="section-num">III — Photographs</div>
        <h2 className="section-title">The house,<br/>chapter by chapter.</h2>
      </Reveal>

      {chapters.map((c, ci) => (
        <div className="chapter" key={c.num}>
          <Reveal className="chapter-head">
            <span className="num">Chapter {c.num}</span>
            <h3>{c.title}</h3>
            <span className="count">{String(c.items.length).padStart(2, "0")} plates</span>
          </Reveal>
          <div className="ch-grid">
            {c.items.map(([key, caption, size], i) => {
              const item = galleryItems.find((g) => g.key === key);
              return (
                <Reveal key={key} className={`g-i ch-${size}`} delay={(i % 4) * 70}>
                  <Plate aspect="3-2" src={item.thumb} alt={caption} onClick={() => onOpen(item.idx)} />
                  <div className="g-cap"><strong>{c.num} · {String(i + 1).padStart(2, "0")}</strong><span>{caption}</span></div>
                </Reveal>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  </section>
);

const Lightbox = ({ index, onClose, onPrev, onNext }) => {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose, onPrev, onNext]);

  const open = index !== null;
  const item = open ? galleryItems[index] : null;
  return (
    <div className={`lightbox ${open ? "open" : ""}`} onClick={onClose}>
      {item && (
        <div className="lightbox-inner" onClick={(e) => e.stopPropagation()}>
          <div className="lightbox-counter">{String(index + 1).padStart(2, "0")} / {String(galleryItems.length).padStart(2, "0")}</div>
          <button className="lightbox-close" onClick={onClose}>Close ✕</button>
          <button className="lightbox-nav lightbox-prev" onClick={onPrev}>‹</button>
          <button className="lightbox-nav lightbox-next" onClick={onNext}>›</button>
          <div className="lightbox-photo">
            <img src={item.src} alt={item.caption} />
            <div className="g-cap" style={{ color: "#c9b890" }}>
              <strong style={{ color: "#f5f0e6" }}>{item.chapter}</strong>
              <span>{item.caption}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

/* ---------- Specifications ---------- */
const Specifications = () => (
  <section className="section" id="plan" style={{ background: "var(--cream-2)" }}>
    <div className="container">
      <Reveal className="section-head">
        <div className="section-num">IV — Plans & Specifications</div>
        <h2 className="section-title">A plan that<br/>runs on one line.</h2>
      </Reveal>

      <div className="fp-wrap">
        <Reveal>
          <p style={{ fontSize: 18, lineHeight: 1.65, color: "var(--umber-2)", marginTop: 0 }}>
            The covered entry opens to the foyer and great room, then straight through to the rear loggia and pool. The primary suite anchors the west wing with a tray-ceilinged bedroom, dressing room and twin-vanity bath. Three further ensuite bedrooms sit along the north side; a fifth bedroom, staff suite, mudroom and pantry complete the east wing beside the three-car garage.
          </p>
          <dl className="fp-stats">
            <div><dt>Under air</dt><dd>4,654 sq ft</dd></div>
            <div><dt>Under roof</dt><dd>7,209 sq ft</dd></div>
            <div><dt>Bedrooms</dt><dd>Six · ensuite</dd></div>
            <div><dt>Baths</dt><dd>Eight</dd></div>
            <div><dt>Lot</dt><dd>0.78 acre</dd></div>
            <div><dt>Garage</dt><dd>Three bays</dd></div>
            <div><dt>Pool &amp; deck</dt><dd>2,884 sq ft</dd></div>
            <div><dt>Cabana</dt><dd>736 sq ft · bath</dd></div>
            <div><dt>Staff suite</dt><dd>Separate</dd></div>
          </dl>
          <div className="spec-note">Architect's stamped plan set (Castillo, Sheet A-1.1)<br/>and builder's specification sheet on request.</div>
        </Reveal>

        <Reveal delay={160}>
          <Plate aspect="4-5" label="The Primary Bath · twin walnut vanities" corner="Plate · II" src="images/pbath-1.jpg" />
        </Reveal>
      </div>
    </div>
  </section>
);

/* ---------- Enquiry ---------- */
const Enquire = () => {
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    const body = `Name: ${f.get("name")}\nEmail: ${f.get("email")}\nPhone: ${f.get("phone") || ""}\nRepresentation: ${f.get("rep") || ""}\n\n${f.get("note") || ""}`;
    window.location.href = `mailto:mrandrealestate@gmail.com,sammysellsmiami@gmail.com?subject=${encodeURIComponent("Villa Francesca · Private enquiry")}&body=${encodeURIComponent(body)}`;
    setSent(true);
  };
  return (
    <section className="enquire" id="enquire">
      <div className="container">
        <Reveal className="section-head">
          <div className="section-num">V — Private Enquiry</div>
          <h2 className="section-title">Shown privately,<br/>by appointment.</h2>
        </Reveal>

        <div className="enq-grid">
          <Reveal className="enq-text">
            <p>Villa Francesca is offered at $5,399,000 and shown by appointment ahead of its public release on October 15. Twilight showings Tuesday and Thursday. Open house Saturday, October 3, 11 AM to 2 PM.</p>
            <div className="enq-rule"></div>
            <div className="enq-agents">
              <div className="enq-contact">
                Michael Rand
                <small>Co-listing agent · Lifestyle International Realty</small>
                <div style={{ marginTop: 14 }}><a href="tel:+13072211984">(307) 221-1984</a></div>
                <div style={{ marginTop: 8 }}><a href="mailto:mrandrealestate@gmail.com">mrandrealestate@gmail.com</a></div>
              </div>
              <div className="enq-contact">
                Sammy Hernandez
                <small>Co-listing agent</small>
                <div style={{ marginTop: 14 }}><a href="tel:+17862038671">(786) 203-8671</a></div>
                <div style={{ marginTop: 8 }}><a href="mailto:sammysellsmiami@gmail.com">sammysellsmiami@gmail.com</a></div>
              </div>
            </div>
            <div style={{ marginTop: 22 }}><a className="enq-ig" href="https://instagram.com/villa_francesca9999" target="_blank" rel="noopener">@villa_francesca9999</a></div>
          </Reveal>

          <Reveal delay={160}>
            {!sent ? (
              <form className="enq-form" onSubmit={submit}>
                <Field label="Name" type="text" name="name" required />
                <Field label="Email" type="email" name="email" required />
                <Field label="Phone" type="tel" name="phone" />
                <Field label="Representation (if any)" type="text" name="rep" />
                <Field label="Preferred day and time" type="textarea" name="note" />
                <button className="btn" type="submit"><span>Request a showing →</span></button>
              </form>
            ) : (
              <div className="enq-success">
                Thank you. Your mail client has opened with the request; send it and we will confirm a time within the day.
                <small>Or text Michael (307) 221-1984 · Sammy (786) 203-8671</small>
              </div>
            )}
          </Reveal>
        </div>
      </div>
    </section>
  );
};

const Field = ({ label, type, name, required }) => {
  const [focus, setFocus] = useState(false);
  const [val, setVal] = useState("");
  const cls = `field ${focus ? "focus" : ""} ${val ? "filled" : ""}`;
  return (
    <div className={cls}>
      <label htmlFor={name}>{label}{required && " *"}</label>
      {type === "textarea" ? (
        <textarea id={name} name={name} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} onChange={(e) => setVal(e.target.value)} required={required}></textarea>
      ) : (
        <input id={name} name={name} type={type} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} onChange={(e) => setVal(e.target.value)} required={required} />
      )}
    </div>
  );
};

const Footer = () => (
  <footer className="footer">
    <div className="container footer-grid">
      <div className="mark">VF · Villa Francesca</div>
      <div>Michael Rand (307) 221-1984 · Sammy Hernandez (786) 203-8671 · Lifestyle International Realty</div>
      <div>Built by The Calta Group · Architecture by Castillo · Cabinetry by Mia Cucina</div>
      <div>© 2026 · Equal Housing Opportunity · Dimensions approximate, buyer to verify</div>
    </div>
  </footer>
);

window.Reveal = Reveal; window.Estate = Estate; window.Provenance = Provenance; window.Quote = Quote;
window.Gallery = Gallery; window.Lightbox = Lightbox; window.Specifications = Specifications;
window.Enquire = Enquire; window.Footer = Footer; window.galleryItems = galleryItems;
