import { useState, useEffect } from 'react';

export default function PushOptIn() {
  const [show, setShow] = useState(false);
  const [status, setStatus] = useState<'idle' | 'subscribing' | 'done'>('idle');

  useEffect(() => {
    // Don't show if: no support, already subscribed, already dismissed, or first visit
    if (!('PushManager' in window) || !('serviceWorker' in navigator)) return;
    if (localStorage.getItem('sp_push_dismissed') || localStorage.getItem('sp_push_subscribed')) return;

    // Show after 2nd page view
    const views = parseInt(localStorage.getItem('sp_page_views') || '0') + 1;
    localStorage.setItem('sp_page_views', String(views));
    if (views >= 3) {
      setTimeout(() => setShow(true), 5000);
    }
  }, []);

  const subscribe = async () => {
    setStatus('subscribing');
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(
          // VAPID public key — generate with: npx web-push generate-vapid-keys
          import.meta.env.PUBLIC_VAPID_KEY || 'BJ_placeholder_replace_with_real_vapid_key'
        ),
      });

      await fetch('/api/push/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(sub.toJSON()),
      });

      localStorage.setItem('sp_push_subscribed', '1');
      setStatus('done');
      if ((window as any).__showToast) (window as any).__showToast('Push notificaties ingeschakeld!', 'success');
      setTimeout(() => setShow(false), 2000);
    } catch {
      setStatus('idle');
    }
  };

  const dismiss = () => {
    setShow(false);
    localStorage.setItem('sp_push_dismissed', '1');
  };

  if (!show) return null;

  return (
    <div className="fixed bottom-[calc(1rem+env(safe-area-inset-bottom))] left-4 right-4 z-50 sm:left-auto sm:right-6 sm:max-w-sm animate-slide-up">
      <div className="rounded-2xl border border-[var(--border)] bg-[var(--bg-card)] p-4 shadow-2xl">
        <div className="flex items-start gap-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[var(--accent)]/10 text-[var(--accent)]">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" /><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" /></svg>
          </div>
          <div className="flex-1">
            <p className="font-bold text-sm text-[var(--text)]">Prijsdaling meldingen</p>
            <p className="text-xs text-[var(--text-secondary)] mt-0.5">
              Ontvang direct een melding wanneer sneakers op je watchlist in prijs dalen.
            </p>
            <div className="mt-3 flex gap-2">
              <button
                onClick={subscribe}
                disabled={status === 'subscribing'}
                className="rounded-lg bg-[var(--accent)] px-4 py-1.5 text-xs font-bold text-[var(--bg)] transition-all hover:opacity-90 disabled:opacity-50"
              >
                {status === 'subscribing' ? 'Even geduld...' : status === 'done' ? 'Ingeschakeld!' : 'Inschakelen'}
              </button>
              <button
                onClick={dismiss}
                className="rounded-lg px-3 py-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text)]"
              >
                Later
              </button>
            </div>
          </div>
          <button onClick={dismiss} className="text-[var(--text-muted)] hover:text-[var(--text)]">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function urlBase64ToUint8Array(base64String: string) {
  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = atob(base64);
  const outputArray = new Uint8Array(rawData.length);
  for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i);
  return outputArray;
}
