function CookieBanner() {
  const [consent, setConsent] = React.useState(null);
  const [show, setShow] = React.useState(false);

  React.useEffect(() => {
    try {
      const stored = localStorage.getItem('bx-cookie-consent');
      if (stored) {
        const parsed = JSON.parse(stored);
        setConsent(parsed);
        if (typeof window.__bxLoadAnalytics === 'function') {
          window.__bxLoadAnalytics(parsed);
        }
      } else {
        setShow(true);
      }
    } catch (e) {
      setShow(true);
    }
  }, []);

  const handleAccept = () => {
    try {
      const nextConsent = { essential: true, analytics: true };
      localStorage.setItem('bx-cookie-consent', JSON.stringify(nextConsent));
      setConsent(nextConsent);
      setShow(false);
      if (typeof window.__bxLoadAnalytics === 'function') {
        window.__bxLoadAnalytics(nextConsent);
      }
    } catch (e) {
      console.warn("Could not save cookie consent:", e);
      setShow(false);
    }
  };

  if (!show) return null;

  const content = (typeof window !== "undefined" && window.__BX_CONTENT && window.__BX_CONTENT.cookies) || {};
  const bannerTitle = content.bannerTitle;
  const bannerText = content.bannerText;
  const bannerCta = content.bannerCta;

  return (
    <div className="bx-cookie-banner">
      {bannerTitle && <div className="bx-cookie-title">{bannerTitle}</div>}
      {bannerText && (
        <p 
          className="bx-cookie-text" 
          dangerouslySetInnerHTML={{ __html: bannerText }} 
        />
      )}
      {bannerCta && (
        <div className="bx-cookie-actions">
          <button className="bx-cookie-btn primary" onClick={handleAccept}>
            {bannerCta}
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CookieBanner });
