---
import QRCode from 'qrcode';
import { getI18n } from '../../lib/i18n';

type ShareStat = {
  label: string;
  value: string;
};

interface Props {
  shareTitle: string;
  summary: string;
  canonicalUrl: string;
  badge?: string;
  kicker?: string;
  title?: string;
  description?: string;
  stats?: ShareStat[];
  wechatShareQrEnabled?: boolean;
}

const { locale, t } = getI18n(Astro);
const isEnglish = locale.startsWith('en');

const {
  shareTitle,
  summary,
  canonicalUrl,
  badge = isEnglish ? 'page share' : '页面分享',
  title = isEnglish ? 'Quick share' : '一键分享',
  description = isEnglish
    ? 'Keep canonical links flowing through social channels so both people and AI search engines can converge on the same source.'
    : '复制链接、摘要或二维码，方便换设备继续看，也方便直接发给别人。',
  stats = [],
  wechatShareQrEnabled = false,
} = Astro.props as Props;

const visibleBadge = badge;
const visibleTitle = title;
const visibleDescription = description;

const copy = isEnglish
  ? {
      summaryTitle: 'Page summary',
      canonical: 'Page link',
      copySummary: 'Copy note',
      copySummarySuccess: 'Share note copied',
      copySummaryFailed: 'Copy failed',
      copyLink: 'Copy permalink',
      copyLinkSuccess: 'Permalink copied',
      copyLinkFailed: 'Permalink copy failed',
      shareSummary: 'Share summary',
      shareSuccess: 'Share panel opened',
      shareFallback: 'Share text copied',
      shareFailed: 'Share failed',
      shareToX: 'Share to X',
      shareToTelegram: 'Share to Telegram',
      shareToWeChat: 'WeChat QR',
      qrModalTitle: 'WeChat scan share',
      qrModalDescription: 'Scan this QR code in WeChat to open the current page on mobile.',
      qrModalHint: 'Sharing the page link is enough for others to continue from here.',
      downloadQr: 'Download QR',
      downloadQrStarted: 'QR download started',
      qrOpened: 'WeChat QR ready',
      toastSuccessTitle: 'Done',
      toastErrorTitle: 'Action failed',
      toastInfoTitle: 'Share ready',
    }
  : {
      summaryTitle: '页面简介',
      canonical: '固定链接',
      copySummary: '复制简介',
      copySummarySuccess: '页面简介已复制',
      copySummaryFailed: '复制失败',
      copyLink: '复制固定链接',
      copyLinkSuccess: '固定链接已复制',
      copyLinkFailed: '固定链接复制失败',
      shareSummary: '直接分享',
      shareSuccess: '已打开系统分享',
      shareFallback: '分享内容已复制',
      shareFailed: '分享失败',
      shareToX: '分享到 X',
      shareToTelegram: '分享到 Telegram',
      shareToWeChat: '微信扫一扫',
      qrModalTitle: '微信扫一扫',
      qrModalDescription: '用微信扫一扫，就能在手机上继续浏览当前页面。',
      qrModalHint: '如果要发给别人，直接复制下方链接会更方便。',
      downloadQr: '下载二维码',
      downloadQrStarted: '二维码开始下载',
      qrOpened: '微信二维码已打开',
      toastSuccessTitle: '操作完成',
      toastErrorTitle: '操作失败',
      toastInfoTitle: '已准备好',
    };

const safeSummary = summary.trim() || shareTitle;
const panelIdSeed = `${shareTitle}-${canonicalUrl}`
  .trim()
  .toLowerCase()
  .replace(/[^a-z0-9]+/g, '-')
  .replace(/^-+|-+$/g, '');
const panelId = `share-${panelIdSeed.slice(0, 48) || 'panel'}`;
const shareClipboardText = [shareTitle, safeSummary, `${copy.canonical}: ${canonicalUrl}`]
  .filter(Boolean)
  .join('\n\n');
const shareSummaryText = [shareTitle, safeSummary, canonicalUrl].filter(Boolean).join('\n\n');
const shareTeaser = [shareTitle, safeSummary].filter(Boolean).join(' — ').slice(0, 220);
const xShareUrl = `https://x.com/intent/tweet?text=${encodeURIComponent(shareTeaser)}&url=${encodeURIComponent(canonicalUrl)}`;
const telegramShareUrl = `https://t.me/share/url?url=${encodeURIComponent(canonicalUrl)}&text=${encodeURIComponent(shareTeaser)}`;

let wechatShareQrSvg = '';
let wechatShareQrPngDataUrl = '';
if (wechatShareQrEnabled) {
  try {
    wechatShareQrSvg = await QRCode.toString(canonicalUrl, {
      type: 'svg',
      margin: 1,
      width: 240,
      color: {
        dark: '#111827',
        light: '#ffffff',
      },
    });
    wechatShareQrPngDataUrl = await QRCode.toDataURL(canonicalUrl, {
      margin: 1,
      width: 420,
      color: {
        dark: '#111827',
        light: '#ffffff',
      },
    });
  } catch (error) {
    console.error('Share panel QR generation error:', error);
  }
}
---

<section
  class="rounded-[28px] border border-[var(--border-color)] bg-[linear-gradient(135deg,rgba(var(--primary-rgb),0.1),rgba(var(--secondary-rgb),0.04)_46%,rgba(var(--bg-rgb),0.92))] p-5 sm:p-6"
  data-share-panel-id={panelId}
>
  <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
    <div class="space-y-3">
      <div class="flex flex-wrap items-center gap-2">
        <span class="inline-flex items-center gap-2 rounded-full border border-[var(--primary)]/20 bg-[var(--primary)]/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-[var(--primary)]">
          <i class="fas fa-satellite-dish text-[10px]"></i>
          {visibleBadge}
        </span>
      </div>

      <div class="space-y-2">
        <h3 class="text-xl font-semibold text-[var(--title-color)]">{visibleTitle}</h3>
        <p class="max-w-3xl text-sm leading-7 text-[var(--text-secondary)]">{visibleDescription}</p>
      </div>
    </div>

    {stats.length > 0 ? (
      <div class="grid gap-3 sm:grid-cols-2 lg:min-w-[16rem]">
        {stats.slice(0, 4).map((item) => (
          <div class="rounded-2xl border border-[var(--border-color)]/75 bg-[var(--terminal-bg)]/76 px-4 py-3">
            <div class="text-[11px] uppercase tracking-[0.18em] text-[var(--text-tertiary)]">{item.label}</div>
            <div class="mt-2 text-lg font-semibold text-[var(--title-color)]">{item.value}</div>
          </div>
        ))}
      </div>
    ) : null}
  </div>

  <div class="mt-5 rounded-[24px] border border-[var(--border-color)]/70 bg-[var(--terminal-bg)]/86 p-5 shadow-[0_16px_40px_rgba(15,23,42,0.06)]">
    <div class="text-[11px] uppercase tracking-[0.18em] text-[var(--text-tertiary)]">{copy.summaryTitle}</div>
    <p class="mt-3 text-base leading-8 text-[var(--title-color)]">{safeSummary}</p>
  </div>

  <div class="mt-4 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
    <div class="flex flex-wrap gap-2">
      <button
        type="button"
        class="terminal-action-button"
        data-share-copy-summary
        data-default-label={copy.copySummary}
        data-success-label={copy.copySummarySuccess}
        data-failed-label={copy.copySummaryFailed}
      >
        <i class="fas fa-copy"></i>
        <span>{copy.copySummary}</span>
      </button>
      <button
        type="button"
        class="terminal-action-button"
        data-share-copy-link
        data-default-label={copy.copyLink}
        data-success-label={copy.copyLinkSuccess}
        data-failed-label={copy.copyLinkFailed}
      >
        <i class="fas fa-link"></i>
        <span>{copy.copyLink}</span>
      </button>
      <button
        type="button"
        class="terminal-action-button terminal-action-button-primary"
        data-share-summary
        data-default-label={copy.shareSummary}
        data-success-label={copy.shareSuccess}
        data-fallback-label={copy.shareFallback}
        data-failed-label={copy.shareFailed}
      >
        <i class="fas fa-share-nodes"></i>
        <span>{copy.shareSummary}</span>
      </button>
    </div>
    <p class="min-h-[1.25rem] text-xs text-[var(--text-tertiary)]" data-share-status aria-live="polite"></p>
  </div>

  <div class="mt-4 rounded-2xl border border-[var(--border-color)]/70 bg-[var(--terminal-bg)]/72 px-4 py-3">
    <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
      <div class="space-y-1">
        <p class="text-[11px] font-semibold uppercase tracking-[0.22em] text-[var(--text-tertiary)]">
          {isEnglish ? 'Share channels' : '分享渠道'}
        </p>
        <p class="text-xs leading-6 text-[var(--text-secondary)]">{visibleDescription}</p>
      </div>
      <div class="flex flex-wrap gap-2">
        <a
          href={xShareUrl}
          target="_blank"
          rel="noopener noreferrer nofollow"
          class="terminal-action-button"
          data-share-link
        >
          <i class="fab fa-twitter"></i>
          <span>{copy.shareToX}</span>
        </a>
        <a
          href={telegramShareUrl}
          target="_blank"
          rel="noopener noreferrer nofollow"
          class="terminal-action-button"
          data-share-link
        >
          <i class="fab fa-telegram-plane"></i>
          <span>{copy.shareToTelegram}</span>
        </a>
        {wechatShareQrEnabled && wechatShareQrSvg ? (
          <button
            type="button"
            class="terminal-action-button"
            data-share-wechat-open
          >
            <i class="fab fa-weixin"></i>
            <span>{copy.shareToWeChat}</span>
          </button>
        ) : null}
      </div>
    </div>
  </div>

  <div class="mt-4 rounded-2xl border border-[var(--border-color)]/70 bg-[var(--terminal-bg)]/82 p-4">
    <div class="text-[11px] uppercase tracking-[0.18em] text-[var(--text-tertiary)]">{copy.canonical}</div>
    <p class="mt-2 break-all font-mono text-xs leading-6 text-[var(--title-color)]">{canonicalUrl}</p>
  </div>

  {wechatShareQrEnabled && wechatShareQrSvg ? (
    <div
      class="fixed inset-0 z-[160] hidden bg-black/70 backdrop-blur-sm"
      data-share-wechat-modal
      aria-hidden="true"
    >
      <div class="flex min-h-screen items-center justify-center p-4">
        <div class="w-full max-w-4xl rounded-[32px] border border-[var(--border-color)]/70 bg-[var(--terminal-bg)] p-5 shadow-[0_30px_90px_rgba(15,23,42,0.36)] sm:p-7">
          <div class="flex items-start justify-between gap-4">
            <div class="space-y-2">
              <span class="terminal-kicker">
                <i class="fab fa-weixin"></i>
                {copy.shareToWeChat}
              </span>
              <div>
                <h3 class="text-2xl font-semibold text-[var(--title-color)]">{copy.qrModalTitle}</h3>
                <p class="mt-2 max-w-2xl text-sm leading-7 text-[var(--text-secondary)]">
                  {copy.qrModalDescription}
                </p>
              </div>
            </div>

            <button
              type="button"
              class="flex h-11 w-11 items-center justify-center rounded-2xl border border-[var(--border-color)] bg-[var(--terminal-bg)] text-[var(--text-secondary)] transition hover:border-[var(--primary)] hover:text-[var(--primary)]"
              data-share-wechat-close
              aria-label={t('common.close')}
            >
              <i class="fas fa-xmark text-base"></i>
            </button>
          </div>

          <div class="mt-6 grid gap-6 lg:grid-cols-[260px_minmax(0,1fr)]">
            <div class="mx-auto w-full max-w-[260px] rounded-[28px] border border-[var(--border-color)]/80 bg-white p-5 shadow-[0_18px_45px_rgba(15,23,42,0.12)]">
              <div class="overflow-hidden rounded-2xl" set:html={wechatShareQrSvg}></div>
            </div>

            <div class="space-y-4">
              <div class="rounded-2xl border border-[var(--border-color)]/70 bg-[var(--header-bg)] p-5">
                <div class="text-[11px] uppercase tracking-[0.2em] text-[var(--text-tertiary)]">
                  {copy.canonical}
                </div>
                <p class="mt-3 break-all font-mono text-sm leading-7 text-[var(--title-color)]">{canonicalUrl}</p>
              </div>

              <div class="rounded-2xl border border-[var(--border-color)]/70 bg-[var(--header-bg)] p-5">
                <div class="text-[11px] uppercase tracking-[0.2em] text-[var(--text-tertiary)]">
                  {copy.summaryTitle}
                </div>
                <p class="mt-3 text-base font-semibold leading-7 text-[var(--title-color)]">{shareTitle}</p>
                <p class="mt-3 text-sm leading-7 text-[var(--text-secondary)]">{safeSummary}</p>
                <p class="mt-3 text-sm leading-7 text-[var(--text-secondary)]">{copy.qrModalHint}</p>
              </div>

              <div class="flex flex-wrap gap-2">
                <button
                  type="button"
                  class="terminal-action-button terminal-action-button-primary"
                  data-share-copy-link
                  data-default-label={copy.copyLink}
                  data-success-label={copy.copyLinkSuccess}
                  data-failed-label={copy.copyLinkFailed}
                >
                  <i class="fas fa-link"></i>
                  <span>{copy.copyLink}</span>
                </button>
                <a
                  href={wechatShareQrPngDataUrl}
                  download={`${panelId}-wechat-share-qr.png`}
                  class="terminal-action-button"
                  data-share-qr-download
                >
                  <i class="fas fa-download"></i>
                  <span>{copy.downloadQr}</span>
                </a>
                <button
                  type="button"
                  class="terminal-action-button"
                  data-share-wechat-close
                >
                  <i class="fas fa-xmark"></i>
                  <span>{t('common.close')}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  ) : null}

  <div
    class="pointer-events-none fixed bottom-5 right-5 z-[70] w-[min(22rem,calc(100vw-1.5rem))] translate-y-4 opacity-0 transition-all duration-300"
    data-share-toast
    data-title-success={copy.toastSuccessTitle}
    data-title-error={copy.toastErrorTitle}
    data-title-info={copy.toastInfoTitle}
    aria-live="polite"
    aria-atomic="true"
  >
    <div class="rounded-2xl border border-emerald-500/25 bg-[var(--terminal-bg)]/96 p-4 shadow-[0_18px_50px_rgba(15,23,42,0.18)] backdrop-blur">
      <div class="flex items-start gap-3">
        <span
          class="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-emerald-500/12 text-emerald-400"
          data-share-toast-icon
        >
          <i class="fas fa-check"></i>
        </span>
        <div class="min-w-0">
          <p class="text-sm font-semibold text-[var(--title-color)]" data-share-toast-title>
            {copy.toastSuccessTitle}
          </p>
          <p class="mt-1 text-sm leading-6 text-[var(--text-secondary)]" data-share-toast-message></p>
        </div>
      </div>
    </div>
  </div>
</section>

<script
  is:inline
  define:vars={{
    panelId,
    shareClipboardText,
    shareSummaryText,
    canonicalUrl,
    shareTitle,
    qrOpenedLabel: copy.qrOpened,
    qrDownloadStartedLabel: copy.downloadQrStarted,
  }}
>
  (() => {
    const root = document.querySelector(`[data-share-panel-id="${panelId}"]`);
    if (!root) return;

    const copySummaryButton = root.querySelector('[data-share-copy-summary]');
    const shareSummaryButton = root.querySelector('[data-share-summary]');
    const copyLinkButtons = root.querySelectorAll('[data-share-copy-link]');
    const shareLinks = root.querySelectorAll('[data-share-link]');
    const wechatOpenButtons = root.querySelectorAll('[data-share-wechat-open]');
    const wechatCloseButtons = root.querySelectorAll('[data-share-wechat-close]');
    const wechatModal = root.querySelector('[data-share-wechat-modal]');
    const qrDownloadButtons = root.querySelectorAll('[data-share-qr-download]');
    const status = root.querySelector('[data-share-status]');
    const toast = root.querySelector('[data-share-toast]');
    const toastIcon = root.querySelector('[data-share-toast-icon]');
    const toastTitle = root.querySelector('[data-share-toast-title]');
    const toastMessage = root.querySelector('[data-share-toast-message]');
    let toastTimer = 0;

    function setStatus(message) {
      if (!status) return;
      status.textContent = message || '';
    }

    function showToast(message, type = 'success') {
      if (!toast || !toastIcon || !toastTitle || !toastMessage) return;

      const title =
        toast.getAttribute(`data-title-${type}`) ||
        toast.getAttribute('data-title-success') ||
        '';

      toastTitle.textContent = title;
      toastMessage.textContent = message || '';
      toast.classList.remove('opacity-0', 'translate-y-4');

      toastIcon.className = 'flex h-9 w-9 shrink-0 items-center justify-center rounded-xl';
      const iconElement = toastIcon.querySelector('i');
      if (iconElement) {
        iconElement.className =
          type === 'error'
            ? 'fas fa-triangle-exclamation'
            : type === 'info'
              ? 'fas fa-share-nodes'
              : 'fas fa-check';
      }

      const toastCard = toast.firstElementChild;
      toastCard?.classList.remove('border-emerald-500/25', 'border-rose-500/25', 'border-sky-500/25');
      toastIcon.classList.remove(
        'bg-emerald-500/12',
        'text-emerald-400',
        'bg-rose-500/12',
        'text-rose-400',
        'bg-sky-500/12',
        'text-sky-400',
      );

      if (type === 'error') {
        toastCard?.classList.add('border-rose-500/25');
        toastIcon.classList.add('bg-rose-500/12', 'text-rose-400');
      } else if (type === 'info') {
        toastCard?.classList.add('border-sky-500/25');
        toastIcon.classList.add('bg-sky-500/12', 'text-sky-400');
      } else {
        toastCard?.classList.add('border-emerald-500/25');
        toastIcon.classList.add('bg-emerald-500/12', 'text-emerald-400');
      }

      window.clearTimeout(toastTimer);
      toastTimer = window.setTimeout(() => {
        toast.classList.add('opacity-0', 'translate-y-4');
      }, 2200);
    }

    function setButtonState(button, iconClass, label) {
      if (!button) return;
      button.innerHTML = `<i class="${iconClass}"></i><span>${label}</span>`;
    }

    function resetButton(button, fallbackIconClass) {
      if (!button) return;
      const defaultLabel = button.getAttribute('data-default-label') || '';
      setButtonState(button, fallbackIconClass, defaultLabel);
    }

    async function writeClipboard(value) {
      await navigator.clipboard.writeText(value);
    }

    async function handleCopySummary() {
      const successLabel = copySummaryButton?.getAttribute('data-success-label') || '';
      const failedLabel = copySummaryButton?.getAttribute('data-failed-label') || '';

      try {
        await writeClipboard(shareClipboardText);
        setButtonState(copySummaryButton, 'fas fa-check', successLabel);
        setStatus(successLabel);
        showToast(successLabel, 'success');
      } catch {
        setButtonState(copySummaryButton, 'fas fa-triangle-exclamation', failedLabel);
        setStatus(failedLabel);
        showToast(failedLabel, 'error');
      } finally {
        window.setTimeout(() => {
          resetButton(copySummaryButton, 'fas fa-copy');
        }, 1800);
      }
    }

    async function handleCopyLink(button) {
      const successLabel = button?.getAttribute('data-success-label') || '';
      const failedLabel = button?.getAttribute('data-failed-label') || '';

      try {
        await writeClipboard(canonicalUrl);
        setButtonState(button, 'fas fa-check', successLabel);
        setStatus(successLabel);
        showToast(successLabel, 'success');
      } catch {
        setButtonState(button, 'fas fa-triangle-exclamation', failedLabel);
        setStatus(failedLabel);
        showToast(failedLabel, 'error');
      } finally {
        window.setTimeout(() => {
          resetButton(button, 'fas fa-link');
        }, 1800);
      }
    }

    async function handleShareSummary() {
      const successLabel = shareSummaryButton?.getAttribute('data-success-label') || '';
      const fallbackLabel = shareSummaryButton?.getAttribute('data-fallback-label') || '';
      const failedLabel = shareSummaryButton?.getAttribute('data-failed-label') || '';

      try {
        if (navigator.share) {
          await navigator.share({
            title: shareTitle,
            text: shareSummaryText,
            url: canonicalUrl,
          });
          setButtonState(shareSummaryButton, 'fas fa-check', successLabel);
          setStatus(successLabel);
          showToast(successLabel, 'success');
        } else {
          await writeClipboard(shareSummaryText);
          setButtonState(shareSummaryButton, 'fas fa-copy', fallbackLabel);
          setStatus(fallbackLabel);
          showToast(fallbackLabel, 'info');
        }
      } catch (error) {
        if (error instanceof DOMException && error.name === 'AbortError') {
          resetButton(shareSummaryButton, 'fas fa-share-nodes');
          return;
        }

        setButtonState(shareSummaryButton, 'fas fa-triangle-exclamation', failedLabel);
        setStatus(failedLabel);
        showToast(failedLabel, 'error');
      } finally {
        window.setTimeout(() => {
          resetButton(shareSummaryButton, 'fas fa-share-nodes');
        }, 1800);
      }
    }

    function openWechatModal() {
      if (!wechatModal) return;
      wechatModal.classList.remove('hidden');
      wechatModal.setAttribute('aria-hidden', 'false');
      document.body.style.overflow = 'hidden';
      setStatus(qrOpenedLabel);
      showToast(qrOpenedLabel, 'info');
    }

    function closeWechatModal() {
      if (!wechatModal) return;
      wechatModal.classList.add('hidden');
      wechatModal.setAttribute('aria-hidden', 'true');
      document.body.style.overflow = '';
    }

    copySummaryButton?.addEventListener('click', async () => {
      await handleCopySummary();
    });

    shareSummaryButton?.addEventListener('click', async () => {
      await handleShareSummary();
    });

    copyLinkButtons.forEach((button) => {
      button.addEventListener('click', async () => {
        await handleCopyLink(button);
      });
    });

    shareLinks.forEach((link) => {
      link.addEventListener('click', () => {
        const label = link.textContent?.trim() || '';
        if (!label) return;
        setStatus(label);
        showToast(label, 'info');
      });
    });

    wechatOpenButtons.forEach((button) => {
      button.addEventListener('click', () => {
        openWechatModal();
      });
    });

    wechatCloseButtons.forEach((button) => {
      button.addEventListener('click', () => {
        closeWechatModal();
      });
    });

    qrDownloadButtons.forEach((button) => {
      button.addEventListener('click', () => {
        setStatus(qrDownloadStartedLabel);
        showToast(qrDownloadStartedLabel, 'info');
      });
    });

    wechatModal?.addEventListener('click', (event) => {
      if (event.target === wechatModal) {
        closeWechatModal();
      }
    });

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape' && wechatModal && !wechatModal.classList.contains('hidden')) {
        closeWechatModal();
      }
    });
  })();
</script>
