// pages.jsx — About, Projects, Builder Reps, Contact

const { useState, useEffect } = React;

// ============================================
// PAGE HERO
// ============================================
function PageHero({ title, subtitle, bg, hidePattern, bgPosition, bgSize }) {
  const bgImg = bg || placeholder('PAGE HERO IMAGE', 215, 28);
  return (
    <section className="pagehero">
      <div
        className="pagehero__bg"
        style={{
          backgroundImage: `url("${bgImg}")`,
          backgroundPosition: bgPosition || 'center',
          backgroundSize: bgSize || 'cover',
          backgroundRepeat: 'no-repeat'
        }}
      />
      {!hidePattern && <div className="pagehero__pattern" />}
      <div className="pagehero__inner">
        <h1 className="pagehero__title">{title}</h1>
        <div className="pagehero__rule" />
        {subtitle && <p className="pagehero__sub">{subtitle}</p>}
      </div>
    </section>
  );
}

// ============================================
// ABOUT PAGE
// ============================================
const ABOUT_TEAM = [
  {
    name: 'Tyson Riggins',
    role: 'Owner / Builder',
    photo: 'assets/tyson.webp',
    email: 'tyson@rigginsdesign.com',
    bio: `Building is in Tyson’s blood. A third-generation Gainesville native, he grew up learning every trade from his father — and by fifteen, he was already drafting floor plans for local builders, some of which are still in use today. After years working alongside his father and other respected craftsmen in the area, Tyson partnered with Spain & Cooper Homes, one of Gainesville’s most established custom building names. In 2022, he became sole owner and in 2026, rebranded as Riggins Design + Build. His reputation is built on doing things right — finding the right properties, building quality homes, and standing behind every one of them. Outside of work, Tyson and his wife Amy spend their time with their three sons, usually near the water.`
  },
  {
    name: 'Lauren Halvorson',
    role: 'Designer / Project Manager',
    photo: 'assets/lauren.jpg',
    email: 'lauren@rigginsdesign.com',
    bio: `Lauren doesn’t just help you pick finishes — she runs the process. With a degree in Interior Design from Florida State and years running her own firm, Lauren Durand Designs, she joined the team in 2018 and quickly became indispensable. She works exclusively with Riggins clients, on site daily, managing selections, vendors, deliveries, and budgets with the kind of detail-oriented calm that builds trust fast. Clients often say she understands their style better than they do. Born in Jupiter and now at home in Gainesville, Lauren and her husband Drew spend their free time with their two kids — and hunting when the season allows.`
  },
  {
    name: 'Joe Diaz',
    role: 'Office Manager',
    photo: 'assets/joe-diaz.png',
    email: 'joe@rigginsdesign.com',
    bio: `Joe keeps the day-to-day running smoothly at Riggins Design + Build. From scheduling and vendor coordination to client communication and back-office details, he makes sure nothing slips through the cracks. He’s often the first point of contact for clients and the person making sure every project stays on schedule and on budget.`
  },
  {
    name: 'Tim Steele',
    role: 'Project Coordinator',
    photo: 'assets/tim-steele.png',
    bio: `Tim runs the jobs on site for Riggins Design + Build. He walks every project daily, catching the small things before they become big ones and holding the work to a higher standard than most. He’s also the first to roll up his sleeves and tackle the jobs the subs won’t — the punch-list details and finishing touches that turn a finished house into a finished home. His hands-on approach and attention to detail are a big part of why the homes come out the way they do.`
  },
  {
    name: 'Taybin Riggins',
    role: 'Construction Management',
    photo: 'assets/taybin.jpeg',
    email: 'taybin@rigginsdesign.com',
    bio: `Taybin is Tyson’s eldest son and is already earning his place in the business. Born and raised in Gainesville, he’s currently studying construction management at the University of Florida while working hands-on in both the office and in the field. He brings a fresh perspective and a genuine enthusiasm for the craft — and the foundation to back it up.`
  }
];

function AboutPage() {
  return (
    <React.Fragment>
      <PageHero
        title="Meet the Team"
        subtitle="One team, under one roof, from concept to completion."
        bg={'assets/about-hero.webp'}
        hidePattern
      />
      <section className="section section--paper">
        <div className="container">
          <div className="team">
            {ABOUT_TEAM.map((m, i) => (
              <Reveal key={m.name}>
                <div className={`team__row ${i % 2 === 1 ? 'team__row--reverse' : ''}`}>
                  <div
                    className="team__photo team__photo--circle"
                    style={{ backgroundImage: `url("${m.photo}")` }}
                  />
                  <div className="team__info">
                    <h2 className="team__name">{m.name}</h2>
                    <p className="team__role">{m.role}</p>
                    <div className="team__rule" />
                    <p className="team__bio">{m.bio}</p>
                    {m.email && (
                      <div className="team__contact">
                        <div><span>Email</span><a href={`mailto:${m.email}`}>{m.email}</a></div>
                      </div>
                    )}
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============================================
// BUILDER REPS PAGE
// ============================================
const REPS = [
  {
    name: 'Tiffany Thomas',
    role: 'Builder Representative',
    photo: 'assets/tiffany.png',
    email: 'tiffany@thomasgrouprealty.com',
    phone: '352-316-5556',
    bio: `Tiffany is the first call most Riggins clients make — and for good reason. A full-time Realtor and co-owner of Better Homes & Gardens Thomas Group alongside her husband, Matt, she’s been in the real estate business since 2006 and knows the Gainesville market as well as anyone. She knows the build process inside and out, guiding clients through lot selection, floor plan design, and every detail in between before a single nail is driven. Her background in competitive athletics shaped the drive and discipline she brings to every transaction. If you have questions about how the process works, available lots, or upcoming spec homes, Tiffany is your first stop.`
  },
  {
    name: 'Holly Moebus',
    role: 'Builder Representative',
    photo: 'assets/holly.png',
    email: 'holly@thomasgrouprealty.com',
    phone: '786-423-4566',
    bio: `Holly came to Riggins the same way many of our clients do — as a homeowner who experienced the process firsthand. That perspective is what makes her exceptional at walking others through it. A top-performing Realtor with Better Homes & Gardens Thomas Group and a University of Florida graduate, Holly has deep roots in Gainesville and a genuine love for the community. She listens well, knows the product inside and out, and brings a warmth to the process that puts clients at ease from the very first conversation.`
  },
  {
    name: 'Serenity Riggins',
    role: 'Builder Representative',
    photo: 'assets/serenity.png',
    email: 'serenity@thomasgrouprealty.com',
    phone: '352-507-3457',
    bio: `Serenity grew up in Gainesville and knows the city the way only a local can. A Florida State graduate and Realtor with Thomas Group Realty, she came to real estate the natural way — through a genuine love of people and a talent for making them feel at ease. She has a gift for listening, for understanding what someone needs before they’ve fully said it, and for guiding them through big decisions with calm and clarity. As a Riggins, she also knows the build process from the inside out, which means clients get someone who can speak to both sides of the table. Outside of work, Serenity is most at home in the kitchen or taking time to slow down — journaling, meditating, and staying grounded in the things that matter.`
  }
];

function RepsPage({ onContact }) {
  return (
    <React.Fragment>
      <PageHero
        title="Your First Step Starts Here"
        subtitle="Before a single nail is driven, our representatives walk you through lots, plans, and process."
        bg={'assets/reps-hero.webp'}
        hidePattern
      />
      <section className="section section--paper">
        <div className="container">
          <div className="team">
            {REPS.map((m, i) => (
              <Reveal key={m.name}>
                <div className={`team__row ${i % 2 === 1 ? 'team__row--reverse' : ''}`}>
                  <div
                    className="team__photo team__photo--circle"
                    style={{ backgroundImage: `url("${m.photo}")` }}
                  />
                  <div className="team__info">
                    <h2 className="team__name">{m.name}</h2>
                    <p className="team__role">{m.role}</p>
                    <div className="team__rule" />
                    <p className="team__bio">{m.bio}</p>
                    <div className="team__contact">
                      {m.email && <div><span>Email</span><a href={`mailto:${m.email}`}>{m.email}</a></div>}
                      {m.phone && <div><span>Phone</span><a href={`tel:${m.phone.replace(/[^0-9+]/g, '')}`}>{m.phone}</a></div>}
                    </div>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>

          <div style={{ textAlign: 'center', marginTop: 120 }}>
            <Reveal>
              <p className="eyebrow">Ready to Begin?</p>
              <h3 className="section__title section__title--center" style={{ marginBottom: 28 }}>
                Schedule a conversation
              </h3>
              <button className="btn btn--solid" onClick={onContact}>
                Contact Us
              </button>
            </Reveal>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

// ============================================
// PROJECTS PAGE — masonry + lightbox
// ============================================
function ProjectsPage({ openProject }) {
  return (
    <React.Fragment>
      <PageHero
        title="Our Work"
        subtitle="Every home is designed around the people who live in it."
        bg={'assets/projects-hero.webp'}
        hidePattern
      />
      <section className="section section--paper">
        <div className="container">
          <div className="masonry">
            {PROJECTS.map((p, i) => (
              <Reveal key={p.id} delay={(i % 3) * 0.05}>
                <div
                  className="masonry__item"
                  onClick={() => openProject(p)}
                  style={{ aspectRatio: 'unset' }}
                >
                  <div
                    className="masonry__img"
                    style={{
                      backgroundImage: `url("${p.cover}")`,
                      aspectRatio: `4 / ${5 * p.height}`
                    }}
                  />
                  <div className="masonry__caption">
                    <h3 className="masonry__name">{p.name}</h3>
                    <span className="masonry__view">View Project →</span>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

function ProjectLightbox({ project, onClose }) {
  const gallery = React.useMemo(() => {
    if (!project) return [];
    return project.gallery && project.gallery.length ? project.gallery : [project.cover];
  }, [project]);

  const [idx, setIdx] = useState(0);
  useEffect(() => setIdx(0), [project]);

  useEffect(() => {
    if (!project) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setIdx((i) => (i + 1) % gallery.length);
      if (e.key === 'ArrowLeft') setIdx((i) => (i - 1 + gallery.length) % gallery.length);
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [project, gallery.length, onClose]);

  if (!project) return null;

  return (
    <div className="lightbox" onClick={onClose}>
      <div className="lightbox__panel" onClick={(e) => e.stopPropagation()}>
        <div className="lightbox__media">
          <button className="lightbox__close" onClick={onClose} aria-label="Close">×</button>
          <div
            className="lightbox__img"
            style={{ backgroundImage: `url("${gallery[idx]}")` }}
          />
          <button
            className="lightbox__nav lightbox__nav--prev"
            onClick={() => setIdx((i) => (i - 1 + gallery.length) % gallery.length)}
            aria-label="Previous"
          >‹</button>
          <button
            className="lightbox__nav lightbox__nav--next"
            onClick={() => setIdx((i) => (i + 1) % gallery.length)}
            aria-label="Next"
          >›</button>
        </div>
        <div className="lightbox__info">
          <p className="lightbox__counter">
            {String(idx + 1).padStart(2, '0')} / {String(gallery.length).padStart(2, '0')}
          </p>
          <h2 className="lightbox__title">{project.name}</h2>
          <p className="lightbox__loc">{project.location}</p>
        </div>
      </div>
    </div>
  );
}

// ============================================
// CONTACT PAGE
// ============================================
function ContactPage() {
  const [data, setData] = useState({
    first: '', last: '', email: '', phone: '', message: ''
  });
  const [sent, setSent] = useState(false);

  const update = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    const subject = `New Inquiry from ${data.first} ${data.last}`;
    const body =
      `Name: ${data.first} ${data.last}\n` +
      `Email: ${data.email}\n` +
      `Phone: ${data.phone}\n\n` +
      `Message:\n${data.message}\n`;
    window.location.href =
      `mailto:Tiffany@thomasgrouprealty.com?subject=${encodeURIComponent(subject)}` +
      `&body=${encodeURIComponent(body)}`;
    setSent(true);
  };

  return (
    <React.Fragment>
      <PageHero
        title="Let’s Build Something Together"
        subtitle="Tell us about the home you’re imagining. We’ll be in touch within a business day."
        bg={'assets/contact-hero.webp'}
        bgPosition="center 35%"
        hidePattern
      />
      <section className="section section--paper">
        <div className="container">
          {sent ? (
            <div className="form">
              <p className="form__sent">
                Thank you. We’ve received your note —
                <br />we’ll be in touch shortly.
              </p>
            </div>
          ) : (
            <form className="form" onSubmit={submit}>
              <div className="form__row">
                <div className="form__field">
                  <label className="form__label">First Name</label>
                  <input className="form__input" required value={data.first} onChange={update('first')} />
                </div>
                <div className="form__field">
                  <label className="form__label">Last Name</label>
                  <input className="form__input" required value={data.last} onChange={update('last')} />
                </div>
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label className="form__label">Email</label>
                  <input type="email" className="form__input" required value={data.email} onChange={update('email')} />
                </div>
                <div className="form__field">
                  <label className="form__label">Phone Number</label>
                  <input type="tel" className="form__input" value={data.phone} onChange={update('phone')} />
                </div>
              </div>
              <div className="form__row">
                <div className="form__field form__field--full">
                  <label className="form__label">Tell us about your project</label>
                  <textarea
                    className="form__textarea"
                    required
                    value={data.message}
                    onChange={update('message')}
                    placeholder="Lot, timeline, square footage, style — anything you'd like us to know."
                  />
                </div>
              </div>
              <button type="submit" className="btn btn--solid form__submit">
                Submit
              </button>
            </form>
          )}

          <div className="contact-meta">
            <div>
              <p className="contact-meta__label">Office</p>
              <p className="contact-meta__value">14245 SW 4th Place, Suite 10</p>
              <p className="contact-meta__value">Jonesville, FL 32669</p>
            </div>
            <div>
              <p className="contact-meta__label">Email</p>
              <p className="contact-meta__value"><a href="mailto:Joe@rigginsdesign.com">Joe@rigginsdesign.com</a></p>
            </div>
            <div>
              <p className="contact-meta__label">Phone</p>
              <p className="contact-meta__value"><a href="tel:+13523766372">352-376-6372</a></p>
            </div>
            <div>
              <p className="contact-meta__label">Hours</p>
              <p className="contact-meta__value">Monday – Friday: 8am – 5pm</p>
              <p className="contact-meta__value">Saturday – Sunday: Closed</p>
            </div>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

Object.assign(window, {
  PageHero,
  AboutPage,
  RepsPage,
  ProjectsPage,
  ProjectLightbox,
  ContactPage
});
