// @design-system: domain/ShareButton

'use client';

import { useCallback, useState } from 'react';
import { cn } from '@/lib/cn';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { ToastProvider, ToastViewport, Toast, ToastTitle } from '@/components/ui/overlays/Toast';
import { useT } from '@/lib/i18n/react';
import { captureCaught } from '@/lib/observability';
import { getCsrfToken } from '@/lib/csrf';

/** Props for ShareButton */
export interface ShareButtonProps {
  /** The URL to share. Defaults to the current page URL. Also used as fallback when shareParams API call fails. */
  url?: string;
  /** Share title (used by native share sheet). */
  title?: string;
  /** Share text (used by native share sheet). */
  text?: string;
  /** Called after a successful share/copy. */
  onShared?: () => void;
  /** Show visible text label alongside the icon. */
  showLabel?: boolean;
  /** Additional class names. */
  className?: string;
  /**
   * When provided, POST /api/share before sharing to get a tracked short URL.
   * Falls back to `url` prop (or window.location.href) on API error.
   */
  shareParams?: {
    targetUrl: string;
    dealId?: string;
    dealSlug?: string;
    campaignName?: string;
  };
}

/**
 * ShareButton - opens native share sheet via `navigator.share()`.
 * Falls back to clipboard copy with a toast confirmation.
 *
 * @example
 * ```tsx
 * <ShareButton url={`https://multideal.co.il/deals/${deal.id}`} title={deal.title} />
 * ```
 */
export function ShareButton({
  url,
  title,
  text,
  onShared,
  showLabel,
  className,
  shareParams,
}: ShareButtonProps) {
  const t = useT('domain_share');
  const [copied, setCopied] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleShare = useCallback(async () => {
    let shareUrl = url ?? (typeof window !== 'undefined' ? window.location.href : '');

    if (shareParams) {
      try {
        setLoading(true);
        const res = await fetch('/api/share', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'x-csrf-token': getCsrfToken() },
          body: JSON.stringify({ ...shareParams, channel: 'direct' }),
        });
        if (!res.ok) throw new Error(`share API ${res.status}`);
        const json = (await res.json()) as { data: { shortUrl: string } };
        shareUrl = json.data.shortUrl;
      } catch (err) {
        captureCaught(err, {
          scope: 'components.ui.domain.ShareButton.ShareButton',
          severity: 'warning',
        });
        // fall through with original url
      } finally {
        setLoading(false);
      }
    }

    const shareData: ShareData = { url: shareUrl, title, text };

    if (typeof navigator !== 'undefined' && navigator.share) {
      try {
        await navigator.share(shareData);
        onShared?.();
      } catch (err) {
        captureCaught(err, {
          scope: 'components.ui.domain.ShareButton.ShareButton',
          severity: 'warning',
        });
        // User cancelled - no error
      }
      return;
    }

    // Fallback: copy link to clipboard
    if (typeof navigator !== 'undefined' && navigator.clipboard) {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      onShared?.();
    }
  }, [url, shareParams, title, text, onShared]);

  return (
    <ToastProvider swipeDirection="right">
      <Button
        variant="ghost"
        size="sm"
        onClick={handleShare}
        disabled={loading}
        iconStart={<Icon name="Share2" size="sm" />}
        className={cn('hover:text-brand-primary-600 text-neutral-500', className)}
        aria-label={t('button_label')}
      >
        {showLabel ? t('button_label') : undefined}
      </Button>
      <Toast tone="success" open={copied} onOpenChange={setCopied} duration={2000}>
        <ToastTitle>{t('copied')}</ToastTitle>
      </Toast>
      <ToastViewport />
    </ToastProvider>
  );
}
