<script setup lang="ts">
import { App as CapacitorApp } from "@capacitor/app";
import { Capacitor } from "@capacitor/core";
import type { NotificationSettings, UserBotAccess } from "~/types";

definePageMeta({
  middleware: "auth"
});

const { ensurePushSubscription } = usePush();
const settings = ref<NotificationSettings>({
  signalsPushEnabled: true,
  resultsPushEnabled: false
});
const subscriptions = ref<UserBotAccess[]>([]);
const message = ref("");
const appVersion = ref("");
const isAndroidApp = ref(false);

onMounted(async () => {
  try {
    const [notificationSettings, subscriptionItems] = await Promise.all([
      useApi<NotificationSettings>("/me/notification-settings"),
      useApi<UserBotAccess[]>("/me/subscriptions")
    ]);

    settings.value = notificationSettings;
    subscriptions.value = subscriptionItems;
  } catch {
    message.value = "";
  }

  if (!process.client || !Capacitor.isNativePlatform() || Capacitor.getPlatform() !== "android") {
    return;
  }

  isAndroidApp.value = true;

  try {
    const appInfo = await CapacitorApp.getInfo();
    appVersion.value = appInfo.version?.trim() ?? "";
  } catch {
    appVersion.value = "";
  }
});

const save = async () => {
  settings.value = await useApi<NotificationSettings>("/me/notification-settings", {
    method: "PATCH",
    body: settings.value
  });
  message.value = "Настройки сохранены";
};

const enablePush = async () => {
  await ensurePushSubscription();
  message.value = "Push-уведомления подключены";
};
</script>

<template>
  <section class="page">
    <div class="panel notification-settings">
      <div class="notification-settings__header">
        <p class="eyebrow">Уведомления</p>
        <h1>Настройки уведомлений</h1>
        <p class="muted">Выберите, какие уведомления должны приходить на это устройство.</p>
      </div>

      <div class="notification-settings__list">
        <label class="notification-option">
          <input v-model="settings.signalsPushEnabled" type="checkbox" />
          <span class="notification-option__body">
            <strong>Новые сигналы</strong>
            <small>Мгновенные push-уведомления при появлении новых матчей и сигналов.</small>
          </span>
        </label>

        <label class="notification-option">
          <input v-model="settings.resultsPushEnabled" type="checkbox" />
          <span class="notification-option__body">
            <strong>Результаты сигналов</strong>
            <small>Уведомления после расчёта исхода: выигрыш, проигрыш или возврат.</small>
          </span>
        </label>
      </div>

      <div class="notification-settings__actions">
        <button @click="save">Сохранить настройки</button>
        <button class="secondary" @click="enablePush">Подключить Web Push</button>
      </div>

      <p v-if="message" class="success">{{ message }}</p>
    </div>

    <div class="panel notification-settings">
      <div class="notification-settings__header">
        <p class="eyebrow">Подписки</p>
        <h2>Доступ к ботам</h2>
        <p class="muted">Здесь показаны текущие подписки и срок действия доступа.</p>
      </div>

      <div class="notification-settings__list">
        <div v-for="subscription in subscriptions" :key="subscription.id" class="notification-option">
          <span class="notification-option__body">
            <strong>{{ subscription.bot.name }}</strong>
            <small>
              Статус: {{ subscription.status }}
              <template v-if="subscription.expiresAt">
                · до {{ new Date(subscription.expiresAt).toLocaleString("ru-RU") }}
              </template>
              <template v-else>
                · без ограничения по сроку
              </template>
            </small>
            <small v-if="subscription.notes">{{ subscription.notes }}</small>
          </span>
        </div>

        <p v-if="subscriptions.length === 0" class="muted">Подписок пока нет.</p>
      </div>
    </div>
    <div v-if="isAndroidApp && appVersion" class="settings-version">
      Версия приложения для Android: {{ appVersion }}
    </div>
  </section>
</template>
