/* page.jsx — assembled continuous Arbiter homepage V3.
   Picks: Hero Constellation · §2 Descend · §3 Constellation · §4 Sankey · §5-8 as built. */

function PageNav(){
  const [scrolled,setScrolled]=React.useState(false);
  React.useEffect(()=>{
    const on=()=>setScrolled(window.scrollY > window.innerHeight*0.72);
    on();window.addEventListener('scroll',on,{passive:true});
    return()=>window.removeEventListener('scroll',on);
  },[]);
  return (
    <nav className={'pnav'+(scrolled?' scrolled':'')}>
      <a className="brand3" href="#main"><BrandMark size={24} glow={!scrolled}/><span>Arbiter<span className="dot">.</span></span></a>
      <div className="navlinks">
        <a href="#network-teaser">Arbiter Network</a>
        <a href="#resources">Resources</a>
        <a className="ncta" href="#schedule">Book a call</a>
      </div>
    </nav>
  );
}

const MPAINS=['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'];

/* Partner → primary pain points that get pre-checked when the modal is opened from
   that partner's "Details +" link (#schedule-bestfit, #schedule-synrgy, etc). */
const PARTNER_PAINS={
  bestfit: ['HR or PEO complexity or pricing'],
  synrgy:  ['High payroll taxes',"High workers' comp costs"],
  rma:     ['High health insurance premiums or claims'],
  aia:     ['Missed tax credits (R&D, cost seg, energy)'],
};

function ScheduleModal(){
  const [open,setOpen]=React.useState(false);
  const [preselect,setPreselect]=React.useState([]);
  const [status,setStatus]=React.useState('idle'); // idle | submitting | success | error
  React.useEffect(()=>{
    const handle=()=>{
      const h=window.location.hash;
      const m=h.match(/^#schedule-([a-z]+)$/);
      if(m && PARTNER_PAINS[m[1]]){
        setPreselect(PARTNER_PAINS[m[1]]);
        setOpen(true);
        setStatus('idle');
        history.replaceState(null,'','#schedule');
      } else if(h==='#schedule'){
        setOpen(true);
      } else {
        setOpen(false);
        setPreselect([]);
        setStatus('idle');
      }
    };
    const onEsc=(e)=>{ if(e.key==='Escape') doClose(); };
    window.addEventListener('hashchange',handle);
    window.addEventListener('keydown',onEsc);
    handle();
    return ()=>{
      window.removeEventListener('hashchange',handle);
      window.removeEventListener('keydown',onEsc);
    };
  },[]);
  const doClose=()=>{
    setOpen(false);
    setPreselect([]);
    setStatus('idle');
    if(window.location.hash){
      history.replaceState(null,'',location.pathname+location.search);
    }
  };
  const close=(e)=>{ if(e){e.preventDefault();e.stopPropagation();} doClose(); };
  const handleSubmit=async(e)=>{
    e.preventDefault();
    setStatus('submitting');
    try{
      const res=await fetch('https://formspree.io/f/maqzekyr',{
        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');}
  };
  const modalStyle = {display: open ? 'flex' : 'none'};
  return (
    <div className="smodal" id="schedule" style={modalStyle} onClick={(e)=>{if(e.target.id==='schedule')close(e);}}>
      <div className="mcard">
        <button type="button" className="smx" onClick={close} aria-label="Close" style={{background:'transparent',border:'none',cursor:'pointer',font:'inherit'}}>×</button>
        {status==='success'?(
          <div style={{textAlign:'center',padding:'1rem 0 .5rem'}}>
            <div className="mk">REQUEST RECEIVED</div>
            <h3>Thanks. We'll be in touch.</h3>
            <p className="fs" style={{marginBottom:'1.4rem'}}>We respond within one business day to schedule your 20-minute working session with a Network advisor.</p>
            <button type="button" className="ssub" onClick={close} style={{maxWidth:'200px'}}>Close</button>
          </div>
        ):(
        <React.Fragment>
        <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>
        <form onSubmit={handleSubmit}>
          <div className="sfg">
            <div className="sff"><label>Your name</label><input type="text" name="name" required/></div>
            <div className="sff"><label>Work email</label><input type="email" name="email" required/></div>
            <div className="sff w"><label>Company name</label><input type="text" name="company" required/></div>
            <div className="sff"><label>Industry</label><input type="text" name="industry" required/></div>
            <div className="sff"><label>Employees</label>
              <select name="employees" required defaultValue="">
                <option value="" disabled>Select range</option>
                <option>Under 50</option><option>50 to 200</option><option>200 to 500</option>
                <option>500 to 1,000</option><option>1,000 to 3,000</option><option>3,000+</option>
              </select>
            </div>
            <div className="sff w"><label>Where are you looking for relief?</label>
              <div className="scg" key={preselect.join('|')}>{MPAINS.map((p,i)=>(<label className="scr" key={i}><input type="checkbox" name="pain[]" value={p} defaultChecked={preselect.includes(p)}/><span>{p}</span></label>))}</div>
            </div>
            <div className="sff w"><label>Anything else we should know? (optional)</label><textarea name="notes"></textarea></div>
          </div>
          <button type="submit" className="ssub" disabled={status==='submitting'}>{status==='submitting'?'Submitting...':'Request a working session'}</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="snote">Submitting this form does not book a call. We review every request and respond within one business day.</div>
        </form>
        </React.Fragment>
        )}
      </div>
    </div>
  );
}

const Fade=({from,to,h=80})=>(<div style={{height:h,background:`linear-gradient(${from},${to})`,position:'relative',zIndex:20}}/>);

function Page(){
  return (
    <div className="page" id="main">
      <PageNav/>

      <section className="pwrap pwrap-hero"><HeroConstellation/></section>

      <Fade from="#0b1011" to="var(--bg)" h={120}/>

      <section className="pwrap" id="how-it-works" style={{height:660}}><MethodologyDescend/></section>
      <section className="pwrap" id="network-teaser" style={{height:760}}><NetworkConstellation/></section>
      <section className="pwrap" id="cascade" style={{height:700}}><CascadeBuild/></section>
      <section className="pwrap" id="mission" style={{height:470}}><Mission/></section>
      <section className="pwrap" id="resources" style={{height:840}}><Resources/></section>
      <section className="pwrap" id="contact" style={{height:680}}><GetInTouch/></section>

      <Fade from="var(--bg)" to="#0b1011" h={120}/>

      <section className="pwrap" id="closing" style={{height:600}}><FinalCTA/></section>

      <ScheduleModal/>
    </div>
  );
}

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