// AdCard.jsx v2
// Ændringer fra v1:
// - Video ads (creative_type === 'video') uden video_url renderes som thumbnail med play-overlay
// - Klik på play-overlay åbner PreviewModal med FB iframe via ad.preview_url
// - Modal-state bevares via App-niveau callback (onOpenPreview)

const CTA_LABELS = {
  LEARN_MORE: 'Læs mere',
  SHOP_NOW: 'Shop nu',
  SIGN_UP: 'Tilmeld dig',
  GET_OFFER: 'Få tilbud',
  GET_QUOTE: 'Få tilbud',
  CONTACT_US: 'Kontakt os',
  DOWNLOAD: 'Download',
  BOOK_TRAVEL: 'Book',
  SUBSCRIBE: 'Abonnér',
  APPLY_NOW: 'Ansøg nu',
  GET_STARTED: 'Kom i gang',
  ORDER_NOW: 'Bestil nu',
  WATCH_MORE: 'Se mere',
  SEE_MORE: 'Se mere',
  INSTALL_MOBILE_APP: 'Installer app',
  INSTALL_NOW: 'Installer',
  TRY_FREE: 'Prøv gratis',
  REQUEST_TIME: 'Anmod om tid',
  SEND_MESSAGE: 'Send besked',
  WHATSAPP_MESSAGE: 'Send WhatsApp',
  GET_DIRECTIONS: 'Få rute',
  CALL_NOW: 'Ring nu',
  PLAY_GAME: 'Spil',
  USE_APP: 'Brug app',
  NO_BUTTON: null,
};

function getDomain(url) {
  if (!url) return null;
  try {
    return new URL(url).hostname.replace(/^www\./, '');
  } catch {
    return null;
  }
}

const AdCard = ({ ad, onOpenPreview }) => {
  const [creative, setCreative] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [errorMsg, setErrorMsg] = React.useState('');
  const [visible, setVisible] = React.useState(false);
  const cardRef = React.useRef(null);

  // Initialiser med data fra /api/ads (det er allerede joined)
  React.useEffect(() => {
    if (ad.creative_type) {
      setCreative({
        creative_type: ad.creative_type,
        image_url: ad.image_url,
        video_url: ad.video_url,
        thumbnail_url: ad.thumbnail_url,
        body: ad.body,
        title: ad.title,
        cta_type: ad.cta_type,
        link_url: ad.link_url,
        page_name: ad.page_name,
        page_picture_url: ad.page_picture_url,
      });
      setLoading(false);
    }
  }, [ad]);

  // IntersectionObserver til lazy fetch
  React.useEffect(() => {
    if (creative) return; // allerede loaded fra DB
    const el = cardRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        setVisible(true);
        observer.disconnect();
      }
    }, { rootMargin: '400px' });
    observer.observe(el);
    return () => observer.disconnect();
  }, [creative]);

  // Fetch fra Graph API on-demand
  React.useEffect(() => {
    if (!visible || creative) return;
    fetch(`/api/creative/${ad.ad_id}`)
      .then(r => r.json())
      .then(data => {
        if (data.error) {
          setErrorMsg(data.error);
        } else {
          setCreative(data.creative);
        }
        setLoading(false);
      })
      .catch(err => {
        setErrorMsg(String(err));
        setLoading(false);
      });
  }, [visible, ad.ad_id, creative]);

  // NYT i v2: Render video media — enten direkte <video> hvis video_url findes
  // (kommer ikke til at ske nu pga. permission-issue, men vi beholder fallback for fremtiden),
  // ellers thumbnail med play-overlay der åbner modal.
  const renderVideoMedia = () => {
    if (creative.video_url) {
      // Direkte video — virker når Marketing API video-source bliver tilgængeligt
      return (
        <video
          src={creative.video_url}
          poster={creative.thumbnail_url}
          controls
          preload="metadata"
        />
      );
    }

    // Fallback: thumbnail med play-overlay
    const hasPreviewUrl = !!ad.preview_url;
    const handlePlayClick = (e) => {
      e.stopPropagation();
      if (hasPreviewUrl && onOpenPreview) {
        onOpenPreview(ad.preview_url, ad.headline);
      }
    };

    return (
      <div className="ad-card__video-fallback">
        {creative.thumbnail_url ? (
          <img src={creative.thumbnail_url} alt={creative.title || ad.headline} />
        ) : (
          <div className="ad-card__no-thumbnail">Video</div>
        )}
        {hasPreviewUrl && (
          <button
            type="button"
            className="ad-card__play-overlay"
            onClick={handlePlayClick}
            aria-label="Afspil video preview"
          >
            <svg viewBox="0 0 80 80" width="64" height="64" aria-hidden="true">
              <circle cx="40" cy="40" r="38" fill="rgba(0,0,0,0.55)" stroke="rgba(255,255,255,0.9)" strokeWidth="2"/>
              <path d="M32 24 L32 56 L58 40 Z" fill="#ffffff"/>
            </svg>
          </button>
        )}
        {!hasPreviewUrl && (
          <div className="ad-card__video-no-preview">
            Ingen preview tilgængelig
          </div>
        )}
      </div>
    );
  };

  const renderContent = () => {
    if (loading) {
      return (
        <div className="ad-card__loading">
          <div className="spinner" />
        </div>
      );
    }

    if (errorMsg && !creative) {
      return (
        <div className="ad-card__error">
          Kunne ikke hente kreativ
          <span className="ad-card__error-detail">{errorMsg}</span>
        </div>
      );
    }

    if (!creative) return null;

    const ctaLabel = CTA_LABELS[creative.cta_type] || (creative.cta_type ? creative.cta_type.replace(/_/g, ' ').toLowerCase() : null);
    const domain = getDomain(creative.link_url);
    const pageName = creative.page_name || ad.brand?.toUpperCase() || 'Annonce';

    return (
      <>
        <div className="ad-card__header">
          {creative.page_picture_url ? (
            <img className="ad-card__avatar" src={creative.page_picture_url} alt={pageName} />
          ) : (
            <div className="ad-card__avatar" />
          )}
          <div>
            <div className="ad-card__page-name">{pageName}</div>
            <div className="ad-card__sponsored">Sponsoreret</div>
          </div>
        </div>

        {creative.body && (
          <div className="ad-card__body">{creative.body}</div>
        )}

        <div className="ad-card__media">
          {creative.creative_type === 'video' ? (
            renderVideoMedia()
          ) : creative.image_url ? (
            <img src={creative.image_url} alt={creative.title || ad.headline} />
          ) : creative.thumbnail_url ? (
            <img src={creative.thumbnail_url} alt={creative.title || ad.headline} />
          ) : (
            <div style={{aspectRatio: '1/1', display:'flex', alignItems:'center', justifyContent:'center', color:'#999', fontSize:'13px', background:'#f0f2f5'}}>
              Ingen mediefil
            </div>
          )}
        </div>

        {(creative.title || ctaLabel) && (
          <div className="ad-card__link">
            <div className="ad-card__link-info">
              {domain && <div className="ad-card__link-domain">{domain}</div>}
              {creative.title && <div className="ad-card__link-title">{creative.title}</div>}
            </div>
            {ctaLabel && (
              <button className="ad-card__cta" type="button">{ctaLabel}</button>
            )}
          </div>
        )}

        <div className="ad-card__meta">
          <span><span className="ad-card__meta-label">Adset:</span> {ad.adset_name}</span>
        </div>
      </>
    );
  };

  return (
    <div className="ad-card" ref={cardRef}>
      {renderContent()}
    </div>
  );
};
