/* ===== Schedule of Rates · Mobilisation · Live-Site/Night Works ===== */
const { useState:useS2, useEffect:useE2 } = React;

/* ---------- Schedule of Rates Framework ---------- */
const RATE_CATS = [
  ['user','Supervision','Site leadership & control','Dedicated supervision, sequencing and on-site decision-making mapped to each works window.',['Site Supervisor','Working Foreman','Shift Lead']],
  ['wrench','Labour & Trade Support','Crew & trade coordination','Structured labour and trade-support lines, scaled to scope and tracked against the program.',['Trade Support','Labour','Specialist Trades']],
  ['truck','Mobilisation','Deploy to the work','Packaged deployment of people, tools and vehicles from Tasmania to the project state.',['Crew Deployment','Tooling','Fleet']],
  ['bed','Travel & Accommodation','Away-team logistics','Transparent travel and accommodation lines for interstate and regional mobilisation.',['Transport','Accommodation','Per-Day Logistics']],
  ['box','Equipment','Plant & tooling','Equipment and plant lines structured per project, owned or hired, tracked to site.',['Access Equipment','Power Tools','Hired Plant']],
  ['refresh','Variations','Controlled change','Every variation captured as a line item — reviewed, approved and recorded against scope.',['Scope Change','Client Request','Site Condition']],
  ['chart','Reporting','Visibility & record','Daily and shift reporting lines that keep the client inside the delivery, not outside it.',['Daily Reports','Shift Reports','Handover Pack']],
];

function RatesFramework(){
  const [active,setActive] = useS2(0);
  const cat = RATE_CATS[active];
  return (
    <section className="section" style={{borderTop:'1px solid var(--line)'}}>
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <span className="eyebrow">Schedule of Rates Framework</span>
            <h2 className="h-sec">Transparent Estimating,<br/>Structured Line by Line.</h2>
            <p className="sub">Prime Control uses a client-specific Schedule of Rates framework to support transparent estimating, line-item review, variation control and repeat-project consistency. A control system — not a price list.</p>
          </div>
        </div>

        <div className="rates-shell reveal">
          <div className="rates-panel panel">
            <div className="rates-top">
              <h4><Icon name="layers" size={16}/> Rate Framework</h4>
              <span className="mono" style={{fontSize:11,color:'var(--muted)'}}>7 CATEGORIES</span>
            </div>
            <div className="rates-rows">
              {RATE_CATS.map((c,i)=>(
                <div key={c[1]} className={'rate-row'+(i===active?' active':'')} onClick={()=>setActive(i)}>
                  <div className="ri"><Icon name={c[0]} size={18}/></div>
                  <div className="rt"><b>{c[1]}</b><span>{c[2]}</span></div>
                  <div className="rs">STRUCTURED</div>
                  <div className="chev"><Icon name="arrow" size={15}/></div>
                </div>
              ))}
            </div>
          </div>

          <div className="rates-right">
            <div className="rate-detail panel">
              <div className="rd-head">
              <span className="eyebrow">Category · {String(active+1).padStart(2,'0')} / 07</span>
              <h3>{cat[1]}</h3>
              <p>{cat[3]}</p>
            </div>
            <div className="rd-meta">
              {cat[4].map((line,i)=>(
                <div className="rd-cell" key={line}>
                  <div className="k">Line Item · {String(i+1).padStart(2,'0')}</div>
                  <div className="v">{line}</div>
                </div>
              ))}
              <div className="rd-cell" style={{gridColumn:'span 2', background:'linear-gradient(90deg,color-mix(in oklab,var(--accent) 12%,transparent),transparent)'}}>
                <div className="k">Estimating Basis</div>
                <div className="v" style={{color:'var(--ink)'}}>Client-specific · reviewed before mobilisation · consistent across repeat projects</div>
              </div>
            </div>
            <div className="ledger">
              <span className="pill">TRANSPARENT</span> Line-item review · variation control · no public pricing — estimates issued per scope.
            </div>
            </div>
            <a className="btn btn-primary" onClick={()=>openAssistant('Can you explain how the Schedule of Rates framework works?')}>Ask About the SOR Framework <Icon name="arrow" size={16}/></a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Mobilisation map ---------- */
const NODES = [
  ['NT','Northern Territory','reach'],
  ['QLD','Queensland','reach'],
  ['SA','South Australia','reach'],
  ['NSW','New South Wales','reach'],
  ['ACT','ACT','reach'],
  ['VIC','Victoria','reach'],
  ['TAS','Tasmania','home'],
];
const CYCLE = ['TAS','VIC','NSW','ACT','QLD','NT','SA'];
const CAPS = (window.AUS_REAL && window.AUS_REAL.caps) || {};
function cap(code){ return CAPS[code] || [600,450]; }
const LBL = {
  WA:{dx:26,dy:8,a:'start'}, NT:{dx:0,dy:-24,a:'middle'}, QLD:{dx:-22,dy:8,a:'end'},
  SA:{dx:0,dy:-24,a:'middle'}, NSW:{dx:22,dy:8,a:'start'}, ACT:{dx:-22,dy:8,a:'end'},
  VIC:{dx:0,dy:42,a:'middle'}, TAS:{dx:0,dy:44,a:'middle'},
};
function regionStatus(kind){
  if(kind==='home') return {t:'Home Base · Active', c:'var(--ok)'};
  if(kind==='soon') return {t:'Not Yet Serviced', c:'var(--warn)'};
  return {t:'Reachable · Ready', c:'var(--ink-soft)'};
}
function MobMap(){
  const [hover,setHover] = useS2('TAS');
  const [auto,setAuto] = useS2(true);
  const active = NODES.find(n=>n[0]===hover) || NODES.find(n=>n[0]==='TAS');
  const st = regionStatus(active[2]);
  const O = cap('TAS'), A = cap(active[0]);
  // auto-cycle through regions when the user isn't actively hovering
  useE2(()=>{
    if(!auto) return;
    const id = setInterval(()=>{
      setHover(h=>{ const i=CYCLE.indexOf(h); return CYCLE[(i+1)%CYCLE.length]; });
    }, 2000);
    return ()=>clearInterval(id);
  },[auto]);
  const cards=[
    ['user','People','Trade-qualified crew matched to the scope, shift pattern and trade mix — landed on site ready to work, not ready to start figuring it out.'],
    ['wrench','Tools','Tooling specified line-by-line against the works window, tracked from depot to site so nothing arrives missing on day one.'],
    ['truck','Vehicles','Fleet sized and routed from Tasmania — vans, utes and trailers configured per project, kept on site for the full deployment.'],
    ['bed','Accommodation','Crew billeting, per-day logistics and away-team welfare booked and managed — your project, our duty of care.'],
    ['cart','Procurement','Long-lead and bulk materials sourced, staged and on the ground before mobilisation lands, not the week after.'],
    ['cog','Site Setup','Hoardings, dust separation, customer barriers and trade access controls installed so the works are isolated and the business keeps trading.'],
    ['doc','Documentation','WHS plans, SWMS, inductions, site rules and program issued before boots hit the ground — head contractors get the pack, not chase it.'],
    ['chart','Reporting','Daily and shift reporting straight from site to your inbox — progress, issues, photos and tomorrow\'s plan, every single day.'],
  ];
  return (
    <section className="section" id="mobilisation" style={{borderTop:'1px solid var(--line)'}}>
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <span className="eyebrow">Mobilisation</span>
            <h2 className="h-sec">Mobilised From Tasmania.<br/>Built to Follow the Work.</h2>
            <p className="sub">A complete deployment system — people, tools, vehicles, accommodation and procurement — packaged to land on site, anywhere the work is.</p>
          </div>
        </div>

        <div className="mob-shell reveal">
          <div className="map-panel panel" onMouseLeave={()=>setAuto(true)}>
            <div className="map-readout">
              <div className="ro-item">
                <span className="k">Selected Region</span>
                <span className="v acc">{active[1]}</span>
              </div>
              <div className="ro-sep"></div>
              <div className="ro-item">
                <span className="k">Status</span>
                <span className="v" style={{color:st.c}}>{st.t}</span>
              </div>
            </div>
            <svg viewBox="0 0 1200 1050" aria-label="Australia mobilisation map">
              <defs>
                <radialGradient id="mg" cx="50%" cy="46%" r="66%">
                  <stop offset="0%" stopColor="rgba(27,161,243,0.13)"/><stop offset="100%" stopColor="transparent"/>
                </radialGradient>
                <linearGradient id="ausfill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="rgba(255,255,255,0.05)"/>
                  <stop offset="100%" stopColor="rgba(27,161,243,0.06)"/>
                </linearGradient>
              </defs>
              <rect x="0" y="0" width="1200" height="1050" fill="url(#mg)"/>

              <g transform="translate(0,120)">
                {/* real Australia outline */}
                <path d={window.AUS_REAL.mainland} fill="url(#ausfill)" stroke="rgba(160,205,245,0.42)" strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round"/>
                <path d={window.AUS_REAL.tas} fill="url(#ausfill)" stroke="rgba(160,205,245,0.42)" strokeWidth="2.4" strokeLinejoin="round"/>

                {/* active node pulse — green rings, 2 pulses over ~2s */}

                {/* capital-city nodes */}
                {NODES.map(n=>{
                  const isA = hover===n[0];
                  const home = n[2]==='home', soon = n[2]==='soon';
                  const [cx,cy] = cap(n[0]);
                  const fill = home?'var(--accent-2)':soon?'rgba(255,255,255,0.06)':(isA?'var(--accent)':'#8197b8');
                  const l = LBL[n[0]] || {dx:0,dy:-22,a:'middle'};
                  return (
                    <g key={n[0]} transform={`translate(${cx},${cy})`} style={{cursor:soon?'not-allowed':'pointer'}}
                       onMouseEnter={()=>{ setAuto(false); setHover(n[0]); }}>
                      {home && <circle r="40" fill="none" stroke="var(--accent-2)" strokeWidth="2" opacity="0.5">
                        <animate attributeName="r" from="24" to="56" dur="2.4s" repeatCount="indefinite"/>
                        <animate attributeName="opacity" from="0.6" to="0" dur="2.4s" repeatCount="indefinite"/>
                      </circle>}
                      {isA && !soon && !home && (
                        <g key={'pulse-'+n[0]}>
                          <circle r="14" fill="none" stroke="var(--ok)" strokeWidth="3">
                            <animate attributeName="r" values="14;44" dur="1s" repeatCount="indefinite"/>
                            <animate attributeName="opacity" values="0.8;0" dur="1s" repeatCount="indefinite"/>
                          </circle>
                          <circle r="14" fill="none" stroke="var(--ok)" strokeWidth="3">
                            <animate attributeName="r" values="14;44" dur="1s" begin="0.5s" repeatCount="indefinite"/>
                            <animate attributeName="opacity" values="0.8;0" dur="1s" begin="0.5s" repeatCount="indefinite"/>
                          </circle>
                        </g>
                      )}
                      <circle r={home||isA?14:10} fill={home?'var(--accent-2)':soon?'rgba(255,255,255,0.06)':(isA?'var(--ok)':'#8197b8')}
                        stroke={soon?'var(--muted-2)':'rgba(5,8,15,0.9)'} strokeWidth={soon?2.4:3.4}
                        strokeDasharray={soon?'4 5':''}
                        style={{filter:isA&&!soon&&!home?'drop-shadow(0 0 14px var(--ok))':((isA||home)&&!soon?'drop-shadow(0 0 14px var(--accent-glow))':'none'), transition:'.2s'}}/>
                      <text x={l.dx} y={l.dy} textAnchor={l.a}
                        fill={soon?'var(--muted-2)':(isA||home?'var(--ink)':'var(--muted)')} fontFamily="var(--mono)" fontSize="21" fontWeight="600">{n[0]}</text>
                      {soon && <text x="0" y="34" textAnchor="middle" fill="var(--warn)" fontFamily="var(--mono)" fontSize="15" letterSpacing="1" opacity="0.9">SOON</text>}
                    </g>
                  );
                })}
              </g>
            </svg>
            <div className="map-legend">
              <span><i className="dot" style={{background:'var(--accent-2)'}}></i> Home Base · TAS</span>
              <span><i className="dot" style={{background:'var(--ok)'}}></i> Active Region</span>
            </div>
          </div>

          <div className="mob-right">
            <div className="mob-cards">
            {cards.map(([ic,t,d])=>(
              <div className="mob-cell" key={t}>
                <div className="mc-head">
                  <div className="ic"><Icon name={ic} size={17}/></div>
                  <b>{t}</b>
                </div>
                <p>{d}</p>
              </div>
            ))}
            </div>
            <a className="btn btn-primary" onClick={()=>openAssistant('How does Prime Control mobilise interstate from Tasmania?')}>Ask About Mobilisation <Icon name="arrow" size={16}/></a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Live-site / Night works ---------- */
function NightWorks(){
  const checks=['Staged works','Customer / staff separation','Noise & dust control','Daily make-safe','Clean-down before trading','Shift reporting','Security & access control','Controlled handover'];
  const shift=[['18:00','Mobilise & make-safe',100],['20:30','Staged works',86],['01:00','Progressive clean-down',64],['04:30','Make-safe & handover',38]];
  return (
    <section className="section" style={{borderTop:'1px solid var(--line)'}}>
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <span className="eyebrow">Live-Site & Night Works</span>
            <h2 className="h-sec">Works Delivered Around<br/>Active Businesses.</h2>
            <p className="sub">Staged works around trading businesses — separation, dust and noise control, daily make-safe and clean-down before the doors open again.</p>
          </div>
        </div>
        <div className="night reveal">
          <div className="night-grid">
            <div className="night-l">
              <div className="night-checks">
                {checks.map(c=>(
                  <div className="ncheck" key={c}>
                    <div className="box"><Icon name="check" size={14}/></div>
                    <span>{c}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="night-r">
              <div className="shift-card">
                <div className="top"><b><Icon name="moon" size={15}/> &nbsp;Night Shift · Sequence</b><span className="tm">18:00 → 05:00</span></div>
                {shift.map(([t,l,w])=>(
                  <div className="shift-line" key={t}>
                    <span className="tick">{t}</span>
                    <div className="track"><i style={{width:w+'%'}}></i></div>
                  </div>
                ))}
                <div style={{display:'flex',justifyContent:'space-between',marginTop:14,fontFamily:'var(--mono)',fontSize:11,color:'var(--muted)'}}>
                  <span>CLEAN-DOWN ✓</span><span>HANDOVER BEFORE TRADE</span>
                </div>
              </div>
              <p className="night-quote">Night works are won <span className="hl">before the first trade arrives</span> — through planning, materials, sequencing, and communication.</p>
              <a className="btn btn-primary" style={{alignSelf:'flex-start'}} onClick={()=>openAssistant('How do you handle night works around a trading business?')}>Ask About Night Works <Icon name="arrow" size={16}/></a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window,{ RatesFramework, MobMap, NightWorks });
