'use client';

// ═══════════════════════════════════════════════════════════════
//  useClientPushNotifications — CLIENT PORTAL version of your
//  existing usePushNotifications.ts.
//
//  Identical flow (service worker → permission → VAPID subscribe →
//  send subscription to backend), with TWO differences:
//    · token comes from "clientPortalToken" (not "access_token")
//    · subscription is posted to a client-portal subscribe endpoint
//
//  This gives the client OS-level browser notifications that appear
//  even when they're logged out or on another tab/site — the same
//  way your staff push works.
//
//  ── Requires (see notes under the file) ──
//   · /sw.js present in the CLIENT portal's public/ folder
//   · NEXT_PUBLIC_VAPID_PUBLIC_KEY set in the client portal env
//     (same VAPID key pair the backend signs with)
//   · a backend route that saves the client's subscription against
//     their user id — see the backend snippet I provide separately
//
//  Mount once, high in the client dashboard tree (layout.tsx):
//     "use client";
//     import { useClientPushNotifications } from "@/lib/hooks/useClientPushNotifications";
//     export default function DashboardLayout({ children }) {
//       useClientPushNotifications();
//       return <>{children}</>;
//     }
// ═══════════════════════════════════════════════════════════════

import { useEffect } from 'react';

const API = process.env.NEXT_PUBLIC_API_URL?.replace('/api', '') ?? 'http://localhost:3008';
const VAPID_PUBLIC_KEY = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? '';

// Where to register the client's push subscription. Override with
// NEXT_PUBLIC_CLIENT_PUSH_SUBSCRIBE_PATH if your route differs.
const SUBSCRIBE_PATH =
  process.env.NEXT_PUBLIC_CLIENT_PUSH_SUBSCRIBE_PATH ?? '/api/client-portal/push/subscribe';

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

export function useClientPushNotifications() {
  useEffect(() => {
    const setup = async () => {
      try {
        if (typeof window === 'undefined') return;
        if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
          console.warn('[client-push] not supported in this browser');
          return;
        }
        const token = localStorage.getItem('clientPortalToken');
        if (!token) return; // subscribe only while logged in; the sub survives logout

        // 1. Register service worker (must exist at the portal's /sw.js)
        const reg = await navigator.serviceWorker.register('/sw.js');
        await navigator.serviceWorker.ready;

        // 2. Ask permission
        let perm = Notification.permission;
        if (perm === 'default') perm = await Notification.requestPermission();
        if (perm !== 'granted') { console.warn('[client-push] permission denied'); return; }

        // 3. Subscribe (or reuse existing)
        let sub = await reg.pushManager.getSubscription();
        if (!sub) {
          if (!VAPID_PUBLIC_KEY) { console.error('[client-push] missing NEXT_PUBLIC_VAPID_PUBLIC_KEY'); return; }
          sub = await reg.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
          });
        }

        // 4. Send to backend (tied to the client user via the JWT)
        await fetch(`${API}${SUBSCRIBE_PATH}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify(sub),
        });

        console.log('[client-push] subscribed ✓');
      } catch (err) {
        console.error('[client-push] setup failed', err);
      }
    };
    setup();
  }, []);
}

export default useClientPushNotifications;