---
import BaseLayout from '../../layouts/BaseLayout.astro';
import DiscoveryBrief from '../../components/seo/DiscoveryBrief.astro';
import PageViewTracker from '../../components/seo/PageViewTracker.astro';
import SharePanel from '../../components/seo/SharePanel.astro';
import TerminalWindow from '../../components/ui/TerminalWindow.astro';
import CommandPrompt from '../../components/ui/CommandPrompt.astro';
import FriendLinkCard from '../../components/FriendLinkCard.astro';
import FriendLinkApplication from '../../components/FriendLinkApplication.astro';
import { api, DEFAULT_SITE_SETTINGS } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import { buildDiscoveryHighlights, buildFaqJsonLd, buildPageFaqs } from '../../lib/seo';
import type { AppFriendLink } from '../../lib/api/client';

export const prerender = false;

let siteSettings = DEFAULT_SITE_SETTINGS;
let friendLinks: AppFriendLink[] = [];
let error: string | null = null;
const { locale, t } = getI18n(Astro);
const isEnglish = locale.startsWith('en');

try {
  [siteSettings, friendLinks] = await Promise.all([
    api.getSiteSettings(),
    api.getFriendLinks(),
  ]);
  friendLinks = friendLinks.filter(friend => friend.status === 'approved');
} catch (e) {
  error = e instanceof Error ? e.message : t('common.apiUnavailable');
  console.error('Failed to fetch friend links:', e);
}

const categories = [...new Set(friendLinks.map(friend => friend.category || t('common.other')))];
const groupedLinks = categories.map(category => ({
  category,
  links: friendLinks.filter(friend => (friend.category || t('common.other')) === category)
}));
const siteBaseUrl = (siteSettings.siteUrl || new URL(Astro.request.url).origin).replace(/\/$/, '');
const friendsCanonicalUrl = new URL('/friends', siteBaseUrl).toString();
const friendsJsonLd = [
  {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: t('friends.title'),
    description: t('friends.pageDescription', { siteName: siteSettings.siteName }),
    url: friendsCanonicalUrl,
    inLanguage: locale,
  },
  {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${t('friends.title')} list`,
    itemListElement: friendLinks.map((friend, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      url: friend.url,
      name: friend.name,
      description: friend.description || friend.category || t('common.other'),
    })),
  },
  {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      {
        '@type': 'ListItem',
        position: 1,
        name: siteSettings.siteName,
        item: siteBaseUrl,
      },
      {
        '@type': 'ListItem',
        position: 2,
        name: t('friends.title'),
        item: friendsCanonicalUrl,
      },
    ],
  },
];
const sharePanelCopy = isEnglish
  ? {
      badge: 'network map',
      title: 'Share the friends directory',
      description:
        'Use the friend links page as a canonical network map so AI search and readers can understand the site’s trusted neighbors and outbound references.',
      links: 'Links',
      groups: 'Groups',
    }
    : {
      badge: '友情链接',
      title: '分享友情链接页',
      description: '把友情链接页分享出去，方便查看常访问的网站与推荐来源。',
      links: '友链数',
      groups: '分组数',
    };
const friendsHighlights = buildDiscoveryHighlights([
  t('friends.intro'),
  `${t('common.friendsCount', { count: friendLinks.length })}`,
  `${t('common.reviewedOnly')}`,
  ...categories.slice(0, 3).map((item) => `${item} (${groupedLinks.find((group) => group.category === item)?.links.length || 0})`),
]);
const friendsFaqs = buildPageFaqs({
  locale,
  pageTitle: t('friends.pageTitle'),
  summary: t('friends.pageDescription', { siteName: siteSettings.siteName }),
  primaryLabel: t('friends.title'),
  primaryUrl: friendsCanonicalUrl,
  relatedLinks: [
    { label: t('nav.about'), url: `${siteBaseUrl}/about` },
    { label: t('nav.articles'), url: `${siteBaseUrl}/articles` },
    { label: t('nav.categories'), url: `${siteBaseUrl}/categories` },
  ],
  signals: friendsHighlights,
});
const friendsFaqJsonLd = buildFaqJsonLd(friendsFaqs);
---

<BaseLayout
  title={`${t('friends.pageTitle')} - ${siteSettings.siteShortName}`}
  description={t('friends.pageDescription', { siteName: siteSettings.siteName })}
  siteSettings={siteSettings}
  jsonLd={[...friendsJsonLd, friendsFaqJsonLd].filter(Boolean)}
>
  <PageViewTracker pageType="friends" entityId="friends-index" />
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/friends" class="w-full">
      <div class="mb-6 px-4">
        <CommandPrompt command={t('friends.promptBrowse')} />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">network map</div>
          <div class="terminal-section-title mt-4">
            <span class="terminal-section-icon">
              <i class="fas fa-link"></i>
            </span>
            <div>
              <h1 class="text-2xl font-bold text-[var(--title-color)]">{t('friends.title')}</h1>
              <p class="mt-2 max-w-2xl text-sm leading-6 text-[var(--text-secondary)]">
                {t('friends.intro')}
              </p>
            </div>
          </div>
          <div class="mt-5 flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-globe text-[var(--primary)]"></i>
              <span>{t('common.friendsCount', { count: friendLinks.length })}</span>
            </span>
            <span class="terminal-stat-pill">
              <i class="fas fa-check-circle text-[var(--primary)]"></i>
              <span>{t('common.reviewedOnly')}</span>
            </span>
          </div>
        </div>

        <div class="ml-4 mt-4">
          <SharePanel
            shareTitle={`${t('friends.pageTitle')} - ${siteSettings.siteShortName || siteSettings.siteName}`}
            summary={t('friends.pageDescription', { siteName: siteSettings.siteName })}
            canonicalUrl={friendsCanonicalUrl}
            badge={sharePanelCopy.badge}
            kicker="geo / network"
            title={sharePanelCopy.title}
            description={sharePanelCopy.description}
            stats={[
              { label: sharePanelCopy.links, value: String(friendLinks.length) },
              { label: sharePanelCopy.groups, value: String(categories.length) },
            ]}
            wechatShareQrEnabled={siteSettings.seo.wechatShareQrEnabled}
          />
        </div>

        <div class="ml-4 mt-4">
          <DiscoveryBrief
            badge={isEnglish ? 'link brief' : '友链摘要'}
            kicker="geo / network"
            title={isEnglish ? 'AI-readable link-network brief' : '给 AI 看的友链网络摘要'}
            summary={t('friends.pageDescription', { siteName: siteSettings.siteName })}
            highlights={friendsHighlights}
            faqs={friendsFaqs}
          />
        </div>
      </div>

      {error && (
        <div class="px-4 mb-6">
          <div class="ml-4 p-4 rounded-lg border border-[var(--danger)]/20 bg-[var(--danger)]/10 text-[var(--danger)] text-sm">
            {error}
          </div>
        </div>
      )}

      <div class="px-4 space-y-8">
        {groupedLinks.map(group => (
          <div class="terminal-panel-muted">
            <div class="mb-4 flex items-center justify-between gap-3">
              <div class="flex items-center gap-3">
                <span class="flex h-10 w-10 items-center justify-center rounded-2xl bg-[var(--primary)]/10 text-[var(--primary)]">
                  <i class="fas fa-folder-open"></i>
                </span>
                <div>
                  <h2 class="text-lg font-bold text-[var(--title-color)]">{group.category}</h2>
                  <p class="text-xs uppercase tracking-[0.2em] text-[var(--text-tertiary)]">{t('friends.collection')}</p>
                </div>
              </div>
              <span class="terminal-chip text-xs py-1 px-2.5">({group.links.length})</span>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {group.links.map(friend => (
                <FriendLinkCard friend={friend} />
              ))}
            </div>
          </div>
        ))}
      </div>

      <div class="px-4 mt-8 pt-8 border-t border-[var(--border-color)]">
        <CommandPrompt command={t('friends.promptApply')} />
        <div class="ml-4 mt-4">
          <FriendLinkApplication siteSettings={siteSettings} />
        </div>
      </div>

      <div class="px-4 mt-8 pt-8 border-t border-[var(--border-color)]">
        <CommandPrompt command={t('friends.promptRules')} />
        <div class="terminal-panel ml-4 mt-4">
          <div class="terminal-kicker">exchange rules</div>
          <h3 class="mt-4 font-bold text-[var(--title-color)] text-lg">{t('friends.exchangeRules')}</h3>
          <p class="mt-3 text-sm text-[var(--text-secondary)] mb-4 leading-6">
            {t('friends.exchangeIntro')}
          </p>
          <ul class="text-sm text-[var(--text-secondary)] space-y-1 list-disc list-inside">
            <li>{t('friends.rule1')}</li>
            <li>{t('friends.rule2')}</li>
            <li>{t('friends.rule3')}</li>
          </ul>
          <div class="mt-5 pt-4 border-t border-[var(--border-color)]">
            <p class="text-sm text-[var(--text-tertiary)] font-mono">
              {t('friends.siteInfo')}<br/>
              {t('friends.name')}: {siteSettings.siteName}<br/>
              {t('friends.description')}: {siteSettings.siteDescription}<br/>
              {t('friends.link')}: {siteSettings.siteUrl}
            </p>
          </div>
        </div>
      </div>
    </TerminalWindow>
  </div>
</BaseLayout>
