/* KYDT Donate — our own amount step, then Stripe's Payment Element themed to the
   design system, then our own thank-you. Stripe never takes over the page.

   Server side: functions/api/donate.js (session) and donate-status.js (thank-you).
   The Stripe mode follows the Pages environment's keys, not this file. */
const { useState: dUseState, useEffect: dUseEffect, useRef: dUseRef } = React;

/* Mirrors functions/_stripe.js — the server recomputes, this is display only. */
const FEE_PERCENT = 0.0265, FEE_FIXED_CENTS = 30, MIN_DOLLARS = 5;
const withFeeCents = (c)=> Math.ceil((c + FEE_FIXED_CENTS) / (1 - FEE_PERCENT));
const money = (cents)=> '$' + (cents/100).toLocaleString('en-NZ', { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2 });

/* Quick picks only — donors can type any amount. */
const QUICK_AMOUNTS = [25, 50, 100, 250];

/* Stripe Appearance, in the design system's own values (Stripe cannot read CSS vars). */
const STRIPE_APPEARANCE = {
  theme: 'stripe',
  variables: {
    colorPrimary: '#005078',
    colorText: '#0e1c26',
    colorTextSecondary: '#556974',
    colorDanger: '#b4462f',
    colorBackground: '#ffffff',
    fontFamily: "'Work Sans', system-ui, -apple-system, 'Segoe UI', sans-serif",
    fontSizeBase: '16px',
    borderRadius: '8px',
    spacingUnit: '4px',
  },
  rules: {
    '.Input': { border: '1.5px solid #b8c4cb', boxShadow: 'none', padding: '12px 14px' },
    '.Input:focus': { borderColor: '#1aa6c9', boxShadow: '0 0 0 3px rgba(26,166,201,0.25)' },
    '.Label': { fontWeight: '500', color: '#0e1c26', fontSize: '14px' },
    '.Tab': { border: '1.5px solid #dbe2e6', boxShadow: 'none' },
    '.Tab--selected': { borderColor: '#005078', boxShadow: '0 0 0 1px #005078' },
  },
};
const STRIPE_FONTS = [{ cssSrc: 'https://fonts.googleapis.com/css2?family=Work+Sans:wght@400;500;600&display=swap' }];

function DonatePage(){
  const DS = window.KYDTDesignSystem_1d4054;
  const { Card, Button, Input, Checkbox, Badge } = DS;
  const { Reveal, PageHero } = window;
  /* Lucide swaps <i> for <svg> outside React; the keyed span gives React a node
     it still owns, so changing step never removes a node that is already gone. */
  const I = (n, size)=> <span key={n} style={{display:'inline-flex'}}>{window.KIcon(n, size)}</span>;
  window.useScrollFX('donate');
  dUseEffect(()=>{ window.playPageHero && window.playPageHero(); },[]);

  const sessionId = new URLSearchParams(location.search).get('session_id');
  const [step, setStep] = dUseState(sessionId ? 'done' : 'choose');
  const [frequency, setFrequency] = dUseState('once');
  const [amount, setAmount] = dUseState('50');
  const [coverFee, setCoverFee] = dUseState(true);
  const [name, setName] = dUseState('');
  const [email, setEmail] = dUseState('');
  const [error, setError] = dUseState('');
  const [busy, setBusy] = dUseState(false);
  const [canConfirm, setCanConfirm] = dUseState(false);
  const [testMode, setTestMode] = dUseState(false);
  const [result, setResult] = dUseState(null);
  const checkoutRef = dUseRef(null);
  const cardRef = dUseRef(null);

  const baseCents = Math.round((parseFloat(String(amount).replace(/[^0-9.]/g,'')) || 0) * 100);
  const totalCents = coverFee ? withFeeCents(baseCents) : baseCents;
  const feeCents = totalCents - baseCents;
  const per = frequency === 'monthly' ? ' / month' : '';

  dUseEffect(()=>{ window.lucide && window.lucide.createIcons(); }, [step, result, busy, canConfirm]);

  const scrollToCard = ()=> cardRef.current && cardRef.current.scrollIntoView({ behavior:'smooth', block:'start' });

  async function startPayment(e){
    e.preventDefault();
    setError('');
    if (baseCents < MIN_DOLLARS*100) return setError('The smallest gift online is $5.');
    if (!name.trim()) return setError('Please add your full name, so your tax receipt is made out to you.');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) return setError('Please check your email address.');
    if (!window.Stripe) return setError('The secure payment form did not load. Please refresh and try again.');
    setBusy(true);
    try {
      const cfgRes = await fetch('/api/donate');
      const cfg = await cfgRes.json();
      if (!cfgRes.ok) throw new Error(cfg.error || 'Donations are not available just now.');
      setTestMode(!!cfg.testMode);
      const stripe = window.Stripe(cfg.publishableKey);
      const clientSecret = fetch('/api/donate', {
        method:'POST', headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify({ frequency, amount: baseCents/100, coverFee, name: name.trim(), email: email.trim() }),
      }).then(async r=>{ const d = await r.json(); if(!r.ok) throw new Error(d.error); return d.clientSecret; });
      await clientSecret; // surface server-side validation before showing the card form
      const checkout = stripe.initCheckoutElementsSdk({
        clientSecret,
        elementsOptions: { appearance: STRIPE_APPEARANCE, fonts: STRIPE_FONTS },
      });
      checkout.on('change', (s)=> setCanConfirm(!!s.canConfirm));
      checkoutRef.current = checkout;
      setStep('pay');
      scrollToCard();
    } catch (err) {
      setError(err.message || 'We could not start the donation. Please try again.');
    } finally {
      setBusy(false);
    }
  }

  /* Mount the Payment Element once its container exists. */
  dUseEffect(()=>{
    if (step !== 'pay' || !checkoutRef.current) return;
    const el = checkoutRef.current.createPaymentElement();
    el.mount('#kydt-payment-element');
    return ()=>{ try { el.destroy(); } catch(_){} };
  },[step]);

  async function confirm(e){
    e.preventDefault();
    setError(''); setBusy(true);
    try {
      const { actions } = await checkoutRef.current.loadActions();
      const r = await actions.confirm();
      // Only reached on an immediate error; success redirects to return_url.
      if (r.type === 'error') setError(r.error.message);
    } catch (err) {
      setError(err.message || 'Payment did not go through. Please try again.');
    } finally {
      setBusy(false);
    }
  }

  function backToChoose(){
    checkoutRef.current = null;
    setCanConfirm(false);
    setStep('choose');
  }

  /* Thank-you: read the outcome back from Stripe, not from the URL. */
  dUseEffect(()=>{
    if (!sessionId) return;
    fetch('/api/donate-status?session_id=' + encodeURIComponent(sessionId))
      .then(r=>r.json()).then(setResult)
      .catch(()=> setResult({ error:'lookup' }));
  },[]);

  const segBtn = (key, label)=>(
    <button type="button" onClick={()=>setFrequency(key)} aria-pressed={frequency===key}
      style={{flex:1,padding:'12px 16px',border:0,borderRadius:'var(--radius-pill)',cursor:'pointer',
        fontFamily:'var(--font-body)',fontSize:15,fontWeight:600,transition:'background var(--dur-fast), color var(--dur-fast)',
        background: frequency===key ? 'var(--brand-primary)' : 'transparent',
        color: frequency===key ? 'var(--white)' : 'var(--text-body)'}}>{label}</button>
  );

  const chip = (v)=>{
    const on = String(v) === String(amount);
    return (
      <button key={v} type="button" onClick={()=>setAmount(String(v))} aria-pressed={on}
        style={{padding:'10px 16px',borderRadius:'var(--radius-pill)',cursor:'pointer',fontFamily:'var(--font-body)',fontSize:15,fontWeight:600,
          border:`1.5px solid ${on ? 'var(--brand-secondary)' : 'var(--border-default)'}`,
          background: on ? 'var(--jade-100)' : 'var(--white)', color: on ? 'var(--jade-800)' : 'var(--text-body)'}}>${v}</button>
    );
  };

  const errorLine = error && (
    <p role="alert" style={{margin:'14px 0 0',fontSize:14,lineHeight:1.5,color:'var(--danger)'}}>{error}</p>
  );

  let panel;
  if (step === 'choose') panel = (
    <form onSubmit={startPayment} noValidate>
      <div role="group" aria-label="How often" style={{display:'flex',gap:4,padding:4,borderRadius:'var(--radius-pill)',background:'var(--surface-sunken)'}}>
        {segBtn('once','Give once')}
        {segBtn('monthly','Give monthly')}
      </div>

      <label htmlFor="kydt-amount" style={{display:'block',margin:'26px 0 8px',fontSize:14,fontWeight:500,color:'var(--text-heading)'}}>
        Your gift{frequency==='monthly' ? ' each month' : ''}
      </label>
      <div style={{position:'relative'}}>
        <span aria-hidden="true" style={{position:'absolute',left:18,top:'50%',transform:'translateY(-50%)',fontFamily:'var(--font-display)',fontSize:28,color:'var(--text-muted)'}}>$</span>
        <input id="kydt-amount" inputMode="decimal" autoComplete="off" value={amount}
          onChange={e=>setAmount(e.target.value.replace(/[^0-9.]/g,''))}
          style={{width:'100%',boxSizing:'border-box',padding:'16px 18px 16px 40px',fontFamily:'var(--font-display)',fontSize:32,fontWeight:600,
            color:'var(--text-heading)',border:'1.5px solid var(--border-default)',borderRadius:'var(--radius-md)',background:'var(--white)',outline:'none'}}
          onFocus={e=>e.target.style.borderColor='var(--focus-ring)'} onBlur={e=>e.target.style.borderColor='var(--border-default)'} />
      </div>
      <div style={{display:'flex',flexWrap:'wrap',gap:8,marginTop:12}}>{QUICK_AMOUNTS.map(chip)}</div>

      <div style={{marginTop:22,padding:'14px 16px',borderRadius:'var(--radius-md)',background:'var(--surface-sand)'}}>
        <Checkbox checked={coverFee} onChange={e=>setCoverFee(e.target.checked)}
          label={baseCents >= MIN_DOLLARS*100
            ? <span>Add {money(withFeeCents(baseCents)-baseCents)} to cover the card fee, so KYDT receives the full {money(baseCents)}.</span>
            : <span>Add the card fee to my gift, so KYDT receives the full amount.</span>} />
      </div>

      <div style={{display:'grid',gap:14,marginTop:22}}>
        <Input label="Full name" autoComplete="name" value={name} onChange={e=>setName(e.target.value)}
          hint="As it should appear on your tax receipt." />
        <Input label="Email" type="email" autoComplete="email" value={email} onChange={e=>setEmail(e.target.value)}
          hint="We'll send your receipt here." />
      </div>

      {errorLine}
      <div style={{marginTop:24}}>
        <Button type="submit" variant="secondary" size="lg" disabled={busy} iconRight={I('arrow-right')} style={{width:'100%',justifyContent:'center'}}>
          {busy ? 'One moment…' : baseCents >= MIN_DOLLARS*100 ? `Continue · ${money(totalCents)}${per}` : 'Continue'}
        </Button>
      </div>
    </form>
  );

  if (step === 'pay') panel = (
    <form onSubmit={confirm}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:12,paddingBottom:16,marginBottom:20,borderBottom:'1px solid var(--border-subtle)'}}>
        <div>
          <div style={{fontFamily:'var(--font-display)',fontSize:30,fontWeight:600,color:'var(--text-heading)'}}>{money(totalCents)}<span style={{fontSize:16,fontWeight:500,color:'var(--text-muted)'}}>{per}</span></div>
          <div style={{fontSize:13.5,color:'var(--text-muted)',marginTop:4}}>
            {frequency==='monthly' ? 'Monthly gift' : 'One-off gift'}{feeCents ? ` · includes ${money(feeCents)} card fee` : ''} · {name}
          </div>
        </div>
        <button type="button" onClick={backToChoose} style={{border:0,background:'none',padding:0,cursor:'pointer',color:'var(--text-link)',fontSize:14,fontWeight:600,fontFamily:'var(--font-body)'}}>Change</button>
      </div>
      {testMode && (
        <p style={{margin:'0 0 16px',padding:'10px 14px',borderRadius:'var(--radius-sm)',background:'var(--sea-50)',fontSize:13,lineHeight:1.5,color:'var(--sea-700)'}}>
          Test mode — no real money moves. Use card 4242 4242 4242 4242, any future date, any CVC.
        </p>
      )}
      <div id="kydt-payment-element" style={{minHeight:180}} />
      {errorLine}
      <div style={{marginTop:24}}>
        <Button type="submit" variant="secondary" size="lg" disabled={busy || !canConfirm} iconRight={I('heart')} style={{width:'100%',justifyContent:'center'}}>
          {busy ? 'Processing…' : `Give ${money(totalCents)}${per}`}
        </Button>
      </div>
    </form>
  );

  if (step === 'done') {
    const ok = result && !result.error && result.status === 'complete';
    const pending = !result;
    panel = (
      <div aria-live="polite" style={{textAlign:'center',padding:'12px 0'}}>
        <div style={{display:'inline-grid',placeItems:'center',width:64,height:64,borderRadius:'50%',background: ok ? 'var(--jade-100)' : 'var(--surface-sunken)',color: ok ? 'var(--jade-700)' : 'var(--sea-600)'}}>
          {I(ok ? 'heart' : pending ? 'loader' : 'info', 28)}
        </div>
        {pending && <p style={{margin:'18px 0 0',color:'var(--text-muted)'}}>Checking your donation…</p>}
        {ok && <React.Fragment>
          <h2 style={{margin:'18px 0 8px',fontFamily:'var(--font-display)',fontSize:'var(--text-2xl, 32px)',fontWeight:600,color:'var(--text-heading)'}}>
            Ngā mihi nui{result.name ? `, ${result.name.split(' ')[0]}` : ''}.
          </h2>
          <p style={{margin:'0 auto',maxWidth:420,fontSize:16,lineHeight:1.6,color:'var(--text-body)'}}>
            Your {result.frequency==='monthly' ? 'monthly ' : ''}gift of <strong>{money(result.totalCents)}{result.frequency==='monthly' ? ' a month' : ''}</strong> is on its way to rangatahi and whānau in Kaipātiki.
            {result.email ? <React.Fragment> Your tax receipt is being emailed to <strong>{result.email}</strong>.</React.Fragment> : null}
          </p>
          <div style={{marginTop:26}}>
            <Button as="a" href="/" variant="outline" size="md">Back to home</Button>
          </div>
        </React.Fragment>}
        {result && !ok && <React.Fragment>
          <h2 style={{margin:'18px 0 8px',fontFamily:'var(--font-display)',fontSize:26,fontWeight:600,color:'var(--text-heading)'}}>That donation didn't go through</h2>
          <p style={{margin:'0 auto',maxWidth:420,fontSize:15,lineHeight:1.6,color:'var(--text-body)'}}>
            No money has been taken. You can try again, or email <a href="mailto:support@kydt.org.nz" style={{color:'var(--text-link)'}}>support@kydt.org.nz</a>.
          </p>
          <div style={{marginTop:22}}>
            <Button as="a" href="/donate" variant="secondary" size="md">Try again</Button>
          </div>
        </React.Fragment>}
      </div>
    );
  }

  return (
    <div>
      <PageHero eyebrow={<T k="donate.hero.eyebrow">Donate</T>} title={<T k="donate.hero.title">Support the mahi.</T>}
        lead={<T k="donate.hero.lead">Every gift goes straight into walking alongside rangatahi and whānau in Kaipātiki.</T>} />

      <section className="kydt-section" style={{background:'var(--surface-sand)'}}>
        <div className="kydt-container-wide">
          <div className="kydt-split" style={{display:'grid',gridTemplateColumns:'0.85fr 1.15fr',gap:56,alignItems:'start'}}>
            <Reveal>
              <div style={{display:'grid',gap:22,maxWidth:420}}>
                {[
                  ['lock', 'Secure', 'Card details go straight to our payment provider, Stripe. KYDT never sees or stores them.'],
                  ['file-text', 'Tax receipt', 'KYDT is a registered charity (CC48458). Gifts of $5 or more are eligible for a tax credit, and we email a receipt for every donation.'],
                  ['repeat', 'Monthly, your way', 'To change or stop a monthly gift, email support@kydt.org.nz.'],
                ].map(([icon, title, body], i)=>(
                  <div key={title} style={{display:'flex',gap:14,alignItems:'flex-start'}}>
                    <span style={{flexShrink:0,display:'grid',placeItems:'center',width:40,height:40,borderRadius:'50%',background:'var(--white)',color:'var(--jade-700)'}}>{I(icon,18)}</span>
                    <div>
                      <h3 style={{margin:'2px 0 4px',fontFamily:'var(--font-display)',fontSize:'var(--text-md)',fontWeight:600,color:'var(--text-heading)'}}><T k={`donate.info.${i}.title`}>{title}</T></h3>
                      <p style={{margin:0,fontSize:15,lineHeight:1.6,color:'var(--text-body)'}}><T k={`donate.info.${i}.text`}>{body}</T></p>
                    </div>
                  </div>
                ))}
                <p style={{margin:'6px 0 0',fontSize:14,lineHeight:1.6,color:'var(--text-muted)'}}>
                  <T k="donate.info.largerGift">Thinking about a larger gift towards Te Whare Aranga?</T> <a href="/partner" style={{color:'var(--text-link)',fontWeight:600}}><T k="donate.info.partnerLink">Partner with us</T></a>.
                </p>
              </div>
            </Reveal>

            <Reveal delay={0.1}>
              <div ref={cardRef} style={{scrollMarginTop:100}}>
                <Card padding="clamp(20px, 5vw, var(--space-6))" style={{background:'var(--white)'}}>{panel}</Card>
              </div>
            </Reveal>
          </div>
        </div>
      </section>
    </div>
  );
}
window.DonatePage = DonatePage;
