// ConsentBanner.jsx — analytics consent gate. Nothing is tracked until the
// visitor accepts here, so the banner is the only thing that can start
// PostHog on a first visit.
//
// It renders only when analytics is actually configured and no choice is
// stored yet. With no PostHog key set, the site shows no banner at all
// rather than asking permission for something that never happens.
const ConsentBanner = () => {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    if (typeof window.skardiAnalyticsConfigured !== 'function') return;
    if (!window.skardiAnalyticsConfigured()) return;
    const sync = () => setVisible(!window.skardiConsent());  // no stored choice yet
    sync();
    // "Cookie settings" elsewhere on the page clears the choice; re-ask here.
    window.addEventListener('skardi:consent-changed', sync);
    return () => window.removeEventListener('skardi:consent-changed', sync);
  }, []);

  if (!visible) return null;

  const choose = (value) => () => {
    window.skardiSetConsent(value);
    setVisible(false);
  };

  const button = {
    padding: '9px 18px', borderRadius: '2rem', cursor: 'pointer',
    fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
    whiteSpace: 'nowrap',
  };

  return (
    <div role="dialog" aria-label="Analytics consent" style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 60,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 20, flexWrap: 'wrap',
      padding: '16px 24px',
      background: 'rgba(6, 11, 20, 0.96)',
      backdropFilter: 'blur(12px)',
      WebkitBackdropFilter: 'blur(12px)',
      borderTop: '1px solid rgba(125,211,252,0.12)',
    }}>
      <p style={{
        fontFamily: 'Inter, sans-serif', fontSize: 14, lineHeight: 1.55,
        color: '#8ea3c0', margin: 0, maxWidth: 620,
      }}>
        We use cookies to understand which parts of the site are useful. Nothing is
        stored on your device unless you accept, and we never record your screen.
        You can change your mind at any time. See our{' '}
        <a href="/privacy" style={{ color: '#2ee89a', textDecoration: 'underline' }}>
          privacy policy</a>.
      </p>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button type="button" onClick={choose('denied')} style={{
          ...button,
          background: 'transparent',
          border: '1px solid rgba(125,211,252,0.2)',
          color: '#c4d2e2',
        }}>Decline</button>
        <button type="button" onClick={choose('granted')} style={{
          ...button,
          background: 'linear-gradient(90deg,#2ec47a,#1a8fe0)',
          border: '1px solid transparent',
          color: '#fff',
        }}>Accept</button>
      </div>
    </div>
  );
};

window.ConsentBanner = ConsentBanner;
