import React from 'react';

const VITE_VAPID_PUBLIC = 'BD7GhguZw4c_omQrJ9NHVoF9nrVbTijg7-Kb33F8oZKZ4HPh5eVVXZQObsG1-yjJ2pkD24TIM8D9p3Jz7ZjFHj8';

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

const App: React.FC = () => {

const subscribe = async () => {
  const reg = await navigator.serviceWorker.ready;

  // 旧サブスクリプションを解除
  const old = await reg.pushManager.getSubscription();
  if (old) {
    await old.unsubscribe();
    console.log("旧サブスクリプション解除済み");
  }

  try {
    const sub = await reg.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(VITE_VAPID_PUBLIC),
    });

    console.log("📩 新しい購読:", sub);

    await fetch("https://10.0.0.20:4000/api/subscribe", {
      method: "POST",
      body: JSON.stringify(sub),
      headers: { "Content-Type": "application/json" },
    });
  } catch (err) {
    console.error("購読エラー:", err);
  }
};


  // サービスワーカー登録（初回ロード時）
  React.useEffect(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js')
        .then(() => console.log('Service Worker 登録済'))
        .catch(err => console.error('SW 登録失敗:', err));
    }
  }, []);

  return (
    <div style={{ padding: '2rem' }}>
      <h1>Web Push テスト PWA</h1>
      <button onClick={subscribe}>Push購読する</button>
    </div>
  );
};

export default App;
