// Cookie/storage consent banner.
//
// First-visit flow: compact banner with a prominent "Accept" CTA.
// Users who want to fine-tune (analytics, errors, ads) go to
// Dashboard → Settings or click "Manage preferences" in the banner.
// Footer "Cookie preferences" link re-opens the detailed view.

(function () {
  function MMConsentBanner() {
    const [show, setShow]         = React.useState(false);
    const [detail, setDetail]     = React.useState(false);  // detailed toggle view
    const [analytics, setAnalytics]       = React.useState(false);
    const [errors, setErrors]             = React.useState(false);
    const [advertising, setAdvertising]   = React.useState(false);

    React.useEffect(() => {
      // First-visit: show the compact banner.
      if (window.MMConsent && !window.MMConsent.isSet()) setShow(true);

      // Footer link / programmatic re-open → always show detailed view.
      const onOpen = () => {
        const cur = window.MMConsent?.get();
        if (cur) {
          setAnalytics(cur.analytics === true);
          setErrors(cur.errors === true);
          setAdvertising(cur.advertising === true);
        }
        setDetail(true);
        setShow(true);
      };
      window.addEventListener('mm-consent-open', onOpen);
      return () => window.removeEventListener('mm-consent-open', onOpen);
    }, []);

    if (!show) return null;

    const accept = () => {
      window.MMConsent.acceptAll();
      setShow(false); setDetail(false);
    };
    const reject = () => {
      window.MMConsent.rejectNonEssential();
      setShow(false); setDetail(false);
    };
    const saveCustom = () => {
      window.MMConsent.set({ analytics, errors, advertising });
      setShow(false); setDetail(false);
    };

    // ---------- Detailed view (re-opened from footer or "Manage") ----------
    if (detail) {
      return (
        <div className="cc-overlay" role="dialog" aria-label="Cookie preferences" aria-modal="false">
          <div className="cc-banner">
            <div className="cc-head">
              <div className="cc-icon" aria-hidden="true">
                <window.Icon name="lock" size={18} strokeWidth={2} />
              </div>
              <div>
                <div className="cc-title">Privacy preferences</div>
                <div className="cc-sub">
                  Choose which optional features you'd like to enable.
                  You can change these any time in your Dashboard settings.
                </div>
              </div>
              <button className="cc-close" onClick={() => { setShow(false); setDetail(false); }} aria-label="Close">
                <window.Icon name="x" size={16} />
              </button>
            </div>

            <div className="cc-toggles">
              <label className="cc-toggle cc-toggle-locked">
                <input type="checkbox" checked disabled />
                <span className="cc-toggle-text">
                  <strong>Essential</strong>
                  <small>Theme, favourites, sign-in tokens. Always on.</small>
                </span>
              </label>
              <label className={`cc-toggle ${analytics ? 'cc-on' : ''}`}>
                <input type="checkbox" checked={analytics}
                       onChange={(e) => setAnalytics(e.target.checked)} />
                <span className="cc-toggle-text">
                  <strong>Analytics</strong>
                  <small>Anonymous tool usage events.</small>
                </span>
              </label>
              <label className={`cc-toggle ${errors ? 'cc-on' : ''}`}>
                <input type="checkbox" checked={errors}
                       onChange={(e) => setErrors(e.target.checked)} />
                <span className="cc-toggle-text">
                  <strong>Error reports</strong>
                  <small>Stack traces to fix bugs faster.</small>
                </span>
              </label>
              <label className={`cc-toggle ${advertising ? 'cc-on' : ''}`}>
                <input type="checkbox" checked={advertising}
                       onChange={(e) => setAdvertising(e.target.checked)} />
                <span className="cc-toggle-text">
                  <strong>Advertising</strong>
                  <small>Google AdSense ads. Funds free tools.</small>
                </span>
              </label>
            </div>

            <div className="cc-actions">
              <a className="cc-link" href="#/privacy"
                 onClick={() => { setShow(false); setDetail(false); }}>Privacy Policy</a>
              <span className="cc-spacer" />
              <button className="cc-btn cc-btn-ghost" onClick={reject}>Reject all</button>
              <button className="cc-btn cc-btn-primary" onClick={saveCustom}>Save preferences</button>
            </div>
          </div>
        </div>
      );
    }

    // ---------- First-visit compact banner ----------
    return (
      <div className="cc-overlay" role="dialog" aria-label="Cookie consent" aria-modal="false">
        <div className="cc-banner">
          <div className="cc-head">
            <div className="cc-icon" aria-hidden="true">
              <window.Icon name="lock" size={18} strokeWidth={2} />
            </div>
            <div>
              <div className="cc-title">We value your privacy</div>
              <div className="cc-sub">
                We use cookies for analytics and ads to improve MiniMagics and keep it free.
                Your files never leave your browser.
              </div>
            </div>
          </div>
          <div className="cc-actions">
            <button className="cc-btn cc-btn-link" onClick={() => setDetail(true)}>Manage preferences</button>
            <span className="cc-spacer" />
            <button className="cc-btn cc-btn-primary" onClick={accept}>Accept</button>
          </div>
        </div>
      </div>
    );
  }

  window.MMConsentBanner = MMConsentBanner;
})();
