// PAR GROUP — Nav, Hero, Strip, Services
// Loaded as a Babel script. Components attached to window at end.

const { useState, useEffect, useRef, useCallback } = React;

// ─── Hooks ─────────────────────────────────────────────────────────────────

function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { el.classList.add('in'); io.unobserve(el); } });
    }, { threshold: 0.12, rootMargin: '0px 0px -80px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function useCountUp(target, duration = 1600, trigger = true) {
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!trigger) return;
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(eased * target));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration, trigger]);
  return v;
}

// Active section tracking for nav
function useActiveSection(ids) {
  const [active, setActive] = useState(ids[0]);
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + 140;
      let cur = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setActive(cur);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [ids.join(',')]);
  return active;
}

// ─── Navigation ────────────────────────────────────────────────────────────

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const ids = ['work', 'case', 'process', 'about', 'contact'];
  const active = useActiveSection(ids);
  const labels = {
    work: '01 · Services',
    case: '02 · Project',
    process: '03 · Process',
    about: '04 · Studio',
    contact: '05 · Enquire',
  };
  useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onS, { passive: true });
    onS();
    return () => window.removeEventListener('scroll', onS);
  }, []);
  return (
    <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
      <a href="#top" className="nav-brand">
        <span className="mark">P</span>
        <span>PAR GROUP</span>
      </a>
      <div className="nav-links">
        {Object.entries(labels).map(([id, lbl]) => (
          <a key={id} href={'#' + id} className={active === id ? 'active' : ''}>
            {lbl}
          </a>
        ))}
      </div>
      <a href="#contact" className="nav-cta solid">
        Get a quote
        <span className="arrow">→</span>
      </a>
    </nav>
  );
}

// ─── Hero with cursor crosshair ──────────────────────────────────────────

function Hero({ variant, onCrosshair }) {
  const photoRef = useRef(null);
  const heroRef = useRef(null);
  const [cross, setCross] = useState({ x: 50, y: 50, active: false });

  // Parallax on scroll
  useEffect(() => {
    const onScroll = () => {
      const el = photoRef.current; if (!el) return;
      const y = window.scrollY * 0.18;
      el.style.transform = `translate3d(0, ${y}px, 0) scale(1.08)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Cursor crosshair
  useEffect(() => {
    if (!onCrosshair) return;
    const el = heroRef.current; if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const x = ((e.clientX - r.left) / r.width) * 100;
      const y = ((e.clientY - r.top) / r.height) * 100;
      setCross({ x, y, active: true });
    };
    const onLeave = () => setCross((c) => ({ ...c, active: false }));
    el.addEventListener('pointermove', onMove);
    el.addEventListener('pointerleave', onLeave);
    return () => {
      el.removeEventListener('pointermove', onMove);
      el.removeEventListener('pointerleave', onLeave);
    };
  }, [onCrosshair]);

  return (
    <section
      ref={heroRef}
      className={'hero' + (variant === 'blueprint' ? ' blueprint' : '')}
      id="top"
    >
      {variant !== 'blueprint' && (
        <div
          className="hero-photo"
          ref={photoRef}
          style={{ backgroundImage: `url(${window.__resources.imgRedFramePortal})` }}
        ></div>
      )}

      <div
        className={'crosshair' + (cross.active || variant === 'blueprint' ? ' active' : '')}
        style={{ '--cx': cross.x + '%', '--cy': cross.y + '%' }}
      >
        <span className="ch-tag">
          x: {cross.x.toFixed(1)} · y: {cross.y.toFixed(1)}
        </span>
      </div>

      <div className="hero-meta-top">
        <div className="col">
          <span className="mono">N° 001 — Job log</span>
          <span className="v">51.4934° N / 0.0098° W</span>
        </div>
        <div className="col" style={{ alignItems: 'flex-end', textAlign: 'right' }}>
          <span className="mono">Status</span>
          <span className="v"><span className="dot pulse"></span>Taking enquiries · London SE</span>
        </div>
      </div>

      <div className="hero-inner">
        <h1 className="hero-headline">
          <span className="line"><span>We build</span></span>
          <span className="line"><span>the <em>bones.</em></span></span>
        </h1>
        <div className="hero-sub">
          <p className="desc">
            PAR Group is a structural builder operating across London &amp; the South East.
            Steel framing, basement excavations, loft conversions and complete house
            rebuilds — engineered properly, finished cleanly, signed off first time.
          </p>
          <div className="ctas">
            <a href="#case" className="btn primary">
              See the work
              <span className="arrow">→</span>
            </a>
            <a href="#contact" className="btn">
              Get a quote
              <span className="arrow">→</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Marquee strip ─────────────────────────────────────────────────────────

function Strip() {
  const items = [
    'Groundworks & Foundations',
    'Basement Excavation',
    'Structural Steel',
    'Superstructure',
    'Load-bearing Removals',
    'Underpinning',
    'Pile Caps',
    'Joist Replacement',
  ];
  const repeated = [...items, ...items];
  return (
    <div className="strip" aria-hidden="true">
      <div className="strip-track">
        {repeated.map((it, i) => (
          <React.Fragment key={i}>
            <span className={i % 3 === 0 ? 'accent' : ''}>{it}</span>
            <span className="sep">/</span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ─── Services ──────────────────────────────────────────────────────────────

function Services() {
  const ref = useReveal();
  const services = [
    {
      id: '01',
      title: 'Groundworks & Foundations',
      desc: 'Specialist groundworks for structural projects — from trench dig and pile caps to underpinning and mass concrete foundations. Every build we undertake starts with the ground prepared properly, so the structure above it performs for the long term.',
      pts: ['Trench dig & pile caps', 'Underpinning', 'Mass concrete foundations'],
    },
    {
      id: '02',
      title: 'Basement Excavation',
      desc: 'Full or partial dig-outs under existing properties with sequenced underpinning. Engineered retaining walls, tanking, drainage and sump pumps installed to spec.',
      pts: ['Underpinning', 'Type-A & C waterproofing', 'Party-wall agreements'],
    },
    {
      id: '03',
      title: 'Structural Steel & Beams',
      desc: 'Design-coordinated fabrication and installation of RSJs and goalpost openings. Padstones, bearing checks, and Building Control sign-off included.',
      pts: ['UB / UC sections', 'Fire-protective coatings'],
    },
    {
      id: '04',
      title: 'Superstructure',
      desc: 'We construct the structural frame of your building above foundation level — including timber and steel frame partitions, and full joist replacement. Built to engineer\'s spec, on programme.',
      pts: ['Timber & steel frame partitions', 'Full joist replacement', 'Engineer-spec build'],
    },
    {
      id: '05',
      title: 'Load-Bearing Removals',
      desc: 'Take the whole wall out. We design, prop, install and reinstate — opening up Victorian terraces into clean, open layouts.',
      pts: ['Open-plan conversions', 'Temporary propping', 'Engineer-stamped drawings'],
    },
  ];
  return (
    <section className="section" id="work" ref={ref}>
      <div className="container">
        <div className="section-head reveal">
          <div className="section-id">
            <span className="mono">— Section 01 · Services</span>
          </div>
          <h2 className="section-title">
            What we do, in <em>five disciplines</em>.
          </h2>
        </div>
        <div className="services-grid reveal">
          {services.map((s) => (
            <div className="svc" key={s.id}>
              <span className="mono idx">{s.id} / 05</span>
              <h3 className="h-med">{s.title}</h3>
              <p className="body" style={{ margin: 0, fontSize: 15 }}>{s.desc}</p>
              <ul className="pts">
                {s.pts.map((p) => <li key={p}>{p}</li>)}
              </ul>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Strip, Services, useReveal, useCountUp });
