/* sec48.jsx — §4 Cascade (A/B) + §5 Mission, §6 Resources, §7 Form, §8 Final CTA + modal. */

function CountUp({to, dur=1500, prefix='$'}){
  const [v,setV]=React.useState(0);
  const ref=React.useRef(null);
  React.useEffect(()=>{
    if(window.matchMedia('(prefers-reduced-motion: reduce)').matches){setV(to);return;}
    let raf,start,done=false,io;
    const run=()=>{
      const step=(t)=>{if(!start)start=t;const p=Math.min(1,(t-start)/dur);
        setV(Math.round(to*(1-Math.pow(1-p,3))));if(p<1)raf=requestAnimationFrame(step);else done=true;};
      raf=requestAnimationFrame(step);
    };
    if(ref.current && 'IntersectionObserver' in window){
      io=new IntersectionObserver((es)=>{es.forEach(e=>{if(e.isIntersecting){run();io.disconnect();io=null;}});},{threshold:0.25});
      io.observe(ref.current);
    } else { run(); }
    const safety=setTimeout(()=>{if(!done)setV(to);},dur+1400);
    return()=>{cancelAnimationFrame(raf);clearTimeout(safety);if(io)io.disconnect();};
  },[to,dur]);
  return <span ref={ref}>{prefix}{v.toLocaleString('en-US')}</span>;
}

const CASCADE=[
  {name:'BestFit', val:1220000, pct:26.8, mech:'admin + payroll tax + ancillary', color:'#0f9484'},
  {name:'Synrgy',  val:1370000, pct:30.1, mech:'payroll tax + WC + claims utilization', color:'#2aa394'},
  {name:'RMA',     val:4550000, pct:100,  mech:'30% claims management + 10% premium reduction', color:'#0d7a6b'},
  {name:'AIA',     val:1500000, pct:33.0, mech:'one-time · R&D + cost seg', color:'#57b8a9'},
];
const PROFILE="Acme Corp · 1,500 employees · medical device manufacturer · self-funded health · current PEO: ADP Total Source";

function CascadeHead(){
  return (<React.Fragment>
    <SecHead num="§ 04 · The Cascade" title="The Cascade." lead="Four strategies. One coordination."/>
    <div className="profile-line">{PROFILE}</div>
  </React.Fragment>);
}

/* ---------- §4 A · Sankey convergence ---------- */
function CascadeSankey(){
  const ysPct=[14,38,62,82];               // vertical % positions of each stream
  const widths=[7,7.8,26,8.6];             // proportional stream weights
  const OX=255, CX=660, TX=792;            // svg coords in a 1000x400 viewBox
  return (
    <div className="ag ag-paper sec ag-tex-dark">
      <Shards seed={61} count={3} zone="full" region={[74,8,24,40]} intensity={32}/>
      <CascadeHead/>
      <div className="sankey">
        <svg className="sk-svg" viewBox="0 0 1000 400" preserveAspectRatio="none">
          <defs>
            {CASCADE.map((c,i)=>(<linearGradient key={i} id={`skg${i}`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor={c.color} stopOpacity="0.25"/><stop offset="1" stopColor={c.color} stopOpacity="0.95"/></linearGradient>))}
          </defs>
          {CASCADE.map((c,i)=>{
            const y=ysPct[i]/100*400;const d=`M${OX} ${y} C${OX+170} ${y} ${CX-180} 200 ${CX} 200`;
            return (<g key={i}>
              <path d={d} fill="none" stroke={`url(#skg${i})`} strokeWidth={widths[i]} strokeLinecap="round" opacity="0.9"/>
              <circle r={Math.max(2.4,widths[i]/5)} fill="#eafffb"><animateMotion dur={`${2.4+i*0.4}s`} repeatCount="indefinite" begin={`${-i*0.5}s`} path={d}/></circle>
            </g>);
          })}
          <path d={`M${CX} 200 L${TX} 200`} stroke="#0d7a6b" strokeWidth="34" strokeLinecap="round"/>
          <circle cx={CX} cy="200" r="22" fill="#0d7a6b" opacity="0.22"/>
          <circle cx={CX} cy="200" r="15" fill="#0d7a6b"/>
        </svg>
        {CASCADE.map((c,i)=>(
          <div className="sk-label" key={i} style={{top:`${ysPct[i]}%`}}>
            <span className="powered-by" style={{background:c.color+'22',color:c.color}}>{c.name}</span>
            <span className="skv">${c.val.toLocaleString('en-US')}</span>
          </div>
        ))}
        <div className="sk-total">
          <div className="tlabel">Projected Year 1 impact</div>
          <div className="tval"><CountUp to={8640000}/></div>
          <div style={{fontFamily:"'Geist Mono',monospace",fontSize:'.58rem',color:'var(--ink-4)',marginTop:'.4rem'}}>four strategies, compounded</div>
        </div>
      </div>
      <div className="sec-cta" style={{textAlign:'center'}}><a className="btn-primary" href="#schedule">See your savings <Arrow/></a></div>
    </div>
  );
}

/* ---------- §4 B · Sequential compounding build-up ---------- */
function CascadeBuild(){
  return (
    <div className="ag ag-paper sec ag-tex-dark">
      <Shards seed={62} count={5} zone="full" intensity={45}/>
      <CascadeHead/>
      <div className="build">
        {CASCADE.map((c,i)=>(
          <div className="brow" key={i}>
            <span className="powered-by" style={{background:c.color+'22',color:c.color,justifySelf:'start'}}>{c.name}</span>
            <div className="btrack"><div className="bfill" style={{'--w':`${c.pct}%`,background:`linear-gradient(90deg,${c.color},${c.color}cc)`,animationDelay:`${i*0.18}s`}}></div></div>
            <div style={{textAlign:'right'}}>
              <div className="bval"><CountUp to={c.val} dur={1100+i*150}/></div>
              <div className="bmech">{c.mech}</div>
            </div>
          </div>
        ))}
        <div className="btotal">
          <span className="tl">Projected Year 1 impact</span>
          <span className="tv h-extrude"><CountUp to={8640000} dur={1900}/></span>
        </div>
      </div>
      <div className="sec-cta" style={{textAlign:'center'}}><a className="btn-primary" href="#schedule">Build your profile <Arrow/></a></div>
    </div>
  );
}

/* ---------- §5 Mission ---------- */
function Mission(){
  return (
    <div className="ag ag-paper-glow sec ag-tex-dark">
      <Shards seed={71} count={3} zone="full" region={[83,16,15,66]} intensity={32}/>
      <div className="center-col">
        <h2 className="h-extrude" style={{maxWidth:'18ch'}}>Driving value to the <span style={{whiteSpace:'nowrap'}}>mid-market.</span></h2>
        <div className="para">
          <p>Our mission is simple. Make it as easy as possible for employers to explore strategies that have a recurring positive impact on their profitability. The solutions we help our clients implement are designed to reduce fixed costs that all companies deal with. By leveraging the Arbiter Network, you gain immediate access to a hand-picked list of industry-leading experts in their respective fields.</p>
          <p>We believe that a profitable company is a resilient one that will continue to feed more families and strengthen their communities. This is why our solutions come with a dual impact: Drive value for stakeholders as well as employees.</p>
        </div>
      </div>
    </div>
  );
}

/* ---------- §6 Resources (briefing-request form gather) ---------- */
const RPARTNERS=[
  {slug:'bestfit', name:'BestFit Solutions', dom:'PEO + Payroll/HR'},
  {slug:'synrgy',  name:'Synrgy Health',     dom:'Hospital indemnity + preventative care'},
  {slug:'rma',     name:'Risk Management Advisors', dom:'Insurance + claims management'},
  {slug:'aia',     name:'American Incentive Advisors', dom:'Tax credits + tax strategy'},
];
function Resources(){
  const [status,setStatus]=React.useState('idle');
  const rowStyle = {
    display:'flex', alignItems:'flex-start', gap:'.7rem',
    padding:'.7rem .9rem',
    border:'1px solid var(--line)', borderRadius:'7px',
    background:'var(--bg)', cursor:'pointer',
    textAlign:'left', transition:'border-color .15s, background .15s',
  };
  const handleSubmit=async(e)=>{
    e.preventDefault();
    setStatus('submitting');
    try{
      const res=await fetch('https://formspree.io/f/xzdqewzd',{
        method:'POST', body:new FormData(e.target),
        headers:{'Accept':'application/json'},
      });
      if(res.ok){setStatus('success');e.target.reset();}
      else{setStatus('error');}
    }catch(err){setStatus('error');}
  };
  return (
    <div className="ag ag-paper-glow sec ag-tex-dark">
      <Shards seed={72} count={2} zone="full" region={[83,16,15,66]} intensity={30}/>
      <div className="center-col" style={{maxWidth:620}}>
        <h2 className="h-extrude">One briefing from each partner.</h2>
        <p className="lead" style={{marginTop:'-.3rem',maxWidth:'48ch'}}>Tell us which Network partners you'd like to learn more about. We'll send the briefings within one business day.</p>
        <div className="glassform lg" style={{marginTop:'.6rem'}}>
          {status==='success'?(
            <div style={{position:'relative',zIndex:2,textAlign:'center',padding:'1rem .5rem'}}>
              <h3 style={{fontSize:'1.4rem',fontWeight:600,marginBottom:'.5rem',color:'var(--ink)'}}>Thanks. The briefings are on the way.</h3>
              <p style={{fontSize:'.95rem',color:'var(--ink-3)',lineHeight:1.5,maxWidth:'42ch',margin:'0 auto'}}>We'll send the briefings to your inbox within one business day.</p>
            </div>
          ):(
          <form onSubmit={handleSubmit} style={{position:'relative',zIndex:2,textAlign:'left'}}>
            <div className="fg">
              <div className="ff"><label>Your name</label><input type="text" name="name" required/></div>
              <div className="ff"><label>Work email</label><input type="email" name="email" required/></div>
              <div className="ff w"><label>Company name</label><input type="text" name="company" required/></div>
              <div className="ff w">
                <label style={{marginBottom:'.55rem',display:'block'}}>Which partners would you like briefings on?</label>
                <div style={{display:'grid',gap:'.5rem'}}>
                  {RPARTNERS.map((p,i)=>(
                    <label key={i} style={rowStyle}>
                      <input type="checkbox" name={`briefing_${p.slug}`} value={p.name} style={{marginTop:'.18rem',accentColor:'var(--teal)',flex:'0 0 auto'}}/>
                      <span style={{display:'flex',flexDirection:'column',gap:'.1rem',flex:1}}>
                        <strong style={{fontSize:'.92rem',color:'var(--ink)',fontWeight:600,lineHeight:1.3}}>{p.name}</strong>
                        <span style={{fontSize:'.78rem',color:'var(--ink-3)',lineHeight:1.3}}>{p.dom}</span>
                      </span>
                    </label>
                  ))}
                </div>
              </div>
            </div>
            <button type="submit" className="sbmt" disabled={status==='submitting'} style={{marginTop:'1rem'}}>{status==='submitting'?'Sending...':'Send me the briefings'}</button>
            {status==='error' && <div style={{color:'#c54a3a',fontSize:'.82rem',marginTop:'.6rem',textAlign:'center'}}>Something went wrong. Please try again or email us directly.</div>}
            <div className="form-note">We respond within one business day. Nothing automated.</div>
          </form>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- §7 Get in touch (glass form, shards routing in) ---------- */
function GetInTouch(){
  const [status,setStatus]=React.useState('idle');
  const handleSubmit=async(e)=>{
    e.preventDefault();
    setStatus('submitting');
    try{
      const res=await fetch('https://formspree.io/f/xgobaqvy',{
        method:'POST', body:new FormData(e.target),
        headers:{'Accept':'application/json'},
      });
      if(res.ok){setStatus('success');e.target.reset();}
      else{setStatus('error');}
    }catch(err){setStatus('error');}
  };
  return (
    <div className="ag ag-paper-glow sec ag-tex-dark">
      <div className="synth-in" style={{width:'42%'}}><Shards seed={81} count={9} zone="inflow" region={[2,16,58,68]} intensity={60}/></div>
      <div className="center-col" style={{maxWidth:560}}>
        <h2 className="h-extrude">Got a quick question?</h2>
        <p className="lead">Drop a line. We respond within one business day.</p>
        <div className="glassform lg" style={{marginTop:'.6rem'}}>
          {status==='success'?(
            <div style={{position:'relative',zIndex:2,textAlign:'center',padding:'1rem .5rem'}}>
              <h3 style={{fontSize:'1.4rem',fontWeight:600,marginBottom:'.5rem',color:'var(--ink)'}}>Thanks. We got your question.</h3>
              <p style={{fontSize:'.95rem',color:'var(--ink-3)',lineHeight:1.5,maxWidth:'42ch',margin:'0 auto'}}>We'll get back to you within one business day. Nothing automated.</p>
            </div>
          ):(
          <form onSubmit={handleSubmit} style={{position:'relative',zIndex:2}}>
            <div className="fg">
              <div className="ff"><label>Your name</label><input type="text" name="name" required/></div>
              <div className="ff"><label>Work email</label><input type="email" name="email" required/></div>
              <div className="ff w"><label>Company name</label><input type="text" name="company" required/></div>
              <div className="ff w"><label>Your question</label><textarea name="message" required></textarea></div>
            </div>
            <button type="submit" className="sbmt" disabled={status==='submitting'}>{status==='submitting'?'Sending...':'Send message'}</button>
            {status==='error' && <div style={{color:'#c54a3a',fontSize:'.82rem',marginTop:'.6rem',textAlign:'center'}}>Something went wrong. Please try again or email us directly.</div>}
            <div className="form-note"></div>
          </form>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- §8 Final CTA + footer ---------- */
function FinalCTA(){
  return (
    <div className="ag ag-dark ag-tex final">
      {/* teal threads pooling at the bottom */}
      <svg style={{position:'absolute',left:0,right:0,bottom:0,width:'100%',height:'46%',zIndex:1}} viewBox="0 0 1000 300" preserveAspectRatio="none">
        {[150,330,500,670,850].map((x,i)=>(<line key={i} className="glink" x1={x} y1="300" x2="500" y2="120" opacity="0.3"/>))}
        {[150,330,500,670,850].map((x,i)=>(<g key={'p'+i} style={{filter:'drop-shadow(0 0 3px #1fc3a7)'}}><rect x="-5.5" y="-0.75" width="11" height="1.5" rx="0.7" fill="#dffff8"/><animateMotion dur={`${5+i*0.4}s`} repeatCount="indefinite" begin={`${-i*0.6}s`} rotate="auto" path={`M${x} 300 L500 120`}/></g>))}
        <circle cx="500" cy="120" r="6" fill="#bdfff0"/>
      </svg>
      <div style={{position:'relative',zIndex:3,display:'flex',flexDirection:'column',alignItems:'center',gap:'1.3rem'}}>
        <ACore size={64} depth={6}/>
        <h2 className="h-gradient">Let's talk.</h2>
        <a className="btn-inverted" href="#schedule">Book a call <Arrow/></a>
      </div>
      <div className="footer3">
        <div className="fb"><BrandMark size={20}/><span>© 2026 Arbiter Group · All rights reserved.</span></div>
        <div className="fl"><a href="/peo">PEO</a><a href="#resources">Resources</a><a href="#schedule">Book a call</a></div>
      </div>
    </div>
  );
}

/* ---------- Schedule modal preview ---------- */
const PAINS=['High health insurance premiums or claims','High payroll taxes',"High workers' comp costs",'HR or PEO complexity or pricing','Missed tax credits (R&D, cost seg, energy)','Something else'];
function ScheduleModalShot(){
  return (
    <div className="ag ag-paper modalshot">
      <div className="modalcard">
        <div className="mx">×</div>
        <div className="mk">Request a working session</div>
        <h3>Tell us about your business.</h3>
        <p className="fs">We meet with mid-market employers who want to find money in their fixed costs. Share a few details and we'll get back to you within one business day to schedule a 20-minute working session with a Network advisor.</p>
        <div className="fg">
          <div className="ff"><label>Your name</label><input/></div>
          <div className="ff"><label>Work email</label><input/></div>
          <div className="ff w"><label>Company name</label><input/></div>
          <div className="ff"><label>Industry</label><input/></div>
          <div className="ff"><label>Employees</label><input placeholder="Select range" style={{color:'var(--ink-4)'}}/></div>
          <div className="ff w"><label>Where are you looking for relief?</label>
            <div style={{display:'grid',gap:'.4rem',marginTop:'.2rem'}}>
              {PAINS.map((p,i)=>(<div className="chk" key={i}><i></i><span>{p}</span></div>))}
            </div>
          </div>
        </div>
        <button className="sbmt">Request a working session</button>
        <div className="form-note">Submitting this form does not book a call. We review every request and respond within one business day.</div>
      </div>
    </div>
  );
}

Object.assign(window,{CascadeSankey,CascadeBuild,Mission,Resources,GetInTouch,FinalCTA,ScheduleModalShot,CountUp});
