const STEPS=['Gift','Your info','Review','Done'];
const DRAFT_KEY='hm-give-draft';
function StepBar({step}){
  return <ol style={{listStyle:'none',margin:0,padding:0,display:'flex',gap:8}}>{STEPS.slice(0,3).map((s,i)=>{const on=i<=step;return <li key={s} style={{flex:1,display:'flex',flexDirection:'column',gap:8}}><span style={{height:3,background:on?'var(--hm-pine-700)':'var(--hm-granite-200)',borderRadius:2,transition:'background var(--dur-base)'}}/><span style={{fontFamily:'var(--font-label)',fontSize:11,fontWeight:500,letterSpacing:'.16em',textTransform:'uppercase',color:on?'var(--text-1)':'var(--text-3)'}}>{(i+1)+' · '+s}</span></li>})}</ol>;
}
const per=freq=>freq==='Monthly'?' / month':freq==='Annually'?' / year':'';
const money=n=>'$'+(+n||0).toLocaleString(undefined,{minimumFractionDigits:n%1?2:0,maximumFractionDigits:2});
const giftTotal=g=>Math.round((g.amount||0)*(g.fee?1.03:1)*100)/100;
function GiftSummary({g,total}){
  const row=(a,b,strong)=><div style={{display:'flex',justifyContent:'space-between',gap:16,fontSize:strong?17:15,fontWeight:strong?500:400,color:strong?'var(--text-1)':'var(--text-2)'}}><span>{a}</span><span>{b}</span></div>;
  return <div style={{borderTop:'1.5px solid var(--hm-ink)',paddingTop:16,display:'flex',flexDirection:'column',gap:8}}>
    {row(g.freq+' gift',money(g.amount))}
    {g.tribute&&g.honoree&&row(g.tributeType,g.honoree)}
    {g.fee&&row('Processing fee covered',money(Math.round((total-(g.amount||0))*100)/100))}
    <div style={{height:1,background:'var(--border-2)',margin:'4px 0'}}/>
    {row('Total',money(total)+per(g.freq),true)}
  </div>;
}
const loadDraft=()=>{try{return JSON.parse(sessionStorage.getItem(DRAFT_KEY)||'null')}catch(e){return null}};
const saveDraft=g=>{try{sessionStorage.setItem(DRAFT_KEY,JSON.stringify(g))}catch(e){}};
const clearDraft=()=>{try{sessionStorage.removeItem(DRAFT_KEY)}catch(e){}};
function GivePage({go,params}){
  const {Eyebrow,Tabs,AmountPicker,Select,Input,Checkbox,Switch,Button,Badge,Radio}=HM;
  const wide=useWide(980);
  const qs=React.useMemo(()=>new URLSearchParams(location.search),[]);
  const sessionId=qs.get('session_id');
  const canceled=qs.get('canceled')==='1';
  const draft=canceled?loadDraft():null;
  const [step,setStep]=React.useState(sessionId?3:draft?2:0);
  const [err,setErr]=React.useState({});
  const [busy,setBusy]=React.useState(false);
  const [notice,setNotice]=React.useState(canceled?'Checkout was canceled, so no payment was made. Your gift details are still here.':'');
  const [done,setDone]=React.useState(sessionId?{loading:true}:null);
  const [g,setG]=React.useState(draft||{freq:(params&&params.freq)||'One-time',amount:(params&&params.amount)||250,tribute:false,tributeType:'In honor of',honoree:'',first:'',last:'',email:'',phone:'',anon:false,updates:true,fee:true});
  const set=(k,v)=>setG(s=>({...s,[k]:v}));
  const total=giftTotal(g);
  const formRef=React.useRef(null);
  const top=()=>{const el=formRef.current;if(el){const y=el.getBoundingClientRect().top+window.scrollY-100;window.scrollTo({top:y,behavior:'smooth'})}};
  React.useEffect(()=>{
    if(!sessionId&&!canceled)return;
    history.replaceState(null,'',location.pathname+'#/give');
    if(!sessionId)return;
    fetch('/api/checkout/'+encodeURIComponent(sessionId)).then(r=>r.ok?r.json():Promise.reject(r)).then(d=>{clearDraft();setDone(d)}).catch(()=>setDone({error:true}));
  },[]);
  const checkout=async()=>{
    setBusy(true);setNotice('');saveDraft(g);
    try{
      const r=await fetch('/api/checkout',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(g)});
      const d=await r.json().catch(()=>({}));
      if(!r.ok||!d.url)throw new Error(d.error||'We couldn’t start checkout. Please try again.');
      location.href=d.url;
    }catch(e){setBusy(false);setNotice(e.message)}
  };
  const next=()=>{
    const e={};
    if(step===0){if(!g.amount||g.amount<5)e.amount='Please choose an amount of at least $5.';if(g.tribute&&!g.honoree.trim())e.honoree='Who is this gift for?'}
    if(step===1){if(!g.first.trim())e.first='Required';if(!g.last.trim())e.last='Required';if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(g.email))e.email='Enter a valid email for your receipt'}
    setErr(e);if(Object.keys(e).length)return;
    if(step===2){checkout();return}
    setStep(step+1);top();
  };
  const back=()=>{setErr({});setNotice('');setStep(step-1);top()};
  const lbl={display:'block',fontFamily:'var(--font-label)',fontSize:12,fontWeight:500,letterSpacing:'.14em',textTransform:'uppercase',color:'var(--text-2)',marginBottom:10};
  const panels=[
    <>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:16,flexWrap:'wrap'}}><span style={{...lbl,marginBottom:0}}>Frequency</span><Tabs variant="segmented" tabs={['One-time','Monthly','Annually']} value={g.freq} onChange={v=>set('freq',v)}/></div>
      {g.freq!=='One-time'&&<p style={{fontSize:14,color:'var(--text-2)',margin:'-8px 0 0',display:'flex',gap:8,alignItems:'center'}}><HM.Icon name="repeat" size={16} color="var(--hm-pine-700)"/>Recurring partners provide steady support for students year-round. Cancel anytime.</p>}
      <div><span style={lbl}>Amount</span><AmountPicker value={g.amount} onChange={v=>set('amount',v)} amounts={[100,250,500,1000,2500]} impact={g.freq==='One-time'?window.IMPACT:undefined}/>{err.amount&&<p style={{color:'var(--danger)',fontSize:13,marginTop:8}}>{err.amount}</p>}</div>
      <div><span style={lbl}>Where your gift goes</span><p style={{margin:0,fontSize:15,color:'var(--text-2)',lineHeight:1.5}}>Gifts support faculty and administrator salaries, the building and supplies, and student scholarships. The board and administration decide how funds are used as needs arise.</p></div>
      <div style={{display:'flex',flexDirection:'column',gap:14}}><Switch label="Dedicate this gift in honor or memory of someone" checked={g.tribute} onChange={v=>set('tribute',v)}/>
        {g.tribute&&<div style={{display:'flex',flexDirection:'column',gap:14,paddingLeft:56}}><Radio name="tt" direction="row" options={['In honor of','In memory of']} value={g.tributeType} onChange={v=>set('tributeType',v)}/><Input label="Honoree name" value={g.honoree} onChange={e=>set('honoree',e.target.value)} error={err.honoree}/></div>}
      </div>
    </>,
    <>
      <div style={grid(200,16)}><Input label="First name" value={g.first} onChange={e=>set('first',e.target.value)} error={err.first} required/><Input label="Last name" value={g.last} onChange={e=>set('last',e.target.value)} error={err.last} required/></div>
      <Input label="Email" type="email" value={g.email} onChange={e=>set('email',e.target.value)} error={err.email} hint="Your tax receipt will be sent here." required/>
      <Input label="Phone (optional)" type="tel" value={g.phone} onChange={e=>set('phone',e.target.value)}/>
      <div style={{display:'flex',flexDirection:'column',gap:14}}><Switch label="Give anonymously" checked={g.anon} onChange={v=>set('anon',v)}/><Checkbox label="Send me occasional updates from High Mountain" checked={g.updates} onChange={v=>set('updates',v)}/></div>
    </>,
    <>
      <Checkbox label={'Cover the processing fee ('+money(Math.round((total-(g.amount||0))*100)/100)+')'} description="Adds 3% so the full amount of your gift goes to High Mountain." checked={g.fee} onChange={v=>set('fee',v)}/>
      <GiftSummary g={g} total={total}/>
      <div className="sm-paynote"><HM.Icon name="lock" size={18} color="var(--hm-pine-700)"/><span>You’ll finish on Stripe’s secure checkout page and pay by card or bank account there. High Mountain never sees your card or bank details.{g.freq!=='One-time'&&' Your '+g.freq.toLowerCase()+' gift renews automatically until you cancel.'}</span></div>
    </>
  ];
  const doneGift=done&&!done.loading&&!done.error?{freq:done.freq,amount:done.amount,fee:done.fee,tribute:!!done.honoree,tributeType:done.tributeType,honoree:done.honoree}:null;
  const thanks=()=>{
    if(done.loading)return <p style={{color:'var(--text-2)',fontSize:18}}>Confirming your gift…</p>;
    if(done.error||!done.complete)return <div style={{display:'flex',flexDirection:'column',gap:20,alignItems:'flex-start'}}>
      <h2 style={{fontSize:40}}>We couldn’t confirm this gift.</h2>
      <p style={{color:'var(--text-2)',fontSize:18}}>If you finished checkout, Stripe will still email your receipt. If you didn’t, no payment was made. Questions? Get in touch and we’ll sort it out.</p>
      <div style={{display:'flex',gap:12,flexWrap:'wrap'}}><Button onClick={()=>{setDone(null);setStep(0);top()}}>Start a new gift</Button><Button variant="secondary" onClick={()=>go('contact')}>Contact us</Button></div>
    </div>;
    return <div style={{display:'flex',flexDirection:'column',gap:20,alignItems:'flex-start'}}>
      <span style={{width:56,height:56,borderRadius:999,background:'var(--hm-pine-100)',display:'grid',placeItems:'center'}}><HM.Icon name="heart-handshake" size={28} color="var(--hm-pine-700)"/></span>
      <Badge tone="pine">{'Confirmation '+done.ref}</Badge>
      <h2 style={{fontSize:40}}>{'Thank you, '+(done.first||'friend')+'.'}</h2>
      <p style={{color:'var(--text-2)',fontSize:18}}>{'Your '+(done.freq==='One-time'?'':done.freq.toLowerCase()+' ')+'gift to High Mountain helps develop future leaders in faith, character and wisdom.'+(done.email?' A receipt is on its way to '+done.email+'.':'')}</p>
      {done.processing&&<p style={{color:'var(--text-2)',fontSize:15}}>Bank payments take a few business days to clear. We’ll email you once it goes through.</p>}
      <p style={{color:'var(--text-2)',fontSize:15}}>{'Sign in to '}<a href="#/account">My giving</a>{done.freq==='One-time'?' any time to see your gifts and download giving statements.':' any time to see your gifts, download giving statements, or change or cancel this recurring gift.'}</p>
      <div style={{width:'100%'}}><GiftSummary g={doneGift} total={done.total}/></div>
      <div style={{display:'flex',gap:12,flexWrap:'wrap'}}><Button onClick={()=>go('home')}>Back to home</Button><Button variant="secondary" onClick={()=>{setDone(null);setStep(0);top()}}>Give again</Button></div>
    </div>;
  };
  return <div>
    <section className="sm-givesplit">
      <div className="sm-giveside sm-dark"><div style={{padding:'calc(var(--header-h) + 48px) clamp(24px,4vw,64px) clamp(40px,5vw,72px)',display:'flex',flexDirection:'column',gap:28,width:'100%'}}>
        <span className="sm-k sm-rule">Give</span>
        <h1 className="sm-h1" style={{fontSize:'clamp(52px,6vw,104px)'}}>Invest in the <b>next leaders.</b></h1>
        <p className="sm-lead" style={{maxWidth:520}}>Your gift supports faculty and administrators, the building and supplies, and student scholarships.</p>
        <div className="sm-implist">{Object.entries(IMPACT).map(([k,v])=><div key={k}><b>{'$'+(+k).toLocaleString()}</b><span>{v}</span></div>)}</div>
      </div></div>
      <div ref={formRef} className="sm-giveform">
        {step<3?<>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12}}><h2 style={{fontSize:40}}>Make a gift</h2><span style={{display:'flex',gap:6,alignItems:'center',fontSize:13,color:'var(--text-3)'}}><HM.Icon name="lock" size={14}/>Secured by Stripe</span></div>
          <StepBar step={step}/>
          {notice&&<p role="alert" style={{margin:0,padding:'12px 16px',borderRadius:'var(--radius-card)',background:'var(--warning-bg)',color:'var(--text-1)',fontSize:15}}>{notice}</p>}
          {panels[step]}
          <div style={{display:'flex',gap:12,justifyContent:'space-between',alignItems:'center',paddingTop:4}}>
            {step>0?<Button variant="ghost" iconLeft="arrow-left" onClick={back} disabled={busy}>Back</Button>:<span style={{fontSize:14,color:'var(--text-2)'}}>{money(total)+per(g.freq)}</span>}
            {step<2?<Button iconRight="arrow-right" onClick={next}>Continue</Button>:<Button variant="accent" size="lg" iconLeft="heart" onClick={next} disabled={busy}>{busy?'Opening checkout…':'Give '+money(total)+per(g.freq)}</Button>}
          </div>
          <p style={{fontSize:12,color:'var(--text-3)',margin:0}}>Payments are processed by Stripe. Tax-deductibility depends on High Mountain’s nonprofit status.</p>
        </>:thanks()}
      </div>
    </section>
    <Section dark><div style={{display:'flex',flexDirection:'column',gap:56}}>
      <h2 className="sm-h2">Other ways <i>to give.</i></h2>
      <div className="hm-pillars">{[['mail','By check','Payable to High Mountain Enrichment. Mailing address to be confirmed.'],['landmark','Stock, DAF or IRA','Contact us to arrange a gift of securities or a donor-advised fund grant.'],['building-2','Employer matching','Many employers double gifts — ask your HR team.']].map(([ic,t,b])=><div key={t}><HM.Icon name={ic} size={24} color="var(--hm-aspen-500)"/><h3 style={{fontSize:30}}>{t}</h3><p style={{color:'var(--text-2)'}}>{b}</p></div>)}</div>
      <div><button type="button" className="hm-textlink" style={{color:'var(--hm-snow)'}} onClick={()=>go('contact')}>Talk with us about a gift<HM.Icon name="arrow-right" size={16}/></button></div>
    </div></Section>
  </div>;
}
window.GivePage=GivePage;
