// Home.jsx — Broadacres Academy homepage
function Home({ onNavigate, tweaks }) {
  const accent = tweaks.accent; // 'teal' | 'mint' | 'red'
  const accentColor = accent === 'mint' ? '#1CBC91' : accent === 'red' ? '#E20630' : '#039CAC';
  const heroVariant = tweaks.heroVariant; // 'portrait' | 'running' | 'studio'

  const heroImages = {
    running: 'assets/photos/web/hero-running.png',
    portrait: 'assets/photos/web/hero-forest-girl.jpg',
    studio: 'assets/photos/web/students-highschool-pair.jpg'
  };

  const [walkIdx, setWalkIdx] = React.useState(0);
  React.useEffect(() => {
    // next walkabout indicator: pick based on day-of-week
    const d = new Date().getDay(); // 0 sun..6 sat
    const map = { 2: 0, 4: 1, 5: 2 };
    setWalkIdx(map[d] ?? 0);
  }, []);

  return (
    <>
      <Hero image={heroImages[heroVariant] || heroImages.running} cutout={heroVariant === 'portrait' ? 'assets/photos/web/hero-forest-girl-cutout.png' : null} showDandelion={tweaks.dandelion} onCta={() => onNavigate('home')} />

      <Welcome />

      <Story />

      <Phases onPhaseClick={(p) => onNavigate({ preschool: 'preschool', junior: 'juniorprep', senior: 'seniorprep', high: 'highschool' }[p])} dandelion={tweaks.dandelion} />

      <Walkabout nextIdx={walkIdx} dandelion={tweaks.dandelion} />

      <Events />

      <Affiliations />

      <Footer />
    </>);

}

function Hero({ image, showDandelion, onCta, cutout }) {
  return (
    <section className="hero">
      <div className="hero__media">
        <img src={image} alt="" />
      </div>
      <div className="hero__tint" />
      {showDandelion &&
      <div className="hero__dandelion-wrap" aria-hidden="true">
          <Dandelion size={360} variant="mint" opacity={1} />
        </div>
      }
      {cutout &&
      <div className="hero__cutout" aria-hidden="true">
          <img src={cutout} alt="" />
        </div>
      }
      <div className="hero__inner">
        <div className="hero__eyebrow"><span className="dot" /> Enrolments for 2027 now open</div>
        <h1 className="hero__headline" data-rv-flow>
          <span className="hero__headline-white" style={{ color: '#ffffff' }}>Learning,</span><br />
          <span className="italic-word">naturally.</span>
        </h1>
        <p className="hero__sub more-text-space">
          Where children learn the way they're meant to. One community across three campuses and four phases, from six months old to matric.
        </p>
        <div className="hero__cta-row">
          <a className="btn btn-primary" href={window.WALKABOUT_URL} target="_blank" rel="noopener noreferrer">
            Book a walkabout
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
          </a>
        </div>
      </div>
    </section>);

}

function Welcome() {
  return (
    <section className="welcome">
      <div className="container">
        <div className="welcome__grid">
          <div>
            <div className="eyebrow-txt welcome__eyebrow">Welcome to Broadacres Academy</div>
            <h2 className="welcome__headline">
              Where every child is <em>known and seen.</em>
            </h2>
            <p className="welcome__lead">We teach children from six months old through to matric, across three campuses in Broadacres and Chartwell. We keep our classes small, so our teachers really know your child. Our classrooms flood with natural light and give plenty of room to move. Our school day is built for the age of the child.

            </p>
            <p className="welcome__close">
              One community. One philosophy. We call it <span className="welcome__brandmark">Learning, naturally</span>.
            </p>
          </div>
          <div className="welcome__pillars">
            <div className="pillar">
              <div className="pillar__num">01</div>
              <h3 className="pillar__title">Three campuses, a short drive apart</h3>
              <p className="pillar__body">Preschool and Junior Prep share Syringa. Senior Prep and High School sit opposite each other in Chartwell.</p>
            </div>
            <div className="pillar">
              <div className="pillar__num">02</div>
              <h3 className="pillar__title">Four phases, one philosophy</h3>
              <p className="pillar__body">From a six-month-old hearing her first stories to a Grade 12 defending her own experiment.</p>
            </div>
            <div className="pillar">
              <div className="pillar__num">03</div>
              <h3 className="pillar__title">CAPS and IEB, taught deeply</h3>
              <p className="pillar__body">A strong nationally recognised foundation, and an internationally benchmarked matric.</p>
            </div>
            <div className="pillar">
              <div className="pillar__num">04</div>
              <h3 className="pillar__title">Teachers who stay</h3>
              <p className="pillar__body">Real relationships at the centre of every lesson. Children known by name, quirks and favourite colour.</p>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

function Story() {
  const iframeRef = React.useRef(null);
  const [muted, setMuted] = React.useState(true);

  const unmute = () => {
    const win = iframeRef.current && iframeRef.current.contentWindow;
    if (win) {
      const cmd = (func, args) => win.postMessage(
        JSON.stringify({ event: 'command', func, args: args || [] }),
        'https://www.youtube.com'
      );
      cmd('unMute');
      cmd('setVolume', [100]);
      cmd('playVideo');
    }
    setMuted(false);
  };

  return (
    <section className="story">

      <div className="container" style={{ position: 'relative' }}>
        <div className="story__head">
          <div className="eyebrow-txt eyebrow-light">Our story</div>
          <h2 className="story__headline">
            Children are free to learn, <em>naturally.</em>
          </h2>
        </div>
        <div className="story__video story__video--embed">
          <iframe
            ref={iframeRef}
            className="story__video-iframe"
            src="https://www.youtube.com/embed/U-GsdV0uQqI?enablejsapi=1&autoplay=1&mute=1&loop=1&playlist=U-GsdV0uQqI&rel=0&playsinline=1&modestbranding=1"
            title="Our story"
            allow="autoplay; encrypted-media; picture-in-picture"
            allowFullScreen />
          {muted &&
          <button type="button" className="story__sound-pill" onClick={unmute} aria-label="Turn on sound">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M11 5 6 9H3v6h3l5 4V5z" fill="currentColor" stroke="none" />
                <path d="M15.5 8.5a5 5 0 0 1 0 7" />
                <path d="M18.5 6a9 9 0 0 1 0 12" />
              </svg>
              Better with sound
            </button>
          }
        </div>
      </div>
    </section>);

}

function Phases({ onPhaseClick, dandelion }) {
  const gridRef = React.useRef(null);
  const [atStart, setAtStart] = React.useState(true);
  const [atEnd, setAtEnd] = React.useState(false);
  const [active, setActive] = React.useState(0);

  const update = React.useCallback(() => {
    const el = gridRef.current;
    if (!el) return;
    setAtStart(el.scrollLeft <= 4);
    setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - 4);
    const cards = el.querySelectorAll('.phase-card');
    const elLeft = el.getBoundingClientRect().left;
    let idx = 0, min = Infinity;
    cards.forEach((c, i) => {
      const d = Math.abs(c.getBoundingClientRect().left - elLeft);
      if (d < min) { min = d; idx = i; }
    });
    setActive(idx);
  }, []);

  React.useEffect(() => {
    update();
    const el = gridRef.current;
    if (!el) return;
    el.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      el.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [update]);

  const scrollBy = (dir) => {
    const el = gridRef.current;
    if (!el) return;
    const card = el.querySelector('.phase-card');
    const step = card ? card.getBoundingClientRect().width + 16 : el.clientWidth * 0.8;
    el.scrollBy({ left: dir * step, behavior: 'smooth' });
  };

  const scrollToIndex = (i) => {
    const el = gridRef.current;
    if (!el) return;
    const cards = el.querySelectorAll('.phase-card');
    if (!cards.length) return;
    const step = cards.length > 1
      ? cards[1].getBoundingClientRect().left - cards[0].getBoundingClientRect().left
      : cards[0].getBoundingClientRect().width;
    el.scrollTo({ left: Math.round(i * step), behavior: 'smooth' });
  };

  const phases = [
  { key: 'preschool', cls: 'phase-card--preschool', ages: '6 months – Gr 00', name: 'Preschool', tag: 'The Age of Discovery', photo: 'assets/cutout-preschool.png', dandelionVariant: 'mint' },
  { key: 'junior', cls: 'phase-card--junior', ages: 'Grade 0 – Grade 3', name: 'Junior Prep', tag: 'The Age of Wonder', photo: 'assets/photos/web/junior-cutout.png', dandelionVariant: 'teal' },
  { key: 'senior', cls: 'phase-card--senior', ages: 'Grade 4 – Grade 6', name: 'Senior Prep', tag: 'The Age of Adventure', photo: 'assets/cutout-senior.png', dandelionVariant: 'teal' },
  { key: 'high', cls: 'phase-card--high', ages: 'Grade 7 – Grade 12', name: 'High School', tag: 'The Age of Becoming', photo: 'assets/cutout-high.png?v=2', dandelionVariant: 'red' }];

  return (
    <section className="phases" id="phases">
      <div className="container">
        <div className="phases__intro">
          <div className="eyebrow-txt">Learning Communities</div>
          <h2 className="phases__title">Four phases, one <em>philosophy</em>.</h2>
        </div>
        <div className="phases__scroller">
          <div className="phase-grid" ref={gridRef}>
            {phases.map((p, i) =>
            <a href="#" key={p.key} className={`phase-card ${p.cls}`}
            style={{ animationDelay: `${i * 80}ms` }}
            onClick={(e) => {e.preventDefault();onPhaseClick?.(p.key);}}>
                {dandelion && <Dandelion size={188} variant={p.dandelionVariant} className="phase-card__dandelion" animate={false} />}
                <div className="phase-card__media"><img src={p.photo} alt="" /></div>
                <div className="phase-card__tint" />
                <div className="phase-card__body">
                  <div className="phase-card__ages">{p.ages}</div>
                  <div className="phase-card__name">{p.name}</div>
                  <div className="phase-card__tag">{p.tag}</div>
                  <span className="phase-card__readmore" aria-hidden="true">
                    Read more <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
                  </span>
                </div>
              </a>
            )}
          </div>
        </div>
        <div className="phases__controls">
          <div className="phases__arrows">
            <button type="button" onClick={() => scrollBy(-1)} disabled={atStart} aria-label="Previous phases">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 6l-6 6 6 6" /></svg>
            </button>
          </div>
          <div className="phases__dots" role="tablist" aria-label="Phases">
            {phases.map((p, i) =>
            <button type="button" key={p.key} className={`phases__dot ${i === active ? 'is-active' : ''}`}
            onClick={() => scrollToIndex(i)} aria-label={`Go to ${p.name}`} aria-selected={i === active} />
            )}
          </div>
          <div className="phases__arrows">
            <button type="button" onClick={() => scrollBy(1)} disabled={atEnd} aria-label="More phases">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6" /></svg>
            </button>
          </div>
        </div>
      </div>
    </section>);

}

function Events() {
  return (
    <section className="events events--compact">
      <div className="container">
        <div className="event-compact">
          <div className="event-compact__media">
            <img src="assets/photos/web/openday-courtyard.jpg" alt="Broadacres pupils walking through the courtyard garden" loading="lazy" decoding="async" />
          </div>
          <div className="event-compact__body">
            <div className="eyebrow-txt">Save the date</div>
            <h3 className="event-compact__title">Open Day <em>2026</em></h3>
            <p className="event-compact__meta">6 September 2026</p>
            <p className="event-compact__copy">Join us for our annual Chartwell Market Day at the High School — with guided tours and hands-on activities over at the Senior Prep campus. It's the perfect chance to meet our teachers and explore the campus. Register your interest below and we'll send you all the details, and a way to RSVP, closer to the time.</p>
            <a href="https://forms.cloud.microsoft/r/xG1msKqW8N" target="_blank" rel="noopener noreferrer" className="event-compact__link">
              Register your interest
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </a>
          </div>
        </div>
      </div>
    </section>);

}

function Facilities() {
  return (
    <section className="facilities">
      <div className="container">
        <div className="facilities__grid">
          <div className="facilities__text">
            <div className="eyebrow-txt">Our campuses</div>
            <h2 className="facilities__title">
              Room to think, <em>room to grow.</em>
            </h2>
            <p className="facilities__body">
              Three campuses spread across Broadacres and Chartwell, built with natural light, generous outdoor space, and classrooms sized for real conversation. Libraries that invite lingering. Labs, art studios, sports fields, music rooms. Spaces designed to match the age of the children who use them.
            </p>
            <a href="#" className="facilities__link">
              Explore our campuses
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </a>
          </div>
          <div className="facilities__photos">
            <div className="facilities__photo facilities__photo--primary">
              <img src="assets/photo-hs-walking.jpg" alt="Students walking between classes" />
            </div>
            <div className="facilities__photo facilities__photo--secondary">
              <img src="assets/photo-hs-chatting.jpg" alt="Students gathered outside" />
            </div>
          </div>
        </div>
      </div>
    </section>);

}

function Walkabout({ nextIdx, dandelion }) {
  const items = [
  { phase: 'Preschool', head: 'Karen · Preschool Head', loc: 'Syringa campus', day: 'Tuesdays', time: '09:00' },
  { phase: 'Junior Prep', head: 'Bridget · Prep School Head', loc: 'Syringa campus', day: 'Thursdays', time: '09:00' },
  { phase: 'Senior Prep', head: 'Bridget · Prep School Head', loc: 'Chartwell campus', day: 'Fridays', time: '09:00' },
  { phase: 'High School', head: 'Vashni · High School Head', loc: 'Chartwell campus', day: 'Thursdays', time: '09:00' }];

  return (
    <section className="walkabout">
      {dandelion && <Dandelion size={900} variant="teal" className="walkabout__dandelion" opacity={0.12} />}
      <div className="container">
        <div className="walkabout__intro">
          <div className="eyebrow-txt eyebrow-light">Book a walkabout</div>
          <h2 className="walkabout__title">
            Come and walk the school <em>with us.</em>
          </h2>
          <p className="walkabout__body">
            Walk the grounds with the Campus Head, meet a few of the teachers, look in on a real lesson. The school you see on a walkabout is the school you get every day. Each phase runs its own weekly walkabout, hosted by the person who leads it.
          </p>
        </div>
        <ul className="schedule">
          {items.map((it, i) =>
          <li key={it.phase}>
              <div className="schedule__day">{it.day}</div>
              <div className="schedule__meta">
                <strong>{it.phase}</strong>
                <span>{it.head}</span>
                <span className="schedule__loc">{it.loc}</span>
              </div>
              <div className="schedule__time">{it.time}</div>
            </li>
          )}
        </ul>
        <div className="walkabout__cta">
          <a className="btn btn-primary" href={window.WALKABOUT_URL} target="_blank" rel="noopener noreferrer">
            Book a walkabout
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
          </a>
        </div>
      </div>
    </section>);

}

function ApplyBanner({ onApply, dandelion, compact, photo }) {
  const isPhoto = !!photo;
  return (
    <section className={`apply-banner${isPhoto ? ' apply-banner--photo' : ''}${compact ? ' apply-banner--compact' : ''}`}>
      {isPhoto &&
      <div className="apply-banner__media" aria-hidden="true">
          <img src={photo} alt="" />
          <div className="apply-banner__wash" />
        </div>
      }
      {dandelion && <Dandelion size={700} variant={isPhoto ? 'mint' : 'white'} className="apply-banner__dandelion" opacity={isPhoto ? 0.22 : 0.35} />}
      <div className="container" style={{ position: 'relative' }}>
        <div className="eyebrow-txt" style={{ color: isPhoto ? 'var(--ba-mint-light, #8AE7C9)' : 'var(--ba-navy)' }}>Curious?</div>
        {compact ?
        <h2 className="apply-banner__title">
            Book a walkabout, or start your <em>application.</em>
          </h2> :

        <>
            <h2 className="apply-banner__title">
              Come and see what learning <em>naturally</em> looks like.
            </h2>
            <p className="apply-banner__sub">Book a walkabout, or start your application. Children were built to learn. We just don't get in the way.</p>
          </>
        }
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: compact ? 28 : 0 }}>
          {compact ?
          <a className={isPhoto ? 'btn btn-light' : 'btn btn-dark'} href={window.WALKABOUT_URL} target="_blank" rel="noopener noreferrer">
              Book a walkabout
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </a> :

          <button className={isPhoto ? 'btn btn-light' : 'btn btn-dark'} onClick={onApply}>
              Apply now
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </button>
          }
          <button className={isPhoto ? 'btn btn-ghost-light' : 'btn btn-ghost-dark'} onClick={compact ? onApply : undefined}>{compact ? 'Apply' : 'Download 2027 prospectus'}</button>
        </div>
      </div>
    </section>);

}

function Affiliations() {
  const logos = [
  { src: 'assets/affiliations/isasa-trim.png', alt: 'ISASA — Independent Schools Association of Southern Africa', cls: 'aff-logo--isasa' },
  { src: 'assets/affiliations/umalusi-trim.png', alt: 'Umalusi Council for Quality Assurance', cls: 'aff-logo--umalusi' },
  { src: 'assets/affiliations/ieb-trim.png', alt: 'IEB — Independent Examinations Board', cls: 'aff-logo--ieb' },
  { src: 'assets/affiliations/thriveed-trim.png', alt: 'ThriveEd Learning Community', cls: 'aff-logo--thriveed' }];

  return (
    <section className="affiliations reveal">
      <div className="container">
        <div className="affiliations__row">
          <p className="affiliations__eyebrow eyebrow-txt">Accredited &amp; affiliated</p>
          {logos.map((l) =>
          <div key={l.src} className="aff-logo">
              <img src={l.src} alt={l.alt} className={l.cls} loading="lazy" />
            </div>
          )}
        </div>
      </div>
    </section>);

}

Object.assign(window, { Home, Hero, Welcome, Story, Phases, Events, Walkabout, ApplyBanner, Affiliations });