/* ===== Nav · Hero · Capability · Difference ===== */
const { useState:useS1, useEffect:useE1, useRef:useR1, useLayoutEffect:useL1 } = React;

function openAssistant(seed){ window.dispatchEvent(new CustomEvent('pc-open-assistant',{detail:{seed}})); }

function Nav(){
  const [scrolled,setScrolled] = useS1(false);
  const [menuOpen,setMenuOpen] = useS1(false);
  const navRef = useR1(null), brandRef = useR1(null);
  const [geo,setGeo] = useS1({w:0,h:74,vx:60});
  useE1(()=>{
    const h=()=>setScrolled(window.scrollY>20);
    window.addEventListener('scroll',h,{passive:true}); h();
    return ()=>window.removeEventListener('scroll',h);
  },[]);
  const measure = ()=>{
    const nav=navRef.current, brand=brandRef.current;
    if(!nav||!brand) return;
    const nr=nav.getBoundingClientRect(), br=brand.getBoundingClientRect();
    // logo height is fixed in CSS, so the chevron tip is at a stable offset
    // (tip is at x-fraction 0.1305 of the logo; logo width = height * 2.842)
    const logoH = scrolled ? 40 : 46;
    const vx = (br.left - nr.left) + logoH*0.371;
    setGeo({ w:Math.round(nr.width), h:Math.round(nr.height), vx:Math.round(vx) });
  };
  useL1(()=>{ measure(); const t=setTimeout(measure,340); return ()=>clearTimeout(t); },[scrolled]);
  useE1(()=>{
    const f=()=>measure(); window.addEventListener('resize',f);
    const t=setTimeout(measure,200); // after fonts/logo settle
    return ()=>{ window.removeEventListener('resize',f); clearTimeout(t); };
  },[]);
  const links=[['Home','#top'],['Services','#services'],['The Prime Control Difference','#difference'],['Projects','#projects'],['About','#mobilisation'],['Contact','#contact']];
  const {w,h,vx} = geo, V=16, D=11;
  const barPath = `M0 0 L${w} 0 L${w} ${h} L${vx+V} ${h} L${vx} ${h+D} L${vx-V} ${h} L0 ${h} Z`;
  const borderPath = `M0 ${h} L${vx-V} ${h} L${vx} ${h+D} L${vx+V} ${h} L${w} ${h}`;
  return (
    <nav ref={navRef} className={'nav'+(scrolled?' scrolled':'')}>
      <div className="nav-bg" style={{clipPath:`path('${barPath}')`, WebkitClipPath:`path('${barPath}')`}}></div>
      <svg className="nav-border" width={w} height={h+D+2} viewBox={`0 0 ${w} ${h+D+2}`} preserveAspectRatio="none" aria-hidden="true">
        <path d={borderPath} />
      </svg>
      <div className="wrap">
        <div className="nav-inner">
          <div className="brand" ref={brandRef} onClick={()=>window.scrollTo({top:0,behavior:'smooth'})}>
            <img className="brand-logo brand-logo-full" src="assets/logo-stacked.svg" alt="Prime Control" onLoad={measure} />
            <img className="brand-logo brand-logo-icon" src="assets/logo-icon.svg" alt="Prime Control" onLoad={measure} />
          </div>
          <div className="nav-links">
            {links.map(([l,h])=><a key={l} href={h}>{l}</a>)}
          </div>
          <div className="nav-cta">
            <a className="btn btn-primary" href="#contact">Discuss a Project <Icon name="arrow" size={16}/></a>
            <button className={'nav-burger'+(menuOpen?' open':'')} onClick={()=>setMenuOpen(v=>!v)} aria-label="Menu">
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>
        <div className={'nav-mobile'+(menuOpen?' open':'')}>
          {links.map(([l,h])=><a key={l} href={h} onClick={()=>setMenuOpen(false)}>{l}</a>)}
        </div>
      </div>
    </nav>
  );
}

function HeroCarousel(){
  const slides=[
    {src:'assets/proj-hardy-harper.webp', title:'Retail Brand Fit-Out', loc:'Spencer Outlet · Melbourne'},
    {src:'assets/proj-hey-caddy.webp', title:'Leisure Fit-Out', loc:'Palmerston · NT'},
    {src:'assets/fitout-hero.jpg', title:'Hospitality Fit-Out', loc:'Launceston · TAS'},
  ];
  const n = slides.length;
  const [i,setI] = useS1(0);
  useE1(()=>{
    const t = setInterval(()=>setI(p=>(p+1)%n), 5000);
    return ()=>clearInterval(t);
  },[i,n]);
  const next=()=>setI(p=>(p+1)%n);
  const prev=()=>setI(p=>(p-1+n)%n);
  return (
    <div className="hero-carousel">
      <div className="hc-stage">
        {slides.map((s,idx)=>{
          let pos = idx - i;
          if(pos > n/2) pos -= n;
          if(pos < -n/2) pos += n;
          const cls = pos===0?'center':pos===-1?'prev':pos===1?'next':'hidden';
          return (
            <div key={idx} className={'hc-card '+cls}>
              <div className="hc-img" style={{backgroundImage:`url('${s.src}')`}}></div>
              <div className="hc-overlay">
                <div className="hc-tit">{s.title}</div>
                <div className="hc-loc">{s.loc}</div>
              </div>
            </div>
          );
        })}
      </div>
      <button className="hc-arrow hc-prev" onClick={prev} aria-label="Previous"><Icon name="arrow" size={16}/></button>
      <button className="hc-arrow hc-next" onClick={next} aria-label="Next"><Icon name="arrow" size={16}/></button>
    </div>
  );
}

function Hero(){
  return (
    <header className="hero" id="top">
      <div className="wrap">
        <div className="hero-stack reveal in">
          <h2 className="h-sec">Commercial Projects.<br/><span style={{color:'var(--accent-2)'}}>Control</span>led from Scope to Handover.</h2>
          <div className="hero-carousel-wrap"><HeroCarousel/></div>
          <p className="sub">Prime Control delivers commercial fit-outs, shopfitting, contract site management and nationwide-capable mobilisation from Tasmania — running every project on a controlled, transparent delivery system.</p>
          <span className="eyebrow">On time · Within budget · Above expectations</span>
        </div>
      </div>
    </header>
  );
}

function CapabilityStrip(){
  const caps=[
    ['01','Commercial Fit-Outs','Scope → handover control'],
    ['02','Contract Site Management','Supervision on your terms'],
    ['03','National Mobilisation','Built to follow the work'],
    ['04','Live-Site & Night Works','Delivered around trading'],
  ];
  return (
    <section className="cap-strip reveal">
      <div className="wrap">
        <div className="cap-grid">
          {caps.map(([n,t,d])=>(
            <div className="cap" key={n}>
              <div className="num">{n}</div>
              <h5>{t}</h5>
              <p>{d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Difference(){
  const cards=[
    ['layers','Schedule of Rates Framework','Client-specific line-item structure for transparent estimating, variation control and repeat-project consistency.'],
    ['truck','Mobilisation System','People, tools, vehicles, accommodation and procurement packaged to deploy interstate from Tasmania.'],
    ['moon','Live-Site / Night Works','Staged works around active businesses — make-safe, clean-down and controlled handover every shift.'],
    ['cam','5G Site Camera','Connected client access to the site — visibility without standing on the floor.'],
    ['shield','Contract Site Management','Supervision, sequencing and reporting delivered under your contract or ours.'],
  ];
  return (
    <section className="section" id="difference" style={{borderTop:'1px solid var(--line)'}}>
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <span className="eyebrow">The Prime Control Difference</span>
            <h2 className="h-sec">A Commercial Delivery System<br/>Built Around Control.</h2>
            <p className="sub">Not a trade crew with a logo. An operating system for commercial works — estimating, mobilisation, supervision and reporting in one controlled framework.</p>
          </div>
        </div>
        <div className="grid-3">
          {cards.map(([ic,t,d],i)=>(
            <div className={'card card-glow reveal'+(i>=3?' wide':'')} key={t} style={{transitionDelay:(i*60)+'ms', gridColumn:(i===3?'span 1':i===4?'span 2':'span 1')}}>
              <div className="idx">{String(i+1).padStart(2,'0')}</div>
              <div className="ic"><Icon name={ic}/></div>
              <h4>{t}</h4>
              <p>{d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window,{ Nav, Hero, CapabilityStrip, Difference, openAssistant });
