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

const token = Astro.url.searchParams.get('token')?.trim() ?? '';
const api = createApiClient({ requestUrl: Astro.url });

let success = false;
let message = '缺少确认令牌。';
let manageToken = '';

if (token) {
  try {
    const response = await api.confirmSubscription(token);
    success = true;
    manageToken = response.subscription.manage_token?.trim() ?? '';
    message = '订阅已确认，现在开始你会收到后续更新。';
  } catch (error) {
    message = error instanceof Error ? error.message : '确认失败，请稍后重试。';
  }
}
---

<BaseLayout title="确认订阅" description="确认订阅邮件中的链接，激活后续通知。" noindex>
  <section class="subscription-shell">
    <div class="subscription-card">
      <p class="subscription-kicker">subscriptions / confirm</p>
      <h1>确认订阅</h1>
      <p class={`subscription-status ${success ? 'is-success' : 'is-warning'}`}>{message}</p>
      <div class="subscription-actions">
        <a href="/">返回首页</a>
        {manageToken && <a href={`/subscriptions/manage?token=${encodeURIComponent(manageToken)}`}>管理偏好</a>}
      </div>
    </div>
  </section>
</BaseLayout>

<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-status {
    margin: 1rem 0 0;
    padding: 0.95rem 1rem;
    border-radius: 0.95rem;
    line-height: 1.8;
  }

  .subscription-status.is-success {
    background: rgba(16, 185, 129, 0.14);
    color: #d1fae5;
  }

  .subscription-status.is-warning {
    background: rgba(245, 158, 11, 0.14);
    color: #fde68a;
  }

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

  .subscription-actions a {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 999px;
    border: 1px solid rgba(148, 163, 184, 0.24);
    color: var(--text-primary);
    padding: 0.8rem 1rem;
    text-decoration: none;
  }
</style>
