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

/* ============================================================
   Logo - simplified geometric rose hexagon mark
   Original mark, recreated as inline SVG so it scales cleanly.
   ============================================================ */
function Logo({ size = 36, color = "currentColor" }) {
  const [markup, setMarkup] = useState("");
  useEffect(() => {
    let alive = true;
    fetch("assets/logo-vector.svg").
    then((r) => r.text()).
    then((t) => {
      if (!alive) return;
      // Recolor the white fill to inherit currentColor so it can sit on any background.
      const recolored = t.
      replace(/fill="#ffffff"/gi, 'fill="currentColor"').
      replace(/width="2000px"/, 'width="100%"').
      replace(/height="2000px"/, 'height="100%"');
      setMarkup(recolored);
    });
    return () => {alive = false;};
  }, []);
  return (
    <span
      aria-label="Rose Family Properties"
      style={{
        display: "inline-block",
        width: size,
        height: size,
        color,
        lineHeight: 0
      }}
      dangerouslySetInnerHTML={{ __html: markup }} />);


}

/* ============================================================
   Nav
   ============================================================ */
function Nav({ route, onNavigate, mode = "hero" }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Lock body scroll when the mobile drawer is open
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  // Close on route change
  useEffect(() => { setMenuOpen(false); }, [route]);

  const cls =
  "nav " + (
  mode === "light" ?
  "nav--light" :
  scrolled ?
  "nav--scrolled" :
  "nav--on-hero");

  const items = [
  { id: "home", label: "Home" },
  { id: "projects", label: "Projects" },
  { id: "about", label: "About", anchor: "about" },
  { id: "contact", label: "Contact", anchor: "contact" }];


  const go = (item, e) => {
    e.preventDefault();
    setMenuOpen(false);
    if (item.anchor && route === "home") {
      const el = document.getElementById(item.anchor);
      if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
    } else if (item.anchor) {
      onNavigate("home", item.anchor);
    } else {
      onNavigate(item.id);
    }
  };

  return (
    <header className={cls + (menuOpen ? " nav--menu-open" : "")}>
      <a href="#" className="nav__brand" onClick={(e) => {e.preventDefault();setMenuOpen(false);onNavigate("home");}}>
        <span className="nav__logo"><Logo size={38} /></span>
        <span className="nav__wordmark">
          <span className="top">Rose Family Properties</span>
          <span className="bot">Est. Chester · North West</span>
        </span>
      </a>
      <nav className="nav__links">
        {items.map((it) =>
        <a key={it.id} href="#" onClick={(e) => go(it, e)} className={route === it.id ? "is-active" : ""}>
            {it.label}
          </a>
        )}
        <a href="#" className="cta" onClick={(e) => {e.preventDefault();setMenuOpen(false);onNavigate("sell");}}>
          Sell Your Property
        </a>
      </nav>
      <button
        className={"nav__burger" + (menuOpen ? " is-open" : "")}
        onClick={() => setMenuOpen((v) => !v)}
        aria-label={menuOpen ? "Close menu" : "Open menu"}
        aria-expanded={menuOpen}>
        <span /><span /><span />
      </button>

      <div className={"nav__drawer" + (menuOpen ? " is-open" : "")} aria-hidden={!menuOpen}>
        <nav className="nav__drawer-links">
          {items.map((it) =>
            <a key={it.id} href="#" onClick={(e) => go(it, e)}>{it.label}</a>
          )}
          <a href="#" className="nav__drawer-cta" onClick={(e) => {e.preventDefault();setMenuOpen(false);onNavigate("sell");}}>
            Sell Your Property <span aria-hidden="true">→</span>
          </a>
        </nav>
      </div>
    </header>);

}

/* ============================================================
   Hero - Ken Burns slideshow, text anchored left
   ============================================================ */
const HERO_SLIDES = [
{ src: "assets/photos/raymond-01-lounge.webp", caption: "Lounge · 19 Raymond Street" },
{ src: "assets/photos/raymond-02-bedroom.webp", caption: "Bedroom · 19 Raymond Street" },
{ src: "assets/photos/raymond-04-living.webp", caption: "Living & Dining · 19 Raymond Street" },
{ src: "assets/photos/raymond-03-kitchen-dining.webp", caption: "Open Plan Kitchen · 19 Raymond Street" },
{ src: "assets/photos/raymond-05-kitchen.webp", caption: "Marble Kitchen · 19 Raymond Street" }];

const HERO_DURATION_MS = 6500;

function Hero({ onNavigate }) {
  const [active, setActive] = useState(0);

  // Preload all images once
  useEffect(() => {
    HERO_SLIDES.forEach((s) => {const i = new Image();i.src = s.src;});
  }, []);

  // Auto-advance (respects prefers-reduced-motion)
  useEffect(() => {
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = setInterval(() => {
      setActive((a) => (a + 1) % HERO_SLIDES.length);
    }, HERO_DURATION_MS);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero" id="home">
      <div className="hero__kb" aria-hidden="true">
        {HERO_SLIDES.map((s, i) =>
        <div
          key={s.src}
          className={"hero__kb-slide" + (i === active ? " is-active" : "")}
          style={{ backgroundImage: `url("${s.src}")` }} />

        )}
      </div>
      <div className="hero__grain" aria-hidden="true" />
      <div className="hero__overlay" />

      <div className="container hero__inner">
        <div className="hero__content reveal in" style={{ opacity: "1" }}>
          <div className="eyebrow hero__eyebrow">FAMILY-OWNED · CHESTER · EST. 2018</div>
          <h1 className="display hero__headline">
            We acquire, convert and operate <em>residential property</em> across the North West.
          </h1>
          <p className="lede hero__sub">A Chester-based family business built on long-term relationships; sourcing, developing and managing property.

          </p>
          <div className="hero__cta-row">
            <button className="btn btn--cream" onClick={() => onNavigate("projects")}>
              View Our Projects <span className="btn__arrow">→</span>
            </button>
            <button className="btn-ghost" onClick={() => {
              const el = document.getElementById("about");
              if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
            }}>
              About the family
            </button>
          </div>
        </div>
      </div>

      <div className="hero__corners">
        <div>Chester · Manchester · North Wales</div>
      </div>
    </section>);

}

/* ============================================================
   Reveal-on-scroll hook
   ============================================================ */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { rootMargin: "-10% 0px -10% 0px", threshold: 0.05 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ============================================================
   Section heading
   ============================================================ */
function SectionHead({ eyebrow, title, lede, eyebrowMod, stacked }) {
  if (stacked) {
    return (
      <div className="section-head section-head--stacked">
        <div className={"eyebrow section-head__eyebrow " + (eyebrowMod || "")}>{eyebrow}</div>
        <h2 className="section-head__title">{title}</h2>
        {lede && <p className="section-head__lede">{lede}</p>}
      </div>);
  }
  return (
    <div className="section-head">
      <div>
        <div className={"eyebrow " + (eyebrowMod || "")}>{eyebrow}</div>
        <h2 className="section-head__title">{title}</h2>
      </div>
      {lede && <p className="section-head__lede">{lede}</p>}
    </div>);

}

/* ============================================================
   What We Do
   ============================================================ */
function WhatWeDo() {
  const cols = [
  {
    n: "i.",
    title: "Acquire",
    body: "Freehold acquisitions - commercial and residential - sourced directly across Cheshire, North Wales and Greater Manchester.",
    list: ["Off-market sourcing", "Direct-to-vendor", "Commercial & residential"]
  },
  {
    n: "ii.",
    title: "Convert",
    body: "Planning-led conversions to high-quality residential. We complete the deals others can't.",
    list: ["Permitted development", "Full planning", "Commercial stock"]
  },
  {
    n: "iii.",
    title: "Operate",
    body: "Structured leasing and active management across private residential, HMOs, supported living and FRI-backed residential.",
    list: ["Private residential", "Supported living", "FRI commercial leases"]
  }];

  return (
    <section className="section section--olive" id="what-we-do">
      <div className="container">
        <SectionHead
          eyebrow="What We Do"
          eyebrowMod="eyebrow"
          stacked
          title="Complete property operations; from acquisition to long-term tenancy."
          lede="Three disciplines, one team. We control every stage of the deal because that's how long-term value is actually built." />
        
        <div className="pillars reveal">
          {cols.map((c) =>
          <div className="pillar" key={c.title}>
              <div className="pillar__num">{c.n}</div>
              <div className="pillar__title">{c.title}</div>
              <ul className="pillar__list">
                {c.list.map((l) => <li key={l}>{l}</li>)}
              </ul>
              <div className="pillar__body">{c.body}</div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ============================================================
   About
   ============================================================ */
function About() {
  return (
    <section className="section section--cream" id="about">
      <div className="container">
        <div className="about-grid">
          <div className="about-photo" style={{ backgroundImage: 'url("assets/photos/rose-family.webp")', backgroundSize: "cover", backgroundPosition: "center" }} role="img" aria-label="George & Sam Rose" />
          <div className="about-copy reveal">
            <div className="eyebrow">About the Family</div>
            <h3>A decade of patient ownership in the North West.</h3>
            <p className="body-l">Rose Family Properties is a Chester-based development and investment company run by George and Sam Rose. We source, convert and hold residential property across the North West - building the kind of relationships with owners, industry professionals and lenders that complete deals others walk away from.

            </p>
            <p className="body-l">For nearly a decade we've bought and developed property in Chester, North Wales and Greater Manchester. Our portfolio spans commercial conversions, supported living, HMOs and high-end private residential. Short term results, long term vision.

            </p>
            <div className="about-meta">
              <div className="about-meta__item">
                <div className="k">Founded</div>
                <div className="v">2018, Chester</div>
              </div>
              <div className="about-meta__item">
                <div className="k">Region</div>
                <div className="v">North West &amp; N. Wales</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ============================================================
   Projects Teaser
   ============================================================ */
const PROJECTS = [
{
  id: "raymond",
  title: "Professional Apartments",
  loc: "Chester",
  tag: "Private Residential",
  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.",
  photo: "Lounge - 19 Raymond Street",
  photoSrc: "assets/photos/raymond-01-lounge.webp",
  hasBA: true
},
{
  id: "duke",
  title: "Commercial to Residential",
  loc: "Ellesmere Port",
  tag: "Commercial Conversion",
  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.",
  photo: "Ellesmere Port - Commercial to Residential conversion",
  photoSrc: "assets/photos/ellesmere-1.webp"
},
{
  id: "wrexham",
  title: "FRI Backed Apartments",
  loc: "Ellesmere Port",
  tag: "Block Acquisition",
  desc: "Thirteen studio apartment residential block acquired from a single vendor; to be refurbished and let to a supported living provider.",
  photo: "Street view - Wrexham Road terraces",
  photoSrc: "assets/photos/wrexham-1.webp",
  status: "active"
}];


function ProjectsTeaser({ onNavigate }) {
  return (
    <section className="section section--paper">
      <div className="container">
        <SectionHead
          eyebrow="Selected Projects"
          title="A portfolio built deal by deal."
          lede="Nearly a decade of off-market acquisitions, planning-led conversions and long-hold operation." />
        
        <div className="projects-grid reveal">
          {PROJECTS.map((p) =>
          <div className="proj-card" key={p.id} onClick={() => onNavigate("projects")}>
              <div className="proj-card__media">
                <div
                className={"ph" + (p.photoSrc ? " ph--photo" : p.id === "duke" ? " ph--olive" : p.id === "deeside" ? " ph--terracotta" : "")}
                data-label={p.photoSrc ? "" : p.photo}
                style={p.photoSrc ? { backgroundImage: `url("${p.photoSrc}")`, backgroundSize: "cover", backgroundPosition: "center" } : undefined} />
              
                <div className="proj-card__tag">{p.tag}</div>
                {p.status === "active" ?
                  <div className="proj-card__flag proj-card__flag--active">In Progress</div> :
                p.status === "completed" ?
                  <div className="proj-card__flag proj-card__flag--completed">Completed</div> :
                  null
                }
              </div>
              <div>
                <div className="proj-card__loc">{p.loc}</div>
                <h4 className="proj-card__title">{p.title}</h4>
                <p className="proj-card__desc">{p.desc}</p>
              </div>
            </div>
          )}
        </div>
        <div style={{ marginTop: 64, display: "flex", justifyContent: "center" }}>
          <button className="btn btn--solid" onClick={() => onNavigate("projects")}>
            View all projects <span className="btn__arrow">→</span>
          </button>
        </div>
      </div>
    </section>);

}

/* ============================================================
   Contact
   ============================================================ */
function Contact() {
  return (
    <section className="section section--olive" id="contact">
      <div className="container">
        <div className="contact-block reveal">
          <div className="eyebrow eyebrow--cream" style={{ color: "var(--terracotta-soft)", opacity: 1 }}>Get in touch</div>
          <h2>We're always open to a conversation.</h2>
          <p className="lede" style={{ color: "var(--cream)" }}>Whether you're selling a property, interested in working with us, or institutionally curious - we'd like to hear from you.

          </p>
          <div className="contact-social" role="list">
            <a className="contact-social__btn" role="listitem" href="https://www.instagram.com/roseproperties/" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="18" height="18" rx="5" ry="5" />
                <circle cx="12" cy="12" r="4" />
                <circle cx="17.5" cy="6.5" r="0.9" fill="currentColor" stroke="none" />
              </svg>
            </a>
            <a className="contact-social__btn" role="listitem" href="https://www.facebook.com/people/Rose-Properties/61587160544094/" target="_blank" rel="noopener noreferrer" aria-label="Facebook">
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M13.5 22v-8.5h2.85l.43-3.32H13.5V8.06c0-.96.27-1.62 1.65-1.62h1.76V3.47A23.6 23.6 0 0 0 14.34 3.3c-2.55 0-4.3 1.56-4.3 4.42v2.46H7.2v3.32h2.84V22h3.46Z" />
              </svg>
            </a>
          </div>
        </div>
      </div>
    </section>);

}

/* ============================================================
   Footer - liquid-glass card over a looping video background
   ============================================================ */
function SocialIcon({ name }) {
  // Inline lucide-style stroked icons (originals, not branded).
  const stroke = "currentColor";
  const common = { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke, strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  if (name === "instagram") return (
    <svg {...common} aria-label="Instagram"><rect x="3" y="3" width="18" height="18" rx="5" /><circle cx="12" cy="12" r="4" /><circle cx="17.5" cy="6.5" r="0.6" fill={stroke} /></svg>);

  if (name === "linkedin") return (
    <svg {...common} aria-label="LinkedIn"><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M7 10v7" /><circle cx="7" cy="7" r="0.6" fill={stroke} /><path d="M11 17v-4a2.5 2.5 0 0 1 5 0v4" /><path d="M11 10v7" /></svg>);

  if (name === "x") return (
    <svg {...common} aria-label="X"><path d="M4 4l16 16M20 4L4 20" /></svg>);

  if (name === "email") return (
    <svg {...common} aria-label="Email"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></svg>);

  if (name === "facebook") return (
    <svg {...common} aria-label="Facebook"><path d="M18 2h-3a4 4 0 0 0-4 4v3H8v4h3v9h4v-9h3l1-4h-4V6a1 1 0 0 1 1-1h3z" /></svg>);

  if (name === "youtube") return (
    <svg {...common} aria-label="YouTube"><rect x="2" y="6" width="20" height="12" rx="3" /><path d="M10 9l5 3-5 3z" /></svg>);

  return null;
}

function Footer({ onNavigate }) {
  const cardRef = useRef(null);
  useEffect(() => {
    const el = cardRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => {
        if (e.isIntersecting) {el.classList.add("in");io.disconnect();}
      }),
      { threshold: 0.15 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const cols = [
  {
    title: "",
    items: [
    { label: "Get in Touch", to: "home", anchor: "contact" },
    { label: "Sell Your Property", to: "sell" },
    { label: "Privacy Policy", to: "privacy" },
    { label: "Cookies Policy", to: "cookies" },
    { label: "Acceptable Use", to: "acceptable" },
    { label: "Terms of Use", to: "terms" }]

  }];


  return (
    <footer className="footer">
      <video className="footer__video" autoPlay muted loop playsInline disablePictureInPicture preload="metadata" aria-hidden="true">
        <source src="assets/hero-bg.mp4" type="video/mp4" />
      </video>
      <div className="footer__video-overlay" />

      <div className="liquid-glass footer__card" ref={cardRef}>
        <div className="footer__top">
          <div className="footer__brand">
            <div className="footer__brand-row">
              <Logo size={28} color="var(--cream)" />
              <div className="footer__wordmark">Rose Family Properties</div>
            </div>
            <p className="footer__brand-desc">A Chester-based family run property development and investment company. We acquire, convert and operate residential property across the North West - built on long-term ownership and stable income.

            </p>
          </div>
          <div className="footer__links">
            {cols.map((c) =>
            <div className="footer__col" key={c.title || "links"}>
                {c.title && <h5>{c.title}</h5>}
                <ul>
                  {c.items.map((it) =>
                <li key={it.label} onClick={() => it.to && onNavigate(it.to, it.anchor)}>
                      {it.label}
                    </li>
                )}
                </ul>
              </div>
            )}
          </div>
        </div>

        <div className="footer__bottom">
          <p className="footer__copy">© 2026 Rose Family Properties Ltd · Chester</p>
          <div className="footer__social">
            <span className="label">Follow the family:</span>
            <div className="icons">
              <a href="https://www.instagram.com/roseproperties/" target="_blank" rel="noopener noreferrer" aria-label="Instagram"><SocialIcon name="instagram" /></a>
              <a href="https://www.facebook.com/people/Rose-Properties/61587160544094/" target="_blank" rel="noopener noreferrer" aria-label="Facebook"><SocialIcon name="facebook" /></a>
              <a href="#" onClick={(e) => {e.preventDefault();onNavigate("sell");}} aria-label="Sell your property"><SocialIcon name="email" /></a>
            </div>
          </div>
        </div>
      </div>
    </footer>);

}

/* Expose to other files */
Object.assign(window, {
  Logo, Nav, Hero, useReveal, SectionHead, WhatWeDo, About, ProjectsTeaser, Contact, Footer, PROJECTS
});