/* global React, Nav, useReveal, Logo, PROJECTS */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ============================================================
   Project gallery - main image + thumbnail strip
   ============================================================ */
function ProjectGallery({ photos, label, aspect }) {
  const [idx, setIdx] = useStateP(0);
  return (
    <div className={"proj-gallery" + (aspect === "portrait" ? " proj-gallery--portrait" : aspect === "landscape-sm" ? " proj-gallery--landscape-sm" : "")}>
      <div
        className="proj-gallery__main"
        style={{ backgroundImage: `url("${photos[idx]}")` }}
        role="img"
        aria-label={label + " - image " + (idx + 1) + " of " + photos.length} />
      
      {photos.length > 1 &&
      <div className="proj-gallery__thumbs">
        {photos.map((p, i) =>
        <button
          key={p}
          className={"proj-gallery__thumb" + (i === idx ? " is-active" : "")}
          style={{ backgroundImage: `url("${p}")` }}
          onClick={() => setIdx(i)}
          aria-label={"View image " + (i + 1)} />

        )}
      </div>
      }
    </div>);

}

/* ============================================================
   Before / After slider
   ============================================================ */
function BeforeAfter({ before, after }) {
  const wrapRef = useRefP(null);
  const [x, setX] = useStateP(50);
  const dragging = useRefP(false);

  const update = (e) => {
    const r = wrapRef.current.getBoundingClientRect();
    const cx = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
    const pct = Math.max(0, Math.min(100, cx / r.width * 100));
    setX(pct);
  };

  useEffectP(() => {
    const move = (e) => {if (dragging.current) update(e);};
    const up = () => {dragging.current = false;};
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move);
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
  }, []);

  return (
    <div
      className="beforeafter"
      ref={wrapRef}
      style={{ "--ba-x": x + "%" }}
      onMouseDown={(e) => {dragging.current = true;update(e);}}
      onTouchStart={(e) => {dragging.current = true;update(e);}}>
      
      <div className="ph ph--olive before" data-label={before} />
      <div className="after">
        <div className="ph" data-label={after} style={{ width: "100%", height: "100%" }} />
      </div>
      <div className="beforeafter__handle" />
      <div className="beforeafter__labels">
        <span>Before</span><span>After</span>
      </div>
    </div>);

}

/* ============================================================
   Projects Page
   ============================================================ */
const ALL_PROJECTS = [
{
  id: "raymond",
  title: "Professional Apartments",
  loc: "Chester",
  year: "2024",
  tags: ["Private Residential", "Refurbishment"],
  desc: "A full refurbishment of four mid terrace apartments, with a two minute walk to the city centre. Fully furnished to suit modern professional rental demand.",
  hasGallery: true,
  photos: [
  "assets/photos/raymond-02-bedroom.webp",
  "assets/photos/raymond-01-lounge.webp",
  "assets/photos/raymond-03-kitchen-dining.webp",
  "assets/photos/raymond-04-living.webp",
  "assets/photos/raymond-05-kitchen.webp"],

  photo: "Bedroom - 19 Raymond Street"
},
{
  id: "duke",
  title: "Commercial to Residential",
  loc: "Ellesmere Port",
  year: "2022",
  tags: ["Commercial Conversion", "Development"],
  desc: "Acquired off-market via an architect. Developed under planning to seven studio apartments for professionals. A short walk to the train station and local amenities.",
  hasGallery: true,
  photos: [
  "assets/photos/ellesmere-1.webp",
  "assets/photos/ellesmere-2.webp",
  "assets/photos/ellesmere-3.webp",
  "assets/photos/ellesmere-4.webp",
  "assets/photos/ellesmere-5.webp"],

  photo: "Ellesmere Port - Commercial to Residential conversion"
},
{
  id: "boughton",
  title: "Commercial to Mixed Use",
  loc: "Flintshire, N. Wales",
  year: "2025",
  tags: ["FRI Lease", "Mixed Use HMO"],
  desc: "Eight-bedroom HMO and commercial unit let on a five-year FRI lease to an emergency housing provider. Hands-off income.",
  hasGallery: true,
  galleryAspect: "portrait",
  photos: [
  "assets/photos/flint-1.webp",
  "assets/photos/flint-2.webp",
  "assets/photos/flint-3.webp",
  "assets/photos/flint-4.webp",
  "assets/photos/flint-5.webp",
  "assets/photos/flint-6.webp"],

  photo: "Flintshire - Commercial to Mixed Use HMO"
},
{
  id: "deeside",
  title: "FRI Backed HMO",
  loc: "Ellesmere Port",
  year: "2024",
  tags: ["Supported Living", "FRI Lease"],
  desc: "Six-bedroom supported living scheme operated on a 5-year FRI lease to a regional care provider. FRI backed, CPI-linked.",
  hasGallery: true,
  galleryAspect: "portrait",
  photos: [
  "assets/photos/deeside-1.webp",
  "assets/photos/deeside-2.webp",
  "assets/photos/deeside-3.webp",
  "assets/photos/deeside-4.webp",
  "assets/photos/deeside-5.webp"],

  photo: "Communal lounge - Deeside Lodge"
},
{
  id: "saltney",
  title: "Offices to FRI Backed Apartments",
  loc: "Conwy, N. Wales",
  year: "2026",
  status: "active",
  tags: ["Commercial Conversion", "FRI Lease"],
  desc: "Two disused offices currently being converted to six two-bedroom apartments. 5-year FRI lease lined up, long-hold within the portfolio.",
  hasGallery: true,
  galleryAspect: "landscape-sm",
  photos: [
  "assets/photos/saltney-1.webp"],

  photo: "Exterior - Saltney Mill brick façade"
},
{
  id: "wrexham",
  title: "FRI Backed Apartments",
  loc: "Ellesmere Port",
  year: "2026",
  status: "active",
  tags: ["Block Acquisition", "FRI Lease"],
  desc: "Thirteen studio apartment residential block acquired from a single vendor; to be refurbished and let to a supported living provider.",
  hasGallery: true,
  galleryAspect: "landscape-sm",
  photos: [
  "assets/photos/wrexham-1.webp"],

  photo: "Street view - Wrexham Road terraces"
}];


function ProjectsPage({ onNavigate }) {
  useReveal();
  return (
    <div>
      <Nav route="projects" onNavigate={onNavigate} mode="light" />
      <header className="page-hero">
        <div className="page-hero__inner">
          <div>
            <div className="eyebrow">Selected Work · 2020-2025</div>
            <h1 className="page-hero__title">Projects.</h1>
          </div>
          <p className="page-hero__lede">A picture of how we work - acquisition, planning, build and long-term operation. 

          </p>
        </div>
      </header>

      <div style={{ background: "var(--paper)" }}>
        {(() => {
          const completed = ALL_PROJECTS.filter((p) => p.status !== "active");
          const active = ALL_PROJECTS.filter((p) => p.status === "active");
          const renderRow = (p, i) =>
          <article className={"project-row reveal" + (p.status === "active" ? " project-row--active" : "")} key={p.id}>
              <div className="container">
                <div className="project-row__inner">
                  <div className="project-row__media">
                    {p.hasGallery ?
                  <ProjectGallery photos={p.photos} label={p.title} aspect={p.galleryAspect} /> :
                  p.hasBA ?
                  <BeforeAfter
                    before="Before - original Edwardian interior"
                    after="After - refurbishment complete, 19 Raymond Street" /> :
                  <div className={"ph" + (i % 3 === 1 ? " ph--olive" : i % 3 === 2 ? " ph--terracotta" : "")} data-label={p.photo} style={{ aspectRatio: "4/3", width: "100%" }} />
                  }
                    {p.status === "active" ?
                  <div className="project-row__active-flag">In Progress</div> :
                  <div className="project-row__completed-flag">Completed</div>
                  }
                  </div>
                  <div className="project-row__meta">
                    <div className="project-row__tags">
                      {p.tags.map((t, idx) =>
                    <span className={"tag " + (idx === 0 ? "tag--olive" : "")} key={t}>{t}</span>
                    )}
                      <span className="tag">{p.year}</span>
                    </div>
                    <div className="project-row__loc">{p.loc}</div>
                    <h2 className="project-row__title">{p.title}</h2>
                    <p className="project-row__desc">{p.desc}</p>
                  </div>
                </div>
              </div>
            </article>;

          return (
            <React.Fragment>
              <div className="project-group-head">
                <div className="container">
                  <div className="project-group-head__inner">
                    <div className="eyebrow">Completed</div>
                    <div className="project-group-head__count">{completed.length} schemes</div>
                  </div>
                </div>
              </div>
              {completed.map(renderRow)}

              <div className="project-group-head project-group-head--active">
                <div className="container">
                  <div className="project-group-head__inner">
                    <div className="eyebrow" style={{ color: "var(--terracotta)" }}>
                      <span className="project-group-head__dot" /> Active
                    </div>
                    <div className="project-group-head__count">{active.length} schemes in progress</div>
                  </div>
                </div>
              </div>
              {active.map(renderRow)}
            </React.Fragment>);

        })()}
      </div>

      <section className="section section--olive">
        <div className="container">
          <div style={{ textAlign: "center", maxWidth: 720, margin: "0 auto" }}>
            <div className="eyebrow" style={{ color: "var(--terracotta-soft)" }}>Talk to us</div>
            <h2 className="section-head__title" style={{ marginTop: 16, marginBottom: 32 }}>
              Selling a property? <em style={{ fontStyle: "italic", fontFamily: "var(--font-serif)", fontWeight: 400, color: "var(--terracotta-soft)" }}>Let's talk.</em>
            </h2>
            <button className="btn btn--cream" onClick={() => onNavigate("sell")}>
              Sell your property <span className="btn__arrow">→</span>
            </button>
          </div>
        </div>
      </section>

      <Footer onNavigate={onNavigate} />
    </div>);

}

/* ============================================================
   Sell Your Property - lead form
   ============================================================ */
function SellPage({ onNavigate }) {
  const [form, setForm] = useStateP({ name: "", phone: "", email: "", address: "", desc: "", consent: false });
  const [submitted, setSubmitted] = useStateP(false);
  const [errors, setErrors] = useStateP({});

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.trim()) e.email = "Required";else
    if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = "Invalid email";
    if (!form.address.trim()) e.address = "Required";
    if (!form.desc.trim()) e.desc = "Required";
    if (!form.consent) e.consent = "Required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;

    // Post silently to Google Forms in the background.
    // No-cors fetch: we can't read the response, but submission still goes through.
    const GFORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSdSSXaTJGI-r0238xxIArzOKQFW3LaA1llevsAS27eftIipVw/formResponse";
    const data = new FormData();
    data.append("entry.1547138098", form.name);
    data.append("entry.1664777010", form.phone);
    data.append("entry.2067243839", form.email);
    data.append("entry.1312253479", form.address);
    data.append("entry.380913317", form.desc);
    fetch(GFORM_URL, { method: "POST", mode: "no-cors", body: data }).catch(() => {});

    setSubmitted(true);
  };

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value });

  return (
    <div className="sell-page">
      <header className="sell-header">
        <div className="sell-header__brand" onClick={() => onNavigate("home")}>
          <Logo size={32} color="var(--olive)" />
          <span>Rose Family Properties</span>
        </div>
        <div className="sell-header__back" onClick={() => onNavigate("home")}>← Back to site</div>
      </header>

      <div className="sell-shell">
        <aside className="sell-aside">
          <div className="sell-aside__ph ph ph--olive" data-label="" />
          <div className="sell-aside__content">
            <div className="eyebrow eyebrow--cream" style={{ color: "var(--terracotta-soft)", opacity: 1 }}>Sell your property</div>
            <h1>Thinking of selling?</h1>
            <p>We buy property directly from owners - no agents, no chain, no obligation. 

If you own the property; a house, block of apartments or commercial unit in any condition, and are considering a sale - we'd like to hear from you.</p>
            <ul className="sell-aside__bullets">
              <li>Direct purchase, no agent fees</li>
              <li>Cash buyers, any condition</li>
              <li>Owner-occupied, tenanted or vacant</li>
              <li>Chester · Manchester · North Wales</li>
            </ul>
          </div>
          <div className="signoff">George & Sam Rose</div>
        </aside>

        <div className="sell-form-wrap">
          {submitted ?
          <div className="sell-success">
              <div className="sell-success__mark">✓</div>
              <div className="eyebrow">Received</div>
              <h3>Thank you, {form.name.split(" ")[0]}.</h3>
              <p>We've received your details and will be in touch shortly.</p>
              <button className="btn btn--solid" style={{ marginTop: 16 }} onClick={() => onNavigate("home")}>
                Back to homepage <span className="btn__arrow">→</span>
              </button>
            </div> :

          <form className="sell-form" onSubmit={submit} noValidate>
              <div>
                <div className="eyebrow">Your details</div>
                <h3>Tell us about the property.</h3>
                <p className="form-lede">No pressure, no obligation. We'll be in touch shortly.</p>
              </div>

              <div className="field">
                <label>Full name <span className="req">*</span></label>
                <input type="text" value={form.name} onChange={update("name")} autoComplete="name" />
                {errors.name && <div className="error">{errors.name}</div>}
              </div>

              <div className="field--row">
                <div className="field">
                  <label>Phone <span style={{ opacity: 0.5, fontWeight: 500 }}>(optional)</span></label>
                  <input type="tel" value={form.phone} onChange={update("phone")} autoComplete="tel" />
                  {errors.phone && <div className="error">{errors.phone}</div>}
                </div>
                <div className="field">
                  <label>Email <span className="req">*</span></label>
                  <input type="email" value={form.email} onChange={update("email")} autoComplete="email" />
                  {errors.email && <div className="error">{errors.email}</div>}
                </div>
              </div>

              <div className="field">
                <label>Property address / postcode <span className="req">*</span></label>
                <input type="text" value={form.address} onChange={update("address")} autoComplete="street-address" />
                {errors.address && <div className="error">{errors.address}</div>}
              </div>

              <div className="field">
                <label>Brief description <span className="req">*</span></label>
                <textarea rows={3} value={form.desc} onChange={update("desc")} placeholder="Anything we should know - tenure, current use, condition…" />
                {errors.desc && <div className="error">{errors.desc}</div>}
              </div>

              <label className="consent">
                <input type="checkbox" checked={form.consent} onChange={update("consent")} />
                <span>I consent to Rose Family Properties storing the details above for the purpose of responding to my enquiry. We won't share them.</span>
              </label>
              {errors.consent && <div className="error">Please consent to continue.</div>}

              <button type="submit" className="btn btn--solid" style={{ marginTop: 16, alignSelf: "flex-start" }}>
                Get in touch <span className="btn__arrow">→</span>
              </button>
            </form>
          }
        </div>
      </div>
    </div>);

}

Object.assign(window, { BeforeAfter, ProjectsPage, SellPage, ALL_PROJECTS });