'use client';

import { useEffect, useState, useSyncExternalStore } from 'react';
import { useTranslations } from 'next-intl';
import { Cookie } from 'lucide-react';
import { readConsent, subscribeConsent, subscribeConsentOpen, writeConsent } from '@/lib/analytics/consent';

const noopSubscribe = () => () => {};

// Bottom banner asking before analytics / ad pixels load (see
// lib/analytics/consent.ts). Rendered only when the admin has it on and at
// least one tracking tag is set. Shows until the shopper chooses; the footer's
// "Cookie settings" link opens it again. Both buttons are equally prominent,
// as GDPR guidance expects.
export default function CookieConsentBanner() {
  const t = useTranslations('CookieConsent');
  const consent = useSyncExternalStore(subscribeConsent, readConsent, () => null);
  const hydrated = useSyncExternalStore(noopSubscribe, () => true, () => false);
  const [reopened, setReopened] = useState(false);

  useEffect(() => subscribeConsentOpen(() => setReopened(true)), []);

  if (!hydrated || (consent !== null && !reopened)) return null;

  const choose = (state: 'granted' | 'denied') => {
    setReopened(false);
    writeConsent(state);
  };

  return (
    <div
      role="dialog"
      aria-live="polite"
      aria-label={t('title')}
      className="fixed inset-x-3 bottom-3 z-[60] sm:inset-x-auto sm:start-5 sm:bottom-5 sm:max-w-md"
    >
      <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-2xl shadow-black/15">
        <div className="flex items-start gap-3">
          <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
            <Cookie size={20} />
          </span>
          <div className="min-w-0">
            <p className="font-bold text-dark">{t('title')}</p>
            <p className="mt-1 text-sm leading-relaxed text-gray-custom">{t('text')}</p>
          </div>
        </div>
        <div className="mt-4 grid grid-cols-2 gap-2">
          <button
            type="button"
            onClick={() => choose('denied')}
            className="rounded-full border border-gray-300 px-4 py-2.5 text-sm font-semibold text-dark transition-colors hover:border-dark"
          >
            {t('reject')}
          </button>
          <button
            type="button"
            onClick={() => choose('granted')}
            className="rounded-full bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90"
          >
            {t('accept')}
          </button>
        </div>
      </div>
    </div>
  );
}
