/* GCCReady — ArticleEnhancements
 * Mounts on long-form pages (articles, hub fragments). Adds:
 *  1. Scroll-progress bar fixed at top
 *  2. 50%-scroll non-blocking strip with topic-relevant CTA (auto-dismissable)
 *  3. Exit-intent overlay with email capture (mouse leaves top of viewport)
 *  4. Floating "Take Skill Badge" pill after 30 s on page
 *
 * Each pattern interrupt remembers dismissal in sessionStorage so it doesn't
 * re-fire on the same article visit.
 */

function ArticleEnhancements({ topic, articleSlug, audience = 'student' }) {
  const [scrollPct, setScrollPct] = React.useState(0);
  const [stripOpen, setStripOpen] = React.useState(false);
  const [exitOpen, setExitOpen] = React.useState(false);
  const [pillVisible, setPillVisible] = React.useState(false);
  const [emailStatus, setEmailStatus] = React.useState({ kind:'idle', msg:'' });
  const emailInput = React.useRef(null);

  // Scroll progress + 50% strip trigger
  React.useEffect(() => {
    const dismissedStrip = sessionStorage.getItem(`gr_strip_${articleSlug}`) === '1';
    const onScroll = () => {
      const h = document.documentElement;
      const total = (h.scrollHeight || 0) - (h.clientHeight || 0);
      const pct = total > 0 ? Math.min(100, Math.round(((h.scrollTop || window.scrollY) / total) * 100)) : 0;
      setScrollPct(pct);
      if (!dismissedStrip && pct >= 50 && !stripOpen) setStripOpen(true);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [articleSlug, stripOpen]);

  // Exit-intent: trigger on mouseleave with clientY < 5
  React.useEffect(() => {
    const dismissedExit = sessionStorage.getItem('gr_exit_overlay_dismissed') === '1';
    if (dismissedExit) return;
    const onLeave = (e) => {
      if (e.clientY < 6 && !exitOpen) setExitOpen(true);
    };
    document.addEventListener('mouseleave', onLeave);
    return () => document.removeEventListener('mouseleave', onLeave);
  }, [exitOpen]);

  // Floating pill after 30 s
  React.useEffect(() => {
    const dismissedPill = sessionStorage.getItem('gr_pill_dismissed') === '1';
    if (dismissedPill) return;
    const t = setTimeout(() => setPillVisible(true), 30000);
    return () => clearTimeout(t);
  }, []);

  const dismissStrip = () => {
    sessionStorage.setItem(`gr_strip_${articleSlug}`, '1');
    setStripOpen(false);
  };
  const dismissExit = () => {
    sessionStorage.setItem('gr_exit_overlay_dismissed', '1');
    setExitOpen(false);
  };
  const dismissPill = () => {
    sessionStorage.setItem('gr_pill_dismissed', '1');
    setPillVisible(false);
  };

  const submitExitEmail = async (e) => {
    e.preventDefault();
    const email = emailInput.current && emailInput.current.value;
    if (!email) return;
    setEmailStatus({ kind:'sending', msg:'Saving your bookmark…' });
    const data = {
      form_type:'exit_intent_bookmark',
      email,
      audience,
      topic: topic || '',
      article_slug: articleSlug || '',
      ts_client: new Date().toISOString(),
    };
    try { localStorage.setItem('gr_email_capture_last', JSON.stringify(data)); } catch (_) {}
    const SHEETS_ENDPOINT = (window.GR_CONFIG && window.GR_CONFIG.SHEETS_ENDPOINT) || '';
    if (SHEETS_ENDPOINT) {
      try {
        const params = new URLSearchParams();
        Object.entries(data).forEach(([k, v]) => params.set(k, v));
        const res = await fetch(SHEETS_ENDPOINT, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}, body: params.toString() });
        if (!res.ok) throw new Error();
      } catch (_) {}
    }
    setEmailStatus({ kind:'success', msg:'Bookmarked. Check your inbox in a few minutes.' });
    setTimeout(() => dismissExit(), 1500);
  };

  // Topic → CTA mapping for the 50% strip
  const stripCTA = {
    'US CPA':  { label:'Run the CPA ROI calculator', href:'/tools-static/cpa-roi-calculator.html' },
    'US CMA':  { label:'See the CMA pathway', href:'#/certifications/us-cma' },
    'EA':      { label:'See the EA pathway', href:'#/certifications/ea' },
    'CFA':     { label:'See the CFA pathway', href:'#/certifications/cfa' },
    'ACCA':    { label:'Join the ACCA waitlist', href:'#/certifications/acca' },
    'AI & Tech': { label:'Open the AI Data Analytics pod', href:'#/role/data-analytics' },
    'India Compliance': { label:'Try the GST Computation tool', href:'/tools-static/gst-computation-tool.html' },
    'GCC Job Readiness': { label:'Run the Interview Readiness Assessment', href:'/tools-static/interview-prep-assessment.html' },
  }[topic] || { label:'Take the Skill Badge', href:'#/skill-badge' };

  return (
    <>
      {/* 1. Scroll progress bar */}
      <div style={{
        position:'fixed', top:0, left:0, height:3, width:`${scrollPct}%`,
        background:'linear-gradient(90deg, #FBBF24, #F59E0B)',
        zIndex:60, transition:'width .12s ease-out',
      }} aria-hidden="true"/>

      {/* 2. 50%-scroll non-blocking strip */}
      {stripOpen && (
        <div style={{
          position:'fixed', bottom:20, left:'50%', transform:'translateX(-50%)',
          maxWidth: '92vw', width: 640,
          background:'var(--gr-navy)', color:'#fff',
          padding:'14px 20px', borderRadius:14,
          boxShadow:'0 20px 50px -12px rgba(0,0,0,.45)',
          display:'flex', alignItems:'center', gap:14, zIndex:55,
          animation:'grFade .3s ease-out both',
        }}>
          <Icon name="sparkles" size={18} style={{color:'#FBBF24', flexShrink:0}}/>
          <span style={{font:'600 13.5px/1.4 Inter', flex:1, color:'rgba(255,255,255,.92)'}}>
            Liked this so far? <strong style={{color:'#fff'}}>{stripCTA.label}</strong> in 2 minutes.
          </span>
          <a href={stripCTA.href} className="gr-btn gr-btn-gold" style={{padding:'8px 14px', fontSize:13}}>
            Open <Icon name="arrow-right" size={12}/>
          </a>
          <button onClick={dismissStrip} aria-label="Dismiss" style={{
            background:'none', border:'none', color:'rgba(255,255,255,.6)', cursor:'pointer', padding:6,
          }}><Icon name="x" size={16}/></button>
        </div>
      )}

      {/* 3. Exit-intent overlay */}
      {exitOpen && (
        <div role="dialog" aria-modal="true" style={{
          position:'fixed', inset:0, zIndex:70,
          background:'rgba(13,27,42,.72)', backdropFilter:'blur(6px)',
          display:'grid', placeItems:'center',
          animation:'grFade .25s ease-out both',
        }} onClick={(e) => { if (e.target === e.currentTarget) dismissExit(); }}>
          <div style={{
            background:'#fff', borderRadius:24, padding:40,
            maxWidth:520, width:'92%', boxShadow:'0 30px 80px rgba(0,0,0,.45)',
          }}>
            <div style={{font:'700 11.5px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Before you go</div>
            <h3 className="gr-h3" style={{fontSize:28, marginTop:8}}>Bookmark this — get the personalised plan in your inbox.</h3>
            <p className="gr-p" style={{marginTop:8}}>
              We'll send you a 1-page plan: the cert that fits your degree, the role pod we'd recommend, and the GCCs hiring for your profile. No spam, unsubscribe in 1 click.
            </p>
            {emailStatus.kind === 'success' ? (
              <div style={{
                marginTop:18, padding:'14px 16px', borderRadius:12,
                background:'var(--gr-green-50)', color:'var(--gr-green)',
                font:'600 14px/1.5 Inter',
              }}>
                <Icon name="check-circle" size={16} style={{verticalAlign:'-2px', marginRight:8}}/>
                {emailStatus.msg}
              </div>
            ) : (
              <form onSubmit={submitExitEmail} style={{marginTop:18, display:'flex', gap:10, flexWrap:'wrap'}}>
                <input ref={emailInput} type="email" required placeholder="you@example.com" style={{
                  flex:1, minWidth:200, padding:'12px 14px',
                  font:'500 14.5px/1.4 Inter',
                  border:'1.5px solid var(--gr-border)', borderRadius:11,
                }}/>
                <button type="submit" className="gr-btn gr-btn-gold gr-btn-lg" disabled={emailStatus.kind === 'sending'}>
                  {emailStatus.kind === 'sending' ? 'Sending…' : 'Email my plan'}
                </button>
              </form>
            )}
            <div style={{marginTop:14, display:'flex', justifyContent:'space-between', alignItems:'center', font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)'}}>
              <span>Powered by GCCReady · DPDP-compliant</span>
              <button onClick={dismissExit} style={{background:'none', border:'none', cursor:'pointer', color:'var(--gr-fg-3)', font:'500 12.5px/1 Inter'}}>
                Maybe later
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 4. Floating "Take Skill Badge" pill */}
      {pillVisible && !stripOpen && (
        <a href="#/skill-badge" style={{
          position:'fixed', bottom:24, right:24, zIndex:50,
          background:'linear-gradient(135deg, #FBBF24, #F59E0B)',
          color:'var(--gr-navy)', textDecoration:'none',
          padding:'14px 18px', borderRadius:999,
          font:'700 14px/1 "DM Sans"',
          boxShadow:'0 14px 32px -6px rgba(245,158,11,.55)',
          display:'inline-flex', alignItems:'center', gap:10,
          animation:'grFade .3s ease-out both',
        }}>
          <Icon name="qr" size={16}/>
          <span>Take Skill Badge</span>
          <button onClick={(e) => { e.preventDefault(); dismissPill(); }} style={{
            background:'rgba(13,27,42,.18)', border:'none', cursor:'pointer',
            color:'var(--gr-navy)', borderRadius:'50%', width:22, height:22,
            display:'grid', placeItems:'center',
          }} aria-label="Dismiss">
            <Icon name="x" size={11}/>
          </button>
        </a>
      )}
    </>
  );
}

Object.assign(window, { ArticleEnhancements });
