'use client';

import { useState } from 'react';
import { Globe, ImageOff } from 'lucide-react';
import { CTA_LABELS } from '@/components/admin/marketing/ui';

interface AdPreviewProps {
  pageName: string;
  headline: string;
  primaryText: string;
  description?: string | null;
  cta: string;
  imageUrl?: string | null;
  link?: string | null;
}

function domainOf(link?: string | null): string {
  if (!link) return 'yourstore.com';
  try {
    return new URL(link).hostname.replace(/^www\./, '').toUpperCase();
  } catch {
    return link;
  }
}

// Approximates how the ad looks in the Facebook feed (single image, link
// ad). Always light — it's a picture of Facebook, not of the admin theme.
export default function AdPreview({ pageName, headline, primaryText, description, cta, imageUrl, link }: AdPreviewProps) {
  const [expanded, setExpanded] = useState(false);
  const long = primaryText.length > 180;

  return (
    <div className="w-full max-w-[420px] overflow-hidden rounded-xl border bg-white text-[#050505] shadow-sm" style={{ borderColor: '#dadde1' }}>
      <div className="flex items-center gap-2.5 px-3 pt-3">
        <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#1877F2] text-sm font-bold text-white">
          {(pageName || '?').slice(0, 1).toUpperCase()}
        </div>
        <div className="min-w-0 leading-tight">
          <p className="truncate text-[14px] font-semibold">{pageName || 'Your page'}</p>
          <p className="flex items-center gap-1 text-[12px] text-[#65676B]">Sponsored · <Globe size={11} /></p>
        </div>
      </div>

      <div className="whitespace-pre-line px-3 py-2 text-[14px] leading-snug">
        {long && !expanded ? `${primaryText.slice(0, 180)}… ` : primaryText}
        {long && !expanded && (
          <button type="button" className="font-semibold text-[#65676B] cursor-pointer" onClick={() => setExpanded(true)}>See more</button>
        )}
      </div>

      <div className="aspect-square w-full bg-[#F0F2F5]">
        {imageUrl ? (
          // eslint-disable-next-line @next/next/no-img-element -- any external image URL; preview only
          <img src={imageUrl} alt="" className="h-full w-full object-cover" />
        ) : (
          <div className="flex h-full items-center justify-center text-[#8A8D91]"><ImageOff size={36} /></div>
        )}
      </div>

      <div className="flex items-center justify-between gap-3 bg-[#F0F2F5] px-3 py-2.5">
        <div className="min-w-0">
          <p className="truncate text-[12px] text-[#65676B]">{domainOf(link)}</p>
          <p className="truncate text-[15px] font-semibold leading-tight">{headline || 'Headline'}</p>
          {description && <p className="truncate text-[13px] text-[#65676B]">{description}</p>}
        </div>
        <span className="shrink-0 rounded-md bg-[#E4E6EB] px-3 py-2 text-[14px] font-semibold">{CTA_LABELS[cta] ?? cta}</span>
      </div>
    </div>
  );
}
