// SafeBus homepage — bold redesign. Loaded after data.js, curation-baked.js, tweaks-panel.jsx
const { useState, useEffect, useMemo, useRef, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "beacon"
}/*EDITMODE-END*/;

// short marketing blurbs per category
const CAT_DESC = {
  kit:      "Complete front + rear fitment kits, pre-matched to your bus and state.",
  lights:   "Surface, window, flush, roof & destination-board LED warning lights.",
  stickers: "Compliant school-bus signage and decals for every jurisdiction.",
  cctv:     "In-cabin and external camera systems for school-bus duty.",
  check:    "Driver child-check alarm systems to meet state safety mandates.",
  towbars:  "Heavy-duty towbars and bullbars engineered for bus chassis.",
};

function hasInventory(catId) {
  return window.PRODUCTS.some(p => (p.categories || [p.category || 'lights']).includes(catId));
}

// ---------- Cycling word (matches finder page) ----------
const CYCLE_WORDS = ['light', 'light kit', 'sticker', 'CCTV', 'child check'];
function CycleWord() {
  const [i, setI] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setI(v => (v + 1) % CYCLE_WORDS.length), 2000);
    return () => clearInterval(id);
  }, []);
  return (
    <span className="cycle-word" aria-live="polite">
      {CYCLE_WORDS.map((w, idx) => (
        <span key={w} className={"cycle-word__item " + (idx === i ? "is-in" : "")}>
          {w}
        </span>
      ))}
      <span className="cycle-word__measure" aria-hidden="true">
        {CYCLE_WORDS.reduce((a, b) => b.length > a.length ? b : a)}
      </span>
    </span>
  );
}

// ---------- Popover finder ----------
function Popover({ kind, value, anchorRef, onClose, onSelect }) {
  const isBus = kind === 'bus', isCat = kind === 'category';
  const items = isBus ? window.BUSES : isCat ? window.CATEGORIES : window.STATES;
  const ref = useRef(null);
  const [pos, setPos] = useState(null);

  useEffect(() => {
    const a = anchorRef.current;
    if (!a) return;
    const r = a.getBoundingClientRect();
    const top = r.bottom + window.scrollY + 8;
    let left = r.left + window.scrollX;
    const vw = window.innerWidth;
    if (left + 300 > vw) left = vw - 312;
    setPos({ top, left: Math.max(12, left) });
  }, [anchorRef]);

  const title = { bus: 'Choose your bus', state: 'Where are you registered?', category: 'What are you after?' }[kind];

  return (
    <div className="pop-backdrop" onClick={onClose}>
      <div className="pop" ref={ref} style={pos ? { top: pos.top, left: pos.left } : { visibility: 'hidden' }} onClick={e => e.stopPropagation()}>
        <div className="pop__title">{title}</div>
        {items.map(it => {
          const code = isBus ? it.id : isCat ? it.id : it.code;
          const sel = code === value;
          if (isBus) {
            return (
              <button key={code} className={"pop__opt " + (sel ? "is-sel" : "")} onClick={() => { onSelect(code); onClose(); }}>
                <span className="pop__thumb" style={it.img ? { backgroundImage: `url(${it.img})` } : {}}>{!it.img && it.short.slice(0,3)}</span>
                <span>{it.name}</span>
              </button>
            );
          }
          if (isCat) {
            const inv = hasInventory(it.id);
            return (
              <button key={code} className={"pop__opt " + (sel ? "is-sel" : "")} onClick={() => { onSelect(code); onClose(); }}>
                <span>{it.label.charAt(0).toUpperCase() + it.label.slice(1)}</span>
                {!inv && <span className="pop__soon">Soon</span>}
              </button>
            );
          }
          return (
            <button key={code} className={"pop__opt " + (sel ? "is-sel" : "")} onClick={() => { onSelect(code); onClose(); }}>
              <span className="pop__flag">{it.code}</span>
              <span>{it.name}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Finder() {
  const guess = useMemo(() => window.guessState(), []);
  const [categoryId, setCat] = useState('lights');
  const [busId, setBus] = useState(null);
  const [stateCode, setState] = useState(guess.code);
  const [pop, setPop] = useState(null);
  const catRef = useRef(null), busRef = useRef(null), stateRef = useRef(null);

  const bus = window.BUSES.find(b => b.id === busId);
  const cat = window.CATEGORIES.find(c => c.id === categoryId);
  const st = window.STATES.find(s => s.code === stateCode);

  const ready = categoryId && busId && stateCode;
  const count = useMemo(() => {
    if (!ready) return 0;
    try { return window.matchProducts(busId, stateCode, categoryId, {}).length; } catch (e) { return 0; }
  }, [ready, busId, stateCode, categoryId]);

  const refFor = k => k === 'category' ? catRef : k === 'bus' ? busRef : stateRef;

  return (
    <div className="finder">
      <div className="finder__top">
        <span className="finder__pulse"></span>
        <span>SafeBus fitment finder</span>
      </div>
      <p className="finder__prompt">
        I need{" "}
        <button ref={catRef} className={"blank " + (categoryId ? "" : "is-empty")} onClick={() => setPop('category')}>
          {cat ? cat.label : "lights"}
        </button>{" "}
        for my{" "}
        <button ref={busRef} className={"blank " + (busId ? "" : "is-empty")} onClick={() => setPop('bus')}>
          {bus ? (bus.sentenceName || bus.short) : "bus"}
        </button>,{" "}
        registered in{" "}
        <button ref={stateRef} className={"blank " + (stateCode ? "" : "is-empty")} onClick={() => setPop('state')}>
          {st ? st.code : "my state"}
        </button>.
      </p>
      <div className="finder__result">
        <div className="finder__count">
          {ready ? <><b>{count}</b> compliant match{count === 1 ? '' : 'es'} found</> : "Fill in the blanks to see your matches"}
        </div>
        <a
          className="finder__go"
          href={ready ? `index.html#results` : undefined}
          aria-disabled={!ready}
          onClick={e => { if (!ready) e.preventDefault(); }}
          style={!ready ? { opacity: .45, pointerEvents: 'none' } : {}}
        >
          See matching products
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        </a>
      </div>

      {pop && (
        <Popover
          kind={pop}
          value={pop === 'bus' ? busId : pop === 'category' ? categoryId : stateCode}
          anchorRef={refFor(pop)}
          onClose={() => setPop(null)}
          onSelect={v => { if (pop === 'bus') setBus(v); else if (pop === 'category') setCat(v); else setState(v); }}
        />
      )}
    </div>
  );
}

// ---------- Sections ----------
function Header() {
  return (
    <header className="hdr">
      <div className="hdr__in">
        <a href="home.html"><img className="hdr__logo" src="assets/logo/safebus-logo.png" alt="SafeBus" /></a>
        <nav className="hdr__nav">
          <a href="index.html">Finder</a>
          <a href="shop.html">Shop</a>
          <a href="#install">Installation</a>
          <a href="#compliance">Compliance</a>
          <a href="#contact">Contact</a>
        </nav>
        <div className="hdr__spacer"></div>
        <a className="hdr__phone" href="tel:1300391848">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>
          1300 391 848
        </a>
        <button className="hdr__cart">
          CART <span className="hdr__cart-n">0</span>
        </button>
      </div>
    </header>
  );
}

function Hero({ isFinderStyle }) {
  if (isFinderStyle) {
    return (
      <section className="hero hero--finder">
        <div className="hero__in hero__in--stacked">
          <div className="hero__stack-inner">
            <div className="hero__chips">
              <span className="hero__chip"><span className="dot"></span>100 Series · LED School-Bus Lights</span>
              <span className="hero__chip">12V – 24V</span>
              <span className="hero__chip">All states</span>
            </div>
            <h1 className="hero__title-serif">
              The right <CycleWord /><br />for your school bus.<br />
              <em>In 60 seconds.</em>
            </h1>
            <p className="hero__sub">
              SafeBus 100 series school-bus warning lights — engineered for every common Australian chassis and every state's compliance regime. Tell us what you drive and where you're registered.
            </p>
            <Finder />
          </div>
        </div>
      </section>
    );
  }
  return (
    <section className="hero">
      <div className="hero__beam"></div>
      <div className="hero__in">
        <div>
          <div className="hero__chips">
            <span className="hero__chip"><span className="dot"></span>100 Series · in stock</span>
            <span className="hero__chip">12V – 24V</span>
            <span className="hero__chip">Every state</span>
          </div>
          <h1>Compliant school-bus lights, <span className="hl">matched to your bus.</span></h1>
          <p className="hero__sub">
            Tell us what you drive and where you're registered. SafeBus finds the exact LED warning lights and kits that fit your chassis and meet your state's regulations — including NSW TS-150.
          </p>
          <div className="hero__trust">
            <span><b>20+</b> Australian chassis</span>
            <span><b>8</b> states &amp; territories</span>
            <span><b>1900cd</b> peak output</span>
          </div>
        </div>
        <Finder />
      </div>
    </section>
  );
}

function Stats() {
  const stats = [
    { n: '1900', u: 'cd', l: 'Peak brightness from the flood-light LED core module' },
    { n: '12–24', u: 'V', l: 'Works on every Australian bus electrical system' },
    { n: '8', u: 'states', l: 'Compliance covered nationwide' },
    { n: 'TS-150', u: '', l: 'NSW-compliant variants with the 70mm surround' },
  ];
  return (
    <section className="sec" id="compliance">
      <div className="wrap">
        <div className="sec__head">
          <span className="eyebrow">Why SafeBus</span>
          <h2>Built for every Australian school bus.</h2>
          <p>A complete range of LED warning lights and kits engineered to meet the requirements of all states and territories — with universal and custom fitments for every common chassis.</p>
        </div>
        <div className="stats">
          {stats.map((s, i) => (
            <div className="stat" key={i}>
              <div className="stat__n">{s.n}{s.u && <small>{s.u}</small>}</div>
              <div className="stat__l">{s.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Categories() {
  const cats = window.CATEGORIES;
  const order = ['lights', 'kit', 'stickers', 'cctv', 'check', 'towbars'];
  const sorted = order.map(id => cats.find(c => c.id === id)).filter(Boolean);
  return (
    <section className="sec" id="shop">
      <div className="wrap">
        <div className="sec__head">
          <span className="eyebrow">Shop the range</span>
          <h2>Everything to fit out a school bus.</h2>
          <p>Browse by product type, or use the finder to jump straight to what's compliant and in stock for your bus.</p>
        </div>
        <div className="cats">
          {sorted.map((c, i) => {
            const inv = hasInventory(c.id);
            return (
              <a className="cat" key={c.id} href={inv ? "index.html" : "#contact"}>
                <span className="cat__arrow">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M7 17 17 7M9 7h8v8"/></svg>
                </span>
                <span className="cat__ix">{String(i + 1).padStart(2, '0')}</span>
                <div className="cat__name" style={{ textTransform: 'capitalize' }}>{c.label}</div>
                {!inv && <span className="cat__soon">Coming soon</span>}
                <div className="cat__desc">{CAT_DESC[c.id] || ''}</div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function Showcase() {
  return (
    <section className="sec" id="install">
      <div className="wrap">
        <div className="sec__head">
          <span className="eyebrow">Installed in the field</span>
          <h2>Fitted on real buses, right across the country.</h2>
          <p>Every fitment is photographed on the actual chassis so you can see exactly how the lights sit before you order.</p>
        </div>
        <div className="show">
          <div className="show__big">
            <img src="assets/installed/SB004-Coaster-1.jpg" alt="SafeBus lights fitted to a Toyota Coaster" loading="lazy" />
            <span className="show__tag">Toyota Coaster · roof + surface mount</span>
          </div>
          <div className="show__cell">
            <img src="assets/installed/SB011-installed-2.jpg" alt="Installed warning light" loading="lazy" />
            <span className="show__tag">SB011 · external</span>
          </div>
          <div className="show__cell">
            <img src="assets/installed/SB003W-before-after.jpg" alt="Before and after retrofit" loading="lazy" />
            <span className="show__tag">ECCO retrofit · before / after</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function StatesBand() {
  return (
    <section className="sec">
      <div className="wrap">
        <div className="states-band">
          <div className="sec__head" style={{ marginBottom: 0 }}>
            <span className="eyebrow">State compliance</span>
            <h2>One catalogue, every jurisdiction.</h2>
            <p>Lights and kits are tagged to each state's rules, so the finder only ever shows you road-legal options.</p>
            <div className="ts150">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0, marginTop: 2 }}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/></svg>
              <span><b>NSW TS-150 ready.</b> Dedicated variants ship with the regulation 70mm black surround.</span>
            </div>
          </div>
          <div className="states-grid">
            {window.STATES.map(s => (
              <div className={"state-pill " + (s.code === 'NSW' ? 'is-nsw' : '')} key={s.code}>
                <b>{s.code}</b>
                <span>{s.code === 'NSW' ? 'TS-150' : 'Compliant'}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function CTA() {
  return (
    <section className="sec" id="contact" style={{ borderBottom: 'none' }}>
      <div className="wrap">
        <div className="cta">
          <div>
            <h2>Not sure what fits? We'll spec it for you.</h2>
            <p>Custom chassis, fleet orders or an unusual fitment — talk to the team and we'll build the right kit.</p>
          </div>
          <div className="cta__actions">
            <a className="cta__btn" href="tel:1300391848">
              <span>Call the team<small>Mon–Fri · AEST</small></span>
              <span>1300 391 848</span>
            </a>
            <a className="cta__btn is-ghost" href="mailto:sales@safebus.com.au">
              <span>Trade &amp; fleet enquiry<small>sales@safebus.com.au</small></span>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot__grid">
          <div>
            <img className="foot__logo" src="assets/logo/safebus-logo.png" alt="SafeBus" />
            <p className="foot__desc">School-bus warning lights, engineered in Australia. Compliant in every state and territory — from NSW TS-150 to national fitments.</p>
          </div>
          <div className="foot__col">
            <h4>Products</h4>
            <a href="index.html">Surface mount</a>
            <a href="index.html">Window mount</a>
            <a href="index.html">Flush mount</a>
            <a href="index.html">Roof mount</a>
            <a href="index.html">Destination board</a>
          </div>
          <div className="foot__col">
            <h4>Help</h4>
            <a href="#install">Installation guides</a>
            <a href="#compliance">Compliance</a>
            <a href="#">Warranty</a>
            <a href="#">Returns</a>
          </div>
          <div className="foot__col">
            <h4>Contact</h4>
            <a href="tel:1300391848">1300 391 848</a>
            <a href="mailto:sales@safebus.com.au">sales@safebus.com.au</a>
            <a href="#contact">Trade enquiries</a>
          </div>
        </div>
        <div className="foot__bot">
          <span>© 2026 SafeBus Pty Ltd</span>
          <span>ABN · ADR · TS-150 compliant</span>
        </div>
      </div>
    </footer>
  );
}

const DIR_BY_DESIGN = { signature: 'hivis', alternate: 'signature-alt', finder: 'finder', modern: 'beacon', welcoming: 'editorial' };

function App() {
  const [t, setT] = useTweaks(TWEAK_DEFAULTS);
  const [dir, setDir] = useState('beacon');
  useEffect(() => {
    // The cross-page design switcher owns data-dir when a design is chosen;
    // only fall back to the Tweaks direction when no design is set.
    let design = null;
    try { design = localStorage.getItem('sb-design'); } catch (e) {}
    if (!design || !DIR_BY_DESIGN[design]) {
      document.documentElement.setAttribute('data-dir', t.direction || 'beacon');
      setDir(t.direction || 'beacon');
    } else {
      setDir(DIR_BY_DESIGN[design]);
    }
    const onDesign = (e) => {
      const d = e.detail && e.detail.design;
      if (DIR_BY_DESIGN[d]) {
        document.documentElement.setAttribute('data-dir', DIR_BY_DESIGN[d]);
        setDir(DIR_BY_DESIGN[d]);
      }
    };
    window.addEventListener('sb-design-change', onDesign);
    return () => window.removeEventListener('sb-design-change', onDesign);
  }, []);

  return (
    <React.Fragment>
      <Header />
      <Hero isFinderStyle={dir === 'finder'} />
      <Stats />
      <Categories />
      <Showcase />
      <StatesBand />
      <CTA />
      <Footer />

      <TweaksPanel>
        <TweakSection label="Homepage direction">
          <TweakRadio
            label="Look"
            value={t.direction || 'beacon'}
            onChange={v => { setT('direction', v); document.documentElement.setAttribute('data-dir', v); }}
            options={[
              { value: 'beacon', label: 'Beacon' },
              { value: 'hivis', label: 'Hi-Vis' },
              { value: 'editorial', label: 'Editorial' },
            ]}
          />
          <div style={{ fontSize: 11, color: 'var(--fg-soft)', lineHeight: 1.5, marginTop: 4 }}>
            <strong>Beacon</strong> — dark, amber-glow, premium. <strong>Hi-Vis</strong> — loud safety yellow. <strong>Editorial</strong> — clean, type-led, lots of air.
          </div>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
