---
import { DEFAULT_SITE_SETTINGS, resolvePublicApiBaseUrl } from '../lib/api/client';
import { getI18n } from '../lib/i18n';
import type { SiteSettings } from '../lib/types';

interface Props {
  class?: string;
  siteSettings?: SiteSettings;
}

const { class: className = '', siteSettings = DEFAULT_SITE_SETTINGS } = Astro.props;
const { t } = getI18n(Astro);
const publicApiBaseUrl = resolvePublicApiBaseUrl(Astro.url);
---

<div
  class={`terminal-friend-link-form ${className}`}
  data-api-base={publicApiBaseUrl}
  data-site-name={siteSettings.siteName}
  data-site-url={siteSettings.siteUrl}
  data-site-description={siteSettings.siteDescription}
>
  <form id="friend-link-form" class="terminal-panel space-y-5">
    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
      <div>
        <div class="terminal-kicker">friend-link request</div>
        <h3 class="mt-3 text-xl font-bold text-[var(--title-color)]">{t('friendForm.title')}</h3>
        <p class="mt-2 text-sm leading-6 text-[var(--text-secondary)]">
          {t('friendForm.intro')}
        </p>
      </div>
      <div class="terminal-stat-pill self-start sm:self-auto">
        <i class="fas fa-shield-alt text-[var(--primary)]"></i>
        <span>{t('friendForm.reviewedOnline')}</span>
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <label class="block text-sm text-[var(--text-secondary)] mb-1.5">
          <i class="fas fa-user mr-1"></i>{t('friendForm.siteName')} <span class="text-[var(--primary)]">*</span>
        </label>
        <input
          type="text"
          name="siteName"
          required
          placeholder="your-site-name"
          class="terminal-form-input"
        />
      </div>
      <div>
        <label class="block text-sm text-[var(--text-secondary)] mb-1.5">
          <i class="fas fa-link mr-1"></i>{t('friendForm.siteUrl')} <span class="text-[var(--primary)]">*</span>
        </label>
        <input
          type="url"
          name="siteUrl"
          required
          placeholder="https://example.com"
          class="terminal-form-input"
        />
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <label class="block text-sm text-[var(--text-secondary)] mb-1.5">
          <i class="fas fa-image mr-1"></i>{t('friendForm.avatarUrl')} <span class="text-[var(--text-tertiary)] text-xs">({t('common.optional')})</span>
        </label>
        <input
          type="url"
          name="avatarUrl"
          placeholder="https://example.com/avatar.png"
          class="terminal-form-input"
        />
      </div>
      <div>
        <label class="block text-sm text-[var(--text-secondary)] mb-2">
          <i class="fas fa-folder mr-1"></i>{t('friendForm.category')} <span class="text-[var(--text-tertiary)] text-xs">({t('common.optional')})</span>
        </label>
        <div class="flex flex-wrap gap-3">
          {[
            { value: 'tech', label: t('friendForm.categoryTech') },
            { value: 'life', label: t('friendForm.categoryLife') },
            { value: 'design', label: t('friendForm.categoryDesign') },
            { value: 'other', label: t('friendForm.categoryOther') },
          ].map(category => (
            <label class="ui-filter-pill ui-filter-pill--amber cursor-pointer">
              <input type="radio" name="category" value={category.value} class="sr-only" />
              <i class="fas fa-angle-right text-[10px] opacity-70"></i>
              <span class="text-sm">[{category.label}]</span>
            </label>
          ))}
        </div>
      </div>
    </div>

    <div>
      <label class="block text-sm text-[var(--text-secondary)] mb-1.5">
        <i class="fas fa-align-left mr-1"></i>{t('friendForm.description')} <span class="text-[var(--primary)]">*</span>
      </label>
      <textarea
        name="description"
        required
        rows="3"
        maxlength="200"
        placeholder={t('friendForm.descriptionPlaceholder')}
        class="terminal-form-textarea resize-none"
      ></textarea>
      <p class="text-xs text-[var(--text-tertiary)] mt-1 text-right">{t('common.maxChars', { count: 200 })}</p>
    </div>

    <div class="terminal-panel-muted flex items-start gap-3">
      <input
        type="checkbox"
        name="hasReciprocal"
        id="has-reciprocal"
        class="mt-1 h-4 w-4 rounded border-[var(--border-color)] bg-[var(--header-bg)] text-[var(--primary)] focus:ring-[var(--primary)]"
      />
      <label for="has-reciprocal" class="text-sm leading-6 text-[var(--text-secondary)]">
        {t('friendForm.reciprocal')} <span class="text-[var(--primary)]">*</span>
        <span class="block text-xs text-[var(--text-tertiary)]">{t('friendForm.reciprocalHint')}</span>
      </label>
    </div>

    <div id="reciprocal-info" class="terminal-panel-muted hidden">
      <p class="text-sm text-[var(--text-secondary)] mb-2">
        <i class="fas fa-info-circle mr-1"></i>{t('friends.siteInfo')}
      </p>
      <div class="space-y-1 text-sm">
        <p class="flex items-center gap-2">
          <span class="text-[var(--text-tertiary)]">{t('friends.name')}:</span>
          <span class="text-[var(--text)] font-medium">{siteSettings.siteName}</span>
          <button type="button" class="copy-btn terminal-copy-button" data-text={siteSettings.siteName}>
            <i class="fas fa-copy"></i>{t('friendForm.copy')}
          </button>
        </p>
        <p class="flex items-center gap-2">
          <span class="text-[var(--text-tertiary)]">{t('friends.link')}:</span>
          <span class="text-[var(--text)]">{siteSettings.siteUrl}</span>
          <button type="button" class="copy-btn terminal-copy-button" data-text={siteSettings.siteUrl}>
            <i class="fas fa-copy"></i>{t('friendForm.copy')}
          </button>
        </p>
        <p class="flex items-center gap-2">
          <span class="text-[var(--text-tertiary)]">{t('friends.description')}:</span>
          <span class="text-[var(--text)]">{siteSettings.siteDescription}</span>
          <button type="button" class="copy-btn terminal-copy-button" data-text={siteSettings.siteDescription}>
            <i class="fas fa-copy"></i>{t('friendForm.copy')}
          </button>
        </p>
      </div>
    </div>

    <div class="flex flex-wrap gap-3">
      <button
        type="submit"
        class="terminal-action-button terminal-action-button-primary"
      >
        <i class="fas fa-paper-plane"></i>{t('friendForm.submit')}
      </button>
      <button
        type="reset"
        class="terminal-action-button"
      >
        <i class="fas fa-undo"></i>{t('friendForm.reset')}
      </button>
    </div>

    <div id="form-message" class="hidden p-3 rounded-lg text-sm"></div>
  </form>
</div>

<script>
  const t = window.__termiTranslate;
  const wrapper = document.querySelector('.terminal-friend-link-form');
  const form = document.getElementById('friend-link-form') as HTMLFormElement | null;
  const reciprocalCheckbox = document.getElementById('has-reciprocal') as HTMLInputElement | null;
  const reciprocalInfo = document.getElementById('reciprocal-info') as HTMLDivElement | null;
  const messageDiv = document.getElementById('form-message') as HTMLDivElement | null;
  const copyBtns = document.querySelectorAll('.copy-btn');
  const apiBase = wrapper?.getAttribute('data-api-base') || '/api';

  reciprocalCheckbox?.addEventListener('change', () => {
    reciprocalInfo?.classList.toggle('hidden', !reciprocalCheckbox.checked);
  });

  copyBtns.forEach(btn => {
    btn.addEventListener('click', async () => {
      const text = btn.getAttribute('data-text') || '';
      await navigator.clipboard.writeText(text);
      const originalHTML = btn.innerHTML;
      btn.innerHTML = `<i class="fas fa-check"></i>${t('friendForm.copied')}`;
      setTimeout(() => {
        btn.innerHTML = originalHTML;
      }, 1800);
    });
  });

  function showMessage(message: string, type: 'success' | 'error' | 'info') {
    if (!messageDiv) return;
    messageDiv.classList.remove('hidden', 'bg-green-500/10', 'text-green-500', 'bg-red-500/10', 'text-red-500', 'bg-blue-500/10', 'text-blue-500');

    if (type === 'success') {
      messageDiv.classList.add('bg-green-500/10', 'text-green-500');
    } else if (type === 'error') {
      messageDiv.classList.add('bg-red-500/10', 'text-red-500');
    } else {
      messageDiv.classList.add('bg-blue-500/10', 'text-blue-500');
    }

    messageDiv.textContent = message;
    messageDiv.classList.remove('hidden');
  }

  form?.addEventListener('submit', async (e) => {
    e.preventDefault();

    const formData = new FormData(form);
    const hasReciprocal = formData.get('hasReciprocal') === 'on';

    if (!hasReciprocal) {
      showMessage(t('friendForm.addReciprocalFirst'), 'error');
      return;
    }

    try {
      showMessage(t('friendForm.submitting'), 'info');

      const response = await fetch(`${apiBase}/friend_links`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          siteName: formData.get('siteName'),
          siteUrl: formData.get('siteUrl'),
          avatarUrl: formData.get('avatarUrl'),
          category: formData.get('category'),
          description: formData.get('description'),
        }),
      });

      if (!response.ok) {
        throw new Error(await response.text());
      }

      form.reset();
      reciprocalInfo?.classList.add('hidden');
      showMessage(t('friendForm.submitSuccess'), 'success');
    } catch (error) {
      showMessage(t('friendForm.submitFailed', { message: error instanceof Error ? error.message : t('common.unknownError') }), 'error');
    }
  });
</script>

<style>
  .terminal-friend-link-form input:focus,
  .terminal-friend-link-form textarea:focus,
  .terminal-friend-link-form select:focus {
    box-shadow: 0 0 0 2px var(--primary-alpha, rgba(99, 102, 241, 0.2));
  }

  input[type="checkbox"] {
    accent-color: var(--primary);
  }
</style>
