/* GCCReady — engagement layer
 *  - WhatsApp FAB (floating action button) with tooltip on every page
 *  - Newsletter signup component (used in footer)
 *  - Lightweight analytics shim (queues page-views; ready to wire to GA4 / Plausible)
 */

const GR_WHATSAPP_NUM = '+' + ((window.GR_CONFIG && window.GR_CONFIG.WHATSAPP_NUM) || '919999999999');
const GR_WHATSAPP_GREETING = encodeURIComponent("Hi GCCReady team — I'm interested in:");

function WhatsAppFAB() {
  const [tipOpen, setTipOpen] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setTipOpen(true), 8000);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{position:'fixed', bottom:24, left:24, zIndex:60, display:'flex', flexDirection:'column', gap:10}}>
      {tipOpen && (
        <div style={{
          background:'#fff', color:'var(--gr-navy)',
          padding:'14px 16px', borderRadius:14,
          boxShadow:'0 14px 32px -10px rgba(13,27,42,.30)',
          font:'600 13.5px/1.5 Inter', maxWidth:280,
          border:'1px solid var(--gr-border)',
          position:'relative',
          animation:'grFade .3s ease-out both',
        }}>
          <button onClick={() => setTipOpen(false)} style={{
            position:'absolute', top:8, right:8, background:'none', border:'none',
            cursor:'pointer', color:'var(--gr-fg-3)', padding:4,
          }} aria-label="Dismiss">
            <Icon name="x" size={12}/>
          </button>
          <div style={{font:'800 12px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.12em', textTransform:'uppercase', marginBottom:6}}>Need help choosing?</div>
          WhatsApp our advisors. Replies within 8 business hours.
        </div>
      )}
      <a
        href={`https://wa.me/${GR_WHATSAPP_NUM.replace(/\D/g,'')}?text=${GR_WHATSAPP_GREETING}`}
        target="_blank" rel="noopener noreferrer"
        aria-label="WhatsApp us"
        style={{
          width:60, height:60, borderRadius:'50%',
          background:'#25D366', color:'#fff',
          display:'grid', placeItems:'center', textDecoration:'none',
          boxShadow:'0 14px 28px -8px rgba(37,211,102,.55)',
          transition:'transform .2s ease',
        }}
        onMouseEnter={(e)=>{ e.currentTarget.style.transform='scale(1.06)'; }}
        onMouseLeave={(e)=>{ e.currentTarget.style.transform='none'; }}
      >
        <Icon name="whatsapp" size={28}/>
      </a>
    </div>
  );
}

function NewsletterSignup({ inline = false }) {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState({ kind:'idle', msg:'' });
  const onSubmit = async (e) => {
    e.preventDefault();
    if (!email) return;
    setStatus({ kind:'sending', msg:'Subscribing…' });
    const data = { form_type:'newsletter', email, ts_client: new Date().toISOString() };
    try { localStorage.setItem('gr_newsletter_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 (_) {}
    }
    setStatus({ kind:'success', msg:"You're on the list. First issue lands Friday." });
    setEmail('');
  };
  return (
    <div style={{
      background: inline ? 'var(--gr-bg-cream)' : 'rgba(255,255,255,.06)',
      border: inline ? '1px solid var(--gr-border)' : '1px solid rgba(255,255,255,.10)',
      borderRadius:18, padding: inline ? 28 : 22,
    }}>
      <div style={{font:'800 11.5px/1 Inter', color: inline ? 'var(--gr-gold-700)' : '#FBBF24', letterSpacing:'.14em', textTransform:'uppercase', marginBottom:8}}>The GCC Brief · Weekly</div>
      <h4 style={{font:'800 18px/1.3 "DM Sans"', color: inline ? 'var(--gr-navy)' : '#fff', margin:0, letterSpacing:'-0.01em'}}>
        Real GCC openings + cohort dates + 1 deep-dive — every Friday.
      </h4>
      {status.kind === 'success' ? (
        <div style={{
          marginTop:14, padding:'12px 14px', borderRadius:11,
          background: inline ? 'var(--gr-green-50)' : 'rgba(34,197,94,.16)',
          color: inline ? 'var(--gr-green)' : '#86EFAC',
          font:'600 13.5px/1.5 Inter',
        }}>
          <Icon name="check-circle" size={14} style={{verticalAlign:'-2px', marginRight:7}}/>{status.msg}
        </div>
      ) : (
        <form onSubmit={onSubmit} style={{marginTop:14, display:'flex', gap:8, flexWrap:'wrap'}}>
          <input type="email" required value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="you@example.com"
            style={{
              flex:1, minWidth:180, padding:'12px 14px',
              font:'500 14px/1.4 Inter',
              border:'1.5px solid ' + (inline ? 'var(--gr-border)' : 'rgba(255,255,255,.18)'),
              background: inline ? '#fff' : 'rgba(255,255,255,.08)',
              color: inline ? 'var(--gr-fg-1)' : '#fff',
              borderRadius:11,
            }}/>
          <button type="submit" disabled={status.kind === 'sending'} className="gr-btn gr-btn-gold">
            {status.kind === 'sending' ? 'Sending…' : 'Subscribe'} <Icon name="arrow-right" size={13}/>
          </button>
        </form>
      )}
      <p style={{font:'500 11.5px/1.5 Inter', color: inline ? 'var(--gr-fg-3)' : 'rgba(255,255,255,.55)', marginTop:10}}>
        No spam · unsubscribe in 1 click · DPDP-compliant.
      </p>
    </div>
  );
}

/* Lightweight analytics shim — adds page_view + click events to a queue.
   Wire to GA4 by replacing the body of grTrack(); the queue is ready. */
(function () {
  if (typeof window === 'undefined') return;
  window.__grAnalytics = window.__grAnalytics || [];
  function grTrack(name, props) {
    var ev = { name: name, props: props || {}, ts: Date.now(), path: window.location.hash || '/' };
    window.__grAnalytics.push(ev);
    // GA4 hook (no-op if gtag isn't loaded)
    if (typeof window.gtag === 'function') {
      try { window.gtag('event', name, props || {}); } catch(e) {}
    }
    // Plausible hook
    if (typeof window.plausible === 'function') {
      try { window.plausible(name, { props: props }); } catch(e) {}
    }
  }
  window.grTrack = grTrack;
  // Fire on route change
  var lastHash = '';
  function fireRoute() {
    var h = window.location.hash || '#/';
    if (h !== lastHash) {
      lastHash = h;
      grTrack('route_change', { path: h });
    }
  }
  window.addEventListener('hashchange', fireRoute);
  if (document.readyState !== 'loading') fireRoute();
  else document.addEventListener('DOMContentLoaded', fireRoute);
})();

Object.assign(window, { WhatsAppFAB, NewsletterSignup });
