import { useEffect, useState } from 'react';
import { usePushStore } from '../stores/push.ts';

export function NotificationPrompt() {
  const { isSupported, permission, isSubscribed, subscribe } = usePushStore();
  const [dismissed, setDismissed] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (localStorage.getItem('push-prompt-dismissed') === 'true') {
      setDismissed(true);
    }
  }, []);

  // Don't show if not supported, already subscribed, permission resolved, or dismissed
  if (!isSupported || isSubscribed || permission === 'granted' || permission === 'denied' || dismissed) {
    return null;
  }

  const handleEnable = async () => {
    setLoading(true);
    try {
      await subscribe();
    } catch {
      // user denied or error
    } finally {
      setLoading(false);
    }
  };

  const handleDismiss = () => {
    setDismissed(true);
    localStorage.setItem('push-prompt-dismissed', 'true');
  };

  return (
    <div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 max-w-sm w-[calc(100%-2rem)] bg-gb-bg-s border border-gb-bg-t rounded-lg shadow-2xl p-4 flex items-center gap-3">
      <div className="text-2xl">&#128276;</div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-gb-fg">Enable notifications?</p>
        <p className="text-xs text-gb-fg-f">Get notified about new messages</p>
      </div>
      <div className="flex gap-2 shrink-0">
        <button
          type="button"
          onClick={handleDismiss}
          className="text-xs px-3 py-1.5 rounded-lg text-gb-fg-f hover:text-gb-fg transition-colors"
        >
          Not now
        </button>
        <button
          type="button"
          onClick={handleEnable}
          disabled={loading}
          className="text-xs px-3 py-1.5 rounded-lg bg-gb-aqua text-gb-bg font-bold hover:opacity-90 transition-opacity disabled:opacity-50"
        >
          {loading ? '...' : 'Enable'}
        </button>
      </div>
    </div>
  );
}
