---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { resolvePublicApiBaseUrl } from '../../lib/api/client';

const token = Astro.url.searchParams.get('token')?.trim() ?? '';
const apiBaseUrl = resolvePublicApiBaseUrl(Astro.url);
---

<BaseLayout title="取消订阅" description="如果你不再需要站点通知，可以在这里安全退订。">
  <section class="subscription-shell">
    <div class="subscription-card" data-unsubscribe-root data-token={token} data-api-base={apiBaseUrl}>
      <p class="subscription-kicker">subscriptions / unsubscribe</p>
      <h1>取消订阅</h1>
      <p class="subscription-copy">如果你不再想接收通知，可以点击下面的按钮完成退订。后续也可以重新订阅并再次确认。</p>
      <div class="subscription-actions">
        <button type="button" data-unsubscribe-button disabled={!token}>确认退订</button>
        {token && <a href={`/subscriptions/manage?token=${encodeURIComponent(token)}`}>返回偏好页</a>}
        <a href="/">返回首页</a>
      </div>
      <p class="subscription-status" data-unsubscribe-status>
        {token ? '确认后会立即把当前订阅标记为已退订。' : '缺少退订令牌。'}
      </p>
    </div>
  </section>
</BaseLayout>

<script>
  document.querySelectorAll('[data-unsubscribe-root]').forEach((root) => {
    const button = root.querySelector('[data-unsubscribe-button]');
    const status = root.querySelector('[data-unsubscribe-status]');
    const token = root.getAttribute('data-token') || '';
    const apiBase = root.getAttribute('data-api-base') || '';

    if (!(button instanceof HTMLButtonElement) || !(status instanceof HTMLElement) || !token || !apiBase) {
      return;
    }

    button.disabled = false;
    button.addEventListener('click', async () => {
      button.disabled = true;
      status.textContent = '退订中...';

      try {
        const response = await fetch(`${apiBase}/subscriptions/unsubscribe`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ token }),
        });
        const payload = await response.json().catch(() => ({}));
        if (!response.ok) {
          throw new Error(payload?.description || payload?.message || '退订失败，请稍后再试。');
        }
        status.textContent = '已成功退订，后续不会再收到该订阅的通知。';
      } catch (error) {
        status.textContent = error instanceof Error ? error.message : '退订失败，请稍后再试。';
        button.disabled = false;
      }
    });
  });
</script>

<style>
  .subscription-shell {
    max-width: 48rem;
    margin: 0 auto;
    padding: 2rem 1rem 4rem;
  }

  .subscription-card {
    border: 1px solid rgba(94, 234, 212, 0.16);
    background: linear-gradient(135deg, rgba(15, 23, 42, 0.86), rgba(15, 23, 42, 0.72));
    border-radius: 1.25rem;
    padding: 1.5rem;
    color: var(--text-primary);
  }

  .subscription-kicker {
    margin: 0 0 0.5rem;
    color: var(--primary);
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.22em;
  }

  h1 {
    margin: 0;
    font-size: 1.75rem;
  }

  .subscription-copy {
    margin: 0.85rem 0 0;
    color: var(--text-secondary);
    line-height: 1.8;
  }

  .subscription-actions {
    margin-top: 1.25rem;
    display: flex;
    flex-wrap: wrap;
    gap: 0.85rem;
  }

  .subscription-actions button,
  .subscription-actions a {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 999px;
    padding: 0.85rem 1rem;
    text-decoration: none;
  }

  .subscription-actions button {
    border: 0;
    font-weight: 600;
    color: #08111f;
    background: linear-gradient(135deg, #f97316, #ef4444);
    cursor: pointer;
  }

  .subscription-actions a {
    border: 1px solid rgba(148, 163, 184, 0.24);
    color: var(--text-primary);
  }

  .subscription-status {
    margin: 1rem 0 0;
    color: var(--text-secondary);
    line-height: 1.8;
  }
</style>
