/**
 * ThinkSchool Public Website — Accessible Cookie Consent Banner
 */
function CookieBanner() {
  const siteConfig = window.SITE_CONFIG || {};
  const cookieConfig = siteConfig.cookies || {};
  const storageKey = cookieConfig.storageKey || "thinkschool_cookie_consent_v1";
  const cookiesEnabled = cookieConfig.enabled !== false;

  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    if (!cookiesEnabled) {
      setVisible(false);
      return;
    }

    try {
      const consent = localStorage.getItem(storageKey);
      if (!consent) {
        setVisible(true);
      }
    } catch {
      // localStorage may fail in restrictive environments
    }
  }, [storageKey, cookiesEnabled]);

  const handleAccept = () => {
    try {
      localStorage.setItem(storageKey, JSON.stringify({ accepted: true, date: new Date().toISOString() }));
    } catch {}
    setVisible(false);
  };

  const handleDecline = () => {
    try {
      localStorage.setItem(storageKey, JSON.stringify({ accepted: false, date: new Date().toISOString() }));
    } catch {}
    setVisible(false);
  };

  if (!cookiesEnabled || !visible) return null;

  return (
    <div
      className="fixed bottom-4 left-4 right-4 sm:left-auto sm:right-6 sm:max-w-md z-50 p-5 rounded-2xl bg-zinc-950/95 border border-white/15 shadow-[0_10px_40px_rgba(0,0,0,0.9)] backdrop-blur-xl animate-fade-in text-white font-body"
      role="region"
      aria-label="Cookie consent banner"
    >
      <div className="flex items-start gap-3 mb-3">
        <div className="w-7 h-7 rounded-lg bg-amber-500/15 text-amber-400 flex items-center justify-center shrink-0 mt-0.5">
          <Icon name="shield" size={14} />
        </div>
        <div>
          <h4 className="text-xs uppercase tracking-wider font-mono font-semibold text-zinc-300">
            Privacy & Cookie Preferences
          </h4>
          <p className="text-xs text-zinc-400 mt-1 leading-relaxed">
            We use essential security cookies to ensure site functionality and session integrity. Read our{" "}
            <a href={cookieConfig.policyUrl || "/cookies/"} className="text-amber-400 hover:underline">
              Cookie Policy
            </a>.
          </p>
        </div>
      </div>

      <div className="flex items-center justify-end gap-2 pt-2 border-t border-white/5">
        <button
          type="button"
          onClick={handleDecline}
          className="px-3 py-1.5 rounded-full text-xs font-medium text-zinc-400 hover:text-white hover:bg-white/5 transition-colors"
        >
          Essential Only
        </button>
        <Button onClick={handleAccept} size="sm" variant="primary">
          Accept All
        </Button>
      </div>
    </div>
  );
}

window.CookieBanner = CookieBanner;
